processes.py 4.0 KB

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