Skip to content

Commit

Permalink
automatically increment port
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 f176b49 commit 8f46c97
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
18 changes: 4 additions & 14 deletions package/kedro_viz/launchers/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ def run(
from kedro_viz.launchers.utils import (
_PYPROJECT,
_check_viz_up,
_find_available_port,
_find_kedro_project,
_is_port_in_use,
_start_browser,
_wait_for,
display_cli_message,
Expand Down Expand Up @@ -147,17 +147,8 @@ def run(
"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
port = _find_available_port(host, port)

try:
if port in _VIZ_PROCESSES and _VIZ_PROCESSES[port].is_alive():
_VIZ_PROCESSES[port].terminate()
Expand Down Expand Up @@ -198,8 +189,7 @@ def run(
target=run_server, daemon=False, kwargs={**run_server_kwargs}
)

display_cli_message("Starting Kedro Viz ...", "green")

display_cli_message(f"Starting Kedro Viz on port {port}...", "green")
viz_process.start()

_VIZ_PROCESSES[port] = viz_process
Expand Down
23 changes: 23 additions & 0 deletions package/kedro_viz/launchers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import logging
import socket
import sys
import webbrowser
from pathlib import Path
from time import sleep, time
Expand Down Expand Up @@ -86,6 +87,28 @@ def _is_port_in_use(host: str, port: int):
return s.connect_ex((host, port)) == 0


def _find_available_port(host: str, start_port: int, max_attempts: int = 5) -> int:
max_port = start_port + max_attempts - 1
port = start_port
while port <= max_port:
if not _is_port_in_use(host, port):
return port
display_cli_message(
f"Port {port} is already in use. Trying the next port...",
"yellow",
)
port += 1
display_cli_message(
f"Error: All ports in the range {start_port}-{max_port} are in use.",
"red",
)
display_cli_message(
"Please specify a different port using the '--port' option.",
"red",
)
sys.exit(1)


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 8f46c97

Please sign in to comment.