ConstellationDAQ 0.1__py3-none-any.whl

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 (43) hide show
  1. constellation/core/__init__.py +21 -0
  2. constellation/core/base.py +207 -0
  3. constellation/core/broadcastmanager.py +317 -0
  4. constellation/core/cdtp.py +246 -0
  5. constellation/core/chirp.py +257 -0
  6. constellation/core/chp.py +67 -0
  7. constellation/core/cmdp.py +218 -0
  8. constellation/core/commandmanager.py +259 -0
  9. constellation/core/configuration.py +144 -0
  10. constellation/core/controller.py +724 -0
  11. constellation/core/cscp.py +193 -0
  12. constellation/core/datareceiver.py +285 -0
  13. constellation/core/datasender.py +275 -0
  14. constellation/core/error.py +55 -0
  15. constellation/core/fsm.py +385 -0
  16. constellation/core/heartbeatchecker.py +324 -0
  17. constellation/core/heartbeater.py +68 -0
  18. constellation/core/monitoring.py +469 -0
  19. constellation/core/network.py +125 -0
  20. constellation/core/protocol.py +98 -0
  21. constellation/core/py.typed +0 -0
  22. constellation/core/satellite.py +512 -0
  23. constellation/core/version_code_name +1 -0
  24. constellation/satellites/CaenHV/CaenHV.py +322 -0
  25. constellation/satellites/CaenHV/__main__.py +11 -0
  26. constellation/satellites/CaenHV/lib_caen_ndt1470.py +479 -0
  27. constellation/satellites/H5DataWriter/H5DataWriter.py +177 -0
  28. constellation/satellites/H5DataWriter/__main__.py +11 -0
  29. constellation/satellites/Influx/Influx.py +72 -0
  30. constellation/satellites/Influx/__main__.py +10 -0
  31. constellation/satellites/Keithley/Keithley.py +188 -0
  32. constellation/satellites/Keithley/Keithley2410.py +116 -0
  33. constellation/satellites/Keithley/KeithleyInterface.py +204 -0
  34. constellation/satellites/Keithley/__main__.py +11 -0
  35. constellation/satellites/Mariner/Mariner.py +144 -0
  36. constellation/satellites/Mariner/__main__.py +11 -0
  37. constellation/satellites/__init__.py +4 -0
  38. constellation/tools/H5datareader.py +127 -0
  39. constellation/tools/list_interfaces.py +39 -0
  40. constellationdaq-0.1.dist-info/METADATA +90 -0
  41. constellationdaq-0.1.dist-info/RECORD +43 -0
  42. constellationdaq-0.1.dist-info/WHEEL +4 -0
  43. constellationdaq-0.1.dist-info/entry_points.txt +13 -0
