parallelazy 0.0.7__tar.gz → 0.1.1__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.
- {parallelazy-0.0.7 → parallelazy-0.1.1}/PKG-INFO +1 -1
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/plugin.py +79 -10
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/plugin_data.py +17 -0
- parallelazy-0.1.1/parallelazy/plugin_logging.py +439 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/plugin_manager.py +283 -50
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/plugin_rpc.py +82 -18
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/plugin_transport.py +19 -1
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/plugin_worker.py +286 -120
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/utils.py +5 -2
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy.egg-info/PKG-INFO +1 -1
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy.egg-info/SOURCES.txt +5 -1
- {parallelazy-0.0.7 → parallelazy-0.1.1}/pyproject.toml +1 -1
- parallelazy-0.1.1/tests/test_env_cuda_ipc.py +41 -0
- parallelazy-0.1.1/tests/test_plugin_lifecycle.py +288 -0
- parallelazy-0.1.1/tests/test_plugin_logging.py +323 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/LICENSE +0 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/README.md +0 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/__init__.py +0 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy/environment_manager.py +0 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy.egg-info/dependency_links.txt +0 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy.egg-info/requires.txt +0 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/parallelazy.egg-info/top_level.txt +0 -0
- {parallelazy-0.0.7 → parallelazy-0.1.1}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: parallelazy
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.1.1
|
|
4
4
|
Summary: A lightweight multiprocess worker-plugin framework. Topic-based pub/sub, global enviroment, using process spawn and pipes, pytorch and CUDA ready.
|
|
5
5
|
Author: Cesare Montresor
|
|
6
6
|
Project-URL: Homepage, https://github.com/cesare-montresor/parallelazy
|
|
@@ -5,7 +5,8 @@ Defines the lifecycle, subscription, and service interfaces that all
|
|
|
5
5
|
plugins must implement or can override.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
import logging
|
|
9
|
+
from typing import Any, Callable, Dict, Optional, TYPE_CHECKING, Self
|
|
9
10
|
from enum import Enum
|
|
10
11
|
|
|
11
12
|
from parallelazy.utils import camel_to_kebab
|
|
@@ -59,6 +60,10 @@ class PluginDescriptor:
|
|
|
59
60
|
author: str = ""
|
|
60
61
|
options: Dict[str, Any] = field(default_factory=dict)
|
|
61
62
|
dependencies: list = field(default_factory=list)
|
|
63
|
+
work_dir: Optional[str] = None
|
|
64
|
+
log_dir: Optional[str] = None
|
|
65
|
+
log_level: Optional[int] = None
|
|
66
|
+
display_logs: Optional[bool] = None
|
|
62
67
|
|
|
63
68
|
def to_dict(self) -> Dict[str, Any]:
|
|
64
69
|
"""Convert descriptor to dictionary (JSON-serializable)."""
|
|
@@ -98,7 +103,7 @@ class Plugin:
|
|
|
98
103
|
Subclasses must implement:
|
|
99
104
|
- on_start: Initialize plugin resources (optional)
|
|
100
105
|
- on_stop: Clean up resources (optional)
|
|
101
|
-
- main: Main
|
|
106
|
+
- main: Main-thread work hook, called once after on_start (optional)
|
|
102
107
|
- on_error: Handle errors (optional)
|
|
103
108
|
|
|
104
109
|
|
|
@@ -127,7 +132,18 @@ class Plugin:
|
|
|
127
132
|
return {}
|
|
128
133
|
|
|
129
134
|
@classmethod
|
|
130
|
-
def Descriptor(
|
|
135
|
+
def Descriptor(
|
|
136
|
+
cls,
|
|
137
|
+
version: str,
|
|
138
|
+
author: str,
|
|
139
|
+
description: str = None,
|
|
140
|
+
name: str = None,
|
|
141
|
+
options: Dict[str, Any] = None,
|
|
142
|
+
work_dir: Optional[str] = None,
|
|
143
|
+
log_dir: Optional[str] = None,
|
|
144
|
+
log_level: Optional[int] = None,
|
|
145
|
+
display_logs: Optional[bool] = None,
|
|
146
|
+
) -> PluginDescriptor:
|
|
131
147
|
all_options = cls.default_options().copy()
|
|
132
148
|
all_options.update(options or {})
|
|
133
149
|
|
|
@@ -140,6 +156,10 @@ class Plugin:
|
|
|
140
156
|
package=f"{cls.__module__}",
|
|
141
157
|
class_name=cls.__name__,
|
|
142
158
|
description=description or f"{cls.__doc__}",
|
|
159
|
+
work_dir=work_dir,
|
|
160
|
+
log_dir=log_dir,
|
|
161
|
+
log_level=log_level,
|
|
162
|
+
display_logs=display_logs,
|
|
143
163
|
|
|
144
164
|
)
|
|
145
165
|
|
|
@@ -160,9 +180,30 @@ class Plugin:
|
|
|
160
180
|
self.state = PluginState.INITIALIZED
|
|
161
181
|
self.options = all_options
|
|
162
182
|
self._is_running = False
|
|
183
|
+
self._work_dir = worker.work_dir
|
|
184
|
+
self.logger = logging.getLogger(self.__class__.__module__)
|
|
185
|
+
|
|
186
|
+
@property
|
|
187
|
+
def work_dir(self) -> str:
|
|
188
|
+
"""Absolute working directory resolved for this plugin instance."""
|
|
189
|
+
return self._work_dir
|
|
190
|
+
|
|
191
|
+
def set_log_formats(
|
|
192
|
+
self,
|
|
193
|
+
file_format: Optional[str] = None,
|
|
194
|
+
console_format: Optional[str] = None,
|
|
195
|
+
) -> None:
|
|
196
|
+
"""Change this worker's file and/or console log format."""
|
|
197
|
+
self._worker.set_log_formats(file_format, console_format)
|
|
163
198
|
|
|
164
199
|
|
|
165
|
-
def main(self):
|
|
200
|
+
def main(self) -> None:
|
|
201
|
+
"""Run once on the worker's main thread after startup."""
|
|
202
|
+
pass
|
|
203
|
+
|
|
204
|
+
def wait_for_stop(self, timeout: Optional[float] = None) -> bool:
|
|
205
|
+
"""Wait for a stop request, typically from a blocking main() method."""
|
|
206
|
+
return self._worker.wait_for_stop(timeout)
|
|
166
207
|
|
|
167
208
|
def on_start(self) -> None:
|
|
168
209
|
"""
|
|
@@ -191,11 +232,10 @@ class Plugin:
|
|
|
191
232
|
return self._is_running
|
|
192
233
|
|
|
193
234
|
def stop(self) -> None:
|
|
194
|
-
"""
|
|
195
|
-
|
|
235
|
+
"""Request plugin shutdown; use wait_for_stop() in blocking main() work."""
|
|
196
236
|
self._worker.stop()
|
|
197
237
|
|
|
198
|
-
def topic_subscribe(self, topic:str, callback:
|
|
238
|
+
def topic_subscribe(self, topic:str, callback:Callable) -> None:
|
|
199
239
|
"""Subscribe to a data topic or environment variable."""
|
|
200
240
|
self._worker.topic_subscribe(topic, callback)
|
|
201
241
|
|
|
@@ -212,12 +252,41 @@ class Plugin:
|
|
|
212
252
|
if name is None:
|
|
213
253
|
return self._worker.env_get_all()
|
|
214
254
|
|
|
215
|
-
|
|
255
|
+
value = self._worker.env_get(name)
|
|
256
|
+
return default if value is None else value
|
|
216
257
|
|
|
217
|
-
def env_subscribe(self, name:str, callback:
|
|
258
|
+
def env_subscribe(self, name:str, callback:Callable) -> None:
|
|
218
259
|
"""Subscribe to changes in an environment variable."""
|
|
219
260
|
self._worker.env_subscribe(name, callback)
|
|
220
261
|
|
|
221
262
|
def plugin_call(self, plugin_id: str, method_name: str, *args, **kwargs) -> Any:
|
|
222
263
|
"""Call a method provided by the manager or another plugin."""
|
|
223
|
-
return self._worker.plugin_call(plugin_id, method_name, *args, **kwargs)
|
|
264
|
+
return self._worker.plugin_call(plugin_id, method_name, *args, **kwargs)
|
|
265
|
+
|
|
266
|
+
def plugin_load(
|
|
267
|
+
self,
|
|
268
|
+
descriptor: PluginDescriptor,
|
|
269
|
+
options: Optional[Dict[str, Any]] = None
|
|
270
|
+
) -> bool:
|
|
271
|
+
"""Load a plugin instance from its descriptor."""
|
|
272
|
+
return self._worker.plugin_load(descriptor, options)
|
|
273
|
+
|
|
274
|
+
def plugin_start(self, plugin_id: str) -> bool:
|
|
275
|
+
"""Start another loaded plugin."""
|
|
276
|
+
return self._worker.plugin_start(plugin_id)
|
|
277
|
+
|
|
278
|
+
def plugin_stop(self, plugin_id: str) -> bool:
|
|
279
|
+
"""Stop another loaded plugin."""
|
|
280
|
+
return self._worker.plugin_stop(plugin_id)
|
|
281
|
+
|
|
282
|
+
def plugin_unload(self, plugin_id: str) -> bool:
|
|
283
|
+
"""Unload another plugin."""
|
|
284
|
+
return self._worker.plugin_unload(plugin_id)
|
|
285
|
+
|
|
286
|
+
def plugin_status(self, plugin_id: str = None) -> Any:
|
|
287
|
+
"""Get the status of this plugin or another loaded plugin."""
|
|
288
|
+
return self._worker.plugin_status(plugin_id)
|
|
289
|
+
|
|
290
|
+
def plugin_status_all(self) -> Dict[str, Any]:
|
|
291
|
+
"""Get the status of all loaded plugins."""
|
|
292
|
+
return self._worker.plugin_status_all()
|
|
@@ -173,8 +173,10 @@ class Channel:
|
|
|
173
173
|
|
|
174
174
|
class CommandType:
|
|
175
175
|
"""Standard commands for plugin control."""
|
|
176
|
+
PLUGIN_LOAD = "plugin_load"
|
|
176
177
|
PLUGIN_START = "plugin_start"
|
|
177
178
|
PLUGIN_STOP = "plugin_stop"
|
|
179
|
+
PLUGIN_UNLOAD = "plugin_unload"
|
|
178
180
|
PLUGIN_STATUS = "plugin_status"
|
|
179
181
|
PLUGIN_STATUS_ALL = "plugin_status_all"
|
|
180
182
|
PLUGIN_ERRORS = "plugin_errors"
|
|
@@ -195,8 +197,10 @@ class CommandType:
|
|
|
195
197
|
@classmethod
|
|
196
198
|
def commands(cls):
|
|
197
199
|
return iter([
|
|
200
|
+
cls.PLUGIN_LOAD,
|
|
198
201
|
cls.PLUGIN_START,
|
|
199
202
|
cls.PLUGIN_STOP,
|
|
203
|
+
cls.PLUGIN_UNLOAD,
|
|
200
204
|
cls.PLUGIN_STATUS,
|
|
201
205
|
cls.PLUGIN_STATUS_ALL,
|
|
202
206
|
cls.PLUGIN_ERRORS,
|
|
@@ -350,8 +354,10 @@ class ProcessStatus:
|
|
|
350
354
|
|
|
351
355
|
"""
|
|
352
356
|
Classes for each request command:
|
|
357
|
+
PLUGIN_LOAD = "plugin_load"
|
|
353
358
|
PLUGIN_START = "plugin_start"
|
|
354
359
|
PLUGIN_STOP = "plugin_stop"
|
|
360
|
+
PLUGIN_UNLOAD = "plugin_unload"
|
|
355
361
|
PLUGIN_STATUS = "plugin_status"
|
|
356
362
|
PLUGIN_STATUS_ALL = "plugin_status_all"
|
|
357
363
|
PLUGIN_ERRORS = "plugin_errors"
|
|
@@ -375,6 +381,12 @@ Classes for each request command:
|
|
|
375
381
|
|
|
376
382
|
### Plugin Lifecycle Requests
|
|
377
383
|
|
|
384
|
+
@dataclass
|
|
385
|
+
class RequestPluginLoad(Request):
|
|
386
|
+
command: CommandType = field(default=CommandType.PLUGIN_LOAD, init=False)
|
|
387
|
+
descriptor: Any = None
|
|
388
|
+
options: Optional[dict] = None
|
|
389
|
+
|
|
378
390
|
@dataclass
|
|
379
391
|
class RequestPluginStart(Request):
|
|
380
392
|
command: CommandType = field(default=CommandType.PLUGIN_START, init=False)
|
|
@@ -385,6 +397,11 @@ class RequestPluginStop(Request):
|
|
|
385
397
|
command: CommandType = field(default=CommandType.PLUGIN_STOP, init=False)
|
|
386
398
|
plugin_id: Optional[str] = None
|
|
387
399
|
|
|
400
|
+
@dataclass
|
|
401
|
+
class RequestPluginUnload(Request):
|
|
402
|
+
command: CommandType = field(default=CommandType.PLUGIN_UNLOAD, init=False)
|
|
403
|
+
plugin_id: Optional[str] = None
|
|
404
|
+
|
|
388
405
|
@dataclass
|
|
389
406
|
class RequestPluginStatus(Request):
|
|
390
407
|
command: CommandType = field(default=CommandType.PLUGIN_STATUS, init=False)
|
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Logging setup shared by the manager and isolated plugin workers."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
import hashlib
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from typing import List, Optional, TextIO
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
DEFAULT_FILE_LOG_FORMAT = "[%(elapsed)s] %(levelname)s %(message)s"
|
|
16
|
+
DEFAULT_CONSOLE_LOG_FORMAT = (
|
|
17
|
+
"%(asctime)s.%(msecs)03dZ %(levelname)s [%(plugin_id)s] %(message)s"
|
|
18
|
+
)
|
|
19
|
+
CONSOLE_DATE_FORMAT = "%H:%M:%S"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class PluginRuntimeSettings:
|
|
24
|
+
work_dir: str
|
|
25
|
+
log_dir: str
|
|
26
|
+
log_level: int
|
|
27
|
+
display_logs: bool
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve_directory(path: str, base_dir: Optional[str] = None) -> str:
|
|
31
|
+
"""Return an absolute directory path, resolving relative paths against base_dir."""
|
|
32
|
+
expanded_path = os.path.expanduser(os.fspath(path))
|
|
33
|
+
if not os.path.isabs(expanded_path):
|
|
34
|
+
expanded_path = os.path.join(base_dir or os.getcwd(), expanded_path)
|
|
35
|
+
return os.path.abspath(expanded_path)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def create_run_id() -> str:
|
|
39
|
+
timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
40
|
+
return f"{timestamp}_{os.urandom(6).hex()}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def plugin_log_filename(plugin_id: str) -> str:
|
|
44
|
+
readable_id = "".join(
|
|
45
|
+
character if character.isascii() and (character.isalnum() or character in "-_.") else "_"
|
|
46
|
+
for character in plugin_id
|
|
47
|
+
).strip("._-") or "plugin"
|
|
48
|
+
suffix = hashlib.sha256(plugin_id.encode("utf-8")).hexdigest()[:12]
|
|
49
|
+
return f"{readable_id}-{suffix}.log"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def default_runtime_settings() -> PluginRuntimeSettings:
|
|
53
|
+
work_dir = resolve_directory(os.getcwd())
|
|
54
|
+
log_dir = os.path.join(resolve_directory("logs", work_dir), create_run_id())
|
|
55
|
+
os.makedirs(log_dir, exist_ok=True)
|
|
56
|
+
return PluginRuntimeSettings(
|
|
57
|
+
work_dir=work_dir,
|
|
58
|
+
log_dir=log_dir,
|
|
59
|
+
log_level=logging.INFO,
|
|
60
|
+
display_logs=True,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _CapturedStreamConsoleFilter(logging.Filter):
|
|
65
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
66
|
+
return not getattr(record, "_parallelazy_captured_stream", False)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class _TeeTextStream:
|
|
70
|
+
"""Mirror worker stream writes to the original stream and its log file."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, stream: TextIO, logger: logging.Logger, label: str):
|
|
73
|
+
self._stream = stream
|
|
74
|
+
self._logger = logger
|
|
75
|
+
self._label = label
|
|
76
|
+
self._buffer = ""
|
|
77
|
+
self._lock = threading.RLock()
|
|
78
|
+
self._logging = threading.local()
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def encoding(self):
|
|
82
|
+
return self._stream.encoding
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def errors(self):
|
|
86
|
+
return self._stream.errors
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def buffer(self):
|
|
90
|
+
return self._stream.buffer
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def name(self):
|
|
94
|
+
return self._stream.name
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def closed(self):
|
|
98
|
+
return self._stream.closed
|
|
99
|
+
|
|
100
|
+
def isatty(self) -> bool:
|
|
101
|
+
return self._stream.isatty()
|
|
102
|
+
|
|
103
|
+
def fileno(self) -> int:
|
|
104
|
+
return self._stream.fileno()
|
|
105
|
+
|
|
106
|
+
def writable(self) -> bool:
|
|
107
|
+
return self._stream.writable()
|
|
108
|
+
|
|
109
|
+
def write(self, text: str) -> int:
|
|
110
|
+
if not isinstance(text, str):
|
|
111
|
+
raise TypeError("write() argument must be str")
|
|
112
|
+
with self._lock:
|
|
113
|
+
written = self._stream.write(text)
|
|
114
|
+
if "\r" in text or "\n" in text:
|
|
115
|
+
self._stream.flush()
|
|
116
|
+
if not getattr(self._logging, "active", False):
|
|
117
|
+
self._capture_complete_lines(text)
|
|
118
|
+
return written
|
|
119
|
+
|
|
120
|
+
def _capture_complete_lines(self, text: str) -> None:
|
|
121
|
+
for index, character in enumerate(text):
|
|
122
|
+
if character in ("\r", "\n"):
|
|
123
|
+
if character == "\n" and index > 0 and text[index - 1] == "\r":
|
|
124
|
+
continue
|
|
125
|
+
self._emit_buffer()
|
|
126
|
+
else:
|
|
127
|
+
self._buffer += character
|
|
128
|
+
|
|
129
|
+
def _emit_buffer(self) -> None:
|
|
130
|
+
line = self._buffer
|
|
131
|
+
self._buffer = ""
|
|
132
|
+
self._log_line(line)
|
|
133
|
+
|
|
134
|
+
def _log_line(self, line: str) -> None:
|
|
135
|
+
self._logging.active = True
|
|
136
|
+
try:
|
|
137
|
+
self._logger.info(
|
|
138
|
+
"[%s] %s",
|
|
139
|
+
self._label,
|
|
140
|
+
line,
|
|
141
|
+
extra={"_parallelazy_captured_stream": True},
|
|
142
|
+
)
|
|
143
|
+
finally:
|
|
144
|
+
self._logging.active = False
|
|
145
|
+
|
|
146
|
+
def flush(self) -> None:
|
|
147
|
+
with self._lock:
|
|
148
|
+
self._stream.flush()
|
|
149
|
+
if self._buffer and not getattr(self._logging, "active", False):
|
|
150
|
+
self._emit_buffer()
|
|
151
|
+
|
|
152
|
+
def close(self) -> None:
|
|
153
|
+
self.flush()
|
|
154
|
+
|
|
155
|
+
def __getattr__(self, name):
|
|
156
|
+
return getattr(self._stream, name)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class WorkerOutputCapture:
|
|
160
|
+
"""Restore worker streams after teeing their output into the worker log."""
|
|
161
|
+
|
|
162
|
+
def __init__(self, logger: logging.Logger):
|
|
163
|
+
self._original_stdout = sys.stdout
|
|
164
|
+
self._original_stderr = sys.stderr
|
|
165
|
+
self.stdout = _TeeTextStream(self._original_stdout, logger, "stdout")
|
|
166
|
+
self.stderr = _TeeTextStream(self._original_stderr, logger, "stderr")
|
|
167
|
+
sys.stdout = self.stdout
|
|
168
|
+
sys.stderr = self.stderr
|
|
169
|
+
|
|
170
|
+
def close(self) -> None:
|
|
171
|
+
try:
|
|
172
|
+
self.stdout.flush()
|
|
173
|
+
self.stderr.flush()
|
|
174
|
+
finally:
|
|
175
|
+
if sys.stdout is self.stdout:
|
|
176
|
+
sys.stdout = self._original_stdout
|
|
177
|
+
if sys.stderr is self.stderr:
|
|
178
|
+
sys.stderr = self._original_stderr
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def configure_worker_output(logger: logging.Logger) -> WorkerOutputCapture:
|
|
182
|
+
"""Mirror worker stdout and stderr to both the terminal and plugin log."""
|
|
183
|
+
return WorkerOutputCapture(logger)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _format_elapsed(seconds: float) -> str:
|
|
187
|
+
milliseconds = max(0, int(seconds * 1000))
|
|
188
|
+
hours, remainder = divmod(milliseconds, 3_600_000)
|
|
189
|
+
minutes, remainder = divmod(remainder, 60_000)
|
|
190
|
+
whole_seconds, milliseconds = divmod(remainder, 1000)
|
|
191
|
+
return f"+{hours:02}:{minutes:02}:{whole_seconds:02}.{milliseconds:03}"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class _LogContextFilter(logging.Filter):
|
|
195
|
+
def __init__(self, plugin_id: str, started_at: float):
|
|
196
|
+
super().__init__()
|
|
197
|
+
self.plugin_id = plugin_id
|
|
198
|
+
self.started_at = started_at
|
|
199
|
+
|
|
200
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
201
|
+
record.plugin_id = self.plugin_id
|
|
202
|
+
record.elapsed = _format_elapsed(time.monotonic() - self.started_at)
|
|
203
|
+
return True
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _utc_timestamp() -> str:
|
|
207
|
+
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class _RecoveringFileHandler(logging.Handler):
|
|
211
|
+
"""Append to a log file and recreate it if its path or parent is removed."""
|
|
212
|
+
|
|
213
|
+
terminator = os.linesep
|
|
214
|
+
|
|
215
|
+
def __init__(self, filename: str):
|
|
216
|
+
super().__init__()
|
|
217
|
+
self.base_filename = os.path.abspath(filename)
|
|
218
|
+
self.stream: Optional[TextIO] = None
|
|
219
|
+
self._open_stream()
|
|
220
|
+
|
|
221
|
+
def _create_stream(self, filename: str) -> TextIO:
|
|
222
|
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
|
223
|
+
stream = open(filename, "a", encoding="utf-8")
|
|
224
|
+
try:
|
|
225
|
+
stream.write(f"# Log opened: {_utc_timestamp()}{self.terminator}")
|
|
226
|
+
stream.write(
|
|
227
|
+
"# Elapsed time is relative to this process's logging setup."
|
|
228
|
+
f"{self.terminator}"
|
|
229
|
+
)
|
|
230
|
+
stream.flush()
|
|
231
|
+
except Exception:
|
|
232
|
+
stream.close()
|
|
233
|
+
raise
|
|
234
|
+
return stream
|
|
235
|
+
|
|
236
|
+
def _open_stream(self) -> None:
|
|
237
|
+
self.stream = self._create_stream(self.base_filename)
|
|
238
|
+
|
|
239
|
+
def set_filename(self, filename: str) -> None:
|
|
240
|
+
filename = os.path.abspath(filename)
|
|
241
|
+
if filename == self.base_filename:
|
|
242
|
+
return
|
|
243
|
+
|
|
244
|
+
stream = self._create_stream(filename)
|
|
245
|
+
self.acquire()
|
|
246
|
+
try:
|
|
247
|
+
previous_stream = self.stream
|
|
248
|
+
self.base_filename = filename
|
|
249
|
+
self.stream = stream
|
|
250
|
+
if previous_stream is not None:
|
|
251
|
+
previous_stream.close()
|
|
252
|
+
finally:
|
|
253
|
+
self.release()
|
|
254
|
+
|
|
255
|
+
def _close_stream(self) -> None:
|
|
256
|
+
stream = self.stream
|
|
257
|
+
self.stream = None
|
|
258
|
+
if stream is not None:
|
|
259
|
+
try:
|
|
260
|
+
stream.flush()
|
|
261
|
+
finally:
|
|
262
|
+
stream.close()
|
|
263
|
+
|
|
264
|
+
def _reopen_stream(self) -> None:
|
|
265
|
+
self._close_stream()
|
|
266
|
+
self._open_stream()
|
|
267
|
+
|
|
268
|
+
def _ensure_current_stream(self) -> None:
|
|
269
|
+
if self.stream is None:
|
|
270
|
+
self._open_stream()
|
|
271
|
+
return
|
|
272
|
+
|
|
273
|
+
try:
|
|
274
|
+
path_identity = os.stat(self.base_filename)
|
|
275
|
+
stream_stat = os.fstat(self.stream.fileno())
|
|
276
|
+
except FileNotFoundError:
|
|
277
|
+
self._reopen_stream()
|
|
278
|
+
return
|
|
279
|
+
|
|
280
|
+
if (path_identity.st_dev, path_identity.st_ino) != (
|
|
281
|
+
stream_stat.st_dev,
|
|
282
|
+
stream_stat.st_ino,
|
|
283
|
+
):
|
|
284
|
+
self._reopen_stream()
|
|
285
|
+
|
|
286
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
287
|
+
try:
|
|
288
|
+
self._ensure_current_stream()
|
|
289
|
+
self.stream.write(self.format(record) + self.terminator)
|
|
290
|
+
self.flush()
|
|
291
|
+
except OSError:
|
|
292
|
+
try:
|
|
293
|
+
self._reopen_stream()
|
|
294
|
+
self.stream.write(self.format(record) + self.terminator)
|
|
295
|
+
self.flush()
|
|
296
|
+
except Exception:
|
|
297
|
+
self.handleError(record)
|
|
298
|
+
except Exception:
|
|
299
|
+
self.handleError(record)
|
|
300
|
+
|
|
301
|
+
def flush(self) -> None:
|
|
302
|
+
if self.stream is not None:
|
|
303
|
+
self.stream.flush()
|
|
304
|
+
|
|
305
|
+
def close(self) -> None:
|
|
306
|
+
try:
|
|
307
|
+
self._close_stream()
|
|
308
|
+
finally:
|
|
309
|
+
super().close()
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _make_formatter(format_string: str, datefmt: Optional[str] = None) -> logging.Formatter:
|
|
313
|
+
formatter = logging.Formatter(format_string, datefmt=datefmt)
|
|
314
|
+
formatter.converter = time.gmtime
|
|
315
|
+
|
|
316
|
+
record = logging.LogRecord(
|
|
317
|
+
name="parallelazy",
|
|
318
|
+
level=logging.INFO,
|
|
319
|
+
pathname=__file__,
|
|
320
|
+
lineno=0,
|
|
321
|
+
msg="validation",
|
|
322
|
+
args=(),
|
|
323
|
+
exc_info=None,
|
|
324
|
+
)
|
|
325
|
+
record.plugin_id = "plugin"
|
|
326
|
+
record.elapsed = "+00:00:00.000"
|
|
327
|
+
formatter.format(record)
|
|
328
|
+
return formatter
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class LoggingSession:
|
|
332
|
+
"""Owns the handlers and formatters for one process's logging output."""
|
|
333
|
+
|
|
334
|
+
def __init__(
|
|
335
|
+
self,
|
|
336
|
+
logger: logging.Logger,
|
|
337
|
+
log_file: str,
|
|
338
|
+
plugin_id: str,
|
|
339
|
+
log_level: int,
|
|
340
|
+
display_logs: bool,
|
|
341
|
+
replace_handlers: bool = False,
|
|
342
|
+
):
|
|
343
|
+
if isinstance(log_level, bool) or not isinstance(log_level, int):
|
|
344
|
+
raise TypeError("log_level must be an integer logging level")
|
|
345
|
+
|
|
346
|
+
self.logger = logger
|
|
347
|
+
self.file_format = DEFAULT_FILE_LOG_FORMAT
|
|
348
|
+
self.console_format = DEFAULT_CONSOLE_LOG_FORMAT
|
|
349
|
+
self._context_filter = _LogContextFilter(plugin_id, time.monotonic())
|
|
350
|
+
self._handlers: List[logging.Handler] = []
|
|
351
|
+
|
|
352
|
+
if replace_handlers:
|
|
353
|
+
for handler in list(logger.handlers):
|
|
354
|
+
logger.removeHandler(handler)
|
|
355
|
+
handler.close()
|
|
356
|
+
|
|
357
|
+
logger.setLevel(log_level)
|
|
358
|
+
logger.propagate = False
|
|
359
|
+
|
|
360
|
+
file_handler = _RecoveringFileHandler(log_file)
|
|
361
|
+
file_handler.setLevel(log_level)
|
|
362
|
+
file_handler.addFilter(self._context_filter)
|
|
363
|
+
file_handler.setFormatter(_make_formatter(self.file_format))
|
|
364
|
+
logger.addHandler(file_handler)
|
|
365
|
+
self._handlers.append(file_handler)
|
|
366
|
+
|
|
367
|
+
if display_logs:
|
|
368
|
+
console_handler = logging.StreamHandler(sys.stdout)
|
|
369
|
+
console_handler.setLevel(log_level)
|
|
370
|
+
console_handler.addFilter(self._context_filter)
|
|
371
|
+
console_handler.addFilter(_CapturedStreamConsoleFilter())
|
|
372
|
+
console_handler.setFormatter(
|
|
373
|
+
_make_formatter(self.console_format, CONSOLE_DATE_FORMAT)
|
|
374
|
+
)
|
|
375
|
+
logger.addHandler(console_handler)
|
|
376
|
+
self._handlers.append(console_handler)
|
|
377
|
+
|
|
378
|
+
def set_formats(
|
|
379
|
+
self,
|
|
380
|
+
file_format: Optional[str] = None,
|
|
381
|
+
console_format: Optional[str] = None,
|
|
382
|
+
) -> None:
|
|
383
|
+
new_file_format = self.file_format if file_format is None else file_format
|
|
384
|
+
new_console_format = (
|
|
385
|
+
self.console_format if console_format is None else console_format
|
|
386
|
+
)
|
|
387
|
+
file_formatter = _make_formatter(new_file_format)
|
|
388
|
+
console_formatter = _make_formatter(new_console_format, CONSOLE_DATE_FORMAT)
|
|
389
|
+
|
|
390
|
+
for handler in self._handlers:
|
|
391
|
+
if isinstance(handler, _RecoveringFileHandler):
|
|
392
|
+
handler.setFormatter(file_formatter)
|
|
393
|
+
elif isinstance(handler, logging.StreamHandler):
|
|
394
|
+
handler.setFormatter(console_formatter)
|
|
395
|
+
|
|
396
|
+
self.file_format = new_file_format
|
|
397
|
+
self.console_format = new_console_format
|
|
398
|
+
|
|
399
|
+
def set_log_file(self, log_file: str) -> None:
|
|
400
|
+
for handler in self._handlers:
|
|
401
|
+
if isinstance(handler, _RecoveringFileHandler):
|
|
402
|
+
handler.set_filename(log_file)
|
|
403
|
+
|
|
404
|
+
def close(self) -> None:
|
|
405
|
+
for handler in self._handlers:
|
|
406
|
+
self.logger.removeHandler(handler)
|
|
407
|
+
handler.close()
|
|
408
|
+
self._handlers.clear()
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def configure_worker_logging(
|
|
412
|
+
settings: PluginRuntimeSettings,
|
|
413
|
+
plugin_id: str,
|
|
414
|
+
) -> LoggingSession:
|
|
415
|
+
root_logger = logging.getLogger()
|
|
416
|
+
return LoggingSession(
|
|
417
|
+
logger=root_logger,
|
|
418
|
+
log_file=os.path.join(settings.log_dir, plugin_log_filename(plugin_id)),
|
|
419
|
+
plugin_id=plugin_id,
|
|
420
|
+
log_level=settings.log_level,
|
|
421
|
+
display_logs=settings.display_logs,
|
|
422
|
+
replace_handlers=True,
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def configure_manager_logging(
|
|
427
|
+
log_file: str,
|
|
428
|
+
log_level: int,
|
|
429
|
+
display_logs: bool,
|
|
430
|
+
run_id: str,
|
|
431
|
+
) -> LoggingSession:
|
|
432
|
+
manager_logger = logging.getLogger(f"parallelazy.manager.{run_id}")
|
|
433
|
+
return LoggingSession(
|
|
434
|
+
logger=manager_logger,
|
|
435
|
+
log_file=log_file,
|
|
436
|
+
plugin_id="manager",
|
|
437
|
+
log_level=log_level,
|
|
438
|
+
display_logs=display_logs,
|
|
439
|
+
)
|