44
55import collections
66import contextlib
7- import importlib .metadata
87import os
98import signal
9+ import socket
1010import subprocess
1111from collections .abc import Callable , Generator , Sequence
1212from concurrent import futures
13+ from contextlib import closing
1314from pathlib import Path
1415from typing import Any , Literal , overload
1516
1617import click
17- import psutil
1818from redis .exceptions import RedisError
1919from rich .progress import Progress
2020
@@ -52,29 +52,6 @@ def get_num_workers() -> int:
5252 return (os .cpu_count () or 1 ) * 2 + 1
5353
5454
55- def get_process_on_port (port : int ) -> psutil .Process | None :
56- """Get the process on the given port.
57-
58- Args:
59- port: The port.
60-
61- Returns:
62- The process on the given port.
63- """
64- for proc in psutil .process_iter (["pid" , "name" , "cmdline" ]):
65- with contextlib .suppress (
66- psutil .NoSuchProcess , psutil .AccessDenied , psutil .ZombieProcess
67- ):
68- if importlib .metadata .version ("psutil" ) >= "6.0.0" :
69- conns = proc .net_connections (kind = "inet" )
70- else :
71- conns = proc .connections (kind = "inet" )
72- for conn in conns :
73- if conn .laddr .port == int (port ):
74- return proc
75- return None
76-
77-
7855def is_process_on_port (port : int ) -> bool :
7956 """Check if a process is running on the given port.
8057
@@ -84,18 +61,8 @@ def is_process_on_port(port: int) -> bool:
8461 Returns:
8562 Whether a process is running on the given port.
8663 """
87- return get_process_on_port (port ) is not None
88-
89-
90- def kill_process_on_port (port : int ):
91- """Kill the process on the given port.
92-
93- Args:
94- port: The port.
95- """
96- if get_process_on_port (port ) is not None :
97- with contextlib .suppress (psutil .AccessDenied ):
98- get_process_on_port (port ).kill () # pyright: ignore [reportOptionalMemberAccess]
64+ with closing (socket .socket (socket .AF_INET , socket .SOCK_STREAM )) as sock :
65+ return sock .connect_ex (("127.0.0.1" , port )) == 0
9966
10067
10168def change_port (port : int , _type : str ) -> int :
@@ -133,13 +100,13 @@ def handle_port(service_name: str, port: int, auto_increment: bool) -> int:
133100 Raises:
134101 Exit:when the port is in use.
135102 """
136- if (process := get_process_on_port (port )) is None :
103+ console .debug (f"Checking if { service_name .capitalize ()} port: { port } is in use." )
104+ if not is_process_on_port (port ):
105+ console .debug (f"{ service_name .capitalize ()} port: { port } is not in use." )
137106 return port
138107 if auto_increment :
139108 return change_port (port , service_name )
140- console .error (
141- f"{ service_name .capitalize ()} port: { port } is already in use by PID: { process .pid } ."
142- )
109+ console .error (f"{ service_name .capitalize ()} port: { port } is already in use." )
143110 raise click .exceptions .Exit
144111
145112
0 commit comments