quapp-common 0.0.15.dev5__tar.gz → 0.0.16.dev2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. {quapp_common-0.0.15.dev5/quapp_common.egg-info → quapp_common-0.0.16.dev2}/PKG-INFO +1 -1
  2. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/pyproject.toml +1 -1
  3. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/async_tasks/async_invocation_task.py +7 -2
  4. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/backend/job_heartbeat.py +2 -0
  5. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/backend/job_manager.py +6 -3
  6. quapp_common-0.0.16.dev2/quapp_common/util/process_utils.py +71 -0
  7. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2/quapp_common.egg-info}/PKG-INFO +1 -1
  8. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common.egg-info/SOURCES.txt +2 -0
  9. quapp_common-0.0.16.dev2/tests/test_fork_socket_inheritance.py +468 -0
  10. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/LICENSE +0 -0
  11. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/README.md +0 -0
  12. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/__init__.py +0 -0
  13. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/async_tasks/__init__.py +0 -0
  14. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/async_tasks/async_task.py +0 -0
  15. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/async_tasks/export_circuit_task.py +0 -0
  16. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/async_tasks/post_processing_task.py +0 -0
  17. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/__init__.py +0 -0
  18. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/backend/__init__.py +0 -0
  19. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/backend/invocation.py +0 -0
  20. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/backend/job_fetcher.py +0 -0
  21. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/backend/job_fetching.py +0 -0
  22. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/bridge.py +0 -0
  23. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/callback/__init__.py +0 -0
  24. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/callback/update_job_metadata.py +0 -0
  25. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/circuit_adapter.py +0 -0
  26. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/device/__init__.py +0 -0
  27. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/device/device_selection.py +0 -0
  28. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/dispatcher.py +0 -0
  29. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/component/result_serializer.py +0 -0
  30. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/config/__init__.py +0 -0
  31. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/config/log_context.py +0 -0
  32. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/config/logging_config.py +0 -0
  33. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/config/thread_config.py +0 -0
  34. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/__init__.py +0 -0
  35. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/async_task/__init__.py +0 -0
  36. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/async_task/circuit_export/__init__.py +0 -0
  37. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/async_task/circuit_export/backend_holder.py +0 -0
  38. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/async_task/circuit_export/circuit_holder.py +0 -0
  39. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/backend/__init__.py +0 -0
  40. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/backend/backend_information.py +0 -0
  41. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/callback/__init__.py +0 -0
  42. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/callback/callback_url.py +0 -0
  43. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/device/__init__.py +0 -0
  44. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/device/circuit_running_option.py +0 -0
  45. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/promise/__init__.py +0 -0
  46. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/promise/post_processing_promise.py +0 -0
  47. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/promise/promise.py +0 -0
  48. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/request/__init__.py +0 -0
  49. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/request/invocation_request.py +0 -0
  50. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/request/job_fetching_request.py +0 -0
  51. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/request/request.py +0 -0
  52. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/response/__init__.py +0 -0
  53. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/response/authentication.py +0 -0
  54. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/response/custom_header.py +0 -0
  55. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/response/error_report.py +0 -0
  56. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/data/response/job_response.py +0 -0
  57. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/__init__.py +0 -0
  58. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/base_enum.py +0 -0
  59. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/error_category.py +0 -0
  60. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/http_header.py +0 -0
  61. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/invocation_step.py +0 -0
  62. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/language.py +0 -0
  63. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/media_type.py +0 -0
  64. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/processing_unit.py +0 -0
  65. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/provider_tag.py +0 -0
  66. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/runtime_phase.py +0 -0
  67. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/sdk.py +0 -0
  68. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/status/__init__.py +0 -0
  69. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/status/job_status.py +0 -0
  70. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/status/status_code.py +0 -0
  71. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/enum/token_type.py +0 -0
  72. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/factory/__init__.py +0 -0
  73. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/factory/device_factory.py +0 -0
  74. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/factory/handler_factory.py +0 -0
  75. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/factory/provider_factory.py +0 -0
  76. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/handler/__init__.py +0 -0
  77. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/handler/handler.py +0 -0
  78. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/model/__init__.py +0 -0
  79. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/model/device/__init__.py +0 -0
  80. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/model/device/custom_device.py +0 -0
  81. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/model/device/device.py +0 -0
  82. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/model/invocation.py +0 -0
  83. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/model/provider/__init__.py +0 -0
  84. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/model/provider/provider.py +0 -0
  85. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/util/__init__.py +0 -0
  86. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/util/error_classifier.py +0 -0
  87. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/util/file_utils.py +0 -0
  88. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/util/http_utils.py +0 -0
  89. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/util/invocation_failure.py +0 -0
  90. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/util/json_parser_utils.py +0 -0
  91. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common/util/response_utils.py +0 -0
  92. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common.egg-info/dependency_links.txt +0 -0
  93. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common.egg-info/requires.txt +0 -0
  94. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/quapp_common.egg-info/top_level.txt +0 -0
  95. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/setup.cfg +0 -0
  96. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_callback_payload.py +0 -0
  97. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_circuit_adapter.py +0 -0
  98. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_compute_process.py +0 -0
  99. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_dispatcher_runner_error.py +0 -0
  100. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_error_classifier.py +0 -0
  101. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_error_log_dedupe.py +0 -0
  102. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_error_report.py +0 -0
  103. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_invocation_failure.py +0 -0
  104. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_job_heartbeat.py +0 -0
  105. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_json_parser_utils.py +0 -0
  106. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_language_dispatcher.py +0 -0
  107. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_log_secret_leak.py +0 -0
  108. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_logging_config.py +0 -0
  109. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_no_sdk_dependency.py +0 -0
  110. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_phase_coverage.py +0 -0
  111. {quapp_common-0.0.15.dev5 → quapp_common-0.0.16.dev2}/tests/test_result_serializer.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quapp-common
