Repository navigation
Expand file tree
/
Copy pathptpbox_agent.py
More file actions
3120 lines (2891 loc) · 137 KB
/
Copy pathptpbox_agent.py
File metadata and controls
3120 lines (2891 loc) · 137 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Small, dependency-free API for the PTPBox web console.
The agent intentionally separates read-only observation from privileged control.
It can run as an ordinary user for inventory and log telemetry. Start/stop calls
are delegated to a tightly scoped ptpboxctl sudo rule when the optional system
integration has been installed.
"""
from __future__ import annotations
import argparse
import base64
import binascii
import bisect
import ctypes
import errno
import fcntl
import json
import math
import mimetypes
import os
import re
import shutil
import socket
import sqlite3
import statistics
import subprocess
import sys
import threading
import time
import uuid
from collections import deque
from dataclasses import asdict, dataclass
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, urlparse
sys.path.insert(0, str(Path(__file__).resolve().parent))
from ptpbox_research import ExperimentStore, RollingResearchEngine, path_regime_analysis # noqa: E402
from ptpbox_phc_store import collector_quality, read_records # noqa: E402
import ptpbox_system # noqa: E402
import ptpbox_thermal # noqa: E402
import ptpbox_holdover_control # noqa: E402
import ptpbox_access # noqa: E402
ROOT = Path(os.environ.get("PTPBOX_ROOT", Path.home() / "PTPBox"))
STATE_DIR = Path(os.environ.get("PTPBOX_STATE_DIR", ROOT / "runtime"))
CONFIG_FILE = Path(os.environ.get("PTPBOX_CONFIG", STATE_DIR / "config.json"))
SERVO_REQUEST_FILE = STATE_DIR / "servo-request.json"
SERVO_STATE_FILE = Path(os.environ.get("PTPBOX_SERVO_STATE", "/run/ptpbox/servo-state.json"))
HOLDOVER_SESSION_FILE = STATE_DIR / "holdover-session.json"
KALMAN_STATE_DIR = Path(os.environ.get("PTPBOX_KALMAN_STATE_DIR", "/run/ptpbox"))
CONTROL = Path(os.environ.get("PTPBOX_CONTROL", "/usr/local/sbin/ptpboxctl"))
WEB_ROOT = Path(os.environ.get("PTPBOX_WEB_ROOT", Path(__file__).parent / "static"))
LOG_DIR = Path(os.environ.get("PTPBOX_LOG_DIR", "/var/log/ptpbox"))
TOPOLOGY_FILE = Path(os.environ.get("PTPBOX_TOPOLOGY", Path(__file__).with_name("topology.json")))
PHC_MAP_FILE = Path(os.environ.get("PTPBOX_PHC_MAP", "/run/ptpbox/phcs.json"))
PHC_STORE_FILE = Path(os.environ.get("PTPBOX_PHC_STORE", "/run/ptpbox/phc-samples.sqlite3"))
EXTERNAL_PHC_COLLECTOR = os.environ.get("PTPBOX_EXTERNAL_PHC_COLLECTOR", "0") == "1"
PPS_PROCESS_FILE = Path(os.environ.get("PTPBOX_PROCESS_STATE", "/run/ptpbox/processes.json"))
PATH_EVENT_FILE = Path(os.environ.get("PTPBOX_PATH_EVENTS", "/run/ptpbox/path-events.jsonl"))
FAULT_REQUEST_FILE = STATE_DIR / "fault-request.json"
FAULT_STATE_FILE = Path(os.environ.get("PTPBOX_FAULT_STATE", "/run/ptpbox/fault-state.json"))
IDENTIFICATION_REQUEST_FILE = STATE_DIR / "identification-request.json"
COMPENSATE_REQUEST_FILE = STATE_DIR / "compensate-request.json"
IDENTIFICATION_STATE_FILE = Path(os.environ.get("PTPBOX_IDENTIFICATION_STATE", "/run/ptpbox/identification-state.json"))
ALBUM_DIR = Path(os.environ.get("PTPBOX_ALBUM_DIR", STATE_DIR / "album"))
ALLOW_ORIGIN = os.environ.get("PTPBOX_ALLOW_ORIGIN", "*")
TELEMETRY_MAX_BYTES = 2_000_000
TELEMETRY_MAX_SAMPLES = 4096
TELEMETRY_STALE_AFTER_SECONDS = 5.0
TELEMETRY_MAX_PATH_DELAY_NS = 1_000_000.0
PHC_HISTORY_MAX_SAMPLES = 20_000
PHC_STALE_AFTER_SECONDS = 3.0
PHC_CROSS_TIMESTAMP_SAMPLES = 9
RESEARCH_CACHE_SECONDS = max(1.0, float(os.environ.get("PTPBOX_RESEARCH_CACHE_SECONDS", "10")))
ALBUM_REQUEST_MAX_BYTES = 12_000_000
ALBUM_MAX_IMAGE_BYTES = 8_000_000
ALBUM_MAX_ITEMS = 500
SUPPORTED_SERVOS = {"pi", "linreg", "nullf", "kalman", "adaptive-kalman", "imm"}
LINUXPTP_NATIVE_SERVOS = {"pi", "linreg", "nullf"}
LOG_PATTERN = re.compile(
r"offset\s+(?P<offset>-?\d+(?:\.\d+)?)\s+"
r"(?:(?P<servo_state>s\d+)\s+)?freq\s+(?P<freq>[+-]?\d+(?:\.\d+)?)\s+"
r"path delay\s+(?P<delay>-?\d+(?:\.\d+)?)",
re.IGNORECASE,
)
LOG_TIME_PATTERN = re.compile(r"\[(?P<seconds>\d+(?:\.\d+)?)\]")
LOG_SESSION_PATTERN = re.compile(r"(?:selected /dev/ptp\d+ as PTP clock|PTPBox session start)", re.IGNORECASE)
DEFAULT_CONFIG: dict[str, Any] = {
"profile": "G.8275.1 Telecom",
"domain": 24,
"transport": "L2",
"delay_mechanism": "E2E",
"log_sync_interval": 0,
"two_step": True,
"hardware_timestamping": True,
"servo": {
"type": "pi",
"kp": 0.7,
"ki": 0.3,
"step_threshold_ns": 0,
"first_step_threshold_ns": 20_000,
"sanity_freq_limit_ppb": 200_000,
"kalman": {
"measurement_noise_ns": 200.0,
"process_noise_ppb": 10.0,
"phase_time_constant_s": 4.0,
"innovation_gate_sigma": 6.0,
"drift_noise_ppb_s2": 0.05,
},
},
"security": {
"authentication": {
"enabled": False,
"spp": 0,
"active_key_id": 1,
"sa_file": "/etc/linuxptp/ptpbox-sa.cfg",
"allow_unauth": 0,
},
},
"pps": {
"enabled": False,
"source": "BC1",
"sinks": [],
"output_pin": 0,
"input_pin": 0,
"channel": 0,
"polarity": "rising",
"pulse_width_ns": 100_000_000,
"perout_phase_ns": 0,
"extts_correction_ns": 0,
"comparison": {
"enabled": False,
"measure_only": True,
"reference": "BC2",
"history": 256,
},
"ts2phc": {
"servo": "pi",
"kp": 0.7,
"ki": 0.3,
"step_threshold_ns": 0,
"first_step_threshold_ns": 20_000,
"holdover_seconds": 0,
"stable_threshold_ns": 100,
"stable_samples": 10,
"logging_level": 6,
},
},
}
PROFILE_RULES: dict[str, dict[str, Any]] = {
"IEEE 1588 Default": {"transport": {"L2", "UDPv4", "UDPv6"}, "delay": {"E2E", "P2P"}, "domain": (0, 127), "two_step": None},
"G.8275.1 Telecom": {"transport": {"L2"}, "delay": {"E2E"}, "domain": (24, 43), "two_step": None},
"G.8275.2 Telecom": {"transport": {"UDPv4", "UDPv6"}, "delay": {"E2E"}, "domain": (44, 63), "two_step": None},
"IEEE 802.1AS gPTP": {"transport": {"L2"}, "delay": {"P2P"}, "domain": (0, 0), "two_step": True},
"IEEE C37.238 Power": {"transport": {"L2"}, "delay": {"P2P"}, "domain": (254, 254), "two_step": None},
}
class Timespec(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)]
class PtpClockTime(ctypes.Structure):
_fields_ = [("sec", ctypes.c_int64), ("nsec", ctypes.c_uint32), ("reserved", ctypes.c_uint32)]
class PtpSysOffsetPrecise(ctypes.Structure):
_fields_ = [
("device", PtpClockTime),
("sys_realtime", PtpClockTime),
("sys_monoraw", PtpClockTime),
("reserved", ctypes.c_uint32 * 4),
]
class PtpSysOffsetExtended(ctypes.Structure):
_fields_ = [
("n_samples", ctypes.c_uint32),
("clockid", ctypes.c_int32),
("reserved", ctypes.c_uint32 * 2),
("ts", (PtpClockTime * 3) * 25),
]
def linux_iowr(type_: str, number: int, structure: type[ctypes.Structure]) -> int:
"""Build a Linux _IOWR request number without a compiled extension."""
return (3 << 30) | (ctypes.sizeof(structure) << 16) | (ord(type_) << 8) | number
PTP_SYS_OFFSET_PRECISE = linux_iowr("=", 8, PtpSysOffsetPrecise)
PTP_SYS_OFFSET_EXTENDED = linux_iowr("=", 9, PtpSysOffsetExtended)
CLOCK_REALTIME = 0
CLOCK_MONOTONIC_RAW = 4
LIBC = ctypes.CDLL(None, use_errno=True)
LIBC.clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(Timespec)]
LIBC.clock_gettime.restype = ctypes.c_int
PHC_HISTORY: deque[dict[str, Any]] = deque(maxlen=PHC_HISTORY_MAX_SAMPLES)
PHC_HISTORY_LOCK = threading.Lock()
PHC_FDS: dict[str, int] = {}
PHC_FDS_LOCK = threading.Lock()
PHC_CROSS_TIMESTAMP_METHODS: dict[str, str] = {}
RESEARCH_ENGINE = RollingResearchEngine(PHC_HISTORY_MAX_SAMPLES)
_EXPERIMENT_STORES: dict[str, ExperimentStore] = {}
_EXPERIMENT_STORES_LOCK = threading.Lock()
HOLDOVER_LOCK = threading.RLock()
_TEMPERATURE_CACHE: tuple[float, dict[str, float]] = (0.0, {})
_CAPABILITY_CACHE: tuple[float, dict[str, Any]] = (0.0, {})
_RESEARCH_SNAPSHOT_CACHE: dict[int, tuple[float, dict[str, Any]]] = {}
_RESEARCH_SNAPSHOT_REFRESHING: set[int] = set()
_RESEARCH_SNAPSHOT_CONDITION = threading.Condition()
_ALBUM_LOCK = threading.RLock()
@dataclass
class Interface:
name: str
state: str
carrier: bool
speed_mbps: int | None
mac: str
driver: str | None
bus: str | None
phc: str | None
hardware_timestamping: bool
namespace: str | None = None
assignment: str | None = None
@dataclass(frozen=True)
class PhcCrossTimestamp:
system_ns: int
phc_minus_system_ns: int
delay_ns: int
method: str
def read_text(path: Path, default: str = "") -> str:
try:
return path.read_text(encoding="utf-8").strip()
except (OSError, UnicodeError):
return default
def run(command: list[str], timeout: float = 3.0) -> subprocess.CompletedProcess[str]:
return subprocess.run(command, text=True, capture_output=True, timeout=timeout, check=False)
def linuxptp_version() -> str:
result = run(["ptp4l", "-v"])
match = re.search(r"(\d+(?:\.\d+)+)", result.stdout + result.stderr)
return match.group(1) if match else "unavailable"
def driver_for(interface: Path) -> str | None:
try:
return interface.joinpath("device", "driver").resolve().name
except OSError:
return None
def bus_for(interface: Path) -> str | None:
try:
return interface.joinpath("device").resolve().name
except OSError:
return None
def phc_for(interface: Path) -> str | None:
ptp_dir = interface / "device" / "ptp"
try:
entries = sorted(ptp_dir.iterdir())
return entries[0].name if entries else None
except OSError:
return None
def timestamp_info(name: str, discovered_phc: str | None) -> tuple[str | None, bool]:
if discovered_phc:
return discovered_phc, True
result = run(["ethtool", "-T", name])
output = result.stdout + result.stderr
index = re.search(r"Hardware timestamp provider index:\s*(\d+)", output)
capable = "hardware-raw-clock" in output and "hardware-transmit" in output and "hardware-receive" in output
return (f"ptp{index.group(1)}" if index else None, capable)
def interfaces() -> list[Interface]:
host_interfaces: list[Interface] = []
topology_value = load_json(TOPOLOGY_FILE, {})
management = topology_value.get("management_interfaces", []) if isinstance(topology_value, dict) else []
try:
host_paths = sorted(Path("/sys/class/net").iterdir(), key=lambda item: item.name)
except OSError:
host_paths = []
for interface in host_paths:
if interface.name == "lo":
continue
speed_raw = read_text(interface / "speed")
try:
speed = int(speed_raw)
if speed < 0:
speed = None
except ValueError:
speed = None
phc, hardware_timestamping = timestamp_info(interface.name, phc_for(interface))
assignment = None
if interface.name in management:
assignment = "MANAGEMENT" if management.index(interface.name) == 0 else "SPARE"
host_interfaces.append(
Interface(
name=interface.name,
state=read_text(interface / "operstate", "unknown").upper(),
carrier=read_text(interface / "carrier") == "1",
speed_mbps=speed,
mac=read_text(interface / "address"),
driver=driver_for(interface),
bus=bus_for(interface),
phc=phc,
hardware_timestamping=hardware_timestamping,
assignment=assignment,
)
)
mapped_value = load_json(PHC_MAP_FILE, [])
if not isinstance(mapped_value, list):
return host_interfaces
mapped_interfaces: list[Interface] = []
mapped_names: set[str] = set()
for index, item in enumerate(mapped_value):
if not isinstance(item, dict):
continue
node_id = item.get("id")
namespace = item.get("namespace")
for direction in ("ingress", "egress"):
name = item.get(direction)
phc = item.get(f"{direction}_phc")
details = item.get(f"{direction}_interface", {})
if not isinstance(name, str) or not name or name in mapped_names:
continue
if not isinstance(details, dict):
details = {}
role = "IN" if direction == "ingress" else "OUT"
if index == 0:
role = "INACTIVE IN" if direction == "ingress" else "GM OUT"
elif index == len(mapped_value) - 1:
role = "OC IN" if direction == "ingress" else "INACTIVE OUT"
speed_value = details.get("speed_mbps")
mapped_interfaces.append(
Interface(
name=name,
state=str(details.get("state", "NAMESPACE")).upper(),
carrier=bool(details.get("carrier", False)),
speed_mbps=int(speed_value) if isinstance(speed_value, (int, float)) else None,
mac=str(details.get("mac", "")),
driver=str(details["driver"]) if details.get("driver") else None,
bus=str(details["bus"]) if details.get("bus") else None,
phc=phc if isinstance(phc, str) else None,
hardware_timestamping=bool(details.get("hardware_timestamping", phc)),
namespace=namespace if isinstance(namespace, str) else None,
assignment=f"{node_id} / {role}" if isinstance(node_id, str) else role,
)
)
mapped_names.add(name)
return mapped_interfaces + [item for item in host_interfaces if item.name not in mapped_names]
def namespaces() -> list[str]:
result = run(["ip", "netns", "list"])
return [line.split()[0] for line in result.stdout.splitlines() if line.strip()]
def running_processes() -> list[dict[str, Any]]:
result = run(["ps", "-eo", "pid=,comm=,args="])
processes: list[dict[str, Any]] = []
for line in result.stdout.splitlines():
if not re.search(r"\b(ptp4l|phc2sys|ts2phc|ptpbox-kalman-servo)\b", line):
continue
parts = line.strip().split(maxsplit=2)
if len(parts) >= 2:
processes.append({"pid": int(parts[0]), "name": parts[1], "command": parts[2] if len(parts) == 3 else parts[1]})
return processes
def load_json(path: Path, fallback: Any = None) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return fallback
def experiment_store() -> ExperimentStore:
path = STATE_DIR / "experiments.sqlite3"
key = str(path)
with _EXPERIMENT_STORES_LOCK:
store = _EXPERIMENT_STORES.get(key)
if store is None:
store = ExperimentStore(path)
_EXPERIMENT_STORES[key] = store
return store
def node_temperature_sensors(node_item: dict[str, Any]) -> list[Path]:
"""hwmon temperature inputs belonging to one stage's adapter."""
candidates: list[Path] = []
for direction in ("ingress_interface", "egress_interface"):
details = node_item.get(direction)
bus = details.get("bus") if isinstance(details, dict) else None
if isinstance(bus, str) and bus:
candidates.extend(Path("/sys/bus/pci/devices", bus, "hwmon").glob("hwmon*/temp*_input"))
return sorted(candidates)
def node_temperature_sensor(node: str) -> str | None:
"""One stable sensor path for a stage, for the holdover compensator to poll.
The compensator follows a single input rather than a median across the
adapter's sensors: the model was fitted against whatever the collector
reported, and switching sensors mid-holdover would move the regressor
underneath the model.
"""
for item in phc_inventory():
if str(item.get("id")) != str(node):
continue
for path in node_temperature_sensors(item):
try:
reading = float(path.read_text(encoding="utf-8").strip()) / 1000.0
except (OSError, ValueError):
continue
if -40.0 <= reading <= 150.0:
return str(path)
return None
def clock_temperatures(force: bool = False) -> dict[str, float]:
"""Read NIC-adjacent hwmon sensors and map them to topology clocks."""
global _TEMPERATURE_CACHE
now = time.time()
if not force and now - _TEMPERATURE_CACHE[0] < 1.0:
return dict(_TEMPERATURE_CACHE[1])
values: dict[str, float] = {}
for item in phc_inventory():
candidates = node_temperature_sensors(item)
readings: list[float] = []
for path in candidates:
try:
reading = float(path.read_text(encoding="utf-8").strip()) / 1000.0
if -40.0 <= reading <= 150.0:
readings.append(reading)
except (OSError, ValueError):
continue
if readings:
values[str(item["id"])] = statistics.median(readings)
_TEMPERATURE_CACHE = (now, values)
return dict(values)
def _command_json(command: list[str], timeout: float = 2.0) -> Any:
try:
result = run(command, timeout=timeout)
except (OSError, subprocess.SubprocessError):
return None
if result.returncode:
return None
try:
return json.loads(result.stdout)
except json.JSONDecodeError:
return None
def hardware_capabilities(force: bool = False) -> dict[str, Any]:
"""Probe optional timing hardware without turning unsupported data into zero."""
global _CAPABILITY_CACHE
now = time.time()
if not force and now - _CAPABILITY_CACHE[0] < 10.0:
return _CAPABILITY_CACHE[1]
dpll_binary = shutil.which("dpll")
devlink_binary = shutil.which("devlink")
dpll_devices = _command_json([dpll_binary, "-j", "device", "show"]) if dpll_binary else None
dpll_pins = _command_json([dpll_binary, "-j", "pin", "show"]) if dpll_binary else None
devlink_health = _command_json([devlink_binary, "-j", "health", "show"]) if devlink_binary else None
temperatures = clock_temperatures(force=True)
path_events = raw_path_events(32)
pps_common_edge = load_json(STATE_DIR / "pps-comparison.json", {})
if not isinstance(pps_common_edge, dict):
pps_common_edge = {}
value = {
"dpll": {
"supported": dpll_devices is not None,
"binary": bool(dpll_binary),
"devices": dpll_devices or [],
"pins": dpll_pins or [],
"reason": None if dpll_devices is not None else "Kernel DPLL userspace reporting is unavailable on this host.",
},
"synce": {
"supported": dpll_devices is not None and bool(dpll_pins),
"state": "reported" if dpll_devices is not None and bool(dpll_pins) else "not-reported",
"reason": None if dpll_devices is not None and bool(dpll_pins) else "No DPLL pin state is exposed; SyncE status is not inferred from PTP lock.",
},
"devlink_health": {
"supported": devlink_health is not None,
"reporters": devlink_health or {},
},
"temperature": {
"supported": bool(temperatures),
"nodes": temperatures,
},
"path_monitor": {
"supported": bool(path_events),
"events": len(path_events),
"reason": None if path_events else "No LinuxPTP slave-event-monitor records have arrived yet.",
},
"pps_common_edge": {
"supported": bool(pps_common_edge.get("samples")),
"state": pps_common_edge,
},
"timestamp": now,
}
_CAPABILITY_CACHE = (now, value)
return value
def raw_path_events(limit: int = 128) -> list[dict[str, Any]]:
try:
with PATH_EVENT_FILE.open("rb") as handle:
handle.seek(0, os.SEEK_END)
size = min(handle.tell(), 1_000_000)
handle.seek(-size, os.SEEK_END)
lines = handle.read().decode("utf-8", "replace").splitlines()
except OSError:
return []
events: list[dict[str, Any]] = []
for line in lines[-max(1, min(2048, limit * 3)):]:
try:
event = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(event, dict) and isinstance(event.get("observed_at"), (int, float)):
events.append(event)
return events[-max(1, min(2048, limit)):]
def phc_fd(device: str) -> int:
with PHC_FDS_LOCK:
fd = PHC_FDS.get(device)
if fd is None:
fd = os.open(device, os.O_RDONLY)
PHC_FDS[device] = fd
return fd
def discard_phc_fd(device: str, fd: int) -> None:
with PHC_FDS_LOCK:
if PHC_FDS.get(device) == fd:
PHC_FDS.pop(device, None)
PHC_CROSS_TIMESTAMP_METHODS.pop(device, None)
os.close(fd)
def read_phc_ns(device: str) -> int:
"""Read a Linux PHC without changing its time or frequency."""
fd = phc_fd(device)
try:
# Linux's FD_TO_CLOCKID macro for dynamic POSIX clocks.
clock_id = ((~fd) << 3) | 3
value = Timespec()
if LIBC.clock_gettime(clock_id, ctypes.byref(value)) != 0:
error = ctypes.get_errno()
raise OSError(error, os.strerror(error), device)
return int(value.tv_sec) * 1_000_000_000 + int(value.tv_nsec)
except OSError:
discard_phc_fd(device, fd)
raise
def ptp_time_ns(value: PtpClockTime) -> int:
return int(value.sec) * 1_000_000_000 + int(value.nsec)
def precise_cross_timestamp(fd: int) -> PhcCrossTimestamp:
buffer = bytearray(ctypes.sizeof(PtpSysOffsetPrecise))
value = PtpSysOffsetPrecise.from_buffer(buffer)
fcntl.ioctl(fd, PTP_SYS_OFFSET_PRECISE, buffer, True)
system_ns = ptp_time_ns(value.sys_monoraw)
return PhcCrossTimestamp(
system_ns=system_ns,
phc_minus_system_ns=ptp_time_ns(value.device) - system_ns,
delay_ns=0,
method="PTP_SYS_OFFSET_PRECISE",
)
def extended_cross_timestamp(fd: int, clock_id: int) -> PhcCrossTimestamp:
buffer = bytearray(ctypes.sizeof(PtpSysOffsetExtended))
value = PtpSysOffsetExtended.from_buffer(buffer)
value.n_samples = PHC_CROSS_TIMESTAMP_SAMPLES
value.clockid = clock_id
fcntl.ioctl(fd, PTP_SYS_OFFSET_EXTENDED, buffer, True)
candidates: list[tuple[int, int, int]] = []
for index in range(PHC_CROSS_TIMESTAMP_SAMPLES):
before_ns = ptp_time_ns(value.ts[index][0])
device_ns = ptp_time_ns(value.ts[index][1])
after_ns = ptp_time_ns(value.ts[index][2])
delay_ns = after_ns - before_ns
if delay_ns >= 0:
system_ns = (before_ns + after_ns) // 2
candidates.append((delay_ns, system_ns, device_ns - system_ns))
if not candidates:
raise OSError(errno.EIO, "kernel returned no valid PHC cross timestamps")
delay_ns, system_ns, offset_ns = min(candidates)
clock_name = "CLOCK_MONOTONIC_RAW" if clock_id == CLOCK_MONOTONIC_RAW else "CLOCK_REALTIME"
return PhcCrossTimestamp(
system_ns=system_ns,
phc_minus_system_ns=offset_ns,
delay_ns=delay_ns,
method=f"PTP_SYS_OFFSET_EXTENDED({clock_name}), best of {PHC_CROSS_TIMESTAMP_SAMPLES}",
)
def midpoint_cross_timestamp(device: str) -> PhcCrossTimestamp:
before_ns = time.clock_gettime_ns(CLOCK_MONOTONIC_RAW)
device_ns = read_phc_ns(device)
after_ns = time.clock_gettime_ns(CLOCK_MONOTONIC_RAW)
system_ns = (before_ns + after_ns) // 2
return PhcCrossTimestamp(
system_ns=system_ns,
phc_minus_system_ns=device_ns - system_ns,
delay_ns=after_ns - before_ns,
method="userspace CLOCK_MONOTONIC_RAW midpoint fallback",
)
def read_phc_cross_timestamp(device: str) -> PhcCrossTimestamp:
"""Cross timestamp a PHC to a common system clock, without disciplining it."""
fd = phc_fd(device)
methods = ["precise", "extended-monoraw", "extended-realtime", "midpoint"]
cached = PHC_CROSS_TIMESTAMP_METHODS.get(device)
if cached in methods:
methods.remove(cached)
methods.insert(0, cached)
unsupported = {errno.EINVAL, errno.ENOTTY, errno.EOPNOTSUPP, errno.ENOSYS}
for method in methods:
try:
if method == "precise":
result = precise_cross_timestamp(fd)
elif method == "extended-monoraw":
result = extended_cross_timestamp(fd, CLOCK_MONOTONIC_RAW)
elif method == "extended-realtime":
result = extended_cross_timestamp(fd, CLOCK_REALTIME)
else:
result = midpoint_cross_timestamp(device)
PHC_CROSS_TIMESTAMP_METHODS[device] = method
return result
except OSError as exc:
if method == cached:
PHC_CROSS_TIMESTAMP_METHODS.pop(device, None)
if exc.errno not in unsupported:
if exc.errno in {errno.EBADF, errno.ENODEV, errno.ENXIO}:
discard_phc_fd(device, fd)
raise
raise OSError(errno.EOPNOTSUPP, "no PHC cross-timestamp method is available", device)
def phc_inventory() -> list[dict[str, Any]]:
value = load_json(PHC_MAP_FILE, [])
if not isinstance(value, list):
return []
return [
item
for item in value
if isinstance(item, dict)
and isinstance(item.get("id"), str)
and isinstance(item.get("measurement_phc"), str)
]
def take_phc_sample() -> dict[str, Any] | None:
"""Compare PHCs at a common epoch using kernel cross timestamps."""
inventory = phc_inventory()
if not inventory:
return None
reference = inventory[0]
reference_device = f"/dev/{reference['measurement_phc']}"
observed_at = time.time()
sample_id = f"phc:{time.time_ns()}"
clocks: list[dict[str, Any]] = []
previous_offset: float | None = None
target_measurements: dict[str, PhcCrossTimestamp | OSError] = {}
try:
reference_before = read_phc_cross_timestamp(reference_device)
for item in inventory[1:]:
device = f"/dev/{item['measurement_phc']}"
try:
target_measurements[item["id"]] = read_phc_cross_timestamp(device)
except OSError as exc:
target_measurements[item["id"]] = exc
reference_after = read_phc_cross_timestamp(reference_device)
except OSError as exc:
reference_before = exc
reference_after = exc
for index, item in enumerate(inventory):
try:
if isinstance(reference_before, OSError) or isinstance(reference_after, OSError):
raise reference_before if isinstance(reference_before, OSError) else reference_after
if index == 0:
measurement = reference_after
offset = 0.0
uncertainty = measurement.delay_ns / 2
else:
measurement = target_measurements[item["id"]]
if isinstance(measurement, OSError):
raise measurement
reference_interval = reference_after.system_ns - reference_before.system_ns
if reference_interval:
position = (measurement.system_ns - reference_before.system_ns) / reference_interval
# Cancel the Unix-epoch-sized offsets as integers first.
# Converting either absolute value to float would quantize
# the result to roughly 256 ns at today's epoch.
offset = float(measurement.phc_minus_system_ns - reference_before.phc_minus_system_ns) - position * (
reference_after.phc_minus_system_ns - reference_before.phc_minus_system_ns
)
reference_delay = reference_before.delay_ns + position * (
reference_after.delay_ns - reference_before.delay_ns
)
else:
offset = float(
measurement.phc_minus_system_ns
- (reference_before.phc_minus_system_ns + reference_after.phc_minus_system_ns) // 2
)
reference_delay = max(reference_before.delay_ns, reference_after.delay_ns)
uncertainty = (measurement.delay_ns + max(0.0, reference_delay)) / 2
hop_offset = None if previous_offset is None else offset - previous_offset
clocks.append(
{
"id": item["id"],
"phc": item["measurement_phc"],
"offset_ns": float(offset),
"previous_hop_offset_ns": float(hop_offset) if hop_offset is not None else None,
"read_span_ns": float(measurement.delay_ns),
"comparison_uncertainty_ns": float(uncertainty),
"cross_timestamp_method": measurement.method,
"observed_at": observed_at,
"sample_id": f"{sample_id}:{item['id']}",
"raw": True,
"valid": True,
"error": None,
}
)
previous_offset = offset
except OSError as exc:
clocks.append(
{
"id": item["id"],
"phc": item["measurement_phc"],
"offset_ns": None,
"previous_hop_offset_ns": None,
"read_span_ns": None,
"comparison_uncertainty_ns": None,
"cross_timestamp_method": None,
"observed_at": observed_at,
"sample_id": f"{sample_id}:{item['id']}",
"raw": True,
"valid": False,
"error": str(exc),
}
)
previous_offset = None
return {
"observed_at": observed_at,
"sample_id": sample_id,
"reference": reference["id"],
"reference_phc": reference["measurement_phc"],
"clocks": clocks,
"raw": True,
"method": "common-system cross timestamps with interpolated BC1 reference",
}
def record_phc_sample() -> dict[str, Any] | None:
sample = take_phc_sample()
if sample is not None:
with PHC_HISTORY_LOCK:
PHC_HISTORY.append(sample)
temperatures = clock_temperatures()
RESEARCH_ENGINE.add(sample, temperatures)
try:
experiment_store().record_phc(sample, temperatures)
except (OSError, sqlite3.Error):
pass
return sample
def phc_telemetry(history_seconds: float = 120.0, since: float | None = None) -> dict[str, Any]:
now = time.time()
cutoff = now - max(5.0, min(history_seconds, 900.0))
records = read_records(PHC_STORE_FILE, history_seconds) if EXTERNAL_PHC_COLLECTOR else []
temperature_history: list[tuple[float, dict[str, float]]] = []
if records:
history = [record["sample"] for record in records]
for record in records:
readings = record.get("temperatures") or {}
if readings:
temperature_history.append((float(record["sample"]["observed_at"]), readings))
else:
with PHC_HISTORY_LOCK:
history = list(PHC_HISTORY)
window = [sample for sample in history if float(sample["observed_at"]) >= cutoff]
inventory = phc_inventory()
clocks: list[dict[str, Any]] = []
for item in inventory:
values = [
clock
for sample in window
for clock in sample["clocks"]
if clock["id"] == item["id"]
]
measurement = values[-1] if values else None
samples = values if since is None else [sample for sample in values if float(sample["observed_at"]) > since]
valid_offsets = [float(sample["offset_ns"]) for sample in values if sample["valid"] and sample["offset_ns"] is not None]
clocks.append(
{
"id": item["id"],
"phc": item["measurement_phc"],
"measurement": measurement,
"samples": samples,
"temperature_c": next(
(
float(readings[item["id"]])
for _, readings in reversed(temperature_history)
if item["id"] in readings
),
None,
),
"window_sample_count": len(values),
"rms_ns": (
sum(offset * offset for offset in valid_offsets) / len(valid_offsets)
) ** 0.5 if valid_offsets else None,
}
)
fresh = sum(
1
for clock in clocks
if clock["measurement"]
and clock["measurement"]["valid"]
and now - float(clock["measurement"]["observed_at"]) <= PHC_STALE_AFTER_SECONDS
)
mode = "live" if fresh else "stale" if history else "waiting"
return {
"timestamp": now,
"reference": inventory[0]["id"] if inventory else None,
"reference_phc": inventory[0]["measurement_phc"] if inventory else None,
"clocks": clocks,
"fresh_clocks": fresh,
"mode": mode,
"sample_rate_hz": configured_phc_sample_rate_hz(),
"collector": (
collector_quality(PHC_STORE_FILE, configured_phc_sample_rate_hz())
if EXTERNAL_PHC_COLLECTOR
else {
"source": "in-process",
"requested_rate_hz": configured_phc_sample_rate_hz(),
"achieved_rate_hz": None,
"sample_count": len(window),
"gap_count": 0,
"largest_gap_s": 0.0,
"last_sample_age_s": max(0.0, now - float(history[-1]["observed_at"])) if history else None,
"healthy": bool(fresh),
}
),
"raw": True,
"smoothing": "none",
"method": "common-system cross timestamps with interpolated BC1 reference",
}
def phc_sampler_loop(stop: threading.Event) -> None:
while not stop.is_set():
started = time.monotonic()
record_phc_sample()
period = 1.0 / configured_phc_sample_rate_hz()
stop.wait(max(0.0, period - (time.monotonic() - started)))
def load_config() -> dict[str, Any]:
merged = json.loads(json.dumps(DEFAULT_CONFIG))
try:
value = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
if not isinstance(value, dict):
return merged
except (OSError, json.JSONDecodeError):
return merged
def merge(target: dict[str, Any], update: dict[str, Any]) -> None:
for key, item in update.items():
if isinstance(item, dict) and isinstance(target.get(key), dict):
merge(target[key], item)
else:
target[key] = item
merge(merged, value)
return merged
def configured_phc_sample_rate_hz() -> float:
"""Match read-only PHC observation to the applied IEEE 1588 Sync cadence."""
log_interval = load_config().get("log_sync_interval", 0)
if isinstance(log_interval, bool) or not isinstance(log_interval, int) or not -3 <= log_interval <= 1:
log_interval = 0
return float(2 ** -log_interval)
def profile_compliance(value: dict[str, Any] | None = None) -> dict[str, Any]:
config_value = value or load_config()
name = str(config_value.get("profile", ""))
rule = PROFILE_RULES.get(name)
if not rule:
return {"profile": name, "compliant": False, "checks": [], "error": "unknown profile"}
checks = [
{
"name": "Transport",
"actual": config_value.get("transport"),
"expected": sorted(rule["transport"]),
"pass": config_value.get("transport") in rule["transport"],
},
{
"name": "Delay mechanism",
"actual": config_value.get("delay_mechanism"),
"expected": sorted(rule["delay"]),
"pass": config_value.get("delay_mechanism") in rule["delay"],
},
{
"name": "Domain",
"actual": config_value.get("domain"),
"expected": list(rule["domain"]),
"pass": isinstance(config_value.get("domain"), int) and rule["domain"][0] <= config_value["domain"] <= rule["domain"][1],
},
]
if rule["two_step"] is not None:
checks.append(
{
"name": "Two-step operation",
"actual": config_value.get("two_step"),
"expected": rule["two_step"],
"pass": config_value.get("two_step") is rule["two_step"],
}
)
return {
"profile": name,
"compliant": all(check["pass"] for check in checks),
"checks": checks,
"available_profiles": list(PROFILE_RULES),
"scope": "transport, delay mechanism, domain, and two-step compatibility",
"certification": False,
}
def validate_config(value: dict[str, Any]) -> list[str]:
errors: list[str] = []
profile = value.get("profile")
if profile not in PROFILE_RULES:
errors.append(f"profile must be one of: {', '.join(PROFILE_RULES)}")
if not isinstance(value.get("domain"), int) or isinstance(value.get("domain"), bool) or not 0 <= value["domain"] <= 255:
errors.append("domain must be an integer from 0 through 255")
if value.get("transport") not in {"L2", "UDPv4", "UDPv6"}:
errors.append("transport must be L2, UDPv4, or UDPv6")
if value.get("delay_mechanism") not in {"P2P", "E2E"}:
errors.append("delay_mechanism must be P2P or E2E")
if profile in PROFILE_RULES:
rules = PROFILE_RULES[profile]
if value.get("transport") not in rules["transport"]:
errors.append(f"{profile} requires transport: {', '.join(sorted(rules['transport']))}")
if value.get("delay_mechanism") not in rules["delay"]:
errors.append(f"{profile} requires delay mechanism: {', '.join(sorted(rules['delay']))}")
if isinstance(value.get("domain"), int) and not rules["domain"][0] <= value["domain"] <= rules["domain"][1]:
errors.append(f"{profile} requires domain {rules['domain'][0]} through {rules['domain'][1]}")
if rules["two_step"] is not None and value.get("two_step") is not rules["two_step"]:
errors.append(f"{profile} requires two_step={str(rules['two_step']).lower()}")
log_sync_interval = value.get("log_sync_interval")
if isinstance(log_sync_interval, bool) or not isinstance(log_sync_interval, int) or not -3 <= log_sync_interval <= 1:
errors.append("log_sync_interval must be an integer from -3 through 1 (8 Hz through 0.5 Hz)")
servo = value.get("servo")
if not isinstance(servo, dict):
errors.append("servo settings are required")
else:
if servo.get("type") not in SUPPORTED_SERVOS:
errors.append("servo.type must be pi, linreg, nullf, kalman, adaptive-kalman, or imm")
for key in ("kp", "ki"):
if not isinstance(servo.get(key), (int, float)) or not 0 <= float(servo[key]) <= 10:
errors.append(f"servo.{key} must be between 0 and 10")
if not isinstance(servo.get("step_threshold_ns"), (int, float)) or servo["step_threshold_ns"] < 0: