-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpoint_store.py
More file actions
1940 lines (1710 loc) · 77.4 KB
/
Copy pathendpoint_store.py
File metadata and controls
1940 lines (1710 loc) · 77.4 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
"""Endpoint persistence + correlation/event detection (Phase 2.7).
This module owns all reads and writes against the `endpoints`, `endpoint_events`,
`collection_runs`, and `sweep_runs` tables. Callers (endpoint_collector,
discovery, API endpoints) use this module instead of touching the ORM directly.
"""
from __future__ import annotations
import json
import os
from datetime import datetime, timedelta, timezone
from pathlib import Path
from sqlalchemy import delete, func, select
from app import db
from app.logging_config import StructuredLogger
log = StructuredLogger(__name__, module="endpoint_store")
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _parse_dt(value) -> datetime | None:
if not value:
return None
if isinstance(value, datetime):
return value
try:
return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return None
def _now() -> datetime:
return datetime.now(timezone.utc)
# ---------------------------------------------------------------------------
# Endpoint upsert with diff/event generation
# ---------------------------------------------------------------------------
async def _is_watched(session, mac: str) -> bool:
row = (await session.execute(
select(db.EndpointWatch).where(db.EndpointWatch.mac_address == mac)
)).scalar_one_or_none()
return row is not None
async def upsert_endpoint(ep_dict: dict, source: str = "infrastructure",
uplinks: set[tuple[str, str]] | None = None,
change_source: str | None = None) -> dict:
"""Upsert an endpoint observation, keyed on (mac, switch, port, vlan).
Behavior:
- Skips records on uplink ports (logged at DEBUG, no row written).
- If a row already exists for the exact (mac, switch, port, vlan), update
its last_seen and metadata in place.
- If the MAC has other active rows on different (switch, port, vlan)
combinations, mark them inactive and create a new active row.
- Generates `appeared`, `moved_port`, `moved_switch`, `ip_changed`, and
`hostname_changed` events as appropriate.
- When a watched MAC moves, the resulting event gets `details.watched=true`.
Returns: {"action": "new"|"updated"|"unchanged"|"skipped_uplink"|"skipped",
"events": [...]}.
"""
mac = (ep_dict.get("mac") or ep_dict.get("mac_address") or "").upper()
if not mac:
return {"action": "skipped", "events": []}
new_ip = ep_dict.get("ip") or ep_dict.get("current_ip") or None
new_additional_ips = list(ep_dict.get("additional_ips") or [])
if new_ip and new_ip not in new_additional_ips:
new_additional_ips.append(new_ip)
new_switch = ep_dict.get("device_name") or ep_dict.get("current_switch") or None
new_port = ep_dict.get("switch_port") or ep_dict.get("current_port") or None
new_vlan_raw = ep_dict.get("vlan") or ep_dict.get("current_vlan")
try:
new_vlan = int(new_vlan_raw) if new_vlan_raw not in (None, "", "0") else 0
except (TypeError, ValueError):
new_vlan = 0
new_hostname = ep_dict.get("hostname") or None
now = _now()
last_seen = _parse_dt(ep_dict.get("last_seen")) or now
first_seen = _parse_dt(ep_dict.get("first_seen")) or now
# Composite key requires non-null parts. Sweep-only endpoints (no switch
# context) cannot be located on a port — store with sentinel values so the
# MAC identity is still tracked, but they won't move/conflict with infra rows.
new_switch = new_switch or "(none)"
new_port = new_port or "(none)"
# Uplink check: if (switch, port) is in the uplink set, this MAC is just
# transiting a trunk/cross-link. Don't record it as a host location.
if uplinks and (new_switch, new_port) in uplinks:
log.debug("uplink_skip", "Skipping endpoint on uplink port (LLDP/cable)",
context={"mac": mac, "switch": new_switch, "port": new_port})
return {"action": "skipped_uplink", "events": []}
# Secondary uplink check: the collector tags each endpoint with
# `is_access_port`. If False, it was learned on a LAG/IRB/loopback/trunk
# interface — i.e. transit, not an endpoint location. The Nautobot LAG
# mapping is often incomplete, so this catches LAG members that the
# primary uplink set missed.
if ep_dict.get("is_access_port") is False and new_port != "(none)":
log.debug("uplink_skip", "Skipping endpoint on non-access interface",
context={"mac": mac, "switch": new_switch, "port": new_port})
return {"action": "skipped_uplink", "events": []}
events: list[tuple[str, str | None, str | None, dict]] = []
async with db.SessionLocal() as session:
watched = await _is_watched(session, mac)
# 1. Try to find an exact match for the new location
exact = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.mac_address == mac,
db.Endpoint.current_switch == new_switch,
db.Endpoint.current_port == new_port,
db.Endpoint.current_vlan == new_vlan,
)
)).scalar_one_or_none()
# 1b. VLAN upgrade: if no exact match but there's a row on the same
# switch/port with vlan=0 (sentinel for "unknown"), and we now have a
# real VLAN, delete the sentinel row and let the code create a new one
# with the correct VLAN. This prevents stale vlan=0 rows from persisting
# indefinitely after VLAN inference is added.
if exact is None and new_vlan != 0:
sentinel = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.mac_address == mac,
db.Endpoint.current_switch == new_switch,
db.Endpoint.current_port == new_port,
db.Endpoint.current_vlan == 0,
)
)).scalar_one_or_none()
if sentinel is not None:
await session.delete(sentinel)
await session.flush()
# 2. Find any other active rows for this MAC (potential prior locations)
other_active = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.mac_address == mac,
db.Endpoint.active.is_(True),
)
)).scalars().all()
prior = None
for row in other_active:
if exact is None or (row.current_switch != new_switch or
row.current_port != new_port or
row.current_vlan != new_vlan):
prior = row # remember one prior to derive event metadata
row.active = False
action = "unchanged"
# Field-level change diff — captured as (field_name, old, new) tuples
# and written as ChangeHistory rows before commit. This tracks the
# MAC's life story, orthogonal to EndpointEvent which tracks movement.
diffs: list[tuple[str, str | None, str | None]] = []
if exact is not None:
# Update in place — same physical location seen again.
if not exact.active:
exact.active = True
action = "updated"
if new_ip and exact.current_ip and new_ip != exact.current_ip:
events.append(("ip_changed", exact.current_ip, new_ip, {}))
diffs.append(("ip", exact.current_ip, new_ip))
action = "updated"
if new_hostname and exact.hostname and new_hostname != exact.hostname:
events.append(("hostname_changed", exact.hostname, new_hostname, {}))
diffs.append(("hostname", exact.hostname, new_hostname))
action = "updated"
if ep_dict.get("classification") and exact.classification != ep_dict["classification"]:
diffs.append(("classification", exact.classification or None, ep_dict["classification"]))
if ep_dict.get("mac_vendor") and exact.mac_vendor != ep_dict["mac_vendor"]:
diffs.append(("mac_vendor", exact.mac_vendor or None, ep_dict["mac_vendor"]))
if new_ip:
exact.current_ip = new_ip
if new_additional_ips:
merged = list(exact.additional_ips or [])
for ip in new_additional_ips:
if ip and ip not in merged:
merged.append(ip)
exact.additional_ips = merged
if ep_dict.get("mac_vendor"):
exact.mac_vendor = ep_dict["mac_vendor"]
if new_hostname:
exact.hostname = new_hostname
if ep_dict.get("classification") and not exact.classification_override:
exact.classification = ep_dict["classification"]
if ep_dict.get("classification_confidence") and not exact.classification_override:
exact.classification_confidence = ep_dict["classification_confidence"]
if ep_dict.get("dhcp_server"):
exact.dhcp_server = ep_dict["dhcp_server"]
if ep_dict.get("lease_start"):
exact.dhcp_lease_start = _parse_dt(ep_dict["lease_start"])
if ep_dict.get("lease_expiry"):
exact.dhcp_lease_expiry = _parse_dt(ep_dict["lease_expiry"])
exact.last_seen = last_seen
if exact.data_source and exact.data_source != source:
exact.data_source = "both"
elif not exact.data_source:
exact.data_source = source
else:
# New (mac, switch, port, vlan) — create a new active row.
ep = db.Endpoint(
mac_address=mac,
current_switch=new_switch,
current_port=new_port,
current_vlan=new_vlan,
active=True,
is_uplink=False,
current_ip=new_ip,
additional_ips=new_additional_ips,
mac_vendor=ep_dict.get("mac_vendor") or "",
hostname=new_hostname or "",
classification=ep_dict.get("classification") or "",
classification_confidence=ep_dict.get("classification_confidence") or "",
dhcp_server=ep_dict.get("dhcp_server") or "",
dhcp_lease_start=_parse_dt(ep_dict.get("lease_start")),
dhcp_lease_expiry=_parse_dt(ep_dict.get("lease_expiry")),
first_seen=first_seen,
last_seen=last_seen,
data_source=source,
)
session.add(ep)
if prior is None:
events.append(("appeared", None, mac,
{"ip": new_ip, "switch": new_switch, "port": new_port}))
action = "new"
else:
# Movement detected
if prior.current_switch != new_switch:
events.append(("moved_switch", prior.current_switch, new_switch,
{"old_port": prior.current_port, "new_port": new_port}))
diffs.append(("switch", prior.current_switch, new_switch))
else:
events.append(("moved_port", prior.current_port, new_port,
{"switch": new_switch}))
diffs.append(("port", prior.current_port, new_port))
if prior.current_vlan != new_vlan:
diffs.append(("vlan", str(prior.current_vlan), str(new_vlan)))
if new_ip and prior.current_ip and new_ip != prior.current_ip:
events.append(("ip_changed", prior.current_ip, new_ip, {}))
diffs.append(("ip", prior.current_ip, new_ip))
if new_hostname and prior.hostname and new_hostname != prior.hostname:
events.append(("hostname_changed", prior.hostname, new_hostname, {}))
diffs.append(("hostname", prior.hostname, new_hostname))
action = "updated"
for ev_type, old, new, details in events:
details = dict(details or {})
if watched:
details["watched"] = True
session.add(db.EndpointEvent(
mac_address=mac,
event_type=ev_type,
old_value=old,
new_value=new,
details=details,
timestamp=now,
))
# Write field-level change history (separate from EndpointEvent)
effective_source = change_source or source or "unknown"
for field_name, old_val, new_val in diffs:
session.add(db.ChangeHistory(
target_type="endpoint",
target_id=mac,
field_name=field_name,
old_value=str(old_val) if old_val is not None else None,
new_value=str(new_val) if new_val is not None else None,
change_source=effective_source,
changed_at=now,
))
# ------------------------------------------------------------------
# Cross-row IP correlation: the IP belongs to the MAC, not to the
# (mac, switch, port, vlan) row. A Proxmox upsert that has no IP can
# inherit one from an infrastructure-source row that learned it from
# the switch ARP table, and vice versa.
# ------------------------------------------------------------------
await session.flush()
# Pull every active row for this MAC after the flush so newly added
# rows are visible.
siblings = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.mac_address == mac,
db.Endpoint.active.is_(True),
)
)).scalars().all()
# Find the canonical IP for this MAC (any active row's current_ip).
# Prefer the IP we were just given; otherwise pick any non-null one.
canonical_ip = new_ip
if not canonical_ip:
for s in siblings:
if s.current_ip:
canonical_ip = s.current_ip
break
# Build the union of every IP this MAC has been seen with, across
# all (switch, port, vlan) rows. This is the "all known IPs" view.
union_ips: list[str] = []
for s in siblings:
if s.current_ip and s.current_ip not in union_ips:
union_ips.append(s.current_ip)
for ip in (s.additional_ips or []):
if ip and ip not in union_ips:
union_ips.append(ip)
for ip in new_additional_ips:
if ip and ip not in union_ips:
union_ips.append(ip)
for s in siblings:
if canonical_ip and not s.current_ip:
s.current_ip = canonical_ip
if union_ips:
# Replace with the union (including the row's own current_ip
# if it differs) so every row reflects the full picture.
merged = [ip for ip in union_ips if ip != s.current_ip]
s.additional_ips = merged
await session.commit()
return {"action": action, "events": [e[0] for e in events]}
# ---------------------------------------------------------------------------
# Reads
# ---------------------------------------------------------------------------
async def list_endpoints(include_inactive: bool = False) -> list[dict]:
"""Default: only the currently-active row per (mac, switch, port, vlan)."""
async with db.SessionLocal() as session:
stmt = select(db.Endpoint)
if not include_inactive:
stmt = stmt.where(db.Endpoint.active.is_(True))
rows = (await session.execute(stmt)).scalars().all()
return [r.to_dict() for r in rows]
async def count_endpoints() -> int:
"""Count of unique active MACs."""
async with db.SessionLocal() as session:
return (await session.execute(
select(func.count(func.distinct(db.Endpoint.mac_address)))
.where(db.Endpoint.active.is_(True))
)).scalar_one()
async def count_distinct_ips() -> int:
"""Count of unique IPs across all active endpoint rows.
This is the "what does MNM actually know about?" view, as opposed to
Nautobot IPAM which only contains rows that the sweep + collector mirror
successfully wrote. Includes Proxmox-source IPs that don't get mirrored
to Nautobot at all.
"""
async with db.SessionLocal() as session:
return (await session.execute(
select(func.count(func.distinct(db.Endpoint.current_ip)))
.where(db.Endpoint.active.is_(True), db.Endpoint.current_ip.isnot(None))
)).scalar_one()
async def get_endpoint(mac: str) -> dict | None:
"""Return the currently-active row for a MAC (most recent if multiple)."""
mac = mac.upper()
async with db.SessionLocal() as session:
row = (await session.execute(
select(db.Endpoint)
.where(db.Endpoint.mac_address == mac, db.Endpoint.active.is_(True))
.order_by(db.Endpoint.last_seen.desc())
)).scalars().first()
if row is None:
# Fall back to most recent inactive row so detail pages still work
row = (await session.execute(
select(db.Endpoint)
.where(db.Endpoint.mac_address == mac)
.order_by(db.Endpoint.last_seen.desc())
)).scalars().first()
return row.to_dict() if row else None
async def get_endpoint_history(mac: str) -> list[dict]:
"""Return all rows (active + inactive) for a MAC, ordered by last_seen.
This shows every (switch, port, vlan) the MAC has ever been recorded on,
in chronological order — i.e. its movement history at the row level.
"""
mac = mac.upper()
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.Endpoint)
.where(db.Endpoint.mac_address == mac)
.order_by(db.Endpoint.last_seen.asc())
)).scalars().all()
return [r.to_dict() for r in rows]
async def get_endpoint_events(mac: str, limit: int = 500) -> list[dict]:
mac = mac.upper()
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.EndpointEvent)
.where(db.EndpointEvent.mac_address == mac)
.order_by(db.EndpointEvent.timestamp.desc())
.limit(limit)
)).scalars().all()
return [r.to_dict() for r in rows]
async def get_recent_events(event_type: str | None = None, since_hours: int = 24, limit: int = 500) -> list[dict]:
cutoff = _now() - timedelta(hours=since_hours)
async with db.SessionLocal() as session:
stmt = select(db.EndpointEvent).where(db.EndpointEvent.timestamp >= cutoff)
if event_type:
stmt = stmt.where(db.EndpointEvent.event_type == event_type)
stmt = stmt.order_by(db.EndpointEvent.timestamp.desc()).limit(limit)
rows = (await session.execute(stmt)).scalars().all()
return [r.to_dict() for r in rows]
async def register_mac_ip(mac: str, ip: str) -> bool:
"""Propagate an IP to every active row for a MAC, without creating a new
row. Used by the infrastructure collector when it learns an IP from a
switch ARP table for a MAC whose only location is an uplink/LAG port —
in that case the upsert path skips the row creation, but we still want
the IP to land on the Proxmox / sweep rows for that same MAC.
Returns True if at least one row was updated.
"""
if not mac or not ip:
return False
mac = mac.upper()
updated = False
async with db.SessionLocal() as session:
siblings = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.mac_address == mac,
db.Endpoint.active.is_(True),
)
)).scalars().all()
if not siblings:
return False
for s in siblings:
if not s.current_ip:
s.current_ip = ip
updated = True
existing = list(s.additional_ips or [])
if ip not in existing and ip != s.current_ip:
existing.append(ip)
s.additional_ips = existing
updated = True
if updated:
await session.commit()
return updated
async def _get_stale_threshold_days() -> int:
"""Resolve the stale-endpoint threshold in days.
Resolution order:
1. ``anomaly_stale_days`` key in the ``kv_config`` table (operator-set
override via ``POST /api/config``)
2. ``ANOMALY_STALE_DAYS`` environment variable
3. Default: 7 days
"""
default = 7
try:
env_val = int(os.environ.get("ANOMALY_STALE_DAYS", str(default)))
except (TypeError, ValueError):
env_val = default
try:
async with db.SessionLocal() as session:
row = (await session.execute(
select(db.KVConfig).where(db.KVConfig.key == "controller_config")
)).scalar_one_or_none()
if row and isinstance(row.value, dict):
cfg_val = row.value.get("anomaly_stale_days")
if isinstance(cfg_val, (int, float)) and cfg_val > 0:
return int(cfg_val)
except Exception:
pass
return env_val
async def get_anomalies() -> dict:
"""Detect endpoints that look wrong, suspicious, or unidentifiable.
Categories:
- ``ip_conflicts``: same IP claimed by more than one MAC (active rows).
- ``multi_location``: a single MAC active on more than one switch
simultaneously. Legitimate during a move; suspicious otherwise.
- ``no_ip``: active endpoint with no current_ip and no additional_ips —
we know it's there but cannot reach or correlate it with anything.
- ``unclassified``: active endpoint with classification empty / unknown
and no hostname — neither sweep nor any connector identified it.
- ``stale``: active endpoint last seen more than ``anomaly_stale_days``
ago (default 7, configurable via env var ``ANOMALY_STALE_DAYS`` or
the ``anomaly_stale_days`` key in kv_config). Either the device was
decommissioned, the collector stopped seeing it, or it moved to a
port we aren't watching.
Returns ``{"ip_conflicts": [...], "multi_location": [...], "no_ip": [...],
"unclassified": [...], "stale": [...], "summary": {...}}``.
"""
stale_days = await _get_stale_threshold_days()
cutoff_stale = _now() - timedelta(days=stale_days)
result: dict = {
"ip_conflicts": [],
"multi_location": [],
"no_ip": [],
"unclassified": [],
"stale": [],
}
async with db.SessionLocal() as session:
# IP conflicts (reuses the same query as get_ip_conflicts)
rows = await session.execute(
select(db.Endpoint.current_ip,
func.count(func.distinct(db.Endpoint.mac_address)).label("n"))
.where(db.Endpoint.current_ip.isnot(None), db.Endpoint.active.is_(True))
.group_by(db.Endpoint.current_ip)
.having(func.count(func.distinct(db.Endpoint.mac_address)) > 1)
)
for ip, n in rows.all():
macs = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.current_ip == ip, db.Endpoint.active.is_(True)
)
)).scalars().all()
result["ip_conflicts"].append({
"ip": ip, "mac_count": n,
"macs": [m.to_dict() for m in macs],
})
# Multi-location: MAC with >1 distinct active switch
rows = await session.execute(
select(db.Endpoint.mac_address,
func.count(func.distinct(db.Endpoint.current_switch)).label("n"))
.where(db.Endpoint.active.is_(True),
db.Endpoint.current_switch != "(none)",
db.Endpoint.is_uplink.is_(False))
.group_by(db.Endpoint.mac_address)
.having(func.count(func.distinct(db.Endpoint.current_switch)) > 1)
)
for mac, n in rows.all():
locs = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.mac_address == mac, db.Endpoint.active.is_(True)
)
)).scalars().all()
result["multi_location"].append({
"mac": mac, "location_count": n,
"locations": [l.to_dict() for l in locs],
})
# No-IP: active endpoint with no current_ip AND no additional_ips
no_ip_rows = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.active.is_(True),
db.Endpoint.current_ip.is_(None),
)
)).scalars().all()
for r in no_ip_rows:
if r.additional_ips:
continue
if r.current_switch == "(none)":
continue # sweep-only sentinel rows aren't useful here
result["no_ip"].append(r.to_dict())
# Unclassified: active, no classification (or 'unknown'), no hostname
unclass_rows = (await session.execute(
select(db.Endpoint).where(db.Endpoint.active.is_(True))
)).scalars().all()
for r in unclass_rows:
classification = (r.classification or "").lower()
if classification and classification != "unknown":
continue
if r.hostname:
continue
result["unclassified"].append(r.to_dict())
# Stale: active but not seen in 7 days
stale_rows = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.active.is_(True),
db.Endpoint.last_seen < cutoff_stale,
)
)).scalars().all()
result["stale"] = [r.to_dict() for r in stale_rows]
result["summary"] = {
"ip_conflicts": len(result["ip_conflicts"]),
"multi_location": len(result["multi_location"]),
"no_ip": len(result["no_ip"]),
"unclassified": len(result["unclassified"]),
"stale": len(result["stale"]),
"total": sum(len(v) for k, v in result.items() if k != "summary"),
}
return result
async def get_ip_conflicts() -> list[dict]:
"""Find IPs currently claimed by more than one distinct MAC (active rows)."""
async with db.SessionLocal() as session:
result = await session.execute(
select(db.Endpoint.current_ip,
func.count(func.distinct(db.Endpoint.mac_address)).label("n"))
.where(db.Endpoint.current_ip.isnot(None), db.Endpoint.active.is_(True))
.group_by(db.Endpoint.current_ip)
.having(func.count(func.distinct(db.Endpoint.mac_address)) > 1)
)
conflicts = []
for ip, n in result.all():
macs_rows = (await session.execute(
select(db.Endpoint).where(
db.Endpoint.current_ip == ip,
db.Endpoint.active.is_(True),
)
)).scalars().all()
conflicts.append({
"ip": ip,
"mac_count": n,
"macs": [m.to_dict() for m in macs_rows],
})
return conflicts
# ---------------------------------------------------------------------------
# Watchlist
# ---------------------------------------------------------------------------
async def list_watches() -> list[dict]:
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.EndpointWatch).order_by(db.EndpointWatch.created_at.desc())
)).scalars().all()
return [r.to_dict() for r in rows]
async def add_watch(mac: str, reason: str = "", created_by: str = "") -> dict:
mac = mac.upper()
async with db.SessionLocal() as session:
existing = (await session.execute(
select(db.EndpointWatch).where(db.EndpointWatch.mac_address == mac)
)).scalar_one_or_none()
if existing:
existing.reason = reason or existing.reason
existing.created_by = created_by or existing.created_by
await session.commit()
return existing.to_dict()
row = db.EndpointWatch(mac_address=mac, reason=reason, created_by=created_by)
session.add(row)
await session.commit()
return row.to_dict()
async def remove_watch(mac: str) -> bool:
mac = mac.upper()
async with db.SessionLocal() as session:
existing = (await session.execute(
select(db.EndpointWatch).where(db.EndpointWatch.mac_address == mac)
)).scalar_one_or_none()
if not existing:
return False
await session.delete(existing)
await session.commit()
return True
async def is_watched(mac: str) -> bool:
async with db.SessionLocal() as session:
return await _is_watched(session, mac.upper())
# ---------------------------------------------------------------------------
# Discovery exclusions (operator-controlled scope, Rule 6)
# ---------------------------------------------------------------------------
#
# When the operator marks an IP as excluded:
# - the sweep skips it before probing
# - the infrastructure collector skips ARP/MAC correlation for it
# - the Incomplete Devices advisory hides any Nautobot device whose
# primary IP (or interface IP) is in this list
#
# All three call sites pull the full set into memory once at the start of
# their run rather than hitting the DB per IP. The set is small (typically
# a handful of entries) so we just keep an in-process cache and rely on the
# CRUD helpers to invalidate it on writes.
EXCLUDE_TYPE_IP = "ip"
EXCLUDE_TYPE_DEVICE_NAME = "device_name"
_VALID_EXCLUDE_TYPES = {EXCLUDE_TYPE_IP, EXCLUDE_TYPE_DEVICE_NAME}
_exclude_cache_ip: set[str] | None = None
_exclude_cache_device: set[str] | None = None
def _invalidate_exclude_cache() -> None:
global _exclude_cache_ip, _exclude_cache_device
_exclude_cache_ip = None
_exclude_cache_device = None
async def list_excludes() -> list[dict]:
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.DiscoveryExclude).order_by(db.DiscoveryExclude.created_at.desc())
)).scalars().all()
return [r.to_dict() for r in rows]
async def get_excluded_ips() -> set[str]:
"""Return the full set of excluded IP identifiers.
Cached in-process; the cache is invalidated on add/remove. Callers
should refresh once at the start of a run, not per IP.
"""
global _exclude_cache_ip
if _exclude_cache_ip is not None:
return _exclude_cache_ip
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.DiscoveryExclude.identifier)
.where(db.DiscoveryExclude.type == EXCLUDE_TYPE_IP)
)).scalars().all()
_exclude_cache_ip = {r for r in rows if r}
return _exclude_cache_ip
async def get_mac_ip_map_from_observations() -> dict[str, set[str]]:
"""Build MAC→IPs map from ip_observations table (sweep data).
This supplements ARP-derived IPs with IPs discovered during sweeps,
enabling multi-IP endpoint correlation for devices like the SRX320
that have IPs only visible through sweep, not through any node's ARP table.
"""
if not db.is_ready():
return {}
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.IPObservation.mac_address, db.IPObservation.ip_address)
.where(db.IPObservation.mac_address.isnot(None))
)).all()
result: dict[str, set[str]] = {}
for mac, ip in rows:
if mac and ip:
result.setdefault(mac.upper(), set()).add(ip)
return result
async def get_excluded_device_names() -> set[str]:
"""Return the full set of excluded device-name identifiers."""
global _exclude_cache_device
if _exclude_cache_device is not None:
return _exclude_cache_device
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.DiscoveryExclude.identifier)
.where(db.DiscoveryExclude.type == EXCLUDE_TYPE_DEVICE_NAME)
)).scalars().all()
_exclude_cache_device = {r for r in rows if r}
return _exclude_cache_device
async def add_exclude(identifier: str, type: str,
reason: str = "", created_by: str = "") -> dict:
if not identifier:
raise ValueError("identifier is required")
if type not in _VALID_EXCLUDE_TYPES:
raise ValueError(f"type must be one of {sorted(_VALID_EXCLUDE_TYPES)}")
async with db.SessionLocal() as session:
existing = (await session.execute(
select(db.DiscoveryExclude).where(db.DiscoveryExclude.identifier == identifier)
)).scalar_one_or_none()
if existing:
existing.type = type
existing.reason = reason or existing.reason
existing.created_by = created_by or existing.created_by
await session.commit()
_invalidate_exclude_cache()
return existing.to_dict()
row = db.DiscoveryExclude(
identifier=identifier,
type=type,
reason=reason,
created_by=created_by,
)
session.add(row)
await session.commit()
_invalidate_exclude_cache()
return row.to_dict()
async def remove_exclude(identifier: str) -> bool:
async with db.SessionLocal() as session:
existing = (await session.execute(
select(db.DiscoveryExclude).where(db.DiscoveryExclude.identifier == identifier)
)).scalar_one_or_none()
if not existing:
return False
await session.delete(existing)
await session.commit()
_invalidate_exclude_cache()
return True
async def is_excluded_ip(ip: str) -> bool:
"""Single-IP check. For hot loops, prefer get_excluded_ips() once and
test set membership locally."""
if not ip:
return False
return ip in (await get_excluded_ips())
async def is_excluded_device(name: str) -> bool:
if not name:
return False
return name in (await get_excluded_device_names())
# ---------------------------------------------------------------------------
# Run records
# ---------------------------------------------------------------------------
async def record_collection_run(summary: dict) -> None:
async with db.SessionLocal() as session:
session.add(db.CollectionRun(
started_at=_parse_dt(summary.get("started")) or _now(),
completed_at=_parse_dt(summary.get("finished")) or _now(),
duration_seconds=summary.get("duration_seconds"),
devices_queried=summary.get("devices_queried", 0),
endpoints_found=summary.get("endpoints_found", 0),
endpoints_new=summary.get("endpoints_new", 0),
endpoints_updated=summary.get("endpoints_updated", 0),
endpoints_moved=summary.get("endpoints_moved", 0),
))
await session.commit()
async def list_collection_runs(limit: int = 20) -> list[dict]:
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.CollectionRun).order_by(db.CollectionRun.started_at.desc()).limit(limit)
)).scalars().all()
return [r.to_dict() for r in rows]
async def record_sweep_run(cidr_ranges: list[str], started_at: datetime, finished_at: datetime,
summary: dict) -> None:
async with db.SessionLocal() as session:
session.add(db.SweepRun(
cidr=",".join(cidr_ranges) if cidr_ranges else "",
started_at=started_at,
completed_at=finished_at,
duration_seconds=(finished_at - started_at).total_seconds(),
total_scanned=summary.get("total", 0),
total_alive=summary.get("alive", 0),
total_onboarded=summary.get("onboarded", 0),
total_failed=summary.get("failed", 0),
))
await session.commit()
async def list_sweep_runs(limit: int = 20) -> list[dict]:
async with db.SessionLocal() as session:
rows = (await session.execute(
select(db.SweepRun).order_by(db.SweepRun.started_at.desc()).limit(limit)
)).scalars().all()
return [r.to_dict() for r in rows]
async def record_ip_observation(ip: str, host: dict) -> None:
"""Append a sweep snapshot for an IP."""
async with db.SessionLocal() as session:
session.add(db.IPObservation(
ip_address=ip,
mac_address=(host.get("mac_address") or "").upper() or None,
ports_open=host.get("ports_open") or [],
banners=host.get("banners") or {},
snmp_data=host.get("snmp") or {},
http_headers=host.get("http_headers") or {},
tls_data={
"subject": host.get("tls_subject", ""),
"issuer": host.get("tls_issuer", ""),
"expiry": host.get("tls_expiry", ""),
"sans": host.get("tls_sans", ""),
},
ssh_banner=host.get("ssh_banner") or "",
classification=host.get("classification") or "",
dns_name=host.get("dns_name") or "",
))
await session.commit()
# ---------------------------------------------------------------------------
# JSON migration (one-shot, on first startup with empty DB)
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Database hygiene / pruning
# ---------------------------------------------------------------------------
#
# All four prune helpers below take a single ``retention_days`` argument and
# delete rows older than that threshold. They are designed to be safe to run
# concurrently with collection — each operates inside its own short
# transaction and never touches active in-flight rows.
#
# Counts are returned for logging and the admin UI. Structured logging uses
# the dedicated "prune" module so the events are easy to filter in the log
# viewer.
# ---------------------------------------------------------------------------
# Node raw data persistence (Phase 2.85)
# ---------------------------------------------------------------------------
async def upsert_node_arp_bulk(node_name: str, entries: list[dict]) -> int:
"""Bulk upsert ARP entries for a node. Returns count."""
if not db.is_ready() or not entries:
return 0
from sqlalchemy.dialects.postgresql import insert as pg_insert
now = _now()
rows = [{
"node_name": node_name,
"ip": e.get("ip", ""),
"mac": (e.get("mac", "") or "").upper(),
"interface": e.get("interface", ""),
"vrf": "default",
"collected_at": now,
} for e in entries if e.get("ip") and e.get("mac")]
if not rows:
return 0
async with db.SessionLocal() as session:
stmt = pg_insert(db.NodeArpEntry).values(rows)
stmt = stmt.on_conflict_do_update(
constraint="uq_arp_node_ip_mac_vrf",
set_={"interface": stmt.excluded.interface, "collected_at": stmt.excluded.collected_at},
)
await session.execute(stmt)
await session.commit()
return len(rows)
async def upsert_node_mac_bulk(node_name: str, entries: list[dict]) -> int:
"""Bulk upsert MAC table entries for a node. Returns count."""
if not db.is_ready() or not entries:
return 0
from sqlalchemy.dialects.postgresql import insert as pg_insert
now = _now()
rows = [{
"node_name": node_name,
"mac": (e.get("mac", "") or "").upper(),
"interface": e.get("interface", ""),
"vlan": int(e.get("vlan", 0) or 0),
"entry_type": "static" if e.get("static") else "dynamic",
"collected_at": now,
} for e in entries if e.get("mac")]
if not rows:
return 0
async with db.SessionLocal() as session:
stmt = pg_insert(db.NodeMacEntry).values(rows)
stmt = stmt.on_conflict_do_update(
constraint="uq_mac_node_mac_iface_vlan",
set_={"entry_type": stmt.excluded.entry_type, "collected_at": stmt.excluded.collected_at},
)
await session.execute(stmt)
await session.commit()
return len(rows)
async def upsert_node_lldp_bulk(node_name: str, lldp_data: dict) -> int:
"""Bulk upsert LLDP neighbor entries for a node.
lldp_data is the NAPALM-shaped per-interface dict
``{interface: [{hostname, port, ...}, ...]}``. The SNMP path
(``polling.collect_lldp`` from Block C P5 onward) builds the same
shape and additionally supplies the 5 expansion fields added by P2
migration ``c3208527926f``: ``local_port_ifindex``,
``local_port_name``, ``remote_chassis_id_subtype``,
``remote_port_id_subtype``, ``remote_system_description``.
Expansion fields are read from ``n.get(...)`` with ``None`` default —
NAPALM-shaped callers omit them and the columns stay NULL, the SNMP
path supplies them. on_conflict_do_update refreshes the expansion