Repository navigation
Expand file tree
/
Copy pathsbfd_ctl.py
More file actions
executable file
·4268 lines (3813 loc) · 194 KB
/
Copy pathsbfd_ctl.py
File metadata and controls
executable file
·4268 lines (3813 loc) · 194 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
"""
sbfd-ctl - failover controller for sbfd + engarde.
"""
from __future__ import annotations
import argparse
import json
import logging
import math
import sys
import threading
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional
import fec_control
import fec_history
import fec_report
import notify
import egress_observer
# -- Configuration -----------------------------------------------------------
VALID_MODES = {"full", "master_backup"}
VALID_POLICIES = {"static_primary", "dynamic", "static_configured"}
VALID_EGRESS_MODES = {"relay_vpn", "relay_backbone", "relay_direct", "local_direct"}
# Modes whose client traffic rides the tunnel to the relay; the relay picks the exit.
RELAY_EGRESS_MODES = {"relay_vpn", "relay_backbone", "relay_direct"}
@dataclass
class WanCfg:
iface: str
session_id: int
label: str
@dataclass
class RelayCfg:
state_url: str
fetch_interval_s: float = 1.0
fetch_timeout_s: float = 2.0
fec_url: Optional[str] = None
@dataclass
class EngardeCfg:
server_ip: str
server_port: int
admin_url: Optional[str] = None
@dataclass
class NftCfg:
table: str = "sbfd_ctl"
family: str = "inet"
@dataclass
class EgressCfg:
engarde_table: str = "engarde"
wg_iface: str = "wg0"
default_mode: str = "relay_vpn"
# Actual-exit check, or None when it is off.
observe: Optional[egress_observer.ObserveCfg] = None
@dataclass
class PolicyCfg:
default_mode: str = "full"
default_master_policy: str = "static_primary"
default_master_wan: str = "wan2"
failback_hold_s: int = 30
dynamic_rtt_margin_ms: float = 25.0
dynamic_loss_margin_pct: float = 1.0
dynamic_swap_dwell_s: float = 10.0
manage_default_route: bool = False
@dataclass
class WanProfileCfg:
"""Per-WAN FEC policy: table + hysteresis + floor applied while this WAN
is the fec driver. Defaults are the cellular spec values — a bare
`"wan1": {}` profile is the intended common case."""
name: str
loss_table: list
ramp_up_ticks: int
ramp_down_hold_s: float
floor_ratio: str
signal_floor_fec: str
@dataclass
class FecCfg:
enabled: bool
fifo: str
loss_table: list
ramp_up_ticks: int
ramp_down_hold_s: float
full_mode_backoff_fec: str
full_min_up_wans: int
wire_unit: str = "udpspeeder-client"
wire_stale_after_s: float = 30.0
mode: str = fec_control.DEFAULT_MODE
fixed_ratio: str = fec_control.DEFAULT_FIXED_RATIO
floor_ratio: str = fec_control.DEFAULT_FLOOR_RATIO
wan_profiles: dict = field(default_factory=dict)
# Dwell on the DRIVER choice, mirroring policy.dynamic_swap_dwell_s for
# the master. step_level damps the ratio, but nothing damped the driver, so
# a momentary loss blip on the other link swapped the profile — and with it
# the table and floor — beneath the adaptive engine. Only bites when more
# than one WAN is active, i.e. full redundancy.
driver_dwell_s: float = 120.0
@dataclass
class EnvironmentalCfg:
enabled: bool
auto_override_path: str
auto_override_ttl_s: float = 180.0
@dataclass
class CellTelemetryCfg:
"""Reader side of cell_telemetry.py's state file. Thresholds live here
(not in the collector) because the FEC controller is the one consumer."""
state_path: str
wan: str = "wan1"
stale_after_s: float = 10.0
rsrq_degrade_db: float = -12.0
rsrq_recover_db: float = -10.0
rsrp_degrade_dbm: float = -110.0
rsrp_recover_dbm: float = -108.0
handoff_path: str = "/run/sbfd-ctl/cell_handoff.json"
handoff_ttl_s: float = 30.0
@dataclass
class LocationFecCfg:
"""Reader side of location_fec.py's floor file. `enabled` is the boot-time
default; the operator's runtime toggle wins in either direction."""
state_path: str
enabled: bool = True
stale_after_s: float = 30.0
@dataclass
class MaintenanceCfg:
"""Nightly one-at-a-time WAN reboot. `enabled`/`hour` here are boot-time
DEFAULTS only — the operator's runtime overlay wins in either direction.
sbfd-ctl resolves the pair and publishes it; maintenance_reboot.py reads
the resolved values and never re-derives this precedence."""
enabled: bool
hour: int
window_path: str = "/run/sbfd-ctl/maintenance_window.json"
@dataclass
class Config:
wans: dict[str, WanCfg]
relay: RelayCfg
engarde: EngardeCfg
nft: NftCfg
policy: PolicyCfg
ui_listen: str
sbfd_local_state: str
runtime_state: str
persist_state: str
published_state: str
egress: EgressCfg = field(default_factory=EgressCfg)
fec: Optional[FecCfg] = None
environmental: Optional[EnvironmentalCfg] = None
maintenance: Optional[MaintenanceCfg] = None
cell: Optional[CellTelemetryCfg] = None
location: Optional[LocationFecCfg] = None
notifications: Optional["notify.NotifyCfg"] = None
map: object = None # raw `map` config section (dict | None)
# -- Decision logic ----------------------------------------------------------
@dataclass
class DecideInput:
mode: str
policy: str
master_wan_cfg: str
eff_state: dict
rtt_ms: dict
loss_pct: dict
master_up_since: Optional[float]
currently_active: set
now: float
dynamic_master_current: Optional[str] = None
dynamic_candidate: Optional[str] = None
dynamic_candidate_since: Optional[float] = None
@dataclass
class DecideOutput:
desired_active: set
reason: str
master_up_since: Optional[float]
dynamic_master_current: Optional[str] = None
dynamic_candidate: Optional[str] = None
dynamic_candidate_since: Optional[float] = None
# Policy-resolved master. Callers use this for the kernel default route and
# the local_direct egress anchor instead of re-deriving from static config.
effective_master: Optional[str] = None
def _best_link(eff_state: dict, rtt_ms: dict, loss_pct: dict, configured_master: str) -> str:
candidates = list(eff_state.keys())
def key(name):
up = 0 if eff_state.get(name) == "UP" else 1
rtt = rtt_ms.get(name, float("inf"))
loss = loss_pct.get(name, float("inf"))
not_master = 0 if name == configured_master else 1
return (up, rtt, loss, not_master)
candidates.sort(key=key)
return candidates[0]
def _dynamic_pick(eff_state, rtt_ms, loss_pct, configured_master,
current_master, candidate, candidate_since,
rtt_margin_ms, loss_margin_pct, dwell_s, now):
"""
Sticky master with asymmetric margin+dwell hysteresis.
Two regimes:
- On configured_master: a challenger must beat us by margin (rtt or loss)
for >= dwell_s before we swap away. Standard symmetric ranker.
- Off configured_master: configured_master is the implicit challenger
whenever it is UP, unless current_master clearly beats it. After
dwell_s of "configured is good enough", swap back home.
Within both regimes, transient single-tick margin failures preserve any
held candidate that is the configured master — this avoids dwell restart
on RTT jitter near the margin boundary.
"""
ups = [w for w in eff_state if eff_state.get(w) == "UP"]
if not ups:
return configured_master, None, None
if len(ups) == 1:
return ups[0], None, None
if current_master is None or current_master not in ups:
best = min(ups, key=lambda w: (
loss_pct.get(w, 0.0),
rtt_ms.get(w, float("inf")),
0 if w == configured_master else 1,
))
return best, None, None
cur_rtt = rtt_ms.get(current_master, float("inf"))
cur_loss = loss_pct.get(current_master, 0.0)
challenger = None
if current_master == configured_master:
# On configured: standard "challenger must beat by margin".
for w in ups:
if w == current_master:
continue
w_rtt = rtt_ms.get(w, float("inf"))
w_loss = loss_pct.get(w, 0.0)
loss_better = w_loss + loss_margin_pct <= cur_loss
rtt_better = (w_rtt + rtt_margin_ms <= cur_rtt
and w_loss <= cur_loss + loss_margin_pct)
if loss_better or rtt_better:
challenger = w
break
else:
# Off configured: configured_master is implicit challenger unless
# current_master clearly beats it (current beats configured by margin
# on rtt, or has materially better loss).
if configured_master in ups:
cm_rtt = rtt_ms.get(configured_master, float("inf"))
cm_loss = loss_pct.get(configured_master, 0.0)
current_clearly_better = (
(cur_rtt + rtt_margin_ms <= cm_rtt
and cur_loss <= cm_loss + loss_margin_pct)
or (cur_loss + loss_margin_pct <= cm_loss)
)
if not current_clearly_better:
challenger = configured_master
if challenger is None:
# Preserve held candidate if it's configured_master (jitter tolerance).
if candidate is not None and candidate == configured_master:
return current_master, candidate, candidate_since
return current_master, None, None
if candidate == challenger and candidate_since is not None:
if now - candidate_since >= dwell_s:
return challenger, None, None
return current_master, candidate, candidate_since
return current_master, challenger, now
def decide(cfg: Config, i: DecideInput) -> DecideOutput:
if i.mode == "full":
return DecideOutput(
desired_active=set(cfg.wans.keys()),
reason="full redundancy mode: both WANs active",
master_up_since=None,
effective_master=i.master_wan_cfg,
)
new_dyn_master = None
new_dyn_cand = None
new_dyn_cand_since = None
if i.policy == "static_primary":
master = cfg.policy.default_master_wan
elif i.policy == "static_configured":
master = i.master_wan_cfg
elif i.policy == "dynamic":
master, new_dyn_cand, new_dyn_cand_since = _dynamic_pick(
i.eff_state, i.rtt_ms, i.loss_pct, cfg.policy.default_master_wan,
i.dynamic_master_current, i.dynamic_candidate, i.dynamic_candidate_since,
cfg.policy.dynamic_rtt_margin_ms, cfg.policy.dynamic_loss_margin_pct,
cfg.policy.dynamic_swap_dwell_s, i.now,
)
new_dyn_master = master
else:
raise ValueError(f"unknown policy: {i.policy}")
others = [w for w in cfg.wans.keys() if w != master]
if not others:
return DecideOutput(desired_active={master}, reason="single WAN configured",
master_up_since=i.master_up_since,
dynamic_master_current=new_dyn_master,
dynamic_candidate=new_dyn_cand,
dynamic_candidate_since=new_dyn_cand_since,
effective_master=master)
backup = others[0]
master_up = i.eff_state.get(master) == "UP"
backup_up = i.eff_state.get(backup) == "UP"
if not master_up:
new_master_up_since = None
elif i.master_up_since is None:
new_master_up_since = i.now
else:
new_master_up_since = i.master_up_since
if not master_up and not backup_up:
return DecideOutput(
desired_active=set(cfg.wans.keys()),
reason="both WANs DOWN: safety fallback to full redundancy",
master_up_since=new_master_up_since,
dynamic_master_current=new_dyn_master,
dynamic_candidate=new_dyn_cand,
dynamic_candidate_since=new_dyn_cand_since,
effective_master=master,
)
if not master_up and backup_up:
return DecideOutput(
desired_active={backup},
reason=f"master ({master}) DOWN, fail-over to {backup}",
master_up_since=new_master_up_since,
dynamic_master_current=new_dyn_master,
dynamic_candidate=new_dyn_cand,
dynamic_candidate_since=new_dyn_cand_since,
effective_master=master,
)
if master_up and i.currently_active == {backup} and i.policy != "dynamic":
elapsed = i.now - new_master_up_since if new_master_up_since else 0.0
if elapsed >= cfg.policy.failback_hold_s:
return DecideOutput(
desired_active={master},
reason=f"master ({master}) UP for {elapsed:.0f}s, fail-back",
master_up_since=new_master_up_since,
dynamic_master_current=new_dyn_master,
dynamic_candidate=new_dyn_cand,
dynamic_candidate_since=new_dyn_cand_since,
effective_master=master,
)
else:
remaining = cfg.policy.failback_hold_s - elapsed
return DecideOutput(
desired_active={backup},
reason=f"master ({master}) UP but in hysteresis hold ({remaining:.0f}s remaining)",
master_up_since=new_master_up_since,
dynamic_master_current=new_dyn_master,
dynamic_candidate=new_dyn_cand,
dynamic_candidate_since=new_dyn_cand_since,
effective_master=master,
)
return DecideOutput(
desired_active={master},
reason=f"master ({master}) UP, steady state",
master_up_since=new_master_up_since,
dynamic_master_current=new_dyn_master,
dynamic_candidate=new_dyn_cand,
dynamic_candidate_since=new_dyn_cand_since,
effective_master=master,
)
# -- State sensing -----------------------------------------------------------
import os
import re
import time
import json as _json
import http.client
import urllib.parse
import urllib.request
import urllib.error
@dataclass
class WanSample:
state: str
rtt_ms: Optional[float]
loss_pct: Optional[float]
state_since: Optional[float] = None
@dataclass
class StateSnapshot:
ok: bool
per_wan: dict
stale: bool = False
stale_s: float = 0.0
error: str = ""
fetched_at: float = 0.0
def read_local_sbfd_state(path: str,
session_id_to_wan: dict,
stale_threshold_s: float = 10.0) -> StateSnapshot:
try:
st = os.stat(path)
except FileNotFoundError:
return StateSnapshot(ok=False, per_wan={}, error=f"missing: {path}")
except OSError as e:
return StateSnapshot(ok=False, per_wan={}, error=f"stat error: {e}")
age = time.time() - st.st_mtime
try:
with open(path) as f:
raw = _json.load(f)
except (OSError, ValueError) as e:
return StateSnapshot(ok=False, per_wan={}, error=f"parse error: {e}",
stale=age >= stale_threshold_s, stale_s=age)
sessions = raw.get("sessions", {})
by_sid = {}
for sess_data in sessions.values():
sid = sess_data.get("session_id")
if sid is not None:
by_sid[int(sid)] = sess_data
per_wan = {}
for sid, wan_name in session_id_to_wan.items():
sd = by_sid.get(int(sid))
if sd is None:
per_wan[wan_name] = WanSample(state="UNKNOWN", rtt_ms=None, loss_pct=None)
else:
per_wan[wan_name] = WanSample(
state=sd.get("state", "UNKNOWN"),
rtt_ms=sd.get("rtt_ms"),
loss_pct=sd.get("loss_pct"),
state_since=sd.get("state_since"),
)
return StateSnapshot(
ok=True,
per_wan=per_wan,
stale=age >= stale_threshold_s,
stale_s=age,
fetched_at=st.st_mtime,
)
# -- Relay control-plane transport -------------------------------------------
# The controller loop GETs the relay's /state and /fec once per second across
# the management overlay, which in a real deployment rides the metered WAN
# links. urllib opens a fresh TCP connection per call, and for these sub-1KB
# payloads the handshake and teardown outweigh the data itself -- besides adding
# an RTT of staleness to a failover input. So connections are pooled per
# (scheme, host, port) and reused.
#
# A connection is checked OUT of the pool for the duration of a request and
# returned on success, so two callers can never interleave writes on one
# http.client connection and no lock is held across network I/O.
_relay_conns: dict = {}
_relay_conns_lock = threading.Lock()
def close_relay_conns():
"""Drop every pooled relay connection. Safe to call at any time."""
with _relay_conns_lock:
conns = list(_relay_conns.values())
_relay_conns.clear()
for conn in conns:
try:
conn.close()
except OSError:
pass
def _relay_request(url, method="GET", body=None, headers=None, timeout_s=2.0):
"""Request `url` over a pooled keep-alive connection.
Returns (status, reason, body_bytes), and raises OSError / http.client
exceptions on transport failure so callers keep their fail-open handling.
A pooled socket the peer has already closed -- reaped by an idle timeout, or
dropped when the relay daemon restarted -- still looks usable from this side
and only fails on first write or read. That case is retried once on a fresh
connection. A connection that was ALREADY fresh is never retried: the relay
is simply unreachable, and a second attempt would silently double the
caller's timeout budget inside a 0.5s control loop.
"""
parts = urllib.parse.urlsplit(url)
if parts.scheme not in ("http", "https"):
raise ValueError(f"unsupported URL scheme {parts.scheme!r} in {url!r}")
if not parts.hostname:
raise ValueError(f"no host in URL {url!r}")
target = parts.path or "/"
if parts.query:
target = f"{target}?{parts.query}"
key = (parts.scheme, parts.hostname, parts.port)
retried = False
while True:
with _relay_conns_lock:
conn = _relay_conns.pop(key, None)
was_pooled = conn is not None
if not was_pooled:
cls = (http.client.HTTPSConnection if parts.scheme == "https"
else http.client.HTTPConnection)
conn = cls(parts.hostname, parts.port, timeout=timeout_s)
try:
if was_pooled:
# A pooled connection carries the timeout it was built with; the
# live socket needs the current one applied directly. Inside the
# try because a socket the peer already closed raises EBADF
# here, which is exactly the stale case the retry exists for.
conn.timeout = timeout_s
if conn.sock is not None:
conn.sock.settimeout(timeout_s)
conn.request(method, target, body=body, headers=dict(headers or {}))
resp = conn.getresponse()
data = resp.read()
will_close = resp.will_close
except (http.client.HTTPException, OSError):
try:
conn.close()
except OSError:
pass
if not was_pooled or retried:
raise
retried = True
continue
if will_close:
# Peer declined keep-alive (an older HTTP/1.0 relay mid-upgrade, or
# a proxy): don't pool a connection it has already dropped.
try:
conn.close()
except OSError:
pass
else:
with _relay_conns_lock:
if key in _relay_conns:
conn.close() # another caller pooled one while in flight
else:
_relay_conns[key] = conn
return resp.status, resp.reason, data
def fetch_remote_sbfd_state(url: str,
timeout_s: float,
session_id_to_wan: dict) -> StateSnapshot:
"""HTTP GET the relay /state endpoint. Fail-open on any error."""
try:
status, reason, body = _relay_request(url, timeout_s=timeout_s)
except (http.client.HTTPException, OSError, ValueError) as e:
return StateSnapshot(ok=False, per_wan={}, error=f"transport: {e}")
if status != 200:
return StateSnapshot(ok=False, per_wan={}, error=f"HTTP {status}: {reason}")
try:
raw = _json.loads(body.decode())
except (ValueError, UnicodeDecodeError) as e:
return StateSnapshot(ok=False, per_wan={}, error=f"parse: {e}")
by_sid = {}
for sd in raw.get("sessions", {}).values():
sid = sd.get("session_id")
if sid is not None:
by_sid[int(sid)] = sd
per_wan = {}
for sid, wan_name in session_id_to_wan.items():
sd = by_sid.get(int(sid))
if sd is None:
per_wan[wan_name] = WanSample(state="UNKNOWN", rtt_ms=None, loss_pct=None)
else:
per_wan[wan_name] = WanSample(
state=sd.get("state", "UNKNOWN"),
rtt_ms=sd.get("rtt_ms"),
loss_pct=sd.get("loss_pct"),
state_since=sd.get("state_since"),
)
return StateSnapshot(ok=True, per_wan=per_wan, fetched_at=time.time())
def merge_effective(local: StateSnapshot, remote: StateSnapshot) -> dict:
"""DOWN dominates: a WAN is DOWN if a contributing side reports DOWN.
Freshness gating (CR #13): a fresh source always overrides a stale one, so a
stale DOWN can never suppress a WAN that a fresh source reports UP. A stale
source still contributes when the other side has nothing fresher — losing
last-known state entirely would route total blindness into the "both DOWN"
safety fallback. So a stale snapshot is used only if the other side is not
fresh; if both are stale, last-known data (DOWN-dominant) is kept."""
eff = {}
local_fresh = local.ok and not local.stale
remote_fresh = remote.ok and not remote.stale
use_local = local.ok and (local_fresh or not remote_fresh)
use_remote = remote.ok and (remote_fresh or not local_fresh)
wans = set((local.per_wan if local.ok else {}).keys()) | \
set((remote.per_wan if remote.ok else {}).keys())
for w in wans:
l = local.per_wan.get(w) if use_local else None
r = remote.per_wan.get(w) if use_remote else None
states = []
if l: states.append(l.state)
if r: states.append(r.state)
if "DOWN" in states:
eff[w] = "DOWN"
elif "UP" in states:
eff[w] = "UP"
else:
eff[w] = "UNKNOWN"
return eff
import subprocess
# -- nftables actuator -------------------------------------------------------
def compute_nft_init(cfg: Config) -> list:
"""Return nft script lines that idempotently create the table+chain."""
table = f"{cfg.nft.family} {cfg.nft.table}"
return [
f"create table {table}",
f"create chain {table} egress_filter {{ type filter hook output priority 0; }}",
]
def compute_nft_diff(cfg: Config, desired_active: set, current_drops: set) -> list:
"""Return list of nft script lines to converge to (all_wans - desired_active)."""
all_wans = set(cfg.wans.keys())
desired_drops = all_wans - desired_active
to_add = desired_drops - current_drops
to_remove = current_drops - desired_drops
actions = []
table = f"{cfg.nft.family} {cfg.nft.table}"
for wan in sorted(to_add):
actions.append(
f"add rule {table} egress_filter oifname {wan} "
f"ip daddr {cfg.engarde.server_ip} udp dport {cfg.engarde.server_port} drop"
)
for wan in sorted(to_remove):
actions.append(
f"delete rule {table} egress_filter oifname {wan} "
f"ip daddr {cfg.engarde.server_ip} udp dport {cfg.engarde.server_port} drop"
)
return actions
def list_current_drops(cfg: Config) -> set:
try:
out = subprocess.run(
["nft", "-a", "list", "chain", cfg.nft.family, cfg.nft.table, "egress_filter"],
capture_output=True, text=True, check=False,
)
except FileNotFoundError:
logging.error("nft binary not found in PATH")
return set()
if out.returncode != 0:
logging.debug("nft list chain failed: %s", out.stderr.strip())
return set()
drops = set()
for line in out.stdout.splitlines():
s = line.strip()
if " drop" not in s or "oifname" not in s:
continue
toks = s.replace('"', " ").split()
try:
idx = toks.index("oifname")
drops.add(toks[idx + 1])
except (ValueError, IndexError):
continue
return drops
def apply_nft_init(cfg: Config) -> None:
subprocess.run(
["nft", "delete", "table", cfg.nft.family, cfg.nft.table],
capture_output=True, text=True,
)
script = "\n".join(compute_nft_init(cfg)) + "\n"
r = subprocess.run(["nft", "-f", "-"], input=script,
capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError(f"nft init failed: {r.stderr.strip()}")
def _resolve_delete_lines(cfg: Config, actions: list) -> list:
"""nft's `delete rule` only accepts a handle, never a match spec — a
spec-form delete fails the whole `nft -f` batch (per-switch warning noise).
Rewrite delete lines to handle form up front; a delete whose rule is
already absent is dropped (the desired end-state already holds)."""
out = []
for line in actions:
if not line.startswith("delete rule"):
out.append(line)
continue
wan = _wan_from_rule_line(line)
handle = _find_drop_handle(cfg, wan) if wan else None
if handle is None:
logging.debug("nft delete: drop rule for %s already absent; converged", wan)
continue
out.append(f"delete rule {cfg.nft.family} {cfg.nft.table} "
f"egress_filter handle {handle}")
return out
def apply_nft_diff(cfg: Config, actions: list) -> None:
if not actions:
return
actions = _resolve_delete_lines(cfg, actions)
if not actions:
return
script = "\n".join(actions) + "\n"
r = subprocess.run(["nft", "-f", "-"], input=script,
capture_output=True, text=True)
if r.returncode == 0:
return
err = r.stderr.lower()
if "delete" not in err and "no such" not in err and "could not process" not in err:
raise RuntimeError(f"nft apply failed: {r.stderr.strip()}")
logging.warning("nft -f - failed (%s); falling back to per-line", r.stderr.strip())
for line in actions:
r2 = subprocess.run(["nft"] + line.split(),
capture_output=True, text=True)
if r2.returncode == 0:
continue
if line.startswith("delete rule") and " handle " not in line:
wan = _wan_from_rule_line(line)
handle = _find_drop_handle(cfg, wan) if wan else None
if handle is not None:
fallback = ["nft", "delete", "rule", cfg.nft.family, cfg.nft.table,
"egress_filter", "handle", str(handle)]
r3 = subprocess.run(fallback, capture_output=True, text=True)
if r3.returncode == 0:
continue
else:
# Rule is already absent (nft flush, restart, or external
# change). The desired end-state — drop rule gone — already
# holds, so this delete is a no-op. Treating it as an error
# would keep desired != current and re-fire every tick.
logging.debug("nft delete: drop rule for %s already absent; converged", wan)
continue
raise RuntimeError(f"nft action {line!r} failed: {r2.stderr.strip()}")
# -- Kernel default-route actuator -------------------------------------------
# Beats DHCP-installed defaults (typically metric 100/200) by installing our
# own at metric 50, so system traffic (the management overlay, NTP, package mgrs) follows
# the WAN sbfd-ctl considers best — not whichever WAN happened to be installed
# first by the DHCP client.
MANAGED_DEFAULT_METRIC = 50
def pick_default_wan(eff_state: dict, desired_active: set,
configured_master: str,
dynamic_master_current: Optional[str]) -> Optional[str]:
"""Choose the WAN to own the kernel default route. None if all DOWN."""
ups = [w for w in eff_state if eff_state.get(w) == "UP"]
if not ups:
return None
# If engarde is on a single WAN (master_backup), default follows it —
# but only if that WAN is actually UP.
active_ups = [w for w in desired_active if eff_state.get(w) == "UP"]
if len(active_ups) == 1:
return active_ups[0]
# Multiple WANs UP-and-active (full mode, or degenerate): prefer the
# dynamic picker's choice, then configured master, then first UP.
if dynamic_master_current and dynamic_master_current in ups:
return dynamic_master_current
if configured_master in ups:
return configured_master
return sorted(ups)[0]
def worst_active_loss(loss, active_wans):
"""Worst loss among the WANs actually carrying traffic (all WANs when
the active set is empty — mirrors fec_driver_wan's fallback)."""
active = active_wans or set(loss.keys())
return max((loss.get(w, 0.0) for w in active), default=0.0)
def fec_loss_map(local, remote, remote_fresh, wans):
"""Per-WAN loss driving the client->relay FEC leg, plus its source.
sbfd loss_pct is RX-side, so the loss this leg's parity repairs
(client->relay direction) is measured at the RELAY. Prefer the fetched
relay snapshot; the locally measured loss (relay->client direction) is
only a correlation proxy, used when the relay view is missing or stale."""
use_remote = remote.ok and remote_fresh
src, source = (remote, "relay") if use_remote else (local, "local")
loss = {}
for w in wans:
s = src.per_wan.get(w) if src.ok else None
loss[w] = s.loss_pct if (s and s.loss_pct is not None) else 0.0
return loss, source
def compute_fec_target(fec_cfg, mode, eff, loss, active_wans, loss_table=None):
"""Pure: map mode/effective-state/loss to a FEC table level (the
pre-fec-mode-override adaptive choice). Loss = worst among the WANs
actually carrying traffic. loss_table overrides fec_cfg's (per-WAN
profiles); None keeps the global table."""
table = loss_table if loss_table is not None else fec_cfg.loss_table
up_count = sum(1 for w, st in eff.items() if st == "UP")
active_loss = worst_active_loss(loss, active_wans)
return fec_control.mode_aware_level(
mode, up_count, active_loss, table,
fec_cfg.full_min_up_wans, fec_cfg.full_mode_backoff_fec)
def fec_driver_wan(loss, active_wans):
"""The active WAN whose loss feeds compute_fec_target (the max-loss one).
Uses the same active fallback as compute_fec_target. None if no candidates.
active_wans is a set, so its iteration order is hash-dependent; sort it
first so a tie (e.g. both WANs at 0.0 loss) resolves deterministically
instead of depending on set hash order — the driver now selects FEC
policy, so nondeterminism here would make profile selection flaky."""
active = active_wans or set(loss.keys())
if not active:
return None
return max(sorted(active), key=lambda w: loss.get(w, 0.0))
def fec_driver_pick(loss, active_wans, current, candidate, candidate_since,
dwell_s, now, prev_active=None):
"""Sticky version of fec_driver_wan: (driver, candidate, candidate_since).
The driver picks the WHOLE FEC policy — table, floor, hysteresis — so
changing it swaps the ladder beneath the adaptive engine and reseeds its
runtime. step_level damps the ratio against loss jitter, but nothing damped
this, so on a duplicated stream where both links are near zero loss the
driver flipped on noise: measured 82 profile switches in 24h, median 95s
apart, every one of them in full redundancy where the ratio should not have
moved at all.
The challenger is always fec_driver_wan's pick — the worst active link,
ties broken deterministically — and it must hold that position for dwell_s
before taking over. Dwell alone is the whole mechanism: an excursion
shorter than dwell_s is ignored, a sustained one is followed, and because a
tie resolves to the same WAN every tick, the driver returns to the quiet
state's pick once the excursion passes. That return matters beyond
tidiness: the cell signal floor only engages while the cellular WAN is the
driver, so a driver that never came home would silently disarm it.
A loss MARGIN was tried here and removed: whenever no WAN cleared it, the
same WAN challenged anyway as the canonical pick, so it never changed
whether a flip was damped — only which WAN challenged when three or more
were active, and there it picked the first by name rather than the worst.
Only one WAN active — every mode but full redundancy — has no race to lose
and short-circuits, so this cannot delay a master_backup failover.
prev_active is last tick's set. Incumbency means "worst of THIS field for
dwell_s", a claim a WAN that just joined never got to contest, so when the
canonical pick is a newcomer it takes over at once instead of owing dwell.
Entering full redundancy is that case: the second link joins, both are
clean, and the tie hands the driver to a WAN the incumbent had no race
against — waiting 120s there just runs the wrong profile on a live link.
Only the newcomer skips the queue; a WAN that was already active keeps
serving its dwell, and a departure leaves a challenge in flight untouched,
so the anti-flap damping still covers every same-membership tick, which is
where the measured thrash lived. Pass None (the default) when last tick's
set is unknown and every WAN is treated as an incumbent.
"""
active = active_wans or set(loss.keys())
if not active:
return None, None, None
if len(active) == 1:
return next(iter(active)), None, None
if current is None or current not in active:
# Nothing to be sticky about yet (boot, or the incumbent stopped
# carrying traffic): take the raw ranking and start clean.
return fec_driver_wan(loss, active), None, None
challenger = fec_driver_wan(loss, active)
if prev_active and challenger is not None and challenger not in prev_active:
return challenger, None, None
if challenger is None or challenger == current:
return current, None, None
if candidate == challenger and candidate_since is not None:
# Same challenger as last tick: let its clock run rather than
# restarting it, or a challenge could never accumulate dwell.
if now - candidate_since >= dwell_s:
return challenger, None, None
return current, candidate, candidate_since
return current, challenger, now
def resolve_fec_profile(fec_cfg, driver_wan):
"""(name, loss_table, hysteresis, profile_floor, signal_floor_fec) for the
current fec driver WAN. profile_floor is None for the default profile so
effective_fec_floor_ratio falls through to the config default."""
p = fec_cfg.wan_profiles.get(driver_wan) if driver_wan else None
if p is None:
return ("default", fec_cfg.loss_table,
fec_control.FecHysteresis(fec_cfg.ramp_up_ticks,
fec_cfg.ramp_down_hold_s),
None, fec_control.DEFAULT_SIGNAL_FLOOR_FEC)
return (p.name, p.loss_table,
fec_control.FecHysteresis(p.ramp_up_ticks, p.ramp_down_hold_s),
p.floor_ratio, p.signal_floor_fec)
def fec_reseed_runtime(rt, old_table, new_table, now):
"""Client-side name for fec_control.reseed_runtime, which both legs share.
The rationale (and the live incident behind it) lives with the helper."""
return fec_control.reseed_runtime(rt, old_table, new_table, now)
def fec_profile_candidates(cfg: Config, ov: RuntimeOverlay):
"""[(loss_table, floor_ratio)] for every profile that could drive FEC.
The driver WAN is chosen per tick, so any of these can be active moments
from now; the UI's scale has to span all of them or its positions would
shift under the operator on a driver change. Each floor goes through the
same precedence the live path uses, so a runtime override is reflected in
the scale rather than sitting off the end of it."""
if not cfg.fec:
return []
out = [(cfg.fec.loss_table, effective_fec_floor_ratio(cfg, ov))]
for p in cfg.fec.wan_profiles.values():
out.append((p.loss_table,
effective_fec_floor_ratio(cfg, ov,
profile_floor=p.floor_ratio)))
return out
def should_post_fec(desired, last_acked, last_post_ts, now, heartbeat_s=30.0):
"""Reconcile decision: POST when desired differs from last-acked (assert until
acked), on the first tick, or once the heartbeat elapses (defends against an
relay restart that reverted to its default)."""
if desired != last_acked:
return True
if last_post_ts is None:
return True
return (now - last_post_ts) >= heartbeat_s
def _relay_ladder_table(data, ladder_inputs):
"""The loss table to rebuild the relay's row against, or None to keep the
relay's own ladder.
Every setting the rebuild needs must be present IN THE RELAY'S REPORT.
Substituting our desired values for missing ones would publish a floor and
a reachable span the relay never claimed — which is precisely what this
card must never do, since the two disagree exactly when it matters (an
unacknowledged push, or a restart that reverted the relay to its config).
A relay too old to report them keeps its own ladder instead.
`profile` must also be a string: /fec is remote JSON, and an unhashable
value would raise on the dict lookup and take the controller loop with it.