3
- Version: 0.0.15.dev5
3
+ Version: 0.0.16.dev2
4
4
  Summary: Quapp common library supporting Quapp Platform for Quantum Computing
5
5
  Author-email: "CITYNOW Co. Ltd. " <corp@citynow.vn>
6
6
  License: The MIT License (MIT)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "quapp-common"
7
- version = "0.0.15.dev5"
7
+ version = "0.0.16.dev2"
8
8
  description = "Quapp common library supporting Quapp Platform for Quantum Computing"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "CITYNOW Co. Ltd. ", email = "corp@citynow.vn" }]
@@ -19,11 +19,13 @@ from ..config.logging_config import logger
19
19
  from ..factory.handler_factory import HandlerFactory
20
20
  from ..model.invocation import Event, Error, Success
21
21
  from ..util.invocation_failure import report_invocation_failure
22
+ from ..util.process_utils import release_inherited_server_sockets
22
23
 
23
24
  PR_SET_PDEATHSIG = 1
24
25
  ORPHAN_EXIT_CODE = 3
25
26
  PARENT_POLL_SEC = 5.0
26
27
  COMPUTE_PROCESS_PREFIX = 'job-compute'
28
+ CLOSE_CONNECTION_HEADERS = {'Connection': 'close'}
27
29
 
28
30
 
29
31
  def fork_context():
@@ -61,6 +63,7 @@ def _watch_parent(parent_pid: int) -> None:
61
63
 
62
64
 
63
65
  def run_compute(parent_pid: int, target) -> None:
66
+ release_inherited_server_sockets()
64
67
  signal.signal(signal.SIGTERM, signal.SIG_DFL)
65
68
 
66
69
  if not set_parent_death_signal():
@@ -162,11 +165,13 @@ class AsyncInvocationTask(AsyncTask):
162
165
 
163
166
  # Respond immediately so clients can poll GET /jobs/{job_id}
