Skip to content

Commit

Permalink
add check if port is in use
Browse files Browse the repository at this point in the history
Signed-off-by: Sajid Alam <[email protected]>
  • Loading branch information
SajidAlamQB committed Nov 6, 2024
1 parent 02331cc commit 26deebd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
13 changes: 13 additions & 0 deletions package/kedro_viz/launchers/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ def run(
_PYPROJECT,
_check_viz_up,
_find_kedro_project,
_is_port_in_use,
_start_browser,
_wait_for,
display_cli_message,
Expand Down Expand Up @@ -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()
Expand Down
6 changes: 6 additions & 0 deletions package/kedro_viz/launchers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down

0 comments on commit 26deebd

Please sign in to comment.