@@ -0,0 +1,21 @@
1
+ """
2
+ SPDX-FileCopyrightText: 2024 DESY and the Constellation authors
3
+ SPDX-License-Identifier: CC-BY-4.0
4
+ """
5
+
6
+ # Get version via project name in pyproject.toml
7
+ try:
8
+ import importlib.metadata
9
+
10
+ __version__ = importlib.metadata.version("ConstellationDAQ")
11
+ except: # noqa: E722
12
+ __version__ = "0"
13
+ __version_code_name__ = "unknown"
14
+
15
+ # Get version code name via resource in constellation.core module
16
+ try:
17
+ import importlib.resources
18
+
19
+ __version_code_name__ = importlib.resources.read_text("constellation.core", "version_code_name").strip("\n")
20
+ except: # noqa: E722
21
+ __version_code_name__ = "unknown"
@@ -0,0 +1,207 @@
1
+ """
2
+ SPDX-FileCopyrightText: 2024 DESY and the Constellation authors
3
+ SPDX-License-Identifier: CC-BY-4.0
4
+
5
+ This module provides a base class for Constellation Satellite modules.
6
+ """
7
+
8
+ import re
9
+ import zmq
10
+ import threading
11
+ import logging
12
+ from argparse import ArgumentParser
13
+ from queue import Queue
14
+ from typing import cast, Any
15
+ import socket
16
+ import atexit
17
+ import coloredlogs # type: ignore[import-untyped]
18
+
19
+ from . import __version__, __version_code_name__
20
+ from .network import validate_interface, get_interfaces
21
+
22
+
23
+ @atexit.register
24
+ def destroy_satellites() -> None:
25
+ """Close down connections and perform orderly re-entry."""
26
+ for sat in SATELLITE_LIST:
27
+ sat.reentry()
28
+
29
+
30
+ class ConstellationArgumentParser(ArgumentParser):
31
+ """Customized Argument parser providing basic Satellite options."""
32
+
33
+ def __init__(self, *args: Any, **kwargs: Any):
34
+ super().__init__(*args, **kwargs)
35
+ # generic arguments
36
+ self.add_argument(
37
+ "-l",
38
+ "--log-level",
39
+ default="info",
40
+ help="The maximum level of log messages to print to the console.",
41
+ )
42
+ self.add_argument("--version", action="version", version=f"Constellation v{__version__} ({__version_code_name__})")
43
+ # add a constellation argument group
44
+ self.constellation = self.add_argument_group("Constellation")
45
+ self.constellation.add_argument(
46
+ "--name",
47
+ "-n",
48
+ default=socket.gethostname().replace("-", "_"),
49
+ type=str,
50
+ help="The name of the Satellite. This has to be unique within "
51
+ "the Constellation group. Together with the Satellite class, "
52
+ "this forms the Canonical Name.",
53
+ )
54
+ self.constellation.add_argument(
55
+ "--group",
56
+ "-g",
57
+ required=True,
58
+ type=str,
59
+ help="The Constellation group to connect to. This separates "
60
+ "different Constellations running on the same network",
61
+ )
62
+ # add a networking argument group
63
+ self.network = self.add_argument_group("Network configuration")
64
+ self.network.add_argument(
65
+ "--interface",
66
+ type=validate_interface,
67
+ choices=get_interfaces(),
68
+ default="*",
69
+ help="The network interface (i.e. IP address) to bind to. "
70
+ "Use '*' to bind to alla available interfaces "
71
+ "(default: %(default)s).",
72
+ )
73
+
74
+
75
+ EPILOG = "This command is part of the Constellation Python core package."
76
+
77
+
78
+ class ConstellationLogger(logging.getLoggerClass()): # type: ignore[misc]
79
+ """Custom Logger class for Constellation.
80
+
81
+ Defines the following log levels:
82
+
83
+ - logging.NOTSET : 0
84
+ - logging.TRACE : 5
85
+ - logging.DEBUG : 10
86
+ - logging.INFO : 20
87
+ - logging.STATUS : 25
88
+ - logging.WARNING : 30
89
+ - logging.ERROR : mapped to CRITICAL
90
+ - logging.CRITICAL : 50
91
+
92
+ """
93
+
94
+ def __init__(self, *args: Any, **kwargs: Any):
95
+ """Init logger and define extra levels."""
96
+ super().__init__(*args, **kwargs)
97
+ logging.TRACE = logging.DEBUG - 5 # type: ignore[attr-defined]
98
+ logging.addLevelName(logging.DEBUG - 5, "TRACE")
99
+ logging.STATUS = logging.INFO + 5 # type: ignore[attr-defined]
100
+ logging.addLevelName(logging.INFO + 5, "STATUS")
101
+
102
+ def trace(self, msg: str, *args: Any, **kwargs: Any) -> None:
103
+ """Define level for verbose information which allows to follow the call
104
+ stack of the host program."""
105
+ self.log(logging.TRACE, msg, *args, **kwargs) # type: ignore[attr-defined]
106
+
107
+ def status(self, msg: str, *args: Any, **kwargs: Any) -> None:
108
+ """Define level for important information about the host program to the
109
+ end user with low frequency."""
110
+ self.log(logging.STATUS, msg, *args, **kwargs) # type: ignore[attr-defined]
111
+
112
+ def error(self, msg: str, *args: Any, **kwargs: Any) -> None:
113
+ """Map error level to CRITICAL."""
114
+ self.log(logging.CRITICAL, msg, *args, **kwargs)
115
+
116
+
117
+ def setup_cli_logging(name: str, level: str) -> ConstellationLogger:
118
+ logging.setLoggerClass(ConstellationLogger)
119
+ logger = cast(ConstellationLogger, logging.getLogger(name))
120
+ log_level = level
121
+ coloredlogs.install(level=log_level.upper(), logger=logger)
122
+ return logger
123
+
124
+
125
+ class BaseSatelliteFrame:
126
+ """Base class for all Satellite components to inherit from.
127
+
128
+ Provides the basic internal Satellite infrastructure related to logging, ZMQ
129
+ and threading that all Satellite communication service components (i.e.
130
+ mixin classes) share.
131
+
132
+ """
133
+
134
+ def __init__(self, name: str, interface: str, **_kwds: Any):
135
+ # type name == python class name
136
+ self.type = type(self).__name__
137
+ # Check if provided name is valid:
138
+ if not re.match(r"^\w+$", name):
139
+ raise ValueError("Satellite name contains invalid characters")
140
+ # add type name to create the canonical name
141
+ self.name = f"{self.type}.{name}"
142
+ logging.setLoggerClass(ConstellationLogger)
143
+ self.log = cast(ConstellationLogger, logging.getLogger(name))
144
+ self.context = zmq.Context()
145
+
146
+ self.interface = interface
147
+
148
+ # Set up a queue for handling tasks related to incoming requests via
149
+ # CSCP or offers via CHIRP. This makes sure that these can be performed
150
+ # thread-safe from the main thread of the Satellite. A 'task' consists
151
+ # of a tuple consisting of a callback method and an object passed as
152
+ # argument (DiscoveredService and CSCPMessage for CHIRP and CSCP,
153
+ # respectively).
154
+ self.task_queue: Queue = Queue() # type: ignore[type-arg]
155
+
156
+ # dict to keep references to all communication service threads usually
157
+ # running in the background
158
+ self._com_thread_pool: dict[str, threading.Thread] = {}
159
+ # Event to indicate to communication service threads to stop
160
+ self._com_thread_evt: threading.Event | None = None
161
+
162
+ # add self to list of satellites to destroy on shutdown
163
+ global SATELLITE_LIST
164
+ SATELLITE_LIST.append(self)
165
+
166
+ def _add_com_thread(self) -> None:
167
+ """Method to add a background communication service thread to the pool.
168
+
169
+ Does nothing in the base class.
170
+
171
+ """
172
+ self.log.debug("Satellite Base class _add_thread called")
173
+ pass
174
+
175
+ def _start_com_threads(self) -> None:
176
+ """Start all background communication threads."""
177
+ self._com_thread_evt = threading.Event()
178
+ for component, thread in self._com_thread_pool.items():
179
+ self.log.debug("Starting thread for %s communication", component)
180
+ thread.start()
181
+
182
+ def _stop_com_threads(self, timeout: float = 1.5) -> None:
183
+ """Stop all background communication threads within timeout [s]."""
184
+ if self._com_thread_evt:
185
+ self._com_thread_evt.set()
186
+ for component, thread in self._com_thread_pool.items():
187
+ if thread.is_alive():
188
+ thread.join(timeout)
189
+ # check if thread is still alive
190
+ if thread.is_alive():
191
+ self.log.error(
192
+ "Could not join background communication thread for %s within timeout",
193
+ component,
194
+ )
195
+ raise RuntimeError(f"Could not join running thread for {component} within timeout of {timeout}s!")
196
+ self._com_thread_evt = None
197
+ self._com_thread_pool = {}
198
+
199
+ def reentry(self) -> None:
200
+ """Orderly destroy the satellite."""
201
+ self.log.debug("Stopping all communication threads.")
202
+ self._stop_com_threads()
203
+ self.log.debug("Terminating ZMQ context.")
204
+ self.context.term()
205
+
206
+
207
+ SATELLITE_LIST: list[BaseSatelliteFrame] = []
@@ -0,0 +1,317 @@
1
+ """
2
+ SPDX-FileCopyrightText: 2024 DESY and the Constellation authors
3
+ SPDX-License-Identifier: CC-BY-4.0
4
+
5
+ BroadcastManger module provides classes for managing CHIRP broadcasts within
6
+ Constellation Satellites.
7
+ """
8
+
9
+ import threading
10
+ from functools import wraps
11
+ from typing import Callable, TypeVar, ParamSpec, Any, Optional
12
+
13
+ import time
14
+ import random
15
+ from uuid import UUID
16
+
17
+ from .base import BaseSatelliteFrame
18
+
19
+ from .chirp import (
20
+ CHIRPServiceIdentifier,
21
+ CHIRPMessage,
22
+ CHIRPMessageType,
23
+ CHIRPBeaconTransmitter,
24
+ )
25
+
26
+
27
+ T = TypeVar("T")
28
+ B = TypeVar("B", bound=BaseSatelliteFrame)
29
+ P = ParamSpec("P")
30
+
31
+
32
+ def chirp_callback(
33
+ request_service: CHIRPServiceIdentifier,
34
+ ) -> Callable[[Callable[P, T]], Callable[P, T]]:
35
+ """Mark a function as a callback for CHIRP service requests."""
36
+
37
+ def decorator(func: Callable[P, T]) -> Callable[P, T]:
38
+ @wraps(func)
39
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
40
+ return func(*args, **kwargs)
41
+
42
+ # mark function as chirp callback
43
+ wrapper.chirp_callback = request_service # type: ignore[attr-defined]
44
+ return wrapper
45
+
46
+ return decorator
47
+
48
+
49
+ class DiscoveredService:
50
+ """Class to hold discovered service data."""
51
+
52
+ def __init__(
53
+ self,
54
+ host_uuid: UUID,
55
+ serviceid: CHIRPServiceIdentifier,
56
+ address: str,
57
+ port: int,
58
+ alive: bool = True,
59
+ ):
60
+ """Initialize variables."""
61
+ self.host_uuid = host_uuid
62
+ self.address = address
63
+ self.port = port
64
+ self.serviceid = serviceid
65
+ self.alive = alive
66
+
67
+ def __eq__(self, other: object) -> bool:
68
+ """Comparison operator for network-related properties."""
69
+ if isinstance(other, DiscoveredService):
70
+ return bool(
71
+ self.host_uuid == other.host_uuid
72
+ and self.serviceid == other.serviceid
73
+ and self.port == other.port
74
+ )
75
+ return NotImplemented
76
+
77
+ def __str__(self) -> str:
78
+ """Pretty-print a string for this service."""
79
+ s = "Host {} offering service {} on {}:{} is alive: {}"
80
+ return s.format(
81
+ self.host_uuid, self.serviceid, self.address, self.port, self.alive
82
+ )
83
+
84
+
85
+ def get_chirp_callbacks(
86
+ cls: object,
87
+ ) -> dict[CHIRPServiceIdentifier, Callable[[B, DiscoveredService], None]]:
88
+ """Loop over all class methods and return those marked as CHIRP callback."""
89
+ res = {}
90
+ for func in dir(cls):
91
+ if isinstance(getattr(type(cls), func, None), property):
92
+ # skip properties
93
+ continue
94
+ call = getattr(cls, func)
95
+ if callable(call) and not func.startswith("__"):
96
+ # regular method
97
+ if hasattr(call, "chirp_callback"):
98
+ res[getattr(call, "chirp_callback")] = call
99
+ return res
100
+
101
+
102
+ class CHIRPBroadcaster(BaseSatelliteFrame):
103
+ """Manages service discovery and broadcast via the CHIRP protocol.
104
+
105
+ Listening and reacting to CHIRP broadcasts is implemented in a dedicated
106
+ thread that can be started after the class has been instantiated.
107
+
108
+ Discovered services are added to an internal cache. Callback methods can be
109
+ registered either by calling register_request() or by using the
110
+ @chirp_callback() decorator. The callback will be added to the satellite's
111
+ internal task queue once the corresponding service has been offered by other
112
+ satellites via broadcast.
113
+
114
+ Offered services can be registered via register_offer() and are announced on
115
+ incoming request broadcasts or via broadcast_offers().
116
+
117
+ """
118
+
119
+ def __init__(
120
+ self,
121
+ name: str,
122
+ group: str,
123
+ interface: str,
124
+ **kwds: Any,
125
+ ):
126
+ """Initialize parameters.
127
+
128
+ :param host: Satellite name the BroadcastManager represents
129
+ :type host: str
130
+ :param group: group the Satellite belongs to
131
+ :type group: str
132
+ """
133
+ super().__init__(name=name, interface=interface, **kwds)
134
+ self.group = group
135
+ self._stop_broadcasting = threading.Event()
136
+ self._beacon = CHIRPBeaconTransmitter(self.name, group, interface)
137
+
138
+ # Offered and discovered services
139
+ self._registered_services: dict[int, CHIRPServiceIdentifier] = {}
140
+ self.discovered_services: list[DiscoveredService] = []
141
+ self._chirp_thread = None
142
+ self._chirp_callbacks: dict[
143
+ CHIRPServiceIdentifier, Callable[[B, DiscoveredService], None]
144
+ ] = get_chirp_callbacks(self)
145
+
146
+ def _add_com_thread(self) -> None:
147
+ """Add the CHIRP broadcaster thread to the communication thread pool."""
148
+ super()._add_com_thread()
149
+ self._com_thread_pool["chirp_broadcaster"] = threading.Thread(
150
+ target=self._run, daemon=True
151
+ )
152
+ self.log.debug("CHIRP broadcaster thread prepared and added to the pool.")
153
+
154
+ def get_discovered(
155
+ self, serviceid: CHIRPServiceIdentifier
156
+ ) -> list[DiscoveredService]:
157
+ """Return a list of already discovered services for a given identifier."""
158
+ res = []
159
+ for s in self.discovered_services:
160
+ if s.serviceid == serviceid:
161
+ res.append(s)
162
+ return res
163
+
164
+ def register_request(
165
+ self,
166
+ serviceid: CHIRPServiceIdentifier,
167
+ callback: Callable[[B, DiscoveredService], None],
168
+ ) -> None:
169
+ """Register new callback for ServiceIdentifier."""
170
+ if serviceid in self._chirp_callbacks:
171
+ self.log.warning("Overwriting CHIRP callback")
172
+ # FIXME the following assignment triggers an error with mypy
173
+ self._chirp_callbacks[serviceid] = callback # type: ignore[assignment]
174
+ # make a callback if a service has already been discovered
175
+ for known in self.get_discovered(serviceid):
176
+ self.task_queue.put((callback, [known]))
177
+
178
+ def register_offer(self, serviceid: CHIRPServiceIdentifier, port: int) -> None:
179
+ """Register new offered service or overwrite existing service."""
180
+ if port in self._registered_services:
181
+ self.log.warning("Replacing service registration for port %d", port)
182
+ self._registered_services[port] = serviceid
183
+
184
+ def request(self, serviceid: CHIRPServiceIdentifier) -> None:
185
+ """Request specific service.
186
+
187
+ Should already have a registered callback via register_request(), or
188
+ any incoming OFFERS will go unnoticed.
189
+
190
+ """
191
+ if serviceid not in self._chirp_callbacks:
192
+ self.log.warning(
193
+ "Serviceid %s does not have a registered callback", serviceid
194
+ )
195
+ self._beacon.broadcast(serviceid, CHIRPMessageType.REQUEST)
196
+
197
+ def broadcast_offers(
198
+ self, serviceid: Optional[CHIRPServiceIdentifier] = None, dest_addr: str = ""
199
+ ) -> None:
200
+ """Broadcast all registered services matching serviceid.
201
+
202
+ Specify None for all registered services.
203
+
204
+ If a destination address dest_addr is provided, broadcast only to that network address.
205
+
206
+ """
207
+ for port, sid in self._registered_services.items():
208
+ if not serviceid or serviceid == sid:
209
+ self.log.debug(
210
+ "Broadcasting service OFFER on '%s':%s for %s", dest_addr, port, sid
211
+ )
212
+ self._beacon.broadcast(sid, CHIRPMessageType.OFFER, port, dest_addr)
213
+
214
+ def broadcast_requests(self) -> None:
215
+ """Broadcast all requests registered via register_request()."""
216
+ for serviceid in self._chirp_callbacks:
217
+ self.log.debug("Broadcasting service REQUEST for %s", serviceid)
218
+ self._beacon.broadcast(serviceid, CHIRPMessageType.REQUEST)
219
+
220
+ def broadcast_depart(self) -> None:
221
+ """Broadcast DEPART for all registered services."""
222
+ for port, sid in self._registered_services.items():
223
+ self.log.debug("Broadcasting service DEPART on %d for %s", port, sid)
224
+ self._beacon.broadcast(sid, CHIRPMessageType.DEPART, port)
225
+
226
+ def _discover_service(self, msg: CHIRPMessage) -> None:
227
+ """Add a service to internal list and possibly queue a callback."""
228
+ service = DiscoveredService(
229
+ msg.host_uuid, msg.serviceid, msg.from_address, msg.port
230
+ )
231
+ if service in self.discovered_services:
232
+ self.log.debug(
233
+ "Service already discovered: %s on host %s:%s",
234
+ msg.serviceid,
235
+ msg.from_address,
236
+ msg.port,
237
+ )
238
+ # NOTE we might want to call the callback method for this service
239
+ # anyway, in case this host was down (without sending DEPART) and is
240
+ # now reconnecting. But then the bookkeeping has to be done higher up.
241
+ else:
242
+ # add service to internal list and queue callback (if registered)
243
+ self.log.debug(
244
+ "Received new OFFER for service: %s on host %s:%s",
245
+ msg.serviceid.name,
246
+ msg.from_address,
247
+ msg.port,
248
+ )
249
+ try:
250
+ callback = self._chirp_callbacks[msg.serviceid]
251
+ self.task_queue.put((callback, [service]))
252
+ except KeyError:
253
+ self.log.debug("No callback for service %s set up.", msg.serviceid)
254
+ self.discovered_services.append(service)
255
+
256
+ def _depart_service(self, msg: CHIRPMessage) -> None:
257
+ """Depart with a service."""
258
+ try:
259
+ service = DiscoveredService(
260
+ msg.host_uuid, msg.serviceid, msg.from_address, msg.port
261
+ )
262
+ self.discovered_services.remove(service)
263
+ self.log.debug(
264
+ "Received depart for service %s on host %s: Removed.",
265
+ msg.serviceid,
266
+ msg.from_address,
267
+ )
268
+ # indicate that service is no longer with us
269
+ service.alive = False
270
+ try:
271
+ callback = self._chirp_callbacks[msg.serviceid]
272
+ self.task_queue.put((callback, [service]))
273
+ except KeyError:
274
+ self.log.debug("No callback for service %s set up.", msg.serviceid)
275
+ except ValueError:
276
+ self.log.debug(
277
+ "Received depart for service %s on host %s: Not in use.",
278
+ msg.serviceid,
279
+ msg.from_address,
280
+ )
281
+
282
+ def _run(self) -> None:
283
+ """Start listening in on broadcast"""
284
+ # assert for mypy static type analysis
285
+ assert isinstance(
286
+ self._com_thread_evt, threading.Event
287
+ ), "BroadcastManager thread Event no set up"
288
+
289
+ while not self._com_thread_evt.is_set():
290
+ msg = self._beacon.listen()
291
+ if not msg:
292
+ continue
293
+
294
+ # Check Message Type
295
+ if msg.msgtype == CHIRPMessageType.REQUEST:
296
+ # wait a short moment to spread out responses somewhat
297
+ time.sleep(random.random() / 5.0)
298
+ self.broadcast_offers(
299
+ serviceid=msg.serviceid,
300
+ # only answer to address we received the msg on
301
+ dest_addr=msg.dest_address,
302
+ )
303
+ continue
304
+
305
+ if msg.msgtype == CHIRPMessageType.OFFER:
306
+ self._discover_service(msg)
307
+ continue
308
+
309
+ if msg.msgtype == CHIRPMessageType.DEPART and msg.port != 0:
310
+ self._depart_service(msg)
311
+ continue
312
+ # shutdown
313
+ self.log.debug("BroadcastManager thread shutting down.")
314
+ self.broadcast_depart()
315
+ # it can take a moment for the network buffers to be flushed
316
+ time.sleep(0.5)
317
+ self._beacon.close()