164
167
  return JSONResponse(status_code=200, content=Success(
165
- JobManager.get_job(job_id)).serialize())
168
+ JobManager.get_job(job_id)).serialize(),
169
+ headers=CLOSE_CONNECTION_HEADERS)
166
170
  except Exception as exception:
167
171
  logger.exception(f"An error occurred: {exception}")
168
172
  return JSONResponse(status_code=400,
169
- content=Error(exception).serialize())
173
+ content=Error(exception).serialize(),
174
+ headers=CLOSE_CONNECTION_HEADERS)
170
175
 
171
176
  def _watch_compute_process(self, loop, process, job_id, job_log) -> None:
172
177
  sentinel = process.sentinel
@@ -12,6 +12,7 @@ import time
12
12
  import requests
13
13
 
14
14
  from ...config.logging_config import logger
15
+ from ...util.process_utils import release_inherited_server_sockets
15
16
 
16
17
  REQUEST_TIMEOUT_SEC = 5.0
17
18
 
@@ -86,6 +87,7 @@ def _wait_for_next_beat(parent_pid: int, stop_event, interval: float) -> bool:
86
87
 
87
88
 
88
89
  def _heartbeat_loop(parent_pid: int, stop_event) -> None:
90
+ release_inherited_server_sockets()
89
91
  while os.getppid() == parent_pid:
90
92
  try:
91
93
  beat_once()
@@ -8,10 +8,12 @@ import atexit
8
8
  import threading
9
9
  import time
10
10
  from datetime import timezone, datetime
11
- from multiprocessing import Manager, current_process, parent_process
11
+ from multiprocessing import current_process, parent_process
12
+ from multiprocessing.managers import SyncManager
12
13
  from typing import Any, Callable, Dict, Iterable, Optional, Tuple
13
14
 
14
15
  from ...config.logging_config import logger
16
+ from ...util.process_utils import release_inherited_server_sockets
15
17
 
16
18
  SCHEDULER_CALLBACK_URL = 'scheduler_callback_url'
17
19
 
