parallelazy 0.0.7__tar.gz → 0.1.0__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 (23) hide show
  1. {parallelazy-0.0.7 → parallelazy-0.1.0}/PKG-INFO +1 -1
  2. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/plugin.py +79 -10
  3. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/plugin_data.py +17 -0
  4. parallelazy-0.1.0/parallelazy/plugin_logging.py +290 -0
  5. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/plugin_manager.py +211 -50
  6. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/plugin_rpc.py +82 -18
  7. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/plugin_transport.py +19 -1
  8. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/plugin_worker.py +281 -120
  9. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/utils.py +5 -2
  10. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy.egg-info/PKG-INFO +1 -1
  11. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy.egg-info/SOURCES.txt +5 -1
  12. {parallelazy-0.0.7 → parallelazy-0.1.0}/pyproject.toml +1 -1
  13. parallelazy-0.1.0/tests/test_env_cuda_ipc.py +41 -0
  14. parallelazy-0.1.0/tests/test_plugin_lifecycle.py +264 -0
  15. parallelazy-0.1.0/tests/test_plugin_logging.py +183 -0
  16. {parallelazy-0.0.7 → parallelazy-0.1.0}/LICENSE +0 -0
  17. {parallelazy-0.0.7 → parallelazy-0.1.0}/README.md +0 -0
  18. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/__init__.py +0 -0
  19. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy/environment_manager.py +0 -0
  20. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy.egg-info/dependency_links.txt +0 -0
  21. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy.egg-info/requires.txt +0 -0
  22. {parallelazy-0.0.7 → parallelazy-0.1.0}/parallelazy.egg-info/top_level.txt +0 -0
  23. {parallelazy-0.0.7 → parallelazy-0.1.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: parallelazy
3
- Version: 0.0.7
3
+ Version: 0.1.0
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
- from typing import Any, Dict, Optional, TYPE_CHECKING, Self
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 execution loop (optional)
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(cls, version:str, author:str, description:str=None, name:str=None, options: Dict[str, Any] = None) -> PluginDescriptor:
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): pass
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
- """Stop the plugin."""
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:str) -> None:
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
- return self._worker.env_get(name) or default
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:str) -> None:
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,290 @@
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 sys
9
+ import time
10
+ from typing import List, Optional, TextIO
11
+
12
+
13
+ DEFAULT_FILE_LOG_FORMAT = "[%(elapsed)s] %(levelname)s %(message)s"
14
+ DEFAULT_CONSOLE_LOG_FORMAT = (
15
+ "%(asctime)s.%(msecs)03dZ %(levelname)s [%(plugin_id)s] %(message)s"
16
+ )
17
+ CONSOLE_DATE_FORMAT = "%H:%M:%S"
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class PluginRuntimeSettings:
22
+ work_dir: str
23
+ log_dir: str
24
+ log_level: int
25
+ display_logs: bool
26
+
27
+
28
+ def resolve_directory(path: str, base_dir: Optional[str] = None) -> str:
29
+ """Return an absolute directory path, resolving relative paths against base_dir."""
30
+ expanded_path = os.path.expanduser(os.fspath(path))
31
+ if not os.path.isabs(expanded_path):
32
+ expanded_path = os.path.join(base_dir or os.getcwd(), expanded_path)
33
+ return os.path.abspath(expanded_path)
34
+
35
+
36
+ def create_run_id() -> str:
37
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
38
+ return f"{timestamp}_{os.urandom(6).hex()}"
39
+
40
+
41
+ def plugin_log_filename(plugin_id: str) -> str:
42
+ readable_id = "".join(
43
+ character if character.isascii() and (character.isalnum() or character in "-_.") else "_"
44
+ for character in plugin_id
45
+ ).strip("._-") or "plugin"
46
+ suffix = hashlib.sha256(plugin_id.encode("utf-8")).hexdigest()[:12]
47
+ return f"{readable_id}-{suffix}.log"
48
+
49
+
50
+ def default_runtime_settings() -> PluginRuntimeSettings:
51
+ work_dir = resolve_directory(os.getcwd())
52
+ log_dir = os.path.join(resolve_directory("logs", work_dir), create_run_id())
53
+ os.makedirs(log_dir, exist_ok=True)
54
+ return PluginRuntimeSettings(
55
+ work_dir=work_dir,
56
+ log_dir=log_dir,
57
+ log_level=logging.INFO,
58
+ display_logs=True,
59
+ )
60
+
61
+
62
+ def _format_elapsed(seconds: float) -> str:
63
+ milliseconds = max(0, int(seconds * 1000))
64
+ hours, remainder = divmod(milliseconds, 3_600_000)
65
+ minutes, remainder = divmod(remainder, 60_000)
66
+ whole_seconds, milliseconds = divmod(remainder, 1000)
67
+ return f"+{hours:02}:{minutes:02}:{whole_seconds:02}.{milliseconds:03}"
68
+
69
+
70
+ class _LogContextFilter(logging.Filter):
71
+ def __init__(self, plugin_id: str, started_at: float):
72
+ super().__init__()
73
+ self.plugin_id = plugin_id
74
+ self.started_at = started_at
75
+
76
+ def filter(self, record: logging.LogRecord) -> bool:
77
+ record.plugin_id = self.plugin_id
78
+ record.elapsed = _format_elapsed(time.monotonic() - self.started_at)
79
+ return True
80
+
81
+
82
+ def _utc_timestamp() -> str:
83
+ return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
84
+
85
+
86
+ class _RecoveringFileHandler(logging.Handler):
87
+ """Append to a log file and recreate it if its path or parent is removed."""
88
+
89
+ terminator = os.linesep
90
+
91
+ def __init__(self, filename: str):
92
+ super().__init__()
93
+ self.base_filename = os.path.abspath(filename)
94
+ self.stream: Optional[TextIO] = None
95
+ self._open_stream()
96
+
97
+ def _open_stream(self) -> None:
98
+ os.makedirs(os.path.dirname(self.base_filename), exist_ok=True)
99
+ stream = open(self.base_filename, "a", encoding="utf-8")
100
+ try:
101
+ stream.write(f"# Log opened: {_utc_timestamp()}{self.terminator}")
102
+ stream.write(
103
+ "# Elapsed time is relative to this process's logging setup."
104
+ f"{self.terminator}"
105
+ )
106
+ stream.flush()
107
+ except Exception:
108
+ stream.close()
109
+ raise
110
+ self.stream = stream
111
+
112
+ def _close_stream(self) -> None:
113
+ stream = self.stream
114
+ self.stream = None
115
+ if stream is not None:
116
+ try:
117
+ stream.flush()
118
+ finally:
119
+ stream.close()
120
+
121
+ def _reopen_stream(self) -> None:
122
+ self._close_stream()
123
+ self._open_stream()
124
+
125
+ def _ensure_current_stream(self) -> None:
126
+ if self.stream is None:
127
+ self._open_stream()
128
+ return
129
+
130
+ try:
131
+ path_identity = os.stat(self.base_filename)
132
+ stream_stat = os.fstat(self.stream.fileno())
133
+ except FileNotFoundError:
134
+ self._reopen_stream()
135
+ return
136
+
137
+ if (path_identity.st_dev, path_identity.st_ino) != (
138
+ stream_stat.st_dev,
139
+ stream_stat.st_ino,
140
+ ):
141
+ self._reopen_stream()
142
+
143
+ def emit(self, record: logging.LogRecord) -> None:
144
+ try:
145
+ self._ensure_current_stream()
146
+ self.stream.write(self.format(record) + self.terminator)
147
+ self.flush()
148
+ except OSError:
149
+ try:
150
+ self._reopen_stream()
151
+ self.stream.write(self.format(record) + self.terminator)
152
+ self.flush()
153
+ except Exception:
154
+ self.handleError(record)
155
+ except Exception:
156
+ self.handleError(record)
157
+
158
+ def flush(self) -> None:
159
+ if self.stream is not None:
160
+ self.stream.flush()
161
+
162
+ def close(self) -> None:
163
+ try:
164
+ self._close_stream()
165
+ finally:
166
+ super().close()
167
+
168
+
169
+ def _make_formatter(format_string: str, datefmt: Optional[str] = None) -> logging.Formatter:
170
+ formatter = logging.Formatter(format_string, datefmt=datefmt)
171
+ formatter.converter = time.gmtime
172
+
173
+ record = logging.LogRecord(
174
+ name="parallelazy",
175
+ level=logging.INFO,
176
+ pathname=__file__,
177
+ lineno=0,
178
+ msg="validation",
179
+ args=(),
180
+ exc_info=None,
181
+ )
182
+ record.plugin_id = "plugin"
183
+ record.elapsed = "+00:00:00.000"
184
+ formatter.format(record)
185
+ return formatter
186
+
187
+
188
+ class LoggingSession:
189
+ """Owns the handlers and formatters for one process's logging output."""
190
+
191
+ def __init__(
192
+ self,
193
+ logger: logging.Logger,
194
+ log_file: str,
195
+ plugin_id: str,
196
+ log_level: int,
197
+ display_logs: bool,
198
+ replace_handlers: bool = False,
199
+ ):
200
+ if isinstance(log_level, bool) or not isinstance(log_level, int):
201
+ raise TypeError("log_level must be an integer logging level")
202
+
203
+ self.logger = logger
204
+ self.file_format = DEFAULT_FILE_LOG_FORMAT
205
+ self.console_format = DEFAULT_CONSOLE_LOG_FORMAT
206
+ self._context_filter = _LogContextFilter(plugin_id, time.monotonic())
207
+ self._handlers: List[logging.Handler] = []
208
+
209
+ if replace_handlers:
210
+ for handler in list(logger.handlers):
211
+ logger.removeHandler(handler)
212
+ handler.close()
213
+
214
+ logger.setLevel(log_level)
215
+ logger.propagate = False
216
+
217
+ file_handler = _RecoveringFileHandler(log_file)
218
+ file_handler.setLevel(log_level)
219
+ file_handler.addFilter(self._context_filter)
220
+ file_handler.setFormatter(_make_formatter(self.file_format))
221
+ logger.addHandler(file_handler)
222
+ self._handlers.append(file_handler)
223
+
224
+ if display_logs:
225
+ console_handler = logging.StreamHandler(sys.stdout)
226
+ console_handler.setLevel(log_level)
227
+ console_handler.addFilter(self._context_filter)
228
+ console_handler.setFormatter(
229
+ _make_formatter(self.console_format, CONSOLE_DATE_FORMAT)
230
+ )
231
+ logger.addHandler(console_handler)
232
+ self._handlers.append(console_handler)
233
+
234
+ def set_formats(
235
+ self,
236
+ file_format: Optional[str] = None,
237
+ console_format: Optional[str] = None,
238
+ ) -> None:
239
+ new_file_format = self.file_format if file_format is None else file_format
240
+ new_console_format = (
241
+ self.console_format if console_format is None else console_format
242
+ )
243
+ file_formatter = _make_formatter(new_file_format)
244
+ console_formatter = _make_formatter(new_console_format, CONSOLE_DATE_FORMAT)
245
+
246
+ for handler in self._handlers:
247
+ if isinstance(handler, _RecoveringFileHandler):
248
+ handler.setFormatter(file_formatter)
249
+ elif isinstance(handler, logging.StreamHandler):
250
+ handler.setFormatter(console_formatter)
251
+
252
+ self.file_format = new_file_format
253
+ self.console_format = new_console_format
254
+
255
+ def close(self) -> None:
256
+ for handler in self._handlers:
257
+ self.logger.removeHandler(handler)
258
+ handler.close()
259
+ self._handlers.clear()
260
+
261
+
262
+ def configure_worker_logging(
263
+ settings: PluginRuntimeSettings,
264
+ plugin_id: str,
265
+ ) -> LoggingSession:
266
+ root_logger = logging.getLogger()
267
+ return LoggingSession(
268
+ logger=root_logger,
269
+ log_file=os.path.join(settings.log_dir, plugin_log_filename(plugin_id)),
270
+ plugin_id=plugin_id,
271
+ log_level=settings.log_level,
272
+ display_logs=settings.display_logs,
273
+ replace_handlers=True,
274
+ )
275
+
276
+
277
+ def configure_manager_logging(
278
+ log_file: str,
279
+ log_level: int,
280
+ display_logs: bool,
281
+ run_id: str,
282
+ ) -> LoggingSession:
283
+ manager_logger = logging.getLogger(f"parallelazy.manager.{run_id}")
284
+ return LoggingSession(
285
+ logger=manager_logger,
286
+ log_file=log_file,
287
+ plugin_id="manager",
288
+ log_level=log_level,
289
+ display_logs=display_logs,
290
+ )