svkt 0.1.0__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.
svkt/__init__.py ADDED
@@ -0,0 +1,226 @@
1
+ """SVKT pure-Python producer client.
2
+
3
+ Records zones, instants, counters, messages, frames and program-flow arrows
4
+ into shared multi-tier in-memory history, streams them live to an SVKT viewer
5
+ over TCP (docs/PROTOCOL.md) and saves snapshots as ``.svkt`` or Chrome Trace
6
+ Event JSON. Standard library only, Python >= 3.8.
7
+
8
+ Quick start::
9
+
10
+ import svkt
11
+ svkt.init(process_name="my_service")
12
+
13
+ with svkt.zone("load", path=p) as z:
14
+ data = load(p)
15
+ z.arg("bytes", len(data))
16
+
17
+ @svkt.traced
18
+ async def handle(req): ...
19
+
20
+ Everything is a cheap no-op before :func:`init` and after :func:`shutdown`.
21
+ """
22
+
23
+ import atexit
24
+ import os
25
+ import time
26
+
27
+ from . import _core
28
+ from . import _proto as P
29
+ from ._core import ( # noqa: F401 - public re-exports
30
+ CRITICAL, DETAIL, ERROR, IMPORTANT, INFO, NORMAL, WARNING, Config, __version__, error,
31
+ error_message, flow_begin, flow_end, flow_step, frame, instant, message, new_flow_id,
32
+ now_ticks, plot, set_min_level, set_thread_name, traced, warn, warn_message, zone,
33
+ )
34
+ from . import _sysinfo
35
+ from ._sysinfo import set_system_info # noqa: F401
36
+ from ._wsgi import wsgi_middleware # noqa: F401
37
+ from ._logging import LoggingHandler # noqa: F401
38
+
39
+ __all__ = [
40
+ "init", "shutdown", "is_active", "port", "stats", "zone", "traced", "instant", "warn",
41
+ "error", "plot", "message", "warn_message", "error_message", "frame", "flow_begin",
42
+ "flow_step", "flow_end", "new_flow_id", "save", "export_chrome_json", "wsgi_middleware",
43
+ "set_thread_name", "set_min_level", "set_system_info", "now_ticks", "LoggingHandler",
44
+ "Config", "DETAIL", "NORMAL", "IMPORTANT", "CRITICAL", "INFO", "WARNING", "ERROR", "__version__",
45
+ ]
46
+
47
+ # init() / shutdown() run under this lock. A _TracerLock: a signal handler that
48
+ # calls shutdown() (or init()) while this thread is already inside one of them,
49
+ # e.g. a second Ctrl+C while the first shutdown joins the server thread, finds
50
+ # the lock held by its own thread and returns instead of deadlocking, and an
51
+ # asynchronous exception never leaves it held.
52
+ _init_lock = _core._TracerLock()
53
+ _atexit_registered = False
54
+
55
+
56
+ def init(process_name=None, port=P.DEFAULT_PORT, **options):
57
+ """Starts recording (and, unless disabled, the streaming server).
58
+
59
+ Options (keyword arguments, see :class:`svkt.Config`):
60
+
61
+ * ``bind_address`` ("127.0.0.1": only consumers on this machine can connect; the
62
+ stream is neither authenticated nor encrypted, so "0.0.0.0" or an interface
63
+ address is an explicit choice; for a remote viewer prefer an SSH tunnel; "" is
64
+ refused: no server, a line on stderr),
65
+ ``port`` (47474; 0 = ephemeral), ``port_range`` (16)
66
+ * ``enable_server`` (True), ``enable_discovery`` (True: the local registry file),
67
+ ``discovery_multicast`` (True: also announces by multicast, only on the
68
+ interface(s) ``bind_address`` listens on, PROTOCOL 7.1; False: registry file only)
69
+ * ``tiers``: list of ``(capacity_in_records, min_level)``; shared by all threads.
70
+ Default ``[(100000, DETAIL), (50000, NORMAL), (25000, IMPORTANT)]``.
71
+ * ``min_level`` (DETAIL): runtime recording filter.
72
+ * ``stream_interval_ms`` (10), ``max_live_records`` (200000, per consumer)
73
+ * ``max_consumers`` (4, clamped to 1..64): consumers served at once; one more
74
+ gets ``Error{Busy}`` unless a consumer has been silent for 5 s (it is replaced)
75
+ * ``allow_remote_save`` (True, loopback peers only),
76
+ ``allow_remote_save_from_network`` (False), ``save_directory`` (Windows %TEMP%/svkt;
77
+ POSIX <TMPDIR or /tmp>/svkt-<euid>, private),
78
+ ``save_max_files`` (50), ``save_max_bytes`` (2 GiB)
79
+
80
+ Returns True if started, False if already active (also when called from a
81
+ signal handler while this thread is inside init() or shutdown()). Raises
82
+ ValueError / TypeError on invalid options.
83
+ """
84
+ try:
85
+ return _init_lock.run(_init_locked, process_name, port, options)
86
+ except _core._Reentrant:
87
+ return False
88
+
89
+
90
+ def _init_locked(process_name, port, options):
91
+ global _atexit_registered
92
+ if _core._tracer is not None:
93
+ return False
94
+ cfg = Config(process_name=process_name, port=port, **options)
95
+ tr = _core.Tracer(cfg)
96
+ listener, bound_port = None, 0
97
+ if cfg.enable_server:
98
+ from ._server import bind_listener
99
+ listener, bound_port = bind_listener(cfg)
100
+ announcer = None
101
+ if cfg.enable_server and cfg.enable_discovery and listener is not None:
102
+ from ._discovery import Announcer
103
+ try:
104
+ listen_address = listener.getsockname()[0]
105
+ except OSError:
106
+ listen_address = None
107
+ # Announced only where the listener listens (PROTOCOL 7.1).
108
+ announcer = Announcer(tr, listen_address)
109
+ from ._server import Server
110
+ srv = Server(tr, listener, bound_port, announcer)
111
+ tr.server = srv
112
+ _core._set_tracer(tr)
113
+ srv.start()
114
+ if cfg.install_atexit and not _atexit_registered:
115
+ atexit.register(_atexit_shutdown)
116
+ _atexit_registered = True
117
+ return True
118
+
119
+
120
+ def _atexit_shutdown():
121
+ try:
122
+ shutdown()
123
+ except Exception: # noqa: BLE001
124
+ pass
125
+
126
+
127
+ def shutdown(timeout=5.0):
128
+ """Stops recording and the server thread (a connected consumer receives the
129
+ remaining live data and Goodbye); removes the registry file.
130
+
131
+ Called from a signal handler while this thread is already inside
132
+ shutdown() (or init()), it returns at once: the outer call finishes."""
133
+ try:
134
+ _init_lock.run(_shutdown_locked, timeout)
135
+ except _core._Reentrant:
136
+ pass
137
+
138
+
139
+ def _shutdown_locked(timeout):
140
+ tr = _core._tracer
141
+ if tr is None:
142
+ return
143
+ _core._set_tracer(None)
144
+ tr.active = False
145
+ if tr.server is not None:
146
+ tr.server.stop(timeout)
147
+
148
+
149
+ def is_active():
150
+ return _core._tracer is not None
151
+
152
+
153
+ def port():
154
+ """The TCP port the server listens on (0 if not listening / not active)."""
155
+ tr = _core._tracer
156
+ if tr is None or tr.server is None:
157
+ return 0
158
+ return tr.server.port
159
+
160
+
161
+ def stats():
162
+ """Counters (events written/demoted/discarded/streamed/dropped, tier fill, ...)."""
163
+ tr = _core._tracer
164
+ if tr is None:
165
+ return {}
166
+ return tr.stats()
167
+
168
+
169
+ def _require():
170
+ tr = _core._tracer
171
+ if tr is None:
172
+ raise RuntimeError("svkt is not initialised (call svkt.init() first)")
173
+ return tr
174
+
175
+
176
+ def save(path=None):
177
+ """Saves all retained data (all tiers, open zones, clock log) as a native
178
+ ``.svkt`` file. Without ``path`` a name ``<process>_<pid>_<UTC time>.svkt``
179
+ in the save directory is used. Runs on the calling thread. Returns the path."""
180
+ from ._save import default_save_directory, prepare_save_directory, save_file_name, save_to_path
181
+ tr = _require()
182
+ if path is not None:
183
+ return save_to_path(tr, path, P.SAVE_NATIVE)
184
+ # Default name: created exclusively, never overwriting an earlier save
185
+ # (a numeric tag is added when two saves fall into the same second).
186
+ d = tr.cfg.save_directory or default_save_directory()
187
+ prepare_save_directory(d, not tr.cfg.save_directory)
188
+ when = time.time()
189
+ for i in range(1000):
190
+ name = save_file_name(tr.process_name, tr.pid, str(i) if i else "", P.SAVE_NATIVE, when)
191
+ try:
192
+ return save_to_path(tr, os.path.join(d, name), P.SAVE_NATIVE, exclusive=True)
193
+ except FileExistsError:
194
+ continue
195
+ raise FileExistsError("no free save file name in %s" % d)
196
+
197
+
198
+ def export_chrome_json(path):
199
+ """Exports all retained data as Chrome Trace Event JSON (Perfetto UI,
200
+ chrome://tracing). Returns the path."""
201
+ from ._save import save_to_path
202
+ tr = _require()
203
+ return save_to_path(tr, path, P.SAVE_CHROME_JSON)
204
+
205
+
206
+ def _after_fork_in_child():
207
+ # The child has no server thread and possibly a lock held by a thread that
208
+ # does not exist there: tracing is off in the child until init() is called.
209
+ # The child's copies of the parent's sockets are closed (no traffic), so a
210
+ # long-lived child does not keep the parent's port listening.
211
+ # set_system_info() entries stay (process state); only their lock is renewed.
212
+ global _init_lock
213
+ _init_lock = _core._TracerLock()
214
+ _sysinfo._after_fork_in_child()
215
+ tr = _core._tracer
216
+ _core._set_tracer(None)
217
+ srv = getattr(tr, "server", None)
218
+ if srv is not None:
219
+ try:
220
+ srv.close_fds_after_fork()
221
+ except Exception: # noqa: BLE001 - never break the child's fork
222
+ pass
223
+
224
+
225
+ if hasattr(os, "register_at_fork"):
226
+ os.register_at_fork(after_in_child=_after_fork_in_child)
svkt/_clock.py ADDED
@@ -0,0 +1,237 @@
1
+ """Timestamps, clock samples, the retained clock log and clock_domain_id.
2
+
3
+ Ticks are ``time.perf_counter_ns()`` (PROTOCOL 2.1: QPC on Windows with the
4
+ exact integer formula, CLOCK_MONOTONIC on Linux) and ``ns_per_tick == 1.0``.
5
+ ``monotonic_ns = ticks + MONO_OFFSET``; ``MONO_OFFSET`` is 0 except on Windows
6
+ with Python < 3.10, where ``perf_counter_ns()`` counts from interpreter start
7
+ (CPython subtracts the QPC value it read first) instead of being system-wide:
8
+ there the offset back to the system-wide QPC clock is measured once at import
9
+ (:func:`_windows_qpc_offset`), so ClockSync, Pong, ``clock_domain_id`` and the
10
+ Chrome export report the system-wide clock while the recording path keeps
11
+ calling ``perf_counter_ns`` directly.
12
+ """
13
+
14
+ import collections
15
+ import sys
16
+ import time
17
+
18
+ from ._lock import _TracerLock
19
+
20
+ now = time.perf_counter_ns
21
+
22
+
23
+ def _windows_qpc_offset(trials=200):
24
+ """System-wide QPC ns minus ``perf_counter_ns()`` (Windows, Python < 3.10).
25
+
26
+ QPC ns use the PROTOCOL 2.1 integer formula. Each trial reads QPC, then
27
+ ``perf_counter_ns``, then QPC again; the offset lies inside every trial's
28
+ interval [lo, hi], so it lies in the intersection of all of them, which is
29
+ at most as wide as the narrowest bracket. The midpoint is returned; when
30
+ the QPC period is a whole number of ns (1e9 % f == 0, e.g. 10 MHz) the
31
+ offset is a multiple of the period and the midpoint is rounded to one
32
+ (still inside the intersection, whose ends are multiples too).
33
+
34
+ Not exact, and no exact method exists: CPython 3.8 / 3.9 compute
35
+ ``perf_counter_ns = muldiv(QPC - t0, 1e9, f)`` with t0, the QPC value read
36
+ at interpreter start, kept in a private C static, so the offset (t0 x the
37
+ period at 10 MHz) can only be bracketed, and a bracket of two ctypes QPC
38
+ calls is wider than one QPC period. Bound: the error is at most the
39
+ distance to the farther end of the intersection, about half its width
40
+ rounded up to one QPC period. Measured on a 10 MHz QPC: intersections 200
41
+ to 300 ns wide on 3.8, so the error is at most 200 ns (in practice 0 or
42
+ one period, varying from process to process). Python 3.8 / 3.9 events can
43
+ thus be up to that far off against other processes on the host.
44
+ Returns None if QPC cannot be read."""
45
+ import ctypes
46
+ k32 = ctypes.WinDLL("kernel32")
47
+ freq = ctypes.c_int64()
48
+ if not k32.QueryPerformanceFrequency(ctypes.byref(freq)) or freq.value <= 0:
49
+ return None
50
+ f = freq.value
51
+ c = ctypes.c_int64()
52
+ ref = ctypes.byref(c)
53
+ qpc = k32.QueryPerformanceCounter
54
+ pc = time.perf_counter_ns
55
+ lo = hi = None
56
+ for _ in range(trials):
57
+ qpc(ref)
58
+ c1 = c.value
59
+ p = pc()
60
+ qpc(ref)
61
+ c2 = c.value
62
+ a = (c1 // f) * 1_000_000_000 + (c1 % f) * 1_000_000_000 // f - p
63
+ b = (c2 // f) * 1_000_000_000 + (c2 % f) * 1_000_000_000 // f - p
64
+ lo = a if lo is None else max(lo, a)
65
+ hi = b if hi is None else min(hi, b)
66
+ if lo > hi: # only possible through +-1 ns conversion rounding
67
+ lo, hi = hi, lo
68
+ off = (lo + hi) // 2
69
+ if 1_000_000_000 % f == 0:
70
+ period = 1_000_000_000 // f
71
+ off = (off + period // 2) // period * period
72
+ return off
73
+
74
+
75
+ # ticks + MONO_OFFSET == system-wide monotonic ns (PROTOCOL 2.1). MONO_OK is
76
+ # False if the offset is needed but could not be measured (then the clock
77
+ # domain is reported as unknown).
78
+ MONO_OFFSET = 0
79
+ MONO_OK = True
80
+ if sys.platform == "win32" and sys.version_info < (3, 10):
81
+ try:
82
+ _off = _windows_qpc_offset()
83
+ except (OSError, AttributeError, ImportError): # pragma: no cover
84
+ _off = None
85
+ if _off is None: # pragma: no cover
86
+ MONO_OK = False
87
+ else:
88
+ MONO_OFFSET = _off
89
+
90
+
91
+ def sample_interval_ns():
92
+ """Spacing of the retained and live clock samples (PROTOCOL 2.2). 1 s while
93
+ ticks are the monotonic clock (identity: consumers map events exactly
94
+ without waiting for a sample). 100 ms when they are not (``MONO_OFFSET !=
95
+ 0``: Windows, Python 3.8 / 3.9), as PROTOCOL 2.2 asks of such producers:
96
+ a live consumer holds events newer than the newest sample back until the
97
+ next one, so this bounds that wait to about 100 ms (the C++ reader's own
98
+ bound is 250 ms)."""
99
+ return 1_000_000_000 if MONO_OFFSET == 0 else 100_000_000
100
+
101
+
102
+ def sample():
103
+ """One tightly bracketed (ticks, monotonic_ns, realtime_ns) sample.
104
+
105
+ Takes the minimum-latency bracket of several ``tick, wall, tick`` reads and
106
+ uses the midpoint tick (PROTOCOL 2.2)."""
107
+ best = None
108
+ pc = time.perf_counter_ns
109
+ wall = time.time_ns
110
+ for _ in range(5):
111
+ a = pc()
112
+ r = wall()
113
+ b = pc()
114
+ if best is None or b - a < best[0]:
115
+ best = (b - a, (a + b) // 2, r)
116
+ mid = best[1]
117
+ return (mid, mid + MONO_OFFSET, best[2])
118
+
119
+
120
+ class ClockLog:
121
+ """Retained clock samples, independent of any consumer (PROTOCOL 2.2).
122
+
123
+ Keeps the init sample, one sample per :func:`sample_interval_ns` (1 s, or
124
+ 100 ms on Windows with Python 3.8 / 3.9) for the last 60 s and one per
125
+ minute in a 1024-entry ring. (Python ticks are the monotonic clock, or
126
+ differ from it by the constant MONO_OFFSET, so mapping is exact at any
127
+ spacing; the 100 ms spacing only shortens how long a live consumer holds
128
+ events back, see :func:`sample_interval_ns`.) Each new sample is also
129
+ streamed to the consumer. Maintained by the background thread via
130
+ :meth:`tick`; thread safe.
131
+
132
+ The lock is a ``_TracerLock`` (sections run through ``run``): saves take
133
+ it on the application's thread, so a signal handler that saves while the
134
+ same thread is inside a section gets ``_Reentrant`` instead of a deadlock,
135
+ and an asynchronous exception (Ctrl+C) never leaves it held, which would
136
+ stop the server thread at its next tick."""
137
+
138
+ def __init__(self, interval_ns=None):
139
+ self._lock = _TracerLock()
140
+ self.interval_ns = sample_interval_ns() if interval_ns is None else int(interval_ns)
141
+ self._init = sample()
142
+ self._seconds = collections.deque(maxlen=max(1, 60_000_000_000 // self.interval_ns))
143
+ self._minutes = collections.deque(maxlen=1024)
144
+ self._last_sec_tick = self._init[0]
145
+ self._last_min_tick = self._init[0]
146
+ self._latest = self._init
147
+
148
+ def tick(self, force=False):
149
+ """Takes a new sample if >= interval_ns passed since the last periodic
150
+ one (or force). Returns the new sample or None. A forced sample (for a
151
+ handshake or a save) is retained but does not move the periodic
152
+ schedule: the next periodic sample, the one streamed to the consumers
153
+ already connected, is still due interval_ns after the previous one, however
154
+ often forced samples are taken (PROTOCOL 2.2)."""
155
+ t = now()
156
+ if not force and t - self._last_sec_tick < self.interval_ns:
157
+ return None
158
+ s = sample()
159
+ self._lock.run(self._add, s, force)
160
+ return s
161
+
162
+ def _add(self, s, force):
163
+ self._seconds.append(s)
164
+ if not force:
165
+ self._last_sec_tick = s[0]
166
+ if s[0] - self._last_min_tick >= 60_000_000_000:
167
+ self._minutes.append(s)
168
+ self._last_min_tick = s[0]
169
+ self._latest = s
170
+
171
+ def latest(self):
172
+ return self._latest # one attribute load: atomic
173
+
174
+ def _items(self):
175
+ items = [self._init]
176
+ items.extend(self._minutes)
177
+ items.extend(self._seconds)
178
+ return items
179
+
180
+ def samples(self):
181
+ """All retained samples, sorted by ticks, without duplicates."""
182
+ items = self._lock.run(self._items)
183
+ seen = set()
184
+ out = []
185
+ for s in sorted(items):
186
+ if s[0] in seen:
187
+ continue
188
+ seen.add(s[0])
189
+ out.append(s)
190
+ return out
191
+
192
+ def to_realtime_ns(self, ticks):
193
+ """Maps ticks to wall clock ns using the nearest retained sample
194
+ (ns_per_tick == 1, so this is a pure offset)."""
195
+ best = None
196
+ for s in self.samples():
197
+ d = abs(s[0] - ticks)
198
+ if best is None or d < best[0]:
199
+ best = (d, s)
200
+ s = best[1]
201
+ return s[2] + (ticks - s[0])
202
+
203
+
204
+ def _windows_machine_guid():
205
+ try:
206
+ import winreg
207
+ except ImportError: # pragma: no cover - not Windows
208
+ return ""
209
+ for access in (winreg.KEY_READ | getattr(winreg, "KEY_WOW64_64KEY", 0), winreg.KEY_READ):
210
+ try:
211
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
212
+ r"SOFTWARE\Microsoft\Cryptography", 0, access) as k:
213
+ value, _ = winreg.QueryValueEx(k, "MachineGuid")
214
+ return str(value)
215
+ except OSError:
216
+ continue
217
+ return ""
218
+
219
+
220
+ def clock_domain_id():
221
+ """PROTOCOL 2.3: Linux boot_id; Windows ``MachineGuid + "-" + boot time``
222
+ where boot time = (realtime_ns - monotonic_ns) rounded to seconds (decimal).
223
+ Empty if unknown."""
224
+ try:
225
+ if sys.platform.startswith("linux"):
226
+ with open("/proc/sys/kernel/random/boot_id", "r", encoding="ascii") as f:
227
+ return f.read().strip()
228
+ if sys.platform == "win32":
229
+ guid = _windows_machine_guid()
230
+ if not guid or not MONO_OK:
231
+ return ""
232
+ _, mono, real = sample()
233
+ boot_s = (real - mono + 500_000_000) // 1_000_000_000
234
+ return "%s-%d" % (guid, boot_s)
235
+ except OSError:
236
+ pass
237
+ return ""