quapp-common 0.0.16.dev1__tar.gz → 0.0.17.dev1__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.
- {quapp_common-0.0.16.dev1/quapp_common.egg-info → quapp_common-0.0.17.dev1}/PKG-INFO +40 -2
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/README.md +38 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/pyproject.toml +4 -2
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/async_tasks/async_invocation_task.py +50 -8
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/backend/job_heartbeat.py +2 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/backend/job_manager.py +6 -3
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/callback/update_job_metadata.py +19 -2
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/config/logging_config.py +27 -0
- quapp_common-0.0.17.dev1/quapp_common/joblog/__init__.py +3 -0
- quapp_common-0.0.17.dev1/quapp_common/joblog/capture.py +118 -0
- quapp_common-0.0.17.dev1/quapp_common/joblog/child.py +109 -0
- quapp_common-0.0.17.dev1/quapp_common/joblog/ingest.py +179 -0
- quapp_common-0.0.17.dev1/quapp_common/joblog/pipes.py +92 -0
- quapp_common-0.0.17.dev1/quapp_common/joblog/shipper.py +510 -0
- quapp_common-0.0.17.dev1/quapp_common/util/process_utils.py +80 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1/quapp_common.egg-info}/PKG-INFO +40 -2
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common.egg-info/SOURCES.txt +9 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common.egg-info/requires.txt +1 -1
- quapp_common-0.0.17.dev1/tests/test_fork_socket_inheritance.py +468 -0
- quapp_common-0.0.17.dev1/tests/test_job_log_capture.py +667 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/LICENSE +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/async_tasks/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/async_tasks/async_task.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/async_tasks/export_circuit_task.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/async_tasks/post_processing_task.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/backend/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/backend/invocation.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/backend/job_fetcher.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/backend/job_fetching.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/bridge.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/callback/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/circuit_adapter.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/device/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/device/device_selection.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/dispatcher.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/result_serializer.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/config/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/config/log_context.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/config/thread_config.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/async_task/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/async_task/circuit_export/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/async_task/circuit_export/backend_holder.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/async_task/circuit_export/circuit_holder.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/backend/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/backend/backend_information.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/callback/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/callback/callback_url.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/device/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/device/circuit_running_option.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/promise/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/promise/post_processing_promise.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/promise/promise.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/request/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/request/invocation_request.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/request/job_fetching_request.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/request/request.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/response/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/response/authentication.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/response/custom_header.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/response/error_report.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/data/response/job_response.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/base_enum.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/error_category.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/http_header.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/invocation_step.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/language.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/media_type.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/processing_unit.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/provider_tag.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/runtime_phase.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/sdk.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/status/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/status/job_status.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/status/status_code.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/enum/token_type.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/factory/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/factory/device_factory.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/factory/handler_factory.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/factory/provider_factory.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/handler/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/handler/handler.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/model/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/model/device/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/model/device/custom_device.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/model/device/device.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/model/invocation.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/model/provider/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/model/provider/provider.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/util/__init__.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/util/error_classifier.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/util/file_utils.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/util/http_utils.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/util/invocation_failure.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/util/json_parser_utils.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/util/response_utils.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common.egg-info/dependency_links.txt +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common.egg-info/top_level.txt +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/setup.cfg +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_callback_payload.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_circuit_adapter.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_compute_process.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_dispatcher_runner_error.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_error_classifier.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_error_log_dedupe.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_error_report.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_invocation_failure.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_job_heartbeat.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_json_parser_utils.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_language_dispatcher.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_log_secret_leak.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_logging_config.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_no_sdk_dependency.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/tests/test_phase_coverage.py +0 -0
- {quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/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.
|
|
3
|
+
Version: 0.0.17.dev1
|
|
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)
|
|
@@ -19,7 +19,7 @@ Classifier: Programming Language :: Python :: 3
|
|
|
19
19
|
Requires-Python: >=3.7
|
|
20
20
|
Description-Content-Type: text/markdown
|
|
21
21
|
License-File: LICENSE
|
|
22
|
-
Requires-Dist: loguru
|
|
22
|
+
Requires-Dist: loguru>=0.5.3
|
|
23
23
|
Requires-Dist: requests
|
|
24
24
|
Requires-Dist: numpy
|
|
25
25
|
Requires-Dist: matplotlib
|
|
@@ -111,6 +111,44 @@ Notes:
|
|
|
111
111
|
|
|
112
112
|
## Recently Changes Highlights
|
|
113
113
|
|
|
114
|
+
### v0.0.17.dev1 — Log job trực tiếp về backend (PQF-23860)
|
|
115
|
+
|
|
116
|
+
Runtime đẩy log của từng job về backend trong lúc job chạy. Loki vẫn là đường dự
|
|
117
|
+
phòng.
|
|
118
|
+
|
|
119
|
+
- **Chỉ bật khi payload có `logIngest`.** Backend gắn block này khi bật
|
|
120
|
+
`INVOCATION_LOGGING_PUSH_ENABLED`. Không có block thì runtime chạy y như bản cũ:
|
|
121
|
+
không pipe, không tiền tố, không gọi mạng. Vì vậy template khai báo
|
|
122
|
+
`quapp-common>=…` lỡ cài bản này ở môi trường chưa bật tính năng cũng không đổi
|
|
123
|
+
hành vi.
|
|
124
|
+
- **Tiến trình compute** (`run_compute`): fd 1 và 2 trỏ vào một pipe riêng của job
|
|
125
|
+
(một pipe nên giữ đúng thứ tự stdout/stderr). `sys.stdout` / `sys.stderr` được
|
|
126
|
+
dựng mới, vì object kế thừa có thể mang lock bị luồng của tiến trình cha giữ lúc
|
|
127
|
+
fork và làm treo lần ghi đầu. Sink loguru được dựng lại trên `sys.stderr` mới,
|
|
128
|
+
`colorize=False`. Khi job xong: đóng pool, flush, rồi `fflush(NULL)` để không mất
|
|
129
|
+
dòng `printf` của code native trước `os._exit`.
|
|
130
|
+
- **Tiến trình server** (`quapp_common/joblog/shipper.py`): một luồng đọc pipe, ghi
|
|
131
|
+
từng dòng ra log container với tiền tố `[ConsoleJobLog][<jobId>]` (trừ dòng đã có
|
|
132
|
+
tag của job hoặc dòng JSON loguru của job), và một luồng gửi chunk về backend:
|
|
133
|
+
cắt ở `\n`, tối đa 256KB, mỗi 2s; lỗi mạng / 5xx / 429 thì gửi lại cùng `seq`;
|
|
134
|
+
mọi 4xx khác và outcome `TRUNCATED` / `SEALED` / `TOO_LATE` thì dừng gửi, chỉ
|
|
135
|
+
còn log container. `close` khi có cả EOF lẫn exit code; tiến trình cháu giữ pipe
|
|
136
|
+
quá 5s thì `close` với `abandoned`. Server tắt (atexit): gửi nốt rồi `close`
|
|
137
|
+
`abandoned`.
|
|
138
|
+
- **Tiến trình lấy kết quả** (payload có `providerJobId`): giữ log lại; nếu không
|
|
139
|
+
gọi callback nào và thoát mã 0 thì đó chỉ là một lần poll, writer được `close`
|
|
140
|
+
`discarded` mà không `open`.
|
|
141
|
+
- **Callback** (`update_job_metadata`): mang `X-Quapp-Log-Writer` +
|
|
142
|
+
`X-Quapp-Log-Token` trong tiến trình có capture, và đếm số lần thử gọi.
|
|
143
|
+
- **Fd thừa**: tiến trình compute, heartbeat và SyncManager đóng pipe của job khác
|
|
144
|
+
(`quapp_common/joblog/pipes.py`, khoá + `os.register_at_fork`).
|
|
145
|
+
- `loguru>=0.5.3`: từ bản này `Handler.stop()` bỏ qua handler của tiến trình khác,
|
|
146
|
+
nên tiến trình con gọi `logger.remove()` an toàn.
|
|
147
|
+
|
|
148
|
+
Test: `tests/test_job_log_capture.py` (33 test, gồm fork thật với một ingest server
|
|
149
|
+
giả). Đã chạy trên Python 3.11 (126 test của các vùng liên quan pass) và với
|
|
150
|
+
`loguru==0.5.3`.
|
|
151
|
+
|
|
114
152
|
### v0.0.14.dev5 — Gỡ toàn bộ dependency SDK lượng tử
|
|
115
153
|
|
|
116
154
|
`quapp-common` không còn phụ thuộc SDK nào. SDK thuộc về lib con.
|
|
@@ -73,6 +73,44 @@ Notes:
|
|
|
73
73
|
|
|
74
74
|
## Recently Changes Highlights
|
|
75
75
|
|
|
76
|
+
### v0.0.17.dev1 — Log job trực tiếp về backend (PQF-23860)
|
|
77
|
+
|
|
78
|
+
Runtime đẩy log của từng job về backend trong lúc job chạy. Loki vẫn là đường dự
|
|
79
|
+
phòng.
|
|
80
|
+
|
|
81
|
+
- **Chỉ bật khi payload có `logIngest`.** Backend gắn block này khi bật
|
|
82
|
+
`INVOCATION_LOGGING_PUSH_ENABLED`. Không có block thì runtime chạy y như bản cũ:
|
|
83
|
+
không pipe, không tiền tố, không gọi mạng. Vì vậy template khai báo
|
|
84
|
+
`quapp-common>=…` lỡ cài bản này ở môi trường chưa bật tính năng cũng không đổi
|
|
85
|
+
hành vi.
|
|
86
|
+
- **Tiến trình compute** (`run_compute`): fd 1 và 2 trỏ vào một pipe riêng của job
|
|
87
|
+
(một pipe nên giữ đúng thứ tự stdout/stderr). `sys.stdout` / `sys.stderr` được
|
|
88
|
+
dựng mới, vì object kế thừa có thể mang lock bị luồng của tiến trình cha giữ lúc
|
|
89
|
+
fork và làm treo lần ghi đầu. Sink loguru được dựng lại trên `sys.stderr` mới,
|
|
90
|
+
`colorize=False`. Khi job xong: đóng pool, flush, rồi `fflush(NULL)` để không mất
|
|
91
|
+
dòng `printf` của code native trước `os._exit`.
|
|
92
|
+
- **Tiến trình server** (`quapp_common/joblog/shipper.py`): một luồng đọc pipe, ghi
|
|
93
|
+
từng dòng ra log container với tiền tố `[ConsoleJobLog][<jobId>]` (trừ dòng đã có
|
|
94
|
+
tag của job hoặc dòng JSON loguru của job), và một luồng gửi chunk về backend:
|
|
95
|
+
cắt ở `\n`, tối đa 256KB, mỗi 2s; lỗi mạng / 5xx / 429 thì gửi lại cùng `seq`;
|
|
96
|
+
mọi 4xx khác và outcome `TRUNCATED` / `SEALED` / `TOO_LATE` thì dừng gửi, chỉ
|
|
97
|
+
còn log container. `close` khi có cả EOF lẫn exit code; tiến trình cháu giữ pipe
|
|
98
|
+
quá 5s thì `close` với `abandoned`. Server tắt (atexit): gửi nốt rồi `close`
|
|
99
|
+
`abandoned`.
|
|
100
|
+
- **Tiến trình lấy kết quả** (payload có `providerJobId`): giữ log lại; nếu không
|
|
101
|
+
gọi callback nào và thoát mã 0 thì đó chỉ là một lần poll, writer được `close`
|
|
102
|
+
`discarded` mà không `open`.
|
|
103
|
+
- **Callback** (`update_job_metadata`): mang `X-Quapp-Log-Writer` +
|
|
104
|
+
`X-Quapp-Log-Token` trong tiến trình có capture, và đếm số lần thử gọi.
|
|
105
|
+
- **Fd thừa**: tiến trình compute, heartbeat và SyncManager đóng pipe của job khác
|
|
106
|
+
(`quapp_common/joblog/pipes.py`, khoá + `os.register_at_fork`).
|
|
107
|
+
- `loguru>=0.5.3`: từ bản này `Handler.stop()` bỏ qua handler của tiến trình khác,
|
|
108
|
+
nên tiến trình con gọi `logger.remove()` an toàn.
|
|
109
|
+
|
|
110
|
+
Test: `tests/test_job_log_capture.py` (33 test, gồm fork thật với một ingest server
|
|
111
|
+
giả). Đã chạy trên Python 3.11 (126 test của các vùng liên quan pass) và với
|
|
112
|
+
`loguru==0.5.3`.
|
|
113
|
+
|
|
76
114
|
### v0.0.14.dev5 — Gỡ toàn bộ dependency SDK lượng tử
|
|
77
115
|
|
|
78
116
|
`quapp-common` không còn phụ thuộc SDK nào. SDK thuộc về lib con.
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "quapp-common"
|
|
7
|
-
version = "0.0.
|
|
7
|
+
version = "0.0.17.dev1"
|
|
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" }]
|
|
@@ -24,7 +24,9 @@ keywords = ["quapp", "quapp-common", "quantum"]
|
|
|
24
24
|
# đột version thật (pytket/lark, pennylane-rigetti/pyquil), và bắt mọi function
|
|
25
25
|
# tải cả 6 SDK dù chỉ dùng một.
|
|
26
26
|
dependencies = [
|
|
27
|
-
|
|
27
|
+
# >=0.5.3: Handler.stop() skips handlers of another process, so a forked
|
|
28
|
+
# compute process can logger.remove() its inherited sinks (PQF-23860).
|
|
29
|
+
"loguru>=0.5.3",
|
|
28
30
|
"requests",
|
|
29
31
|
"numpy",
|
|
30
32
|
"matplotlib",
|
|
@@ -17,13 +17,18 @@ from ..component.backend.job_manager import JobManager
|
|
|
17
17
|
from ..config.log_context import bind_job
|
|
18
18
|
from ..config.logging_config import logger
|
|
19
19
|
from ..factory.handler_factory import HandlerFactory
|
|
20
|
+
from ..joblog import child as job_log_child
|
|
21
|
+
from ..joblog import pipes as job_log_pipes
|
|
22
|
+
from ..joblog.capture import JobLogCapture
|
|
20
23
|
from ..model.invocation import Event, Error, Success
|
|
21
24
|
from ..util.invocation_failure import report_invocation_failure
|
|
25
|
+
from ..util.process_utils import release_inherited_server_sockets
|
|
22
26
|
|
|
23
27
|
PR_SET_PDEATHSIG = 1
|
|
24
28
|
ORPHAN_EXIT_CODE = 3
|
|
25
29
|
PARENT_POLL_SEC = 5.0
|
|
26
30
|
COMPUTE_PROCESS_PREFIX = 'job-compute'
|
|
31
|
+
CLOSE_CONNECTION_HEADERS = {'Connection': 'close'}
|
|
27
32
|
|
|
28
33
|
|
|
29
34
|
def fork_context():
|
|
@@ -60,7 +65,18 @@ def _watch_parent(parent_pid: int) -> None:
|
|
|
60
65
|
time.sleep(PARENT_POLL_SEC)
|
|
61
66
|
|
|
62
67
|
|
|
63
|
-
def run_compute(parent_pid: int, target) -> None:
|
|
68
|
+
def run_compute(parent_pid: int, target, capture_setup=None) -> None:
|
|
69
|
+
"""Body of the compute process.
|
|
70
|
+
|
|
71
|
+
@param capture_setup: JobLogCapture.child_setup when the job's log is
|
|
72
|
+
captured (PQF-23860); it points fd 1/2 at the job's pipe before anything
|
|
73
|
+
else runs. None keeps the old behaviour.
|
|
74
|
+
"""
|
|
75
|
+
if capture_setup is not None:
|
|
76
|
+
capture_setup()
|
|
77
|
+
else:
|
|
78
|
+
job_log_pipes.release_inherited()
|
|
79
|
+
release_inherited_server_sockets()
|
|
64
80
|
signal.signal(signal.SIGTERM, signal.SIG_DFL)
|
|
65
81
|
|
|
66
82
|
if not set_parent_death_signal():
|
|
@@ -77,7 +93,15 @@ def run_compute(parent_pid: int, target) -> None:
|
|
|
77
93
|
name='compute-parent-watch', daemon=True)
|
|
78
94
|
watcher.start()
|
|
79
95
|
|
|
80
|
-
|
|
96
|
+
if capture_setup is None:
|
|
97
|
+
target()
|
|
98
|
+
return
|
|
99
|
+
try:
|
|
100
|
+
target()
|
|
101
|
+
finally:
|
|
102
|
+
# The process ends with os._exit: drain the pools, then flush Python's
|
|
103
|
+
# and libc's buffers so the last lines reach the pipe.
|
|
104
|
+
job_log_child.finish()
|
|
81
105
|
|
|
82
106
|
|
|
83
107
|
class AsyncInvocationTask(AsyncTask):
|
|
@@ -122,7 +146,8 @@ class AsyncInvocationTask(AsyncTask):
|
|
|
122
146
|
response is returned.
|
|
123
147
|
"""
|
|
124
148
|
try:
|
|
125
|
-
|
|
149
|
+
payload = self.event.json()
|
|
150
|
+
job_id = payload.get('jobId')
|
|
126
151
|
if job_id is None:
|
|
127
152
|
raise Exception("Job ID is missing from event")
|
|
128
153
|
|
|
@@ -141,14 +166,22 @@ class AsyncInvocationTask(AsyncTask):
|
|
|
141
166
|
JobManager.ensure_registry()
|
|
142
167
|
ensure_started()
|
|
143
168
|
|
|
169
|
+
# After the registry and heartbeat are up, so neither of those
|
|
170
|
+
# long-lived processes is forked while this job's pipe is open.
|
|
171
|
+
capture = JobLogCapture.prepare(job_id, payload, job_log)
|
|
172
|
+
|
|
144
173
|
loop = asyncio.get_running_loop()
|
|
145
174
|
process = fork_context().Process(
|
|
146
|
-
target=run_compute,
|
|
175
|
+
target=run_compute,
|
|
176
|
+
args=(os.getpid(), _run_handle,
|
|
177
|
+
capture.child_setup if capture else None),
|
|
147
178
|
name=f'{COMPUTE_PROCESS_PREFIX}-{job_id}', daemon=False)
|
|
148
179
|
|
|
149
180
|
try:
|
|
150
181
|
process.start()
|
|
151
182
|
except Exception as start_exception:
|
|
183
|
+
if capture is not None:
|
|
184
|
+
capture.failed_to_start()
|
|
152
185
|
job_log.bind(event='compute_process_start_failed').exception(
|
|
153
186
|
f'Could not start the compute process for job '
|
|
154
187
|
f'{job_id}: {start_exception}')
|
|
@@ -158,23 +191,32 @@ class AsyncInvocationTask(AsyncTask):
|
|
|
158
191
|
context={'jobId': job_id})
|
|
159
192
|
raise
|
|
160
193
|
|
|
161
|
-
|
|
194
|
+
if capture is not None:
|
|
195
|
+
capture.started()
|
|
196
|
+
|
|
197
|
+
self._watch_compute_process(loop, process, job_id, job_log,
|
|
198
|
+
capture)
|
|
162
199
|
|
|
163
200
|
# Respond immediately so clients can poll GET /jobs/{job_id}
|
|
164
201
|
return JSONResponse(status_code=200, content=Success(
|
|
165
|
-
JobManager.get_job(job_id)).serialize()
|
|
202
|
+
JobManager.get_job(job_id)).serialize(),
|
|
203
|
+
headers=CLOSE_CONNECTION_HEADERS)
|
|
166
204
|
except Exception as exception:
|
|
167
205
|
logger.exception(f"An error occurred: {exception}")
|
|
168
206
|
return JSONResponse(status_code=400,
|
|
169
|
-
content=Error(exception).serialize()
|
|
207
|
+
content=Error(exception).serialize(),
|
|
208
|
+
headers=CLOSE_CONNECTION_HEADERS)
|
|
170
209
|
|
|
171
|
-
def _watch_compute_process(self, loop, process, job_id, job_log
|
|
210
|
+
def _watch_compute_process(self, loop, process, job_id, job_log,
|
|
211
|
+
capture=None) -> None:
|
|
172
212
|
sentinel = process.sentinel
|
|
173
213
|
|
|
174
214
|
def _on_process_exit():
|
|
175
215
|
loop.remove_reader(sentinel)
|
|
176
216
|
process.join()
|
|
177
217
|
exit_code = process.exitcode
|
|
218
|
+
if capture is not None:
|
|
219
|
+
capture.process_exited(exit_code)
|
|
178
220
|
if exit_code == 0:
|
|
179
221
|
return
|
|
180
222
|
self._report_compute_failure(loop, job_id, job_log, exit_code)
|
|
@@ -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_fds
|
|
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_fds()
|
|
89
91
|
while os.getppid() == parent_pid:
|
|
90
92
|
try:
|
|
91
93
|
beat_once()
|
{quapp_common-0.0.16.dev1 → quapp_common-0.0.17.dev1}/quapp_common/component/backend/job_manager.py
RENAMED
|
@@ -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
|
|
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_fds
|
|
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[
|
|
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 =
|
|
58
|
+
mgr = SyncManager()
|
|
59
|
+
mgr.start(initializer=release_inherited_fds)
|
|
57
60
|
cls._manager = mgr
|
|
58
61
|
cls._jobs = mgr.dict() # type: ignore[assignment]
|
|
59
62
|
cls._updates_queue = mgr.Queue() # type: ignore[assignment]
|
|
@@ -10,6 +10,8 @@ import requests
|
|
|
10
10
|
from ..backend.job_manager import JobManager
|
|
11
11
|
from ...config.log_context import phase
|
|
12
12
|
from ...config.logging_config import job_logger
|
|
13
|
+
from ...joblog import child as job_log_child
|
|
14
|
+
from ...joblog.ingest import TOKEN_HEADER, WRITER_HEADER
|
|
13
15
|
from ...data.response.job_response import JobResponse
|
|
14
16
|
from ...enum.runtime_phase import RuntimePhase
|
|
15
17
|
from ...util.http_utils import create_application_json_header, \
|
|
@@ -63,6 +65,17 @@ def _json_payload(payload: dict, logger) -> str:
|
|
|
63
65
|
return json.dumps(_sanitize(payload), allow_nan=False, default=str)
|
|
64
66
|
|
|
65
67
|
|
|
68
|
+
def _with_log_writer(headers: dict) -> dict:
|
|
69
|
+
"""Name the job log writer on the event PATCH (PQF-23860), so the backend
|
|
70
|
+
knows a writer whose open never got through. Only in a captured compute
|
|
71
|
+
process, i.e. only when the payload carried ``logIngest``."""
|
|
72
|
+
writer = job_log_child.current_writer()
|
|
73
|
+
if writer is None:
|
|
74
|
+
return headers
|
|
75
|
+
return {**headers, WRITER_HEADER: writer.writer_id,
|
|
76
|
+
TOKEN_HEADER: writer.token}
|
|
77
|
+
|
|
78
|
+
|
|
66
79
|
def update_job_metadata(job_response: JobResponse, callback_url: str):
|
|
67
80
|
# Helpers to improve readability and remove duplication
|
|
68
81
|
def _log_http_result(tag: str, resp):
|
|
@@ -111,6 +124,10 @@ def update_job_metadata(job_response: JobResponse, callback_url: str):
|
|
|
111
124
|
json=scheduler_payload)
|
|
112
125
|
_log_http_result('scheduler', scheduler_response)
|
|
113
126
|
|
|
127
|
+
# Counted before anything can fail: a fetch process that tried to report
|
|
128
|
+
# something about the job keeps its log (see joblog.shipper).
|
|
129
|
+
job_log_child.count_callback()
|
|
130
|
+
|
|
114
131
|
job_id = get_job_id_from_url(callback_url)
|
|
115
132
|
logger = job_logger(job_id)
|
|
116
133
|
logger.info(
|
|
@@ -129,10 +146,10 @@ def update_job_metadata(job_response: JobResponse, callback_url: str):
|
|
|
129
146
|
# for exactly this and had no place that opened it.
|
|
130
147
|
with phase(RuntimePhase.CALLBACK):
|
|
131
148
|
try:
|
|
132
|
-
request_headers = create_application_json_header(
|
|
149
|
+
request_headers = _with_log_writer(create_application_json_header(
|
|
133
150
|
token=job_response.user_token,
|
|
134
151
|
project_header=job_response.project_header,
|
|
135
|
-
workspace_header=job_response.workspace_header)
|
|
152
|
+
workspace_header=job_response.workspace_header))
|
|
136
153
|
|
|
137
154
|
# data= rather than json=: the body goes through _json_payload so no
|
|
138
155
|
# provider object can kill this callback. Content-Type is already
|
|
@@ -316,6 +316,33 @@ def configure_logging(force: bool = False) -> None:
|
|
|
316
316
|
_CONFIGURED = True
|
|
317
317
|
|
|
318
318
|
|
|
319
|
+
def configure_child_logging() -> None:
|
|
320
|
+
"""Re-create the sinks in a captured compute process (PQF-23860).
|
|
321
|
+
|
|
322
|
+
The inherited sinks write through the parent's ``sys.stderr`` object and
|
|
323
|
+
``enqueue=True`` queue; the child replaced ``sys.stderr`` with a fresh object
|
|
324
|
+
on its log pipe, so the sinks are rebuilt on that one. ``remove()`` is safe
|
|
325
|
+
after fork: loguru only stops handlers its own process started.
|
|
326
|
+
|
|
327
|
+
``colorize=False``: the parent recognises this job's lines by their
|
|
328
|
+
``[ConsoleJobLog][<jobId>]`` start, which ANSI codes would hide.
|
|
329
|
+
"""
|
|
330
|
+
global _CONFIGURED
|
|
331
|
+
|
|
332
|
+
logger.remove()
|
|
333
|
+
|
|
334
|
+
if LOG_FORMAT in ('text', 'both'):
|
|
335
|
+
logger.add(sink=sys.stderr, format=__custom_format, level=LOG_LEVEL,
|
|
336
|
+
colorize=False, filter=_prepare_record, enqueue=False,
|
|
337
|
+
backtrace=True, diagnose=False)
|
|
338
|
+
|
|
339
|
+
if LOG_FORMAT in ('json', 'both'):
|
|
340
|
+
logger.add(sink=_json_sink, level=LOG_LEVEL, filter=_prepare_record,
|
|
341
|
+
enqueue=False, backtrace=False, diagnose=False)
|
|
342
|
+
|
|
343
|
+
_CONFIGURED = True
|
|
344
|
+
|
|
345
|
+
|
|
319
346
|
def job_logger(job_id: str = None):
|
|
320
347
|
"""Logger for one job. The old signature is kept so the 12 provider libs and
|
|
321
348
|
the templates need no import changes.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# Quapp Platform Project
|
|
2
|
+
# capture.py
|
|
3
|
+
# Copyright © CITYNOW Co. Ltd. All rights reserved.
|
|
4
|
+
|
|
5
|
+
"""Live job log capture for one compute process (PQF-23860, H7).
|
|
6
|
+
|
|
7
|
+
``AsyncInvocationTask`` uses it around the fork::
|
|
8
|
+
|
|
9
|
+
capture = JobLogCapture.prepare(job_id, payload) # None: old behaviour
|
|
10
|
+
process = Process(target=run_compute,
|
|
11
|
+
args=(..., capture.child_setup if capture else None))
|
|
12
|
+
process.start() # on failure: capture.failed_to_start()
|
|
13
|
+
capture.started() # parent closes its write end, threads start
|
|
14
|
+
...
|
|
15
|
+
capture.process_exited(exit_code)
|
|
16
|
+
|
|
17
|
+
Only a payload with a usable ``logIngest`` block is captured. Without one the
|
|
18
|
+
runtime behaves exactly as before: no pipe, no prefixing, no network. That keeps
|
|
19
|
+
a newer quapp-common harmless where the backend does not send ``logIngest``.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import atexit
|
|
23
|
+
import multiprocessing
|
|
24
|
+
import threading
|
|
25
|
+
import time
|
|
26
|
+
import uuid
|
|
27
|
+
from typing import Optional
|
|
28
|
+
|
|
29
|
+
from . import child, pipes
|
|
30
|
+
from .ingest import IngestClient, LogIngest
|
|
31
|
+
from .shipper import JobLogShipper
|
|
32
|
+
|
|
33
|
+
PROVIDER_JOB_ID = 'providerJobId'
|
|
34
|
+
SHUTDOWN_GRACE_SEC = 8.0
|
|
35
|
+
|
|
36
|
+
_active = set()
|
|
37
|
+
_active_lock = threading.Lock()
|
|
38
|
+
_atexit_registered = False
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class JobLogCapture:
|
|
42
|
+
|
|
43
|
+
def __init__(self, job_id: str, ingest: LogIngest, fetch: bool,
|
|
44
|
+
logger=None):
|
|
45
|
+
self.job_id = job_id
|
|
46
|
+
self.writer_id = str(uuid.uuid4())
|
|
47
|
+
self.fetch = fetch
|
|
48
|
+
self._ingest = ingest
|
|
49
|
+
self._logger = logger
|
|
50
|
+
self._callbacks = multiprocessing.get_context('fork').RawValue('i', 0)
|
|
51
|
+
self._read_fd, self._write_fd = pipes.open_pipe(self.writer_id)
|
|
52
|
+
self._shipper: Optional[JobLogShipper] = None
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def prepare(job_id: str, payload, logger=None) -> Optional['JobLogCapture']:
|
|
56
|
+
ingest = LogIngest.from_payload(payload)
|
|
57
|
+
if ingest is None or not job_id:
|
|
58
|
+
return None
|
|
59
|
+
fetch = isinstance(payload, dict) and payload.get(
|
|
60
|
+
PROVIDER_JOB_ID) is not None
|
|
61
|
+
try:
|
|
62
|
+
return JobLogCapture(job_id, ingest, fetch, logger)
|
|
63
|
+
except Exception as exception:
|
|
64
|
+
if logger is not None:
|
|
65
|
+
logger.warning(f'Live job log is off for job {job_id}: could '
|
|
66
|
+
f'not set up the pipe ({exception})')
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
def child_setup(self) -> None:
|
|
70
|
+
"""Runs in the compute process, before the handler is built."""
|
|
71
|
+
child.attach(self._write_fd, self.writer_id, self._ingest.token,
|
|
72
|
+
self._callbacks)
|
|
73
|
+
|
|
74
|
+
def started(self) -> None:
|
|
75
|
+
"""Runs in the server after the fork succeeded."""
|
|
76
|
+
pipes.close_fd(self._write_fd)
|
|
77
|
+
self._shipper = JobLogShipper(self.job_id, self.writer_id,
|
|
78
|
+
IngestClient(self._ingest,
|
|
79
|
+
self.writer_id),
|
|
80
|
+
self._read_fd, fetch=self.fetch,
|
|
81
|
+
callbacks=self._callbacks,
|
|
82
|
+
logger=self._logger, on_done=_untrack)
|
|
83
|
+
_track(self._shipper)
|
|
84
|
+
self._shipper.start()
|
|
85
|
+
|
|
86
|
+
def failed_to_start(self) -> None:
|
|
87
|
+
pipes.close_fd(self._write_fd)
|
|
88
|
+
pipes.close_fd(self._read_fd)
|
|
89
|
+
|
|
90
|
+
def process_exited(self, exit_code: Optional[int]) -> None:
|
|
91
|
+
if self._shipper is not None:
|
|
92
|
+
self._shipper.process_exited(exit_code)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _track(shipper: JobLogShipper) -> None:
|
|
96
|
+
global _atexit_registered
|
|
97
|
+
with _active_lock:
|
|
98
|
+
_active.add(shipper)
|
|
99
|
+
if not _atexit_registered:
|
|
100
|
+
atexit.register(_shutdown_all)
|
|
101
|
+
_atexit_registered = True
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _untrack(shipper: JobLogShipper) -> None:
|
|
105
|
+
with _active_lock:
|
|
106
|
+
_active.discard(shipper)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _shutdown_all() -> None:
|
|
110
|
+
"""The server is exiting (pod deleted): every live writer sends what it has
|
|
111
|
+
and closes as abandoned, within the pod's grace period."""
|
|
112
|
+
with _active_lock:
|
|
113
|
+
shippers = list(_active)
|
|
114
|
+
for shipper in shippers:
|
|
115
|
+
shipper.request_shutdown()
|
|
116
|
+
deadline = time.monotonic() + SHUTDOWN_GRACE_SEC
|
|
117
|
+
for shipper in shippers:
|
|
118
|
+
shipper.join_sender(max(deadline - time.monotonic(), 0.0))
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Quapp Platform Project
|
|
2
|
+
# child.py
|
|
3
|
+
# Copyright © CITYNOW Co. Ltd. All rights reserved.
|
|
4
|
+
|
|
5
|
+
"""What a captured compute process does with its own output (PQF-23860).
|
|
6
|
+
|
|
7
|
+
``attach`` runs first thing in the child, before the handler is built:
|
|
8
|
+
|
|
9
|
+
1. close the log pipe fds of other jobs (and this job's read end);
|
|
10
|
+
2. point fd 1 and fd 2 at this job's pipe. One pipe for both keeps the order
|
|
11
|
+
between stdout and stderr and gives a single EOF;
|
|
12
|
+
3. build NEW ``sys.stdout`` / ``sys.stderr`` objects on fd 1 / 2. The inherited
|
|
13
|
+
ones may carry a ``BufferedWriter`` lock that a parent thread held at fork
|
|
14
|
+
time; writing through them can hang the child forever, ``reconfigure()``
|
|
15
|
+
included. The old objects are kept referenced so GC never flushes or closes
|
|
16
|
+
them;
|
|
17
|
+
4. replace the inherited loguru sinks by sinks on the new ``sys.stderr``;
|
|
18
|
+
5. remember the writer, so job callbacks carry its headers and are counted.
|
|
19
|
+
|
|
20
|
+
``finish`` runs when the handler returns or raises: drain the thread pools that
|
|
21
|
+
still run analysis / finalization, flush Python's streams, then libc's buffers
|
|
22
|
+
(native ``printf``), because multiprocessing ends the child with ``os._exit``.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
import ctypes
|
|
26
|
+
import os
|
|
27
|
+
import sys
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from typing import Optional
|
|
30
|
+
|
|
31
|
+
from . import pipes
|
|
32
|
+
|
|
33
|
+
ENCODING = 'utf-8'
|
|
34
|
+
ENCODING_ERRORS = 'backslashreplace'
|
|
35
|
+
LINE_BUFFERED = 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class WriterContext:
|
|
40
|
+
writer_id: str
|
|
41
|
+
token: str
|
|
42
|
+
callbacks: object # a fork-shared ctypes int, or None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
_writer: Optional[WriterContext] = None
|
|
46
|
+
_inherited_streams = []
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def current_writer() -> Optional[WriterContext]:
|
|
50
|
+
"""The writer of this compute process, or None outside a captured child."""
|
|
51
|
+
return _writer
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def count_callback() -> None:
|
|
55
|
+
"""Record that this process tried to report something about the job.
|
|
56
|
+
|
|
57
|
+
Called before the request is even built, so a callback that fails still
|
|
58
|
+
counts: a fetch process that reached execution done / analysis / an error
|
|
59
|
+
has job content in its log and must not be discarded.
|
|
60
|
+
"""
|
|
61
|
+
if _writer is None or _writer.callbacks is None:
|
|
62
|
+
return
|
|
63
|
+
try:
|
|
64
|
+
_writer.callbacks.value += 1
|
|
65
|
+
except Exception:
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def attach(write_fd: int, writer_id: str, token: str, callbacks) -> None:
|
|
70
|
+
global _writer
|
|
71
|
+
pipes.release_inherited(keep=(write_fd,))
|
|
72
|
+
for target in (1, 2):
|
|
73
|
+
os.dup2(write_fd, target)
|
|
74
|
+
if write_fd not in (1, 2):
|
|
75
|
+
os.close(write_fd)
|
|
76
|
+
|
|
77
|
+
_inherited_streams.extend((sys.stdout, sys.stderr))
|
|
78
|
+
sys.stdout = open(1, 'w', buffering=LINE_BUFFERED, closefd=False,
|
|
79
|
+
encoding=ENCODING, errors=ENCODING_ERRORS)
|
|
80
|
+
sys.stderr = open(2, 'w', buffering=LINE_BUFFERED, closefd=False,
|
|
81
|
+
encoding=ENCODING, errors=ENCODING_ERRORS)
|
|
82
|
+
|
|
83
|
+
from ..config.logging_config import configure_child_logging
|
|
84
|
+
configure_child_logging()
|
|
85
|
+
|
|
86
|
+
_writer = WriterContext(writer_id, token, callbacks)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def finish() -> None:
|
|
90
|
+
from ..config.thread_config import circuit_exporting_pool, \
|
|
91
|
+
circuit_running_pool
|
|
92
|
+
for pool in (circuit_running_pool, circuit_exporting_pool):
|
|
93
|
+
try:
|
|
94
|
+
pool.shutdown(wait=True)
|
|
95
|
+
except Exception:
|
|
96
|
+
pass
|
|
97
|
+
for stream in (sys.stdout, sys.stderr):
|
|
98
|
+
try:
|
|
99
|
+
stream.flush()
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
flush_libc()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def flush_libc() -> None:
|
|
106
|
+
try:
|
|
107
|
+
ctypes.CDLL(None).fflush(None)
|
|
108
|
+
except Exception:
|
|
109
|
+
pass
|