From 26deebda12ea671340dfdcc8429d8c48b72ffa8b Mon Sep 17 00:00:00 2001 From: Sajid Alam Date: Wed, 6 Nov 2024 09:31:07 +0000 Subject: [PATCH] add check if port is in use Signed-off-by: Sajid Alam --- package/kedro_viz/launchers/cli/run.py | 13 +++++++++++++ package/kedro_viz/launchers/utils.py | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/package/kedro_viz/launchers/cli/run.py b/package/kedro_viz/launchers/cli/run.py index b2e74a48b..02d27e84f 100644 --- a/package/kedro_viz/launchers/cli/run.py +++ b/package/kedro_viz/launchers/cli/run.py @@ -116,6 +116,7 @@ def run( _PYPROJECT, _check_viz_up, _find_kedro_project, + _is_port_in_use, _start_browser, _wait_for, display_cli_message, @@ -145,6 +146,18 @@ def run( "https://github.com/kedro-org/kedro-viz/releases.", "yellow", ) + + # Check if the port is already in use + if _is_port_in_use(host, port): + display_cli_message( + f"Error: Port {port} is already in use. Kedro Viz could not start.", + "red", + ) + display_cli_message( + "Please specify a different port using the '--port' option.", + "red", + ) + return try: if port in _VIZ_PROCESSES and _VIZ_PROCESSES[port].is_alive(): _VIZ_PROCESSES[port].terminate() diff --git a/package/kedro_viz/launchers/utils.py b/package/kedro_viz/launchers/utils.py index 5c6bbae9e..b74af23af 100644 --- a/package/kedro_viz/launchers/utils.py +++ b/package/kedro_viz/launchers/utils.py @@ -2,6 +2,7 @@ used in the `kedro_viz.launchers` package.""" import logging +import socket import webbrowser from pathlib import Path from time import sleep, time @@ -80,6 +81,11 @@ def _check_viz_up(host: str, port: int): return response.status_code == 200 +def _is_port_in_use(host: str, port: int): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + return s.connect_ex((host, port)) == 0 + + def _is_localhost(host: str) -> bool: """Check whether a host is a localhost""" return host in ("127.0.0.1", "localhost", "0.0.0.0")