"""Observe NM recovery; latch only a fresh, proven Core path. Never scan or disconnect.""" import secrets import time TERMINAL = {"applied", "rolled_back", "superseded", "recovering"} class Observation: def restore_adoption(self): pending = (self.operation or {}).get("adoption") if not pending: return self.adapter.restore_profiles(pending["profiles"]) if pending["epoch"] == self.adapter.epoch(): self.adapter.restore_metrics(pending["entries"]) self.operation.pop("adoption") self.save() def observe(self): op = self.operation if not self.context or not self.path_adapter or (op and op["phase"] not in TERMINAL): return if op and op.get('profiles_pending'): return # Restoring profiles must complete before any recovery receipt. try: state = self.adapter.inspect(known=self.known()) candidates = sorted(state["candidates"], key=lambda e: e["id"] != state["current_id"]) chosen, policy = None, None for candidate in candidates: if (op and not self.fallback_enabled() and not op.get('local_override') and candidate['id'] != self.watched_target()): continue proof = self.path_adapter.prepare(self.context["peer"], candidate["interface"]) if self.path_adapter.evidence(proof): chosen, policy = candidate, proof break if chosen is None: self.observed_candidate = None return if ( op and op["phase"] != "recovering" and chosen["id"] == self.watched_target() and op.get("proof_context") == self.context and op.get("watch_policy", op.get("policy")) == policy ): self.observed_candidate = None return # Two separate authenticated Core replies, with a stable physical path. key = (chosen["id"], self.adapter.epoch(), str(self.context)) pending = getattr(self, "observed_candidate", None) if not pending or pending[0] != key: self.observed_candidate = (key, self.clock()) return if self.clock() - pending[1] < 10: return # A local operator owns later profile edits. We observe these without # rewriting them. Health/lease changes alone do not alter saved settings. owned = {e["id"]: e.get("planned") for e in (op or {}).get("profile_baseline", [])} current = self.adapter.profile_preferences() foreign = bool((op or {}).get("local_override")) or any( identity in current and current[identity]["saved"] != expected for identity, expected in owned.items() if expected is not None ) profiles = [] # A recovered exchange on the same physical channel requires no # NetworkManager reapply (which can renew DHCP and change addresses). if op and owned and not foreign and chosen['id'] != self.watched_target(): affected = {e["id"]: e for e in op["profile_baseline"] if e["id"] in current} affected.update({e["id"]: e for e in state["candidates"]}) profiles = self.adapter.snapshot_profiles(list(affected.values()), chosen["id"]) for entry in profiles: entry["planned"]["autoconnect"] = entry["saved"]["autoconnect"] op["adoption"] = dict( profiles=profiles, entries=state["candidates"], epoch=self.adapter.epoch() ) self.save() try: self.adapter.prefer_observed(state["candidates"], chosen["id"], profiles) except Exception: self.restore_adoption() raise op.pop("adoption") if op is None: self.operation = op = dict( network_policy="native-fallback-v2", id=secrets.token_hex(16), binding=self.context["binding"], target=chosen["id"], previous=chosen["id"], baseline=state["candidates"], policy=policy, known=state["candidates"], profile_baseline=[ dict(e, planned=e["saved"]) for e in state["candidates"] ], ) if op.get('phase') == 'recovering': reason = op.get('recovery_reason', 'automatic') previous = op['target'] if reason == 'manual_rollback' else self.watched_target() old = next((e for e in self.known() if e['id'] == previous), None) if old and (previous != chosen['id'] or reason == 'manual_rollback'): event = dict(id=secrets.token_hex(16), at=time.time(), kind=('manual_rollback' if reason == 'manual_rollback' else 'fallback'), source=old['kind'], target=chosen['kind']) op['events'] = [*op.get('events', []), event][-8:] op.update( network_policy="native-fallback-v2", phase=('rolled_back' if op.get('phase') == 'recovering' and chosen['id'] == op['previous'] else 'superseded'), watch_target=chosen["id"], watch_policy=policy, proof_context=self.context.copy(), message="Связь восстановлена. Используется текущее подключение.", ) if profiles: op["profile_baseline"] = profiles elif foreign: op["profile_baseline"] = [] # Do not resume ownership after a local edit. if not foreign: self.select_path(policy) op.pop('recovery_tried', None) op.pop('recovery_attempt_at', None) self.path_ok = True self.observed_candidate = None self.save() except Exception: self.observed_candidate = None # Never turn a failed observation into a network operation.