processes.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. """Process operations."""
  2. from __future__ import annotations
  3. import contextlib
  4. import os
  5. import signal
  6. import subprocess
  7. import sys
  8. from typing import Optional
  9. from urllib.parse import urlparse
  10. import psutil
  11. from reflex import constants
  12. from reflex.config import get_config
  13. from reflex.utils import console, prerequisites
  14. def kill(pid):
  15. """Kill a process.
  16. Args:
  17. pid: The process ID.
  18. """
  19. os.kill(pid, signal.SIGTERM)
  20. def get_num_workers() -> int:
  21. """Get the number of backend worker processes.
  22. Returns:
  23. The number of backend worker processes.
  24. """
  25. return 1 if prerequisites.get_redis() is None else (os.cpu_count() or 1) * 2 + 1
  26. def get_api_port() -> int:
  27. """Get the API port.
  28. Returns:
  29. The API port.
  30. """
  31. port = urlparse(get_config().api_url).port
  32. if port is None:
  33. port = urlparse(constants.API_URL).port
  34. assert port is not None
  35. return port
  36. def get_process_on_port(port) -> Optional[psutil.Process]:
  37. """Get the process on the given port.
  38. Args:
  39. port: The port.
  40. Returns:
  41. The process on the given port.
  42. """
  43. for proc in psutil.process_iter(["pid", "name", "cmdline"]):
  44. try:
  45. for conns in proc.connections(kind="inet"):
  46. if conns.laddr.port == int(port):
  47. return proc
  48. except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
  49. pass
  50. return None
  51. def is_process_on_port(port) -> bool:
  52. """Check if a process is running on the given port.
  53. Args:
  54. port: The port.
  55. Returns:
  56. Whether a process is running on the given port.
  57. """
  58. return get_process_on_port(port) is not None
  59. def kill_process_on_port(port):
  60. """Kill the process on the given port.
  61. Args:
  62. port: The port.
  63. """
  64. if get_process_on_port(port) is not None:
  65. with contextlib.suppress(psutil.AccessDenied):
  66. get_process_on_port(port).kill() # type: ignore
  67. def change_or_terminate_port(port, _type) -> str:
  68. """Terminate or change the port.
  69. Args:
  70. port: The port.
  71. _type: The type of the port.
  72. Returns:
  73. The new port or the current one.
  74. """
  75. console.print(
  76. f"Something is already running on port [bold underline]{port}[/bold underline]. This is the port the {_type} runs on."
  77. )
  78. frontend_action = console.ask("Kill or change it?", choices=["k", "c", "n"])
  79. if frontend_action == "k":
  80. kill_process_on_port(port)
  81. return port
  82. elif frontend_action == "c":
  83. new_port = console.ask("Specify the new port")
  84. # Check if also the new port is used
  85. if is_process_on_port(new_port):
  86. return change_or_terminate_port(new_port, _type)
  87. else:
  88. console.print(
  89. f"The {_type} will run on port [bold underline]{new_port}[/bold underline]."
  90. )
  91. return new_port
  92. else:
  93. console.print("Exiting...")
  94. sys.exit()
  95. def new_process(args, **kwargs):
  96. """Wrapper over subprocess.Popen to unify the launch of child processes.
  97. Args:
  98. args: A string, or a sequence of program arguments.
  99. **kwargs: Kwargs to override default wrap values to pass to subprocess.Popen as arguments.
  100. Returns:
  101. Execute a child program in a new process.
  102. """
  103. kwargs = {
  104. "env": os.environ,
  105. "stderr": subprocess.STDOUT,
  106. "stdout": subprocess.PIPE, # Redirect stdout to a pipe
  107. "universal_newlines": True, # Set universal_newlines to True for text mode
  108. "encoding": "UTF-8",
  109. **kwargs,
  110. }
  111. return subprocess.Popen(
  112. args,
  113. **kwargs,
  114. )