ser2netweb 3.0.1__tar.gz → 3.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.
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/PKG-INFO +1 -1
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/THIRD-PARTY-NOTICES.md +3 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/pyproject.toml +3 -1
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/__init__.py +1 -1
- ser2netweb-3.1.0/ser2netweb/capture.py +189 -0
- ser2netweb-3.1.0/ser2netweb/certwatch.py +259 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/cli.py +4 -2
- ser2netweb-3.1.0/ser2netweb/clockwatch.py +158 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/config.py +632 -18
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/access.py +34 -9
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/bridge.py +569 -92
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/modbus_gateway.py +357 -11
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/mqtt_pub.py +189 -37
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/netguard.py +1 -1
- ser2netweb-3.1.0/ser2netweb/engine/pool.py +217 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/serial_compat.py +27 -2
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/sparkplug_node.py +26 -3
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/supervisor.py +56 -1
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/importer.py +28 -6
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/layout.py +83 -22
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/locale/tr.json +176 -4
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/notify.py +97 -23
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/optional.py +23 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/reload.py +1 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/ser2net_import.py +364 -41
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/state.py +23 -1
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/api.py +452 -18
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/cluster.py +6 -5
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/forms.py +99 -11
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/mappings.py +118 -20
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/ops.py +62 -5
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/settings.py +75 -2
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/system.py +16 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/server.py +4 -2
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/static/app.js +47 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/static/points.js +38 -8
- ser2netweb-3.1.0/ser2netweb/web/static/xterm-addon-fit.js +2 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/static/xterm.css +71 -4
- ser2netweb-3.1.0/ser2netweb/web/static/xterm.js +2 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_mapping_form.html +82 -1
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_mapping_traces.html +14 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_mappings_body.html +15 -3
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/settings.html +49 -1
- ser2netweb-3.1.0/ser2netweb/web/tlsupload.py +250 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb.egg-info/PKG-INFO +1 -1
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb.egg-info/SOURCES.txt +5 -0
- ser2netweb-3.0.1/ser2netweb/web/static/xterm-addon-fit.js +0 -2
- ser2netweb-3.0.1/ser2netweb/web/static/xterm.js +0 -2
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/COMMERCIAL_LICENSE.md +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/LICENSE +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/MANIFEST.in +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/NOTICE +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/packaging/README.pypi.md +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/__main__.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/accounts.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/clock.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/console.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/datalock.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/__init__.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/bindhint.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/cluster.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/modbus.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/netinfo.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/portdiag.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/portlist.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/protocols/__init__.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/protocols/base.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/protocols/raw.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/protocols/rfc2217.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/protocols/telnet.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/serial_io.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/serial_link.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/serial_transport.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/sockopts.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/sparkplug.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/engine/tls.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/envvars.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/explain.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/healthcheck.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/i18n.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/licences.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/logsetup.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/logtext.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/runtime.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/sdnotify.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/signins.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/standalone.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/storage.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/textfold.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/tlsreload.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/watchdog.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/__init__.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/auth.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/certinfo.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/httpguard.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/ldap_auth.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/oidc_auth.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/proxy.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/__init__.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/common.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/console.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/login.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/routes/totp.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/selfsigned.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/starlette_compat.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/static/app.css +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/static/htmx.min.js +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/static/theme.js +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_cluster_body.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_console.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_footer.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_login_notice.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_macros.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_mapping_log.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_modbus_read.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_ports_table.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_serial_port_select.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/_shell.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/audit.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/base.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/dashboard.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/licenses.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/login.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/login_totp.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/setup.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/templates/totp.html +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/web/totp.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb/winservice.py +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb.egg-info/dependency_links.txt +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb.egg-info/entry_points.txt +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb.egg-info/requires.txt +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/ser2netweb.egg-info/top_level.txt +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/setup.cfg +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/tools/licenses/npm/htmx.org.txt +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/tools/licenses/npm/xterm-addon-fit.txt +0 -0
- {ser2netweb-3.0.1 → ser2netweb-3.1.0}/tools/licenses/npm/xterm.txt +0 -0
|
@@ -90,6 +90,9 @@ the files and their sha256, and the license texts are in `tools/licenses/npm/` (
|
|
|
90
90
|
| xterm.js (`xterm.js`, `xterm.css`) | `@xterm/xterm` | MIT |
|
|
91
91
|
| xterm.js fit addon (`xterm-addon-fit.js`) | `@xterm/addon-fit` | MIT |
|
|
92
92
|
|
|
93
|
+
xterm.js 6 includes parts of Visual Studio Code's base library (its scrollbar and event
|
|
94
|
+
code; Copyright (c) Microsoft Corporation), under the same MIT license.
|
|
95
|
+
|
|
93
96
|
## LGPL components
|
|
94
97
|
|
|
95
98
|
ldap3 is an LGPL library. ser2netweb uses it unmodified through its public API. The LGPL
|
|
@@ -115,8 +115,10 @@ include-package-data = false
|
|
|
115
115
|
[tool.setuptools.packages.find]
|
|
116
116
|
include = ["ser2netweb", "ser2netweb.*"]
|
|
117
117
|
|
|
118
|
+
# (distro.json: none in this repository or on PyPI; a distribution's recipe in packaging/
|
|
119
|
+
# writes it into ser2netweb/ before the build, ser2netweb/layout.py reads it)
|
|
118
120
|
[tool.setuptools.package-data]
|
|
119
|
-
ser2netweb = ["locale/*", "web/templates/*", "web/static/*"]
|
|
121
|
+
ser2netweb = ["locale/*", "web/templates/*", "web/static/*", "distro.json"]
|
|
120
122
|
|
|
121
123
|
# (named by its file: for "ser2netweb.__version__" setuptools would read ser2netweb.py, the
|
|
122
124
|
# start script beside the package; it reads the assignment without importing anything)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""ser2netweb — serial-to-network bridge with a web config UI."""
|
|
2
2
|
|
|
3
3
|
# Single source of truth for the version (ser2netweb.py and the web layer import this).
|
|
4
|
-
__version__ = "3.0
|
|
4
|
+
__version__ = "3.1.0"
|
|
5
5
|
|
|
6
6
|
# The product's name: up to 2.9.x it was ser2net (no relation to the C ser2net it can
|
|
7
7
|
# import the configuration of; NOTICE)
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Timed captures: trace a mapping's traffic for a while, then stop by itself.
|
|
2
|
+
|
|
3
|
+
An operator starts one in the mapping's Trace panel or with
|
|
4
|
+
POST /api/v1/mappings/{id}/capture (15 minutes, 1 hour, 24 hours; the REST API takes any
|
|
5
|
+
number of minutes up to CAPTURE_MAX_S). The mapping keeps its clients and its serial port:
|
|
6
|
+
only its trace writer is opened, and closed again at the end (Supervisor.retrace).
|
|
7
|
+
|
|
8
|
+
The end time is stored in the mapping's options (trace_until, Unix seconds), so a capture
|
|
9
|
+
goes on after a restart and ends on time; one whose time passed while ser2netweb was not
|
|
10
|
+
running ends before the mappings start. While this process runs the time left is counted
|
|
11
|
+
on the monotonic clock: a step of the system clock neither cuts a capture short nor keeps
|
|
12
|
+
it going. trace_until is no setting: the edits (the form, a REST POST / PUT / PATCH, an
|
|
13
|
+
import, a Copy) keep a mapping's own and give a new one none. However it was set anyway (by
|
|
14
|
+
hand in config.json, a restored backup), a capture never lasts longer than CAPTURE_MAX_S
|
|
15
|
+
from when this process first saw it.
|
|
16
|
+
|
|
17
|
+
Only a mapping whose trace is off can be captured: its traffic goes to
|
|
18
|
+
traces/<id>-capture.log. A mapping that traces already (a trace file name in its
|
|
19
|
+
options) is refused, and the end of a capture only clears trace_until - a trace that is
|
|
20
|
+
on for good is never turned off here.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import asyncio
|
|
25
|
+
import contextlib
|
|
26
|
+
import time
|
|
27
|
+
from typing import TYPE_CHECKING, Optional
|
|
28
|
+
|
|
29
|
+
from . import clock
|
|
30
|
+
from .config import CAPTURE_MAX_S, ConfigError
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from .state import AppState
|
|
34
|
+
|
|
35
|
+
CHECK_S = 1.0 # how often the ends are looked at
|
|
36
|
+
# what the Trace panel offers, in minutes
|
|
37
|
+
CHOICES_MIN = (15, 60, 24 * 60)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class CaptureRefused(Exception):
|
|
41
|
+
"""A capture that can't begin. `code`: "not_found" (no such mapping), "tracing" (its
|
|
42
|
+
trace is on already, by its trace file name) or "duration" (not 1 minute to
|
|
43
|
+
CAPTURE_MAX_S)."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, code: str) -> None:
|
|
46
|
+
super().__init__(code)
|
|
47
|
+
self.code = code
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def duration_text(seconds: float) -> str:
|
|
51
|
+
"""'15 min', '1 h', '24 h', '1 h 30 min' (English: the log and the audit log)."""
|
|
52
|
+
minutes = max(1, round(seconds / 60))
|
|
53
|
+
hours, rest = divmod(minutes, 60)
|
|
54
|
+
if hours and rest:
|
|
55
|
+
return f"{hours} h {rest} min"
|
|
56
|
+
return f"{hours} h" if hours else f"{rest} min"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Captures:
|
|
60
|
+
"""The timed captures of an AppState's mappings: begin(), end(), and the watcher that
|
|
61
|
+
ends each one at its time."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, state: "AppState") -> None:
|
|
64
|
+
self.state = state
|
|
65
|
+
# mapping id -> (the trace_until it was armed for, when on the monotonic clock, its
|
|
66
|
+
# length in seconds from then): what is left is the length minus the time passed
|
|
67
|
+
# since, so never more than the length (an end stored as start + length, read back
|
|
68
|
+
# as end - now, can round to a hair over it where the clock has not moved yet)
|
|
69
|
+
self._ends: dict[str, tuple[float, float, float]] = {}
|
|
70
|
+
self._task: Optional[asyncio.Task] = None
|
|
71
|
+
|
|
72
|
+
# ---------------- what the pages and the REST API ask ----------------
|
|
73
|
+
def left(self, mapping) -> Optional[float]:
|
|
74
|
+
"""The seconds a mapping's capture still runs, None when it has none."""
|
|
75
|
+
until = mapping.options.trace_until
|
|
76
|
+
if not until:
|
|
77
|
+
return None
|
|
78
|
+
start, length = self._arm(mapping.id, until)
|
|
79
|
+
return min(length, max(0.0, length - (time.monotonic() - start)))
|
|
80
|
+
|
|
81
|
+
def until(self, mapping) -> Optional[float]:
|
|
82
|
+
"""When a mapping's capture ends as the system clock reads now (Unix seconds),
|
|
83
|
+
None when it has none."""
|
|
84
|
+
left = self.left(mapping)
|
|
85
|
+
return None if left is None else time.time() + left
|
|
86
|
+
|
|
87
|
+
async def begin(self, mapping_id: str, seconds: float) -> float:
|
|
88
|
+
"""Capture the mapping's traffic for `seconds` from now (a capture under way gets
|
|
89
|
+
this as its new end). Returns the end (Unix seconds). Raises CaptureRefused, or
|
|
90
|
+
ConfigError when config.json can't be written (nothing changed then)."""
|
|
91
|
+
if not 60 <= seconds <= CAPTURE_MAX_S:
|
|
92
|
+
raise CaptureRefused("duration")
|
|
93
|
+
async with self.state.edit_config(backup=False):
|
|
94
|
+
m = self.state.config.get_mapping(mapping_id)
|
|
95
|
+
if m is None:
|
|
96
|
+
raise CaptureRefused("not_found")
|
|
97
|
+
if m.options.trace_both:
|
|
98
|
+
raise CaptureRefused("tracing")
|
|
99
|
+
until = m.options.trace_until = time.time() + seconds
|
|
100
|
+
self._ends[m.id] = (until, time.monotonic(), float(seconds))
|
|
101
|
+
await self.state.supervisor.retrace(mapping_id)
|
|
102
|
+
return until
|
|
103
|
+
|
|
104
|
+
async def end(self, mapping_id: str, until: Optional[float] = None) -> bool:
|
|
105
|
+
"""End the mapping's capture now. Returns whether it had one. Its trace is closed
|
|
106
|
+
(not one that is on by its trace file name) even when config.json can't be
|
|
107
|
+
written: ConfigError is raised then, and the next start ends it for good.
|
|
108
|
+
`until`: the end the watcher found due; a capture begun again meanwhile (another
|
|
109
|
+
end) is left alone, and False returned."""
|
|
110
|
+
try:
|
|
111
|
+
async with self.state.edit_config(backup=False, keep_on_failure=True):
|
|
112
|
+
m = self.state.config.get_mapping(mapping_id)
|
|
113
|
+
if m is None or not m.options.trace_until:
|
|
114
|
+
self._ends.pop(mapping_id, None)
|
|
115
|
+
return False
|
|
116
|
+
if until is not None and m.options.trace_until != until:
|
|
117
|
+
return False # (extended while this waited for the configuration)
|
|
118
|
+
self._ends.pop(mapping_id, None)
|
|
119
|
+
m.options.trace_until = 0.0
|
|
120
|
+
finally:
|
|
121
|
+
await self.state.supervisor.retrace(mapping_id)
|
|
122
|
+
return True
|
|
123
|
+
|
|
124
|
+
# ---------------- the watcher ----------------
|
|
125
|
+
async def end_overdue(self) -> None:
|
|
126
|
+
"""Before the mappings start: end the captures whose time passed while ser2netweb
|
|
127
|
+
was not running, so that none of them is traced again."""
|
|
128
|
+
now = time.time()
|
|
129
|
+
for m in list(self.state.config.mappings):
|
|
130
|
+
until = m.options.trace_until
|
|
131
|
+
if until and until <= now:
|
|
132
|
+
await self._expire(m, "its time passed while ser2netweb was not running")
|
|
133
|
+
|
|
134
|
+
async def start(self) -> None:
|
|
135
|
+
self._task = asyncio.create_task(self._watch(), name="capture-watch")
|
|
136
|
+
|
|
137
|
+
async def stop(self) -> None:
|
|
138
|
+
task, self._task = self._task, None
|
|
139
|
+
if task is not None:
|
|
140
|
+
task.cancel()
|
|
141
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
142
|
+
await task
|
|
143
|
+
|
|
144
|
+
def _arm(self, mapping_id: str, until: float) -> tuple[float, float]:
|
|
145
|
+
"""When a capture's time began on the monotonic clock and how long it is: from the
|
|
146
|
+
first time this process sees its trace_until, at most CAPTURE_MAX_S."""
|
|
147
|
+
armed = self._ends.get(mapping_id)
|
|
148
|
+
if armed is None or armed[0] != until:
|
|
149
|
+
length = min(max(until - time.time(), 0.0), float(CAPTURE_MAX_S))
|
|
150
|
+
armed = self._ends[mapping_id] = (until, time.monotonic(), length)
|
|
151
|
+
return armed[1], armed[2]
|
|
152
|
+
|
|
153
|
+
async def check(self) -> None:
|
|
154
|
+
"""End the captures whose time has come (the watcher's step)."""
|
|
155
|
+
seen = set()
|
|
156
|
+
for m in list(self.state.config.mappings):
|
|
157
|
+
until = m.options.trace_until
|
|
158
|
+
if not until:
|
|
159
|
+
continue
|
|
160
|
+
seen.add(m.id)
|
|
161
|
+
if not self.left(m):
|
|
162
|
+
await self._expire(m, "")
|
|
163
|
+
for gone in [mid for mid in self._ends if mid not in seen]:
|
|
164
|
+
del self._ends[gone]
|
|
165
|
+
|
|
166
|
+
async def _expire(self, mapping, why: str) -> None:
|
|
167
|
+
name = mapping.name
|
|
168
|
+
try:
|
|
169
|
+
ended = await self.end(mapping.id, until=mapping.options.trace_until)
|
|
170
|
+
except ConfigError as e:
|
|
171
|
+
self.state.log(f"[{name}] timed capture ended, but config.json could not keep "
|
|
172
|
+
f"that ({e}): it ends again at the next start")
|
|
173
|
+
ended = True
|
|
174
|
+
if ended:
|
|
175
|
+
self.state.log(f"[{name}] timed capture ended" + (f": {why}" if why else ""))
|
|
176
|
+
self.state.audit("local", "trace_capture_end", name)
|
|
177
|
+
|
|
178
|
+
async def _watch(self) -> None:
|
|
179
|
+
while True:
|
|
180
|
+
await asyncio.sleep(CHECK_S)
|
|
181
|
+
try:
|
|
182
|
+
await self.check()
|
|
183
|
+
except Exception as e: # never let the watcher die
|
|
184
|
+
self.state.log(f"timed captures: watcher error: {e}")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def describe(until: float, seconds: float) -> str:
|
|
188
|
+
"""'15 min, until 2026-11-13 12:15:00+03:00' for the log and the audit log."""
|
|
189
|
+
return f"{duration_text(seconds)}, until {clock.stamp(until)}"
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""TLS certificates about to end: the admin UI's and each enabled TLS mapping's.
|
|
2
|
+
|
|
3
|
+
Once a day (and once soon after the start) the notifier reads the certificate files in
|
|
4
|
+
use with web/certinfo.py. A certificate that has fewer than 30, 7 or 1 days left, or has
|
|
5
|
+
ended, is logged with a WARNING and — with the optional cert_expiring event on — sent as a
|
|
6
|
+
notification: once per certificate and threshold and channel, also across restarts
|
|
7
|
+
(what was sent is kept in cert-notices.json in the data folder once a channel took it,
|
|
8
|
+
with the channels that did not, which get it at the next check, and only they; what was
|
|
9
|
+
sent for a certificate is kept while it can't be read, while its mapping is disabled or
|
|
10
|
+
the admin UI's TLS is off, and is forgotten when the certificate is renewed (another end
|
|
11
|
+
date at its path) or its mapping is deleted). What was read last is also what /metrics
|
|
12
|
+
(ser2net_tls_certificate_expiry_seconds) and GET /api/v1/status (certificates) answer.
|
|
13
|
+
|
|
14
|
+
Only reads the files; renewing one is the operator's (or certbot's), followed by a reload
|
|
15
|
+
of the configuration or a new upload in Settings.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import dataclasses
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
from typing import Any, Optional
|
|
26
|
+
|
|
27
|
+
from .web import certinfo
|
|
28
|
+
|
|
29
|
+
THRESHOLD_DAYS = (30, 7, 1) # a notification when fewer days than each are left ...
|
|
30
|
+
EXPIRED = 0 # ... and one once the certificate has ended
|
|
31
|
+
CHECK_S = 86400.0 # how often the notifier looks
|
|
32
|
+
FRESH_S = 300.0 # /metrics and the status read the files again after this
|
|
33
|
+
NOTICES_FILE = "cert-notices.json"
|
|
34
|
+
_lock = threading.Lock()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclasses.dataclass
|
|
38
|
+
class Certificate:
|
|
39
|
+
"""A certificate file in use. `key`: "admin" or the mapping's id; `mapping`: the
|
|
40
|
+
mapping's name ("" for the admin UI); `info`: what the file says (None: `problem`
|
|
41
|
+
says why it could not be read)."""
|
|
42
|
+
key: str
|
|
43
|
+
mapping: str
|
|
44
|
+
path: str
|
|
45
|
+
info: Optional[certinfo.CertInfo] = None
|
|
46
|
+
problem: str = ""
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def label(self) -> str:
|
|
50
|
+
"""Whose it is, for the log and the message (English)."""
|
|
51
|
+
return f"mapping {self.mapping!r}" if self.mapping else "admin UI"
|
|
52
|
+
|
|
53
|
+
def view(self, now: Optional[float] = None) -> dict[str, Any]:
|
|
54
|
+
"""As GET /api/v1/status lists it."""
|
|
55
|
+
out: dict[str, Any] = {"use": "mapping" if self.mapping else "admin", "path": self.path}
|
|
56
|
+
if self.mapping:
|
|
57
|
+
out.update(id=self.key, mapping=self.mapping)
|
|
58
|
+
if self.info is None:
|
|
59
|
+
return {**out, "state": "unreadable", "detail": self.problem}
|
|
60
|
+
return {**out, "subject": self.info.subject, "not_after": self.info.not_after,
|
|
61
|
+
"days_left": self.info.days_left(now), "state": self.info.state(now)}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def in_use(config) -> list[Certificate]:
|
|
65
|
+
"""The certificate files the configuration uses now: the admin UI's (when its TLS is
|
|
66
|
+
on) and each enabled TLS mapping's (a listener's certificate, or the client
|
|
67
|
+
certificate of a connect-out mapping)."""
|
|
68
|
+
out = []
|
|
69
|
+
admin = config.admin_ui
|
|
70
|
+
if admin.tls_enabled:
|
|
71
|
+
out.append(Certificate("admin", "", admin.tls_cert))
|
|
72
|
+
for m in config.mappings:
|
|
73
|
+
net = m.network
|
|
74
|
+
if m.enabled and m.kind == "net" and net.tls and net.mode != "udp" and net.tls_cert:
|
|
75
|
+
out.append(Certificate(m.id, m.name, net.tls_cert))
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def read_all(certificates: list[Certificate]) -> list[Certificate]:
|
|
80
|
+
"""Read each certificate's file (blocking)."""
|
|
81
|
+
for c in certificates:
|
|
82
|
+
try:
|
|
83
|
+
c.info = certinfo.read(c.path)
|
|
84
|
+
except certinfo.CertReadError as e:
|
|
85
|
+
c.problem = "no PEM certificate in it" if e.code == "not_pem" else str(e)
|
|
86
|
+
return certificates
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def threshold(info: certinfo.CertInfo, now: float) -> Optional[int]:
|
|
90
|
+
"""The tightest threshold the certificate is past: EXPIRED, else the smallest of
|
|
91
|
+
THRESHOLD_DAYS it has fewer days left than; None while it has more than them all."""
|
|
92
|
+
left = info.not_after - now
|
|
93
|
+
if left < 0:
|
|
94
|
+
return EXPIRED
|
|
95
|
+
reached = [d for d in THRESHOLD_DAYS if left < d * 86400]
|
|
96
|
+
return min(reached) if reached else None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def message(c: Certificate, info: certinfo.CertInfo, now: float) -> str:
|
|
100
|
+
"""The notification's detail and the log line: whose certificate, which file, what it
|
|
101
|
+
says."""
|
|
102
|
+
return f"{c.label} certificate {c.path}: {info.describe(now)}"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def load_notices(path: str) -> dict[str, list]:
|
|
106
|
+
"""What was sent already: "<key>|<path>" -> [not_after, threshold], and a third item,
|
|
107
|
+
the channels that did not take that threshold's notice yet (notify.CHANNELS), when
|
|
108
|
+
there are any. {} when the file is missing or makes no sense (everything is then
|
|
109
|
+
sent once more); an entry that makes no sense is left out."""
|
|
110
|
+
try:
|
|
111
|
+
with open(path, encoding="utf-8") as fh:
|
|
112
|
+
data = json.load(fh)
|
|
113
|
+
except (OSError, ValueError):
|
|
114
|
+
return {}
|
|
115
|
+
if not isinstance(data, dict):
|
|
116
|
+
return {}
|
|
117
|
+
return {k: v for k, v in data.items() if _record(v)}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _record(v: Any) -> bool:
|
|
121
|
+
return (isinstance(v, list) and len(v) in (2, 3)
|
|
122
|
+
and all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in v[:2])
|
|
123
|
+
and (len(v) == 2 or isinstance(v[2], list)
|
|
124
|
+
and all(isinstance(c, str) for c in v[2])))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def kept_unused(notices: dict[str, list], used: set[str], config) -> dict[str, list]:
|
|
128
|
+
"""The records ("<key>|<path>") of certificates not in use now that stay: a disabled
|
|
129
|
+
mapping's, the admin UI's with its TLS off, one a mapping no longer names. Forgotten
|
|
130
|
+
are those of a deleted mapping and those whose file now holds another certificate
|
|
131
|
+
(renewed: another end date); one that can't be read stays. Blocking (reads them)."""
|
|
132
|
+
out = {}
|
|
133
|
+
for name, record in notices.items():
|
|
134
|
+
if name in used:
|
|
135
|
+
continue
|
|
136
|
+
key, _sep, path = name.partition("|")
|
|
137
|
+
if key != "admin" and config.get_mapping(key) is None:
|
|
138
|
+
continue
|
|
139
|
+
try:
|
|
140
|
+
if certinfo.read(path).not_after != record[0]:
|
|
141
|
+
continue
|
|
142
|
+
except certinfo.CertReadError:
|
|
143
|
+
pass
|
|
144
|
+
out[name] = record
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def save_notices(path: str, notices: dict[str, list]) -> None:
|
|
149
|
+
"""Rewrite the file whole (a temporary file renamed over it). Raises OSError."""
|
|
150
|
+
with _lock:
|
|
151
|
+
_write_notices(path, notices)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def note_sent(path: str, name: str, record: list) -> None:
|
|
155
|
+
"""Remember one notice that went out ("<key>|<path>" -> [not_after, threshold]), next
|
|
156
|
+
to what the file holds. Raises OSError."""
|
|
157
|
+
with _lock:
|
|
158
|
+
notices = load_notices(path)
|
|
159
|
+
notices[name] = record
|
|
160
|
+
_write_notices(path, notices)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _write_notices(path: str, notices: dict[str, list]) -> None:
|
|
164
|
+
tmp = path + ".tmp"
|
|
165
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
166
|
+
fh.write(json.dumps(notices, sort_keys=True) + "\n")
|
|
167
|
+
fh.flush()
|
|
168
|
+
os.fsync(fh.fileno())
|
|
169
|
+
os.replace(tmp, path)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class CertWatch:
|
|
173
|
+
"""The certificates in use as last read, and which thresholds were said already."""
|
|
174
|
+
|
|
175
|
+
def __init__(self, state) -> None:
|
|
176
|
+
self.state = state
|
|
177
|
+
self._read: list[Certificate] = []
|
|
178
|
+
self._read_at: Optional[float] = None # time.monotonic() of the last read
|
|
179
|
+
self._logged: dict[str, tuple] = {} # key -> (not_after, threshold) logged
|
|
180
|
+
self._save_failed = False # logged once
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def notices_path(self) -> str:
|
|
184
|
+
return os.path.join(self.state.data_dir, NOTICES_FILE)
|
|
185
|
+
|
|
186
|
+
async def current(self, max_age: float = FRESH_S) -> list[Certificate]:
|
|
187
|
+
"""The certificates in use, read again when the last read is older than
|
|
188
|
+
`max_age` seconds."""
|
|
189
|
+
now = time.monotonic()
|
|
190
|
+
if self._read_at is None or now - self._read_at >= max_age:
|
|
191
|
+
self._read = await asyncio.to_thread(read_all, in_use(self.state.config))
|
|
192
|
+
self._read_at = now
|
|
193
|
+
return self._read
|
|
194
|
+
|
|
195
|
+
async def check(self, emit, now: Optional[float] = None) -> int:
|
|
196
|
+
"""Read the certificates and say which are past a threshold they were not said to
|
|
197
|
+
be past yet: a WARNING in the log (once per run and threshold), and
|
|
198
|
+
emit("cert_expiring", key, mapping name, detail, sent=..., channels=...) -> bool for
|
|
199
|
+
a notification, to every channel (channels None) or to those that did not take
|
|
200
|
+
that threshold's notice before; remembered in cert-notices.json once a channel
|
|
201
|
+
took it, with those that did not (Notifier.emit's sent). Returns how many were
|
|
202
|
+
queued."""
|
|
203
|
+
now = time.time() if now is None else now
|
|
204
|
+
certificates = await self.current(max_age=0)
|
|
205
|
+
notices = await asyncio.to_thread(load_notices, self.notices_path)
|
|
206
|
+
used = {f"{c.key}|{c.path}" for c in certificates}
|
|
207
|
+
kept = await asyncio.to_thread(kept_unused, notices, used, self.state.config)
|
|
208
|
+
due: list[tuple[Certificate, str, list, str, Optional[list[str]]]] = []
|
|
209
|
+
for c in certificates:
|
|
210
|
+
name = f"{c.key}|{c.path}"
|
|
211
|
+
if c.info is None: # (being replaced, say): what was sent for it stays said
|
|
212
|
+
if name in notices:
|
|
213
|
+
kept[name] = notices[name]
|
|
214
|
+
continue
|
|
215
|
+
if name in notices and notices[name][0] == c.info.not_after:
|
|
216
|
+
kept[name] = notices[name]
|
|
217
|
+
reached = threshold(c.info, now)
|
|
218
|
+
if reached is None:
|
|
219
|
+
continue
|
|
220
|
+
text = message(c, c.info, now)
|
|
221
|
+
if self._logged.get(name) != (c.info.not_after, reached):
|
|
222
|
+
self._logged[name] = (c.info.not_after, reached)
|
|
223
|
+
self.state.log(f"WARNING: TLS certificate: {text}")
|
|
224
|
+
before = kept.get(name)
|
|
225
|
+
if before is None or before[1] > reached: # (else said for it, or a tighter one)
|
|
226
|
+
due.append((c, name, [c.info.not_after, reached], text, None))
|
|
227
|
+
elif before[1] == reached and len(before) > 2 and before[2]:
|
|
228
|
+
# said, but not on every channel: to those it did not reach, and only them
|
|
229
|
+
due.append((c, name, [c.info.not_after, reached], text, list(before[2])))
|
|
230
|
+
# (first: a notice that is sent meanwhile is added to what this keeps)
|
|
231
|
+
if kept != notices: # (renewed certificates, deleted mappings: forgotten)
|
|
232
|
+
await self._save(save_notices, kept)
|
|
233
|
+
sent = 0
|
|
234
|
+
for c, name, record, text, channels in due:
|
|
235
|
+
if emit("cert_expiring", f"{name}|{record[1]}", c.mapping, text,
|
|
236
|
+
sent=self._remember(name, record), channels=channels):
|
|
237
|
+
sent += 1
|
|
238
|
+
return sent
|
|
239
|
+
|
|
240
|
+
def _remember(self, name: str, record: list):
|
|
241
|
+
"""What Notifier.emit awaits once the notice was tried: once a channel took it
|
|
242
|
+
(or there was none to try), keep it as sent, with the channels that did not."""
|
|
243
|
+
async def sent(tried: list[str], failed: list[str]) -> None:
|
|
244
|
+
if tried and set(failed) >= set(tried):
|
|
245
|
+
return # nobody got it: the next check tries again (what was kept stays)
|
|
246
|
+
missed = sorted(set(failed))
|
|
247
|
+
await self._save(note_sent, name, record + ([missed] if missed else []))
|
|
248
|
+
return sent
|
|
249
|
+
|
|
250
|
+
async def _save(self, write, *args) -> None:
|
|
251
|
+
try:
|
|
252
|
+
await asyncio.to_thread(write, self.notices_path, *args)
|
|
253
|
+
self._save_failed = False
|
|
254
|
+
except OSError as e:
|
|
255
|
+
if not self._save_failed:
|
|
256
|
+
self._save_failed = True
|
|
257
|
+
self.state.log(f"TLS certificate notices: {NOTICES_FILE} could not be "
|
|
258
|
+
f"written ({e.strerror or e}): a notification may be sent "
|
|
259
|
+
"again after a restart")
|
|
@@ -51,7 +51,9 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
|
51
51
|
default=None, # see below: whether it was given matters to --install-service
|
|
52
52
|
help="Directory for config.json, its backups, the logs and traces (default: data/ "
|
|
53
53
|
"next to ser2netweb.py or the executable (Scoop's: in its persist folder); "
|
|
54
|
-
"/var/lib/ser2netweb for the .deb / .rpm / AUR package's; the
|
|
54
|
+
"/var/lib/ser2netweb for the .deb / .rpm / AUR package's; the data directory of "
|
|
55
|
+
"its service for a distribution's package built from ser2netweb's recipes; the "
|
|
56
|
+
"user's application "
|
|
55
57
|
"data folder for a pip / pipx, winget or Chocolatey install; "
|
|
56
58
|
"$(brew --prefix)/var/ser2netweb for the Homebrew formula's; "
|
|
57
59
|
"/var/snap/ser2netweb/common/data for the snap's as root; here: "
|
|
@@ -236,7 +238,7 @@ def print_about() -> int:
|
|
|
236
238
|
f"Python {platform.python_version()} ({platform.python_implementation()}), "
|
|
237
239
|
f"{ssl.OPENSSL_VERSION}",
|
|
238
240
|
f"Platform: {platform.platform()} ({platform.machine()})",
|
|
239
|
-
f"Build: {layout.
|
|
241
|
+
f"Build: {layout.label()}"]
|
|
240
242
|
components = (("pyserial", "serial"), ("pyserial-asyncio-fast", "serial_asyncio_fast"),
|
|
241
243
|
("starlette", "starlette"), ("uvicorn", "uvicorn"), ("anyio", "anyio"),
|
|
242
244
|
("psutil", "psutil"), ("paho-mqtt", "paho.mqtt"), ("ldap3", "ldap3"), ("pyasn1", "pyasn1"),
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Notice when the system clock is stepped while ser2netweb runs.
|
|
2
|
+
|
|
3
|
+
A clock that is set (by hand, by time sync catching up after a boot without an RTC, by a
|
|
4
|
+
virtual machine host) puts a jump into the times of all.log, audit.log, the mapping logs
|
|
5
|
+
and the traces: lines out of order, an hour that seems to be missing. ser2netweb never
|
|
6
|
+
sets the clock (see clock.py) and measures durations on the monotonic clock, so nothing
|
|
7
|
+
breaks - but whoever reads those files later should know where the jump is.
|
|
8
|
+
|
|
9
|
+
Every CHECK_S seconds the wall clock is compared with a clock no step changes: how much
|
|
10
|
+
further (or less far) the wall clock went than that one since the last look is the step.
|
|
11
|
+
On Linux that clock is CLOCK_BOOTTIME, which counts the time a suspended machine sleeps,
|
|
12
|
+
so a resume is not a step; macOS and the BSDs have a CLOCK_MONOTONIC that does the same.
|
|
13
|
+
On Windows it is GetTickCount64, which counts sleep and hibernation too: Python's
|
|
14
|
+
monotonic clock is QueryPerformanceCounter there since 3.13, which stops while the machine
|
|
15
|
+
is suspended, so every resume would look like a step forward. NTP's slewing changes both
|
|
16
|
+
clocks alike (or by far less than STEP_MIN_S) and is never reported.
|
|
17
|
+
|
|
18
|
+
A step of STEP_MIN_S or more
|
|
19
|
+
- is counted (ser2net_clock_steps_total in /metrics, clock_steps in /api/v1/status);
|
|
20
|
+
- is written to all.log and recorded in the audit log (clock_step), at most once per
|
|
21
|
+
REPORT_EVERY_S (the next line says how many were held back);
|
|
22
|
+
- is noted in every running trace with a "!!" line, where the times jump;
|
|
23
|
+
- sends the optional clock_step notification.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import contextlib
|
|
29
|
+
import functools
|
|
30
|
+
import sys
|
|
31
|
+
import time
|
|
32
|
+
from typing import Callable, Optional
|
|
33
|
+
|
|
34
|
+
from . import clock
|
|
35
|
+
|
|
36
|
+
CHECK_S = 5.0 # how often the clocks are compared
|
|
37
|
+
STEP_MIN_S = 1.0 # a smaller difference is not reported (the files' times are seconds)
|
|
38
|
+
REPORT_EVERY_S = 60.0 # the log line and the audit record: at most this often
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _tick_count() -> Optional[Callable[[], float]]:
|
|
42
|
+
"""Windows: GetTickCount64 in seconds (the milliseconds since the start, sleep and
|
|
43
|
+
hibernation included); None elsewhere or when it can't be had."""
|
|
44
|
+
if sys.platform != "win32":
|
|
45
|
+
return None
|
|
46
|
+
import ctypes
|
|
47
|
+
try:
|
|
48
|
+
get = ctypes.windll.kernel32.GetTickCount64
|
|
49
|
+
except (AttributeError, OSError):
|
|
50
|
+
return None
|
|
51
|
+
get.restype, get.argtypes = ctypes.c_uint64, []
|
|
52
|
+
return lambda: get() / 1000.0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _reference() -> tuple[str, Callable[[], float]]:
|
|
56
|
+
"""(its name, its reader) of the clock steady() reads (see the module docstring)."""
|
|
57
|
+
get = getattr(time, "clock_gettime", None)
|
|
58
|
+
for name in ("CLOCK_BOOTTIME", "CLOCK_MONOTONIC"):
|
|
59
|
+
clock_id = getattr(time, name, None)
|
|
60
|
+
if get is not None and clock_id is not None:
|
|
61
|
+
try:
|
|
62
|
+
get(clock_id)
|
|
63
|
+
except OSError: # a kernel without it
|
|
64
|
+
continue
|
|
65
|
+
return name, functools.partial(get, clock_id)
|
|
66
|
+
ticks = _tick_count()
|
|
67
|
+
if ticks is not None:
|
|
68
|
+
return "GetTickCount64", ticks
|
|
69
|
+
return "monotonic", time.monotonic
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
REFERENCE, _read_reference = _reference()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def steady() -> float:
|
|
76
|
+
"""A clock that no step of the system clock changes and that, where the system has
|
|
77
|
+
one, goes on while the machine is suspended (REFERENCE names it)."""
|
|
78
|
+
return float(_read_reference())
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def describe(step: float, now: float) -> str:
|
|
82
|
+
"""'set forward by 3600.0 s (it now reads 2026-11-13 13:00:00+03:00)' (English: the
|
|
83
|
+
log, the audit log, the trace note and the notification)."""
|
|
84
|
+
way = "forward" if step > 0 else "back"
|
|
85
|
+
return f"set {way} by {abs(step):.1f} s (it now reads {clock.stamp(now)})"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ClockWatch:
|
|
89
|
+
"""Compares the wall clock with steady() (both can be given, for tests) and reports
|
|
90
|
+
its steps to `on_step(step seconds, wall time now)`."""
|
|
91
|
+
|
|
92
|
+
def __init__(self, on_step: Callable[[float, float], None], *,
|
|
93
|
+
wall: Callable[[], float] = time.time,
|
|
94
|
+
reference: Callable[[], float] = steady) -> None:
|
|
95
|
+
self._on_step = on_step
|
|
96
|
+
self._wall, self._reference = wall, reference
|
|
97
|
+
self._last: Optional[tuple[float, float]] = None
|
|
98
|
+
self._task: Optional[asyncio.Task] = None
|
|
99
|
+
self.steps = 0 # steps seen since the start
|
|
100
|
+
|
|
101
|
+
def look(self) -> Optional[float]:
|
|
102
|
+
"""Compare the clocks now: the step since the last look (seconds; positive: set
|
|
103
|
+
forward) when it is STEP_MIN_S or more - counted and reported - else None."""
|
|
104
|
+
now = (self._wall(), self._reference())
|
|
105
|
+
last, self._last = self._last, now
|
|
106
|
+
if last is None:
|
|
107
|
+
return None
|
|
108
|
+
step = (now[0] - last[0]) - (now[1] - last[1])
|
|
109
|
+
if abs(step) < STEP_MIN_S:
|
|
110
|
+
return None
|
|
111
|
+
self.steps += 1
|
|
112
|
+
self._on_step(step, now[0])
|
|
113
|
+
return step
|
|
114
|
+
|
|
115
|
+
async def start(self) -> None:
|
|
116
|
+
self.look()
|
|
117
|
+
self._task = asyncio.create_task(self._run(), name="clock-watch")
|
|
118
|
+
|
|
119
|
+
async def stop(self) -> None:
|
|
120
|
+
task, self._task = self._task, None
|
|
121
|
+
if task is not None:
|
|
122
|
+
task.cancel()
|
|
123
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
124
|
+
await task
|
|
125
|
+
|
|
126
|
+
async def _run(self) -> None:
|
|
127
|
+
while True:
|
|
128
|
+
await asyncio.sleep(CHECK_S)
|
|
129
|
+
with contextlib.suppress(Exception): # (on_step: never let the watcher die)
|
|
130
|
+
self.look()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class Reporter:
|
|
134
|
+
"""What an AppState does about a step (ClockWatch's on_step): the log line and the
|
|
135
|
+
audit record, at most once per REPORT_EVERY_S; the "!!" note in the running traces and
|
|
136
|
+
the clock_step notification for every one (the notifier has its own repeat limit)."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, state) -> None:
|
|
139
|
+
self.state = state
|
|
140
|
+
self._next = 0.0 # time.monotonic() from which the next line is written
|
|
141
|
+
self._held = 0 # steps not written since the last line
|
|
142
|
+
|
|
143
|
+
def __call__(self, step: float, now: float) -> None:
|
|
144
|
+
text = describe(step, now)
|
|
145
|
+
self.state.supervisor.annotate_traces(f"the system clock was {text}")
|
|
146
|
+
notifier = getattr(self.state, "notifier", None)
|
|
147
|
+
if notifier is not None:
|
|
148
|
+
notifier.emit("clock_step", "clock", "", f"The system clock was {text}.")
|
|
149
|
+
mono = time.monotonic()
|
|
150
|
+
if mono < self._next:
|
|
151
|
+
self._held += 1
|
|
152
|
+
return
|
|
153
|
+
more = f" ({self._held} more since the last such line)" if self._held else ""
|
|
154
|
+
self._held, self._next = 0, mono + REPORT_EVERY_S
|
|
155
|
+
self.state.log(f"WARNING: the system clock was {text}{more}: the times in the logs, "
|
|
156
|
+
"the audit log and the traces jump here (ser2netweb never sets the "
|
|
157
|
+
"clock; durations are not affected)")
|
|
158
|
+
self.state.audit("local", "clock_step", text + more)
|