@@ -34,7 +36,7 @@ class JobManager:
34
36
  """
35
37
 
36
38
  # Process-wide singletons (one per process)
37
- _manager: Optional[Manager] = None
39
+ _manager: Optional[SyncManager] = None
38
40
  _jobs: Any = None # proxy dict
39
41
  _updates_queue: Any = None # proxy queue
40
42
  _init_lock = threading.Lock()
@@ -53,7 +55,8 @@ class JobManager:
53
55
  with cls._init_lock:
54
56
  if cls._manager is not None:
55
57
  return
56
- mgr = Manager()
58
+ mgr = SyncManager()
59
+ mgr.start(initializer=release_inherited_server_sockets)
57
60
  cls._manager = mgr
58
61
  cls._jobs = mgr.dict() # type: ignore[assignment]
59
62
  cls._updates_queue = mgr.Queue() # type: ignore[assignment]
@@ -0,0 +1,71 @@
1
+ # Quapp Platform Project
2
+ # process_utils.py
3
+ # Copyright © CITYNOW Co. Ltd. All rights reserved.
4
+
5
+ import os
6
+ import socket
7
+ import stat
8
+ from typing import List, NamedTuple, Optional
9
+
10
+ FD_DIRECTORY = '/proc/self/fd'
11
+ TCP_FAMILIES = (socket.AF_INET, socket.AF_INET6)
12
+
13
+
14
+ class TcpSocket(NamedTuple):
15
+ fd: int
16
+ listening: bool
17
+ port: int
18
+
19
+
20
+ def _describe_tcp_socket(fd: int) -> Optional[TcpSocket]:
21
+ try:
22
+ if not stat.S_ISSOCK(os.fstat(fd).st_mode):
23
+ return None
24
+ duplicate = os.dup(fd)
25
+ except OSError:
26
+ return None
27
+ try:
28
+ probe = socket.socket(fileno=duplicate)
29
+ except OSError:
30
+ os.close(duplicate)
31
+ return None
32
+ with probe:
33
+ if probe.family not in TCP_FAMILIES:
34
+ return None
35
+ try:
36
+ listening = probe.getsockopt(socket.SOL_SOCKET,
37
+ socket.SO_ACCEPTCONN) != 0
38
+ port = probe.getsockname()[1]
39
+ except OSError:
40
+ return None
41
+ return TcpSocket(fd, listening, port)
42
+
43
+
44
+ def _server_side_fds(sockets: List[TcpSocket]) -> List[int]:
45
+ server_ports = {item.port for item in sockets if item.listening}
46
+ return [item.fd for item in sockets
47
+ if item.listening or item.port in server_ports]
48
+
49
+
50
+ def release_inherited_server_sockets() -> None:
51
+ try:
52
+ numbers = [int(name) for name in os.listdir(FD_DIRECTORY)]
53
+ except (OSError, ValueError):
54
+ return
55
+ sockets = [item for item in map(_describe_tcp_socket, numbers)
56
+ if item is not None]
57
+ targets = _server_side_fds(sockets)
58
+ if not targets:
59
+ return
60
+ try:
61
+ devnull = os.open(os.devnull, os.O_RDWR)
62
+ except OSError:
63
+ return
64
+ try:
65
+ for fd in targets:
66
+ try:
67
+ os.dup2(devnull, fd)
68
+ except OSError:
69
+ continue
70
+ finally:
71
+ os.close(devnull)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quapp-common
3
- Version: 0.0.15.dev5
3
+ Version: 0.0.16.dev2
4
4
  Summary: Quapp common library supporting Quapp Platform for Quantum Computing
5
5
  Author-email: "CITYNOW Co. Ltd. " <corp@citynow.vn>
6
6
  License: The MIT License (MIT)
@@ -88,6 +88,7 @@ quapp_common/util/file_utils.py
88
88
  quapp_common/util/http_utils.py
89
89
  quapp_common/util/invocation_failure.py
90
90
  quapp_common/util/json_parser_utils.py
91
+ quapp_common/util/process_utils.py
91
92
  quapp_common/util/response_utils.py
92
93
  tests/test_callback_payload.py
93
94
  tests/test_circuit_adapter.py
@@ -96,6 +97,7 @@ tests/test_dispatcher_runner_error.py
96
97
  tests/test_error_classifier.py
97
98
  tests/test_error_log_dedupe.py
98
99
  tests/test_error_report.py
100
+ tests/test_fork_socket_inheritance.py
99
101
  tests/test_invocation_failure.py
100
102
  tests/test_job_heartbeat.py
101
103
  tests/test_json_parser_utils.py
@@ -0,0 +1,468 @@
1
+ # Quapp Platform Project
2
+ # test_fork_socket_inheritance.py
3
+ # Copyright © CITYNOW Co. Ltd. All rights reserved.
4
+
5
+ import asyncio
6
+ import os
7
+ import shutil
8
+ import socket
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import textwrap
13
+ import time
14
+ import uuid
15
+
16
+ import pytest
17
+
18
+ import quapp_common
19
+ from quapp_common.async_tasks import async_invocation_task
20
+ from quapp_common.async_tasks.async_invocation_task import AsyncInvocationTask, \
21
+ fork_context, run_compute
22
+ from quapp_common.component.backend import job_heartbeat
23
+ from quapp_common.component.backend.job_manager import JobManager
24
+ from quapp_common.factory.handler_factory import HandlerFactory
25
+ from quapp_common.model.invocation import Event
26
+
27
+ REPO_ROOT = os.path.dirname(
28
+ os.path.dirname(os.path.abspath(quapp_common.__file__)))
29
+
30
+ EOF_WAIT_SEC = 3.0
31
+ CHILD_LIFETIME_SEC = 20.0
32
+
33
+
34
+ def free_port():
35
+ with socket.socket() as sock:
36
+ sock.bind(('127.0.0.1', 0))
37
+ return sock.getsockname()[1]
38
+
39
+
40
+ def connected_pair():
41
+ listener = socket.socket()
42
+ listener.bind(('127.0.0.1', 0))
43
+ listener.listen()
44
+ client = socket.create_connection(listener.getsockname())
45
+ server_side, _ = listener.accept()
46
+ listener.close()
47
+ return client, server_side
48
+
49
+
50
+ def peer_sees_eof(client, timeout=EOF_WAIT_SEC):
51
+ client.settimeout(timeout)
52
+ try:
53
+ return client.recv(1) == b''
54
+ except socket.timeout:
55
+ return False
56
+ except ConnectionResetError:
57
+ return True
58
+
59
+
60
+ def stay_alive():
61
+ time.sleep(CHILD_LIFETIME_SEC)
62
+
63
+
64
+ def stop_process(process):
65
+ if process.is_alive():
66
+ process.kill()
67
+ process.join(timeout=5)
68
+
69
+
70
+ def child_env():
71
+ env = dict(os.environ)
72
+ env['PYTHONPATH'] = REPO_ROOT + os.pathsep + env.get('PYTHONPATH', '')
73
+ return env
74
+
75
+
76
+ def run_script(source, timeout=60):
77
+ result = subprocess.run([sys.executable, '-c', textwrap.dedent(source)],
78
+ capture_output=True, text=True, timeout=timeout,
79
+ env=child_env())
80
+ assert result.returncode == 0, result.stderr
81
+ return result.stdout.strip().splitlines()[-1]
82
+
83
+
84
+ class FastHandler:
85
+ def handle(self):
86
+ return 'done'
87
+
88
+
89
+ class FastFactory(HandlerFactory):
90
+ @staticmethod
91
+ def create_handler(event, circuit_preparation_fn, post_processing_fn):
92
+ return FastHandler()
93
+
94
+
95
+ def make_event(job_id):
96
+ event = Event(None)
97
+ event.request_body = {'jobId': job_id}
98
+ return event
99
+
100
+
101
+ @pytest.fixture(autouse=True)
102
+ def clean_heartbeat():
103
+ job_heartbeat.stop()
104
+ yield
105
+ job_heartbeat.stop()
106
+
107
+
108
+ @pytest.fixture
109
+ def workdir():
110
+ path = tempfile.mkdtemp(prefix='fork-socket-test-')
111
+ yield path
112
+ shutil.rmtree(path, ignore_errors=True)
113
+
114
+
115
+ def listening_socket():
116
+ listener = socket.socket()
117
+ listener.bind(('127.0.0.1', 0))
118
+ listener.listen()
119
+ return listener
120
+
121
+
122
+ @pytest.fixture
123
+ def request_connection():
124
+ listener = listening_socket()
125
+ client = socket.create_connection(listener.getsockname())
126
+ server_side, _ = listener.accept()
127
+ yield client, server_side
128
+ for sock in (client, server_side, listener):
129
+ sock.close()
130
+
131
+
132
+ @pytest.fixture
133
+ def outbound_connection():
134
+ remote = listening_socket()
135
+ outbound = socket.create_connection(remote.getsockname())
136
+ remote_end, _ = remote.accept()
137
+ yield outbound, remote_end
138
+ for sock in (outbound, remote_end, remote):
139
+ sock.close()
140
+
141
+
142
+ def test_compute_child_does_not_hold_the_request_connection_open(
143
+ request_connection):
144
+ client, server_side = request_connection
145
+ process = fork_context().Process(target=run_compute,
146
+ args=(os.getpid(), stay_alive),
147
+ daemon=True)
148
+ process.start()
149
+ try:
150
+ time.sleep(0.3)
151
+ server_side.close()
152
+ assert peer_sees_eof(client)
153
+ finally:
154
+ stop_process(process)
155
+
156
+
157
+ def test_heartbeat_process_does_not_hold_the_request_connection_open(
158
+ request_connection):
159
+ JobManager.ensure_registry()
160
+ client, server_side = request_connection
161
+ job_heartbeat.ensure_started()
162
+ time.sleep(0.3)
163
+ server_side.close()
164
+ assert peer_sees_eof(client)
165
+
166
+
167
+ def test_compute_child_can_still_use_an_inherited_outbound_connection(
168
+ request_connection, outbound_connection):
169
+ outbound, remote_end = outbound_connection
170
+ process = fork_context().Process(
171
+ target=run_compute,
172
+ args=(os.getpid(), lambda: send_through(outbound)), daemon=True)
173
+ process.start()
174
+ try:
175
+ process.join(timeout=10)
176
+ remote_end.settimeout(3)
177
+ assert remote_end.recv(4) == b'kept'
178
+ assert process.exitcode == 0
179
+ finally:
180
+ stop_process(process)
181
+
182
+
183
+ def test_manager_process_does_not_hold_the_request_connection_open():
184
+ outcome = run_script('''
185
+ import socket, time
186
+ from quapp_common.component.backend.job_manager import JobManager
187
+
188
+ listener = socket.socket()
189
+ listener.bind(('127.0.0.1', 0))
190
+ listener.listen()
191
+ client = socket.create_connection(listener.getsockname())
192
+ server_side, _ = listener.accept()
193
+
194
+ JobManager.ensure_registry()
195
+ JobManager.add_job('job-1', status='RUNNING', meta={})
196
+ time.sleep(0.3)
197
+ server_side.close()
198
+
199
+ client.settimeout(3.0)
200
+ try:
201
+ eof = client.recv(1) == b''
202
+ except socket.timeout:
203
+ eof = False
204
+ print('EOF' if eof and JobManager.get_status('job-1') == 'RUNNING'
205
+ else 'HELD')
206
+ ''')
207
+ assert outcome == 'EOF'
208
+
209
+
210
+ APP_SOURCE = '''
211
+ from starlette.applications import Starlette
212
+ from starlette.routing import Route
213
+
214
+ from quapp_common.async_tasks.async_invocation_task import AsyncInvocationTask
215
+ from quapp_common.component.backend.job_manager import JobManager
216
+ from quapp_common.factory.handler_factory import HandlerFactory
217
+ from quapp_common.model.invocation import Event
218
+
219
+
220
+ class FastHandler:
221
+ def handle(self):
222
+ return 'done'
223
+
224
+
225
+ class FastFactory(HandlerFactory):
226
+ @staticmethod
227
+ def create_handler(event, circuit_preparation_fn, post_processing_fn):
228
+ return FastHandler()
229
+
230
+
231
+ async def invoke(request):
232
+ body = await request.json()
233
+ event = Event(request)
234
+ event.request_body = body
235
+ JobManager.add_job(body['jobId'], status='RUNNING', meta={})
236
+ return AsyncInvocationTask(FastFactory(), event, None, None).do()
237
+
238
+
239
+ app = Starlette(routes=[Route('/', invoke, methods=['POST'])])
240
+ '''
241
+
242
+
243
+ @pytest.fixture
244
+ def invoke_server(workdir):
245
+ port = free_port()
246
+ with open(os.path.join(workdir, 'app.py'), 'w', encoding='utf-8') as handle:
247
+ handle.write(APP_SOURCE)
248
+ process = subprocess.Popen(
249
+ [sys.executable, '-m', 'uvicorn', '--app-dir', workdir,
250
+ '--host', '127.0.0.1', '--port', str(port),
251
+ '--timeout-keep-alive', '1', '--log-level', 'warning', 'app:app'],
252
+ env=child_env(), start_new_session=True)
253
+ deadline = time.monotonic() + 60
254
+ while time.monotonic() < deadline:
255
+ try:
256
+ socket.create_connection(('127.0.0.1', port), timeout=0.5).close()
257
+ break
258
+ except OSError:
259
+ time.sleep(0.1)
260
+ try:
261
+ yield port
262
+ finally:
263
+ process.terminate()
264
+ try:
265
+ process.wait(timeout=5)
266
+ except subprocess.TimeoutExpired:
267
+ process.kill()
268
+ try:
269
+ os.killpg(process.pid, 9)
270
+ except OSError:
271
+ pass
272
+
273
+
274
+ def post_invoke_keep_alive(port):
275
+ body = ('{"jobId": "%s"}' % uuid.uuid4()).encode()
276
+ connection = socket.create_connection(('127.0.0.1', port))
277
+ connection.sendall(b'POST / HTTP/1.1\r\nHost: fn\r\n'
278
+ b'Content-Type: application/json\r\n'
279
+ b'Connection: keep-alive\r\n'
280
+ b'Content-Length: %d\r\n\r\n' % len(body) + body)
281
+ connection.settimeout(10)
282
+ response = b''
283
+ while b'\r\n\r\n' not in response:
284
+ response += connection.recv(4096)
285
+ head, body = response.split(b'\r\n\r\n', 1)
286
+ headers = head.decode().lower()
287
+ length = int(next(line.split(':', 1)[1] for line in headers.splitlines()
288
+ if line.startswith('content-length:')))
289
+ while len(body) < length:
290
+ body += connection.recv(4096)
291
+ return connection, headers
292
+
293
+
294
+ def test_first_invoke_connection_is_closed_for_real_once_uvicorn_lets_go(
295
+ invoke_server):
296
+ connection, headers = post_invoke_keep_alive(invoke_server)
297
+ try:
298
+ assert headers.startswith('http/1.1 200')
299
+ assert peer_sees_eof(connection, timeout=4.0)
300
+ finally:
301
+ connection.close()
302
+
303
+
304
+ def test_invoke_response_asks_the_proxy_not_to_reuse_the_connection():
305
+ async def call():
306
+ return AsyncInvocationTask(FastFactory(), make_event(str(uuid.uuid4())),
307
+ None, None).do()
308
+
309
+ response = asyncio.run(call())
310
+ assert response.status_code == 200
311
+ assert response.headers.get('connection') == 'close'
312
+
313
+
314
+ def test_rejected_invoke_response_also_closes_the_connection():
315
+ async def call():
316
+ event = Event(None)
317
+ event.request_body = {}
318
+ return AsyncInvocationTask(FastFactory(), event, None, None).do()
319
+
320
+ response = asyncio.run(call())
321
+ assert response.status_code == 400
322
+ assert response.headers.get('connection') == 'close'
323
+
324
+
325
+ def write_through_inherited_handles(pipe_fd, unix_socket):
326
+ os.write(pipe_fd, b'pipe')
327
+ unix_socket.sendall(b'unix')
328
+
329
+
330
+ def test_compute_child_keeps_pipes_and_unix_sockets():
331
+ read_fd, write_fd = os.pipe()
332
+ parent_unix, child_unix = socket.socketpair(socket.AF_UNIX)
333
+ process = fork_context().Process(
334
+ target=run_compute,
335
+ args=(os.getpid(),
336
+ lambda: write_through_inherited_handles(write_fd, child_unix)),
337
+ daemon=True)
338
+ process.start()
339
+ try:
340
+ process.join(timeout=10)
341
+ parent_unix.settimeout(3)
342
+ assert os.read(read_fd, 4) == b'pipe'
343
+ assert parent_unix.recv(4) == b'unix'
344
+ assert process.exitcode == 0
345
+ finally:
346
+ stop_process(process)
347
+ os.close(read_fd)
348
+ os.close(write_fd)
349
+ parent_unix.close()
350
+ child_unix.close()
351
+
352
+
353
+ def connect_and_send(address):
354
+ with socket.create_connection(address, timeout=5) as outbound:
355
+ outbound.sendall(b'callback')
356
+
357
+
358
+ def test_compute_child_can_still_open_new_connections():
359
+ listener = socket.socket()
360
+ listener.bind(('127.0.0.1', 0))
361
+ listener.listen()
362
+ listener.settimeout(10)
363
+ address = listener.getsockname()
364
+ process = fork_context().Process(
365
+ target=run_compute,
366
+ args=(os.getpid(), lambda: connect_and_send(address)), daemon=True)
367
+ process.start()
368
+ try:
369
+ accepted, _ = listener.accept()
370
+ accepted.settimeout(5)
371
+ assert accepted.recv(8) == b'callback'
372
+ accepted.close()
373
+ process.join(timeout=10)
374
+ assert process.exitcode == 0
375
+ finally:
376
+ stop_process(process)
377
+ listener.close()
378
+
379
+
380
+ def send_through(inherited):
381
+ inherited.sendall(b'kept')
382
+
383
+
384
+ def test_forks_made_outside_the_library_keep_their_sockets():
385
+ client, server_side = connected_pair()
386
+ process = fork_context().Process(target=send_through, args=(server_side,),
387
+ daemon=True)
388
+ process.start()
389
+ try:
390
+ process.join(timeout=10)
391
+ client.settimeout(3)
392
+ assert client.recv(4) == b'kept'
393
+ finally:
394
+ stop_process(process)
395
+ client.close()
396
+ server_side.close()
397
+
398
+
399
+ def test_releasing_sockets_never_raises_without_proc(monkeypatch):
400
+ from quapp_common.util import process_utils
401
+
402
+ def missing(path):
403
+ raise FileNotFoundError(path)
404
+
405
+ monkeypatch.setattr(process_utils.os, 'listdir', missing)
406
+ process_utils.release_inherited_server_sockets()
407
+
408
+
409
+ def test_release_drops_server_side_sockets_and_keeps_outbound_ones():
410
+ outcome = run_script('''
411
+ import os, socket, stat
412
+ from quapp_common.util.process_utils import \\
413
+ release_inherited_server_sockets
414
+
415
+ def released(sock):
416
+ return not stat.S_ISSOCK(os.fstat(sock.fileno()).st_mode)
417
+
418
+ server = socket.socket()
419
+ server.bind(('127.0.0.1', 0))
420
+ server.listen()
421
+ proxy = socket.create_connection(server.getsockname())
422
+ served, _ = server.accept()
423
+
424
+ orphan_listener = socket.socket()
425
+ orphan_listener.bind(('127.0.0.1', 0))
426
+ orphan_listener.listen()
427
+ orphan_client = socket.create_connection(orphan_listener.getsockname())
428
+ orphan_served, _ = orphan_listener.accept()
429
+ orphan_listener.close()
430
+
431
+ remote = socket.socket()
432
+ remote.bind(('127.0.0.1', 0))
433
+ remote.listen()
434
+ outbound = socket.create_connection(remote.getsockname())
435
+ remote_end, _ = remote.accept()
436
+
437
+ release_inherited_server_sockets()
438
+ print(' '.join('%s=%s' % (name, released(sock)) for name, sock in
439
+ (('server', server), ('served', served),
440
+ ('outbound', outbound), ('proxy', proxy),
441
+ ('orphan', orphan_served))))
442
+ ''')
443
+ assert outcome == ('server=True served=True outbound=False proxy=False '
444
+ 'orphan=False')
445
+
446
+
447
+ def test_releasing_sockets_keeps_the_fd_number_occupied():
448
+ outcome = run_script('''
449
+ import socket
450
+ from quapp_common.util.process_utils import \\
451
+ release_inherited_server_sockets
452
+
453
+ inherited = socket.socket()
454
+ inherited.bind(('127.0.0.1', 0))
455
+ inherited.listen()
456
+ number = inherited.fileno()
457
+ release_inherited_server_sockets()
458
+ fresh = socket.socket()
459
+ reused = fresh.fileno() == number
460
+ inherited.close()
461
+ try:
462
+ fresh.getsockname()
463
+ alive = True
464
+ except OSError:
465
+ alive = False
466
+ print('SAFE' if alive and not reused else 'CLOBBERED')
467
+ ''')
468
+ assert outcome == 'SAFE'