From 90ded80a539f7ae549e583cc61b640019d258636 Mon Sep 17 00:00:00 2001 From: Khyati Mahendru Date: Fri, 13 Nov 2026 06:59:47 +0000 Subject: [PATCH 1/8] Add upload/discovery schema and replace events_streams with DiscoveryUpload - Add schema/upload_discovery.json defining DiscoveryUpload and ScanManifest for chunked packet capture streaming over upload/discovery. - Add 'upload' to SubType enum in schema/envelope.json and remove legacy schema/events_streams.json. - Regenerate Java and Python schema classes, HTML documentation, and .gencode_hash.txt. - Add schema validation fixtures under tests/schemas/upload_discovery/ and document depth: 'trace' in docs/specs/discovery.md and docs/specs/discovery_bacnet.md. - Ensure deterministic device ID ordering in SiteModel.getDeviceIds(). --- .gencode_hash.txt | 23 +- .../java/com/google/udmi/util/SiteModel.java | 2 +- docs/specs/discovery.md | 2 + docs/specs/discovery_bacnet.md | 13 +- gencode/docs/events.html | 323 ---------- gencode/docs/events_streams.html | 274 -------- gencode/docs/monitoring.html | 4 +- gencode/docs/readme.md | 2 +- gencode/docs/upload_discovery.html | 583 ++++++++++++++++++ gencode/java/udmi/schema/DiscoveryUpload.java | 110 ++++ gencode/java/udmi/schema/Envelope.java | 6 +- gencode/java/udmi/schema/Events.java | 14 +- gencode/java/udmi/schema/ScanManifest.java | 79 +++ gencode/java/udmi/schema/StreamsEvents.java | 95 --- gencode/python/udmi/schema/__init__.py | 2 +- gencode/python/udmi/schema/envelope.py | 2 +- gencode/python/udmi/schema/events.py | 2 - gencode/python/udmi/schema/events_streams.py | 24 - .../python/udmi/schema/upload_discovery.py | 38 ++ schema/envelope.json | 6 +- schema/events.json | 3 - schema/events_streams.json | 40 -- schema/upload_discovery.json | 83 +++ tests/schemas/envelope/errors1.out | 2 +- tests/schemas/upload_discovery/chunk.json | 8 + tests/schemas/upload_discovery/chunk.out | 0 tests/schemas/upload_discovery/eof.json | 22 + tests/schemas/upload_discovery/eof.out | 0 tests/schemas/upload_discovery/start.json | 7 + tests/schemas/upload_discovery/start.out | 0 30 files changed, 966 insertions(+), 803 deletions(-) delete mode 100644 gencode/docs/events_streams.html create mode 100644 gencode/docs/upload_discovery.html create mode 100644 gencode/java/udmi/schema/DiscoveryUpload.java create mode 100644 gencode/java/udmi/schema/ScanManifest.java delete mode 100644 gencode/java/udmi/schema/StreamsEvents.java delete mode 100644 gencode/python/udmi/schema/events_streams.py create mode 100644 gencode/python/udmi/schema/upload_discovery.py delete mode 100644 schema/events_streams.json create mode 100644 schema/upload_discovery.json create mode 100644 tests/schemas/upload_discovery/chunk.json create mode 100644 tests/schemas/upload_discovery/chunk.out create mode 100644 tests/schemas/upload_discovery/eof.json create mode 100644 tests/schemas/upload_discovery/eof.out create mode 100644 tests/schemas/upload_discovery/start.json create mode 100644 tests/schemas/upload_discovery/start.out diff --git a/.gencode_hash.txt b/.gencode_hash.txt index bc8869f070..7592b1e917 100644 --- a/.gencode_hash.txt +++ b/.gencode_hash.txt @@ -7,27 +7,27 @@ f494e38bb63b4910fc3aab1355c5acfce54ab8a2db1ffbb4daf4c70e2a915c5d gencode/docs/c 94bb566ac6a4b6b7f89cd2cf1911f658446cc0bea405014275104623f9964dd3 gencode/docs/configuration_pubber.html 1057fa40fb7a31a23bb2773d21c38cf4590a935bd8b5ea4218e695c6204f5dd9 gencode/docs/data_template.html 1d5294b4a1fea6555e23144e594523e4793c795069b6880ce607ad09a6015581 gencode/docs/equipment_translation.html -90f2e66a6c9e3d05e7a7957bb7fff4b58890aa2f537234ae674da36182a678ef gencode/docs/events.html +100d215be9de68b94b01e7d51ab67a7f6c13b0480deca13fdc22240ef53e1c22 gencode/docs/events.html 70e57ad6ef39330d958727ebf9dcd61ef6ea30e4c8653eac412bf1867fdb3a70 gencode/docs/events_alarmset.html d358a5d99047832a0b8d5c04d3d780a93ed33fc69636e25de36eee8225f84bfc gencode/docs/events_discovery.html eafcc3c48189f605f114cde051fea9d13fc5f1a3e395d64fb0a91cb53d4c9aeb gencode/docs/events_pointset.html -b65ce6e8061e61ba676a72c624f1c425bd238e152ce8e3ebb1e9c23f0e502bcb gencode/docs/events_streams.html 81043ba732caab75704d38e6977b32b1c2bcdad89d94ad2a259d0e70ca4aa40e gencode/docs/events_system.html 46fd37b577c655965346d1e3ececf559c4384791214900eeeea1ad8fc72a02b8 gencode/docs/events_udmi.html baf59590b1a71a49e59d8f499ae5112a1b7a555294dbd72bc821203aecceefa3 gencode/docs/events_validation.html fcedeea524c9f1f26c580b1f3de346ff8bfd7e8002b2afb68e2ddaf0fef199b9 gencode/docs/metadata.html -18178a591940c176371fb9196048eaacd40f1323997cf907ca11eb879a095c7e gencode/docs/monitoring.html +b4ef5fd83f9ec4cc47b796b844c6be6bc5f5b724ecc95053c559e66b09b39ece gencode/docs/monitoring.html 64d21cf916e20566171cf9d723e59c297b576bcba89e2a73aec2b018398cc7da gencode/docs/mosquitto_client_response.html 6f332da9cc64230df3551f9748a4eaa4060146e767cae967fc0e73b1f348be5b gencode/docs/persistent_device.html e11595fd11477947a27461f8ef4fb6facb5f60e2abd6212193f7581ab123ff84 gencode/docs/properties.html 75d90e80269db99cb06199467c6c2483397370e15ac0392241e7e05ddf21852c gencode/docs/query_cloud.html -eb6c623142496b61e3c9b00c9ead0ba8541af2050d76ce652e1721c84aa3a096 gencode/docs/readme.md +a0003efed16bbbfd2fe8c8a6c6bf9c16c5f8fbc74559c583bc04752fe2ecfd10 gencode/docs/readme.md 2768fd01a875d1f58273e76fef9b421986824d2ab02251853840bca777b625c0 gencode/docs/schema_doc.css 165a29291d7d66653e46fd1ac5868f63e18f9d67c06ea9ebcb95d4830a528e68 gencode/docs/schema_doc.min.js 7ed934930aee763e0beebc349725ba3909115e8d346bb762f28bcbe745bb163a gencode/docs/schema_extras.js 7a1bbe014c739078d354ec484147325e1d0bd19468f275a53da38add43ebe089 gencode/docs/site_metadata.html 0993d21a1a0ae485bdb2f1794f279d13f782e841d07832f795624cc9f158ea93 gencode/docs/state.html 275171b2329d64d497fa54f8877656920be7c4f79bc90f67a0ff1bae6700399b gencode/docs/state_validation.html +4643457f1580e601c14d5382aa7ed5070ef56c2c100d8b5d2bbe33a191d67517 gencode/docs/upload_discovery.html 46347b31bc2a56bc74af9bb702ad40c7823887d5e9b1427903a4892cde3cd169 gencode/java/udmi/schema/AlarmAlarmsetConfig.java 520b12eb8cec4f043f81f898c4be12def09b7de138533922e17c038415fb8902 gencode/java/udmi/schema/AlarmAlarmsetEvents.java 0740aeb4462739e9be7e9c846ebc3f3e6f45f3bb752327c681aa013fbd5c2711 gencode/java/udmi/schema/AlarmAlarmsetModel.java @@ -69,12 +69,13 @@ a572f17a61584a32ff19968356f7f7d7bcc8430131ac3701878d0bd221e1a1fa gencode/java/u 9217b2c963003ca51ec61b9aadd40877634f2bea08d7fd412b51521e8ec61cfb gencode/java/udmi/schema/DiscoveryEvents.java af16026c143a592562b77012dd739c02364bd1a9d6bbd6c7ede4f3a5a38b7f4a gencode/java/udmi/schema/DiscoveryModel.java 0fd348086bfd8e38a54a06b0fd205f6d01fdc6236f07ccc8bef49a1832f8c767 gencode/java/udmi/schema/DiscoveryState.java +ed9531d3c260976a56d6803ee0998efeb24d606945cda405916d6e8495eaa016 gencode/java/udmi/schema/DiscoveryUpload.java baef666f5f58f790b73ba7bed8f60eacdd75ba3151b9abc32265954a9da84faa gencode/java/udmi/schema/Electricity.java 421126685b752587bd2e5f2ea7d7cfa140847500ed8c4f2a7146c9a605f0f2b0 gencode/java/udmi/schema/EndpointConfiguration.java 8610ae5a6a32fd17063ce7d488d4546e5ca1fd045c4cc9f0a4b94ad37f58dd60 gencode/java/udmi/schema/Entry.java d8a519092ec7401ffbf3d76d1b77bb360f4429fada288154223932ab0f9ee0cb gencode/java/udmi/schema/Enumerations.java -f890a14567657f5c97c2d3c1c753d751025ee094700ef0659f63f448529cc529 gencode/java/udmi/schema/Envelope.java -9df1e0a689390bda0847a0acab5a13fd7ced8c09b8563c13a7ce000ef1ea4999 gencode/java/udmi/schema/Events.java +d61899ceba3ab172be85db2c54e950c80f7bfb6749fb1173f594179a3567d346 gencode/java/udmi/schema/Envelope.java +c6ce13a723c6b966912aab9b6deabf7e2ae6e1d74812cc3d7f15726a2fbd76c9 gencode/java/udmi/schema/Events.java 8aed152c906c51a72a9224e7aec14bcdbd9ac2e00c2b1fed6bd5515082f79488 gencode/java/udmi/schema/ExecutionConfiguration.java a5a41a2bc809988efbbc121cdf730cbc1eb066372e046747fb6ae3f30e96a8b1 gencode/java/udmi/schema/FamilyDiscovery.java 0de804fb208fdf2ef198539ed5b828b780bc6c5cdd9e31b10067372165c4b7d4 gencode/java/udmi/schema/FamilyDiscoveryConfig.java @@ -125,6 +126,7 @@ fbe287eb5b915a7df6ccffade4e3d6afc82eaf4c0195501f36d2facacbb6590f gencode/java/u a374c601a5d729e31a140ddbf019f346077db7615ffda2d34d638c2ba0ebbbd9 gencode/java/udmi/schema/PubberOptions.java 54e0593235c1f19cf3b5b2708f831e734b0acf049b2576e3b29707c93f1241d9 gencode/java/udmi/schema/RefDiscovery.java 2bf34a526fcf3ee4e4440deeb215c6c8e18de15b07d521e8ef327e51b7fe1db5 gencode/java/udmi/schema/Role.java +f40a56d2080bfbbd48ae441fc41d66b8767fab8188e57dcfab1fa56183591acb gencode/java/udmi/schema/ScanManifest.java f5eda4fdb24fcc3ccbc82fe39fe8ed87cf8b4d4d0699faef31f83de4a1fa1306 gencode/java/udmi/schema/SchemaValidationState.java 4b26a101e8edc299274e5b221db616b83d8e569000e0b59b940d0a0d5387852b gencode/java/udmi/schema/Scoring.java 280e35e8dee942bfa3e205c0c00dd01d14c2cd804e3d55be580c91408dd62137 gencode/java/udmi/schema/SequenceValidationState.java @@ -137,7 +139,6 @@ b8b388f59da9ee6951ba85b2c12e171681e6abe7c97312cf758344e0850c640c gencode/java/u 81df6abb662cbf5dfc4301d770c5e0bf72d07f228dc725b8df35339e73b90762 gencode/java/udmi/schema/StateSystemHardware.java 0110ab92d49749785dc29b92685443c895efa3cbc0637ed4374d3337d2f3be54 gencode/java/udmi/schema/StateSystemOperation.java c7e5fd53e7e1c3a439b5283f81b0555473d6b0e623aa9cdd896080b993a6f80f gencode/java/udmi/schema/States.java -5d531ecfda463512a1f6a97d0b9aa8c0e0f163f5dd63bfcfa63c406d4f820eae gencode/java/udmi/schema/StreamsEvents.java b45a8fd3c70f75bed5f3aa2285007baa6445a23819b31fe69f38c117f837bbab gencode/java/udmi/schema/Structure.java 65babc897b81d05b69e6178433b0918e513e36e861f044b68ecf4eb5f2408b37 gencode/java/udmi/schema/SystemConfig.java 53667a5822c79a1aca9345399e9dd925b761fefb96b06ff2f7c42705256a4112 gencode/java/udmi/schema/SystemDiscoveryData.java @@ -159,7 +160,7 @@ f08d327f322431a8be0e6018a7b8a9835af8e3e6ecc4ab8e18eb36810a44e5f3 gencode/java/u c99d2ec53e670c3b91104a4a8fbc825c1c29530a2f686fe644f977eb6b6edd89 gencode/java/udmi/schema/Water.java 2ff28e8376eb81027522ce91a14d7f6768d02daecd12739210da4aaa8fb49f8b gencode/presentation/presentation.json 4cf98cbd132cde0cc8813ac35cf3712cb46014154c817c04ad2902c268cdd8fe gencode/python/pyproject.toml -f6968fad6fb525139cd063b5a9dc00a55faab999d2a429f0843ca40f54f7727b gencode/python/udmi/schema/__init__.py +3f6e4b10e782ce9f3873120242ae452ab513a46da2a8007ca7350be99652cb96 gencode/python/udmi/schema/__init__.py f9d90861e568b27445bef241f04cce64cc44731c95c8bd9e3f65cef79d42dab0 gencode/python/udmi/schema/_base.py de7d13c346e5d98511d02b4bdccf20afeb013eaca512694ebd7f82e584b11358 gencode/python/udmi/schema/access_iot.py 32a951e2bf13f556082f8d94be079b3df6cc081b6ff59f71a82d32782cf8f8f6 gencode/python/udmi/schema/ancillary_properties.py @@ -197,15 +198,14 @@ f7193dd8eddcae6c646b99fb4c33fe47f43bed7c9615ab1bd0a0bf5612527607 gencode/python 86f262123525f2e6119c174fe4a4cd2f2c35863ced03a66f6db32c08e5a08542 gencode/python/udmi/schema/discovery_feature.py b978caf892bc6d0fb875b2560b81668cd1a47a09436609dc56d6353ef35b5f86 gencode/python/udmi/schema/discovery_ref.py be97796ac8949ccb7fbdecfb4ff087987cf2849bf223ff39b947771a08422156 gencode/python/udmi/schema/entry.py -ab1a8ee1f12d04dd88837b6f026030b5ed3550ef3bfbbfbcb4f77cc4df39e93a gencode/python/udmi/schema/envelope.py +059f350ce6492e1d183f175a800205a4a08750174c83028b6a32d8f42415656f gencode/python/udmi/schema/envelope.py 04f518ca330acb6f376838bdc4425f15582eb185f4b05f00fc76d1af92bac57f gencode/python/udmi/schema/equipment_translation.py -3dcf4daa94b8450b7360e58500e20e1fbe5701502ac28358112ee1a6bd2a87f1 gencode/python/udmi/schema/events.py +555d45b8882e31095e7233bfffbade89840535aff33dbe20cd24e6808b6205a3 gencode/python/udmi/schema/events.py af48a2d32b4ec326df6e3f165d8944b994fb426bd4e663c42c1d592f5cb41f83 gencode/python/udmi/schema/events_alarmset.py b58371ffa7979d1598502a35859f3010ae7a2ec2d851454c010c835e426c7a14 gencode/python/udmi/schema/events_alarmset_alarm.py 3996175098735e889730c87ffc9ce1648e6624d801694458f6d4bc147ff29741 gencode/python/udmi/schema/events_discovery.py 84700f9d8a8975130ff9c62891003f7a12f367fa7dd1ca1db5f5fae7225bf005 gencode/python/udmi/schema/events_pointset.py 9f568bd573d4992e3efa3cc3cb8cdefecb95b15675b0442873abdc7850d108f9 gencode/python/udmi/schema/events_pointset_point.py -282439e4983ae9f310fda69dd6ff979567fa983ebdefcde407df42d631fe1bad gencode/python/udmi/schema/events_streams.py e4cdab07942e52cae243b4dddbc72676794914947dd66df8add0f5969f31fd11 gencode/python/udmi/schema/events_system.py 8c5a6101e62c751714a7440db3993167b7d86bffd80589076bca1feb0a91d214 gencode/python/udmi/schema/events_udmi.py 72559779680c79dace3c5903022709852cbad7b77ed42af97debc8d852d61cb7 gencode/python/udmi/schema/events_validation.py @@ -263,3 +263,4 @@ e23b1b67fc5066ee0c9a948fbc0b31bc425d73740a8d2104b30004173f049f4a gencode/python 6c62d12f392525e4c08d3ee6105f475b941c21e0a8b7a23eaf1650d01a5b5aae gencode/python/udmi/schema/state_validation_feature.py 8a92d352337c118831e3a3b64b350a5ab248fc29150e7cdb968d5e5cf0aae30c gencode/python/udmi/schema/state_validation_schema.py 8862c955ea0aee91db532cb076112305ce6e18d9ac5b323f758fd7fcf75db7cd gencode/python/udmi/schema/state_validation_sequence.py +caa4263df095dcf90c96284442db6aceaa73c72a66808bdf7a07fd4b5aa00a05 gencode/python/udmi/schema/upload_discovery.py diff --git a/common/src/main/java/com/google/udmi/util/SiteModel.java b/common/src/main/java/com/google/udmi/util/SiteModel.java index 5feace1c3b..b6b169b3b6 100644 --- a/common/src/main/java/com/google/udmi/util/SiteModel.java +++ b/common/src/main/java/com/google/udmi/util/SiteModel.java @@ -388,7 +388,7 @@ public Set getDeviceIds() { File devicesFile = getDevicesDir(); File[] files = Objects.requireNonNull(devicesFile.listFiles(), "no files in " + devicesFile.getAbsolutePath()); - return Arrays.stream(files).map(File::getName) + return Arrays.stream(files).map(File::getName).sorted() .filter(device -> validDeviceDirectory(devicesFile, device)).collect(Collectors.toSet()); } diff --git a/docs/specs/discovery.md b/docs/specs/discovery.md index fd2f9c28ea..ba619c275e 100644 --- a/docs/specs/discovery.md +++ b/docs/specs/discovery.md @@ -55,6 +55,7 @@ Discovery `depth` controls the level of detail collected during a scan. Each dep * **`entries`**: Individual discovered devices and cross-family address associations. * **`system`**: Device identity and hardware information. * **`details`**: Enumerated device points, objects, or services. +* **`trace`**: Diagnostic raw packet capture (PCAP) streamed in gzip-compressed chunks over the `upload/discovery` channel ([schema](../../schema/upload_discovery.json)). | `depth` | Description | `bacnet` ([Spec](discovery_bacnet.md)) | `iot` | `ipv4` | | :--- | :--- | :--- | :--- | :--- | @@ -62,6 +63,7 @@ Discovery `depth` controls the level of detail collected during a scan. Each dep | **`entries`** | Device addresses and bindings | Device instances and IP/MAC bindings | IoT device IDs and gateway bindings | Host IP, MAC, and hostname bindings | | **`system`** | Device identity and hardware | Device object identity and vendor info | Reported system hardware and software | Host OS and hardware fingerprint | | **`details`** | Exposed points or services | BACnet objects and properties | Configured or self-enumerated points | Open ports and network services | +| **`trace`** | Diagnostic packet capture | Raw BACnet/IP & MS/TP PCAP chunks (`upload/discovery`) | Raw message trace | Filtered interface PCAP chunks (`upload/discovery`) | ## Enumeration diff --git a/docs/specs/discovery_bacnet.md b/docs/specs/discovery_bacnet.md index bbb1e39b1b..9a33805847 100644 --- a/docs/specs/discovery_bacnet.md +++ b/docs/specs/discovery_bacnet.md @@ -12,14 +12,15 @@ For static BACnet URI addressing rules (`bacnet:////` (`object-name`, `vendor-name`, `model-name`, `serial-number`, etc.) | `entries` + `system` (`name`, `description`, `serial_no`, `hardware`, `ancillary`) | -| **4** | **`details`** | BACnet object references & properties | `ReadProperty` / `ReadPropertyMultiple` on `device,` `object-list` + per-object `(object-type, instance)` properties | `system` + `refs` map (`"/"` $\rightarrow$ populated `RefDiscovery` fields: `name`, `description`, `type`, `units`, `possible_values`, `writable`, `ancillary`) | +| **1** | **`buckets`** | Available BACnet networks & UDP ports | `Who-Is-Router-To-Network` / `I-Am-Router-To-Network` + BACnet/IP UDP port probe (`47808` / `0xBAC0`, etc.) | `events/discovery`: Base envelope + `family: "bacnet"` + `network` + `families.ipv4.port` | +| **2** | **`entries`** | Discovered BACnet devices & MAC/IP bindings | `Who-Is` / `I-Am` (global, network-filtered, or unicast `addrs`) | `events/discovery`: `buckets` + `addr` (Device Instance) + per-device `families` (`ipv4` `addr`/`port`, `ethmac`, `mstp`) | +| **3** | **`system`** | Device Object (`DO/0`) identity properties | `ReadPropertyMultiple` on `device,` (`object-name`, `vendor-name`, `model-name`, `serial-number`, etc.) | `events/discovery`: `entries` + `system` (`name`, `description`, `serial_no`, `hardware`, `ancillary`) | +| **4** | **`details`** | BACnet object references & properties | `ReadProperty` / `ReadPropertyMultiple` on `device,` `object-list` + per-object `(object-type, instance)` properties | `events/discovery`: `system` + `refs` map (`"/"` $\rightarrow$ populated `RefDiscovery` fields: `name`, `description`, `type`, `units`, `possible_values`, `writable`, `ancillary`) | +| **5** | **`trace`** | Raw BACnet packet capture (PCAP) | `tcpdump` capture (`udp port 47808`) + paced raw-socket `Who-Is-Router-To-Network` and `Who-Is` rounds | `upload/discovery`: [`DiscoveryUpload`](../../schema/upload_discovery.json) chunks (`event_no = 0`, `1..N` gzipped base64 `data`, `-(N+1)` with `sha256` + `scan_manifest`) | Each level is strictly additive: requesting a deeper level produces all fields required by the preceding level plus the additional fields defined for that depth. diff --git a/gencode/docs/events.html b/gencode/docs/events.html index ebcb155a01..43eda14ab5 100644 --- a/gencode/docs/events.html +++ b/gencode/docs/events.html @@ -25544,329 +25544,6 @@

- - - - - - - - -
-
-
-

- -

-
- -
-
- -

Streams Events

Type: object
-

Sequential data stream chunks for reliable transport over MQTT (e.g. PCAP traces, firmware blobs, reliable alarms, logs playback).

-
- - No Additional Properties - - - - - - -
-
-
-

- -

-
- -
-
- - Type: stringFormat: date-time
-

RFC 3339 UTC timestamp the stream chunk event was generated

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: string
-

Version of the UDMI schema

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: string
-

Unique session identifier for the continuous stream transmission

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: integer
-

Sequence number for this stream event to support reliable sequential delivery and reassembly

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: integer
-

0-based index of the transmitted chunk payload within the total session

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: integer
-

Total number of chunks comprising the complete transmission binary

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: string
-

Base64-encoded binary chunk payload data

-
- - - - - -
diff --git a/gencode/docs/events_streams.html b/gencode/docs/events_streams.html deleted file mode 100644 index 75f0bea9e5..0000000000 --- a/gencode/docs/events_streams.html +++ /dev/null @@ -1,274 +0,0 @@ - - - - - - - - - - - - - - - - Streams Events - -
- - -
- -

Streams Events

Type: object
-

Sequential data stream chunks for reliable transport over MQTT (e.g. PCAP traces, firmware blobs, reliable alarms, logs playback).

-
No Additional Properties - - - - - - -
-
-
-

- -

-
- -
-
- - Type: stringFormat: date-time
-

RFC 3339 UTC timestamp the stream chunk event was generated

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: string
-

Version of the UDMI schema

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: string
-

Unique session identifier for the continuous stream transmission

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: integer
-

Sequence number for this stream event to support reliable sequential delivery and reassembly

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: integer
-

0-based index of the transmitted chunk payload within the total session

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: integer
-

Total number of chunks comprising the complete transmission binary

-
- - - - - - -
-
-
-
-
-
-
-

- -

-
- -
-
- - Type: string
-

Base64-encoded binary chunk payload data

-
- - - - - - -
-
-
-
- - - \ No newline at end of file diff --git a/gencode/docs/monitoring.html b/gencode/docs/monitoring.html index 9bcd1299d8..c7a9a1ec09 100644 --- a/gencode/docs/monitoring.html +++ b/gencode/docs/monitoring.html @@ -4547,7 +4547,7 @@

subFolder

Type: enum (of string)

Must be one of:

-
  • "udmi"
  • "update"
  • "invalid"
  • "error"
  • "cloud"
  • "discovery"
  • "mapping"
  • "system"
  • "gateway"
  • "swarm"
  • "localnet"
  • "pointset"
  • "validation"
  • "blobset"
  • "monitoring"
  • "streams"
+
  • "udmi"
  • "update"
  • "invalid"
  • "error"
  • "cloud"
  • "discovery"
  • "mapping"
  • "system"
  • "gateway"
  • "swarm"
  • "localnet"
  • "pointset"
  • "validation"
  • "blobset"
  • "monitoring"
@@ -4597,7 +4597,7 @@

subType

Type: enum (of string)

Must be one of:

-
  • "invalid"
  • "local"
  • "reflect"
  • "events"
  • "errors"
  • "commands"
  • "config"
  • "state"
  • "query"
  • "reply"
  • "model"
  • "propose"
+
  • "invalid"
  • "local"
  • "reflect"
  • "events"
  • "errors"
  • "commands"
  • "config"
  • "state"
  • "query"
  • "reply"
  • "model"
  • "propose"
  • "upload"
diff --git a/gencode/docs/readme.md b/gencode/docs/readme.md index a4843f5eab..5d352a3d1d 100644 --- a/gencode/docs/readme.md +++ b/gencode/docs/readme.md @@ -10,10 +10,10 @@ * [**events_alarmset**](events_alarmset.html) - A set of alarms reporting telemetry data. [Alarmset Events Documentation](../../docs/messages/alarmset.md#telemetry) * [**events_discovery**](events_discovery.html) - [Discovery result](../../docs/specs/discovery.md) with implicit discovery * [**events_pointset**](events_pointset.html) - A set of points reporting telemetry data. [Pointset Events Documentation](../../docs/messages/pointset.md#telemetry) -* [**events_streams**](events_streams.html) - Sequential data stream chunks for reliable transport over MQTT (e.g. PCAP traces, firmware blobs, reliable alarms, logs playback). * [**events_system**](events_system.html) - Used for system events such as logging. [System Event Documentation](../../docs/messages/system.md#event) * [**events_udmi**](events_udmi.html) - Used for udmi events such as logging. * [**state**](state.html) - [State](../../docs/messages/state.md) message, defined by [`state.json`] +* [**upload_discovery**](upload_discovery.html) - Sequential compressed capture chunk transport over MQTT upload/discovery framed by config.discovery and state.discovery. ## Site Model * [**metadata**](metadata.html) - [Metadata](../../docs/specs/metadata.md) is a description about the device: a specification about how the device should be configured and expectations about what the device should be doing. Defined by `metadata.json` diff --git a/gencode/docs/upload_discovery.html b/gencode/docs/upload_discovery.html new file mode 100644 index 0000000000..02fa7fc595 --- /dev/null +++ b/gencode/docs/upload_discovery.html @@ -0,0 +1,583 @@ + + + + + + + + + + + + + + + + Discovery Upload + +
+ + +
+ +

Discovery Upload

Type: object
+

Sequential compressed capture chunk transport over MQTT upload/discovery framed by config.discovery and state.discovery.

+
No Additional Properties + + + + + + +
+
+
+

+ +

+
+ +
+
+ + Type: stringFormat: date-time
+

RFC 3339 UTC timestamp the chunk was emitted

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: string
+

Version of the UDMI schema

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: stringFormat: date-time
+

Trigger timestamp / session generation ID matching config.discovery and state.discovery

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: string
+

Protocol family identifier for the trace capture (e.g. bacnet, ether, ipv4)

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: integer
+

0 for start marker, 1..N for gzip-compressed data chunks, and required -(N+1) for stream termination

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: string
+

Base64-encoded gzip-compressed binary PCAP chunk payload (present for event_no > 0)

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: string
+

Expected SHA-256 hex digest of the complete unencoded PCAP file (required on terminal event_no < 0)

+
Must match regular expression: ^[0-9a-f]{64}$ + + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ +

Scan Manifest

Type: object
+

Metadata describing active discovery scan rounds executed during trace capture

+
No Additional Properties + + + + + + +
+
+
+

+ +

+
+ +
+
+ + Type: string
+

Local gateway IPv4 address used during capture

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: string
+

Network interface captured

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: string
+

BPF packet filter applied during capture

+
+ + + + + + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: array of string
+

RFC 3339 UTC timestamps marking active Who-Is discovery scan rounds

+
+ + + + + + No Additional Items

Each item of this array must be:

+
+
+ + + Type: string
+ + + + + + + +
+
+
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: array of integer
+

Routed BACnet DNET numbers discovered via I-Am-Router-To-Network during trace

+
+ + + + + + No Additional Items

Each item of this array must be:

+
+
+ + + Type: integer
+ + + + + + + +
+
+
+
+
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/gencode/java/udmi/schema/DiscoveryUpload.java b/gencode/java/udmi/schema/DiscoveryUpload.java new file mode 100644 index 0000000000..9a63ac1c98 --- /dev/null +++ b/gencode/java/udmi/schema/DiscoveryUpload.java @@ -0,0 +1,110 @@ + +package udmi.schema; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyDescription; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +/** + * Discovery Upload + *

+ * Sequential compressed capture chunk transport over MQTT upload/discovery framed by config.discovery and state.discovery. + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DiscoveryUpload { + + /** + * RFC 3339 UTC timestamp the chunk was emitted + * (Required) + * + */ + @JsonProperty("timestamp") + @JsonPropertyDescription("RFC 3339 UTC timestamp the chunk was emitted") + public Date timestamp; + /** + * Version of the UDMI schema + * (Required) + * + */ + @JsonProperty("version") + @JsonPropertyDescription("Version of the UDMI schema") + public String version; + /** + * Trigger timestamp / session generation ID matching config.discovery and state.discovery + * (Required) + * + */ + @JsonProperty("generation") + @JsonPropertyDescription("Trigger timestamp / session generation ID matching config.discovery and state.discovery") + public Date generation; + /** + * Protocol family identifier for the trace capture (e.g. bacnet, ether, ipv4) + * (Required) + * + */ + @JsonProperty("family") + @JsonPropertyDescription("Protocol family identifier for the trace capture (e.g. bacnet, ether, ipv4)") + public String family; + /** + * 0 for start marker, 1..N for gzip-compressed data chunks, and required -(N+1) for stream termination + * (Required) + * + */ + @JsonProperty("event_no") + @JsonPropertyDescription("0 for start marker, 1..N for gzip-compressed data chunks, and required -(N+1) for stream termination") + public Integer event_no; + /** + * Base64-encoded gzip-compressed binary PCAP chunk payload (present for event_no > 0) + * + */ + @JsonProperty("data") + @JsonPropertyDescription("Base64-encoded gzip-compressed binary PCAP chunk payload (present for event_no > 0)") + public String data; + /** + * Expected SHA-256 hex digest of the complete unencoded PCAP file (required on terminal event_no < 0) + * + */ + @JsonProperty("sha256") + @JsonPropertyDescription("Expected SHA-256 hex digest of the complete unencoded PCAP file (required on terminal event_no < 0)") + public String sha256; + /** + * Scan Manifest + *

+ * Metadata describing active discovery scan rounds executed during trace capture + * + */ + @JsonProperty("scan_manifest") + @JsonPropertyDescription("Metadata describing active discovery scan rounds executed during trace capture") + public ScanManifest scan_manifest; + + @Override + public int hashCode() { + int result = 1; + result = ((result* 31)+((this.generation == null)? 0 :this.generation.hashCode())); + result = ((result* 31)+((this.scan_manifest == null)? 0 :this.scan_manifest.hashCode())); + result = ((result* 31)+((this.data == null)? 0 :this.data.hashCode())); + result = ((result* 31)+((this.sha256 == null)? 0 :this.sha256 .hashCode())); + result = ((result* 31)+((this.event_no == null)? 0 :this.event_no.hashCode())); + result = ((result* 31)+((this.family == null)? 0 :this.family.hashCode())); + result = ((result* 31)+((this.version == null)? 0 :this.version.hashCode())); + result = ((result* 31)+((this.timestamp == null)? 0 :this.timestamp.hashCode())); + return result; + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if ((other instanceof DiscoveryUpload) == false) { + return false; + } + DiscoveryUpload rhs = ((DiscoveryUpload) other); + return (((((((((this.generation == rhs.generation)||((this.generation!= null)&&this.generation.equals(rhs.generation)))&&((this.scan_manifest == rhs.scan_manifest)||((this.scan_manifest!= null)&&this.scan_manifest.equals(rhs.scan_manifest))))&&((this.data == rhs.data)||((this.data!= null)&&this.data.equals(rhs.data))))&&((this.sha256 == rhs.sha256)||((this.sha256 != null)&&this.sha256 .equals(rhs.sha256))))&&((this.event_no == rhs.event_no)||((this.event_no!= null)&&this.event_no.equals(rhs.event_no))))&&((this.family == rhs.family)||((this.family!= null)&&this.family.equals(rhs.family))))&&((this.version == rhs.version)||((this.version!= null)&&this.version.equals(rhs.version))))&&((this.timestamp == rhs.timestamp)||((this.timestamp!= null)&&this.timestamp.equals(rhs.timestamp)))); + } + +} diff --git a/gencode/java/udmi/schema/Envelope.java b/gencode/java/udmi/schema/Envelope.java index 28944ac793..b214235822 100644 --- a/gencode/java/udmi/schema/Envelope.java +++ b/gencode/java/udmi/schema/Envelope.java @@ -111,8 +111,7 @@ public enum SubFolder { POINTSET("pointset"), VALIDATION("validation"), BLOBSET("blobset"), - MONITORING("monitoring"), - STREAMS("streams"); + MONITORING("monitoring"); private final String value; private final static Map CONSTANTS = new HashMap(); @@ -161,7 +160,8 @@ public enum SubType { QUERY("query"), REPLY("reply"), MODEL("model"), - PROPOSE("propose"); + PROPOSE("propose"), + UPLOAD("upload"); private final String value; private final static Map CONSTANTS = new HashMap(); diff --git a/gencode/java/udmi/schema/Events.java b/gencode/java/udmi/schema/Events.java index 463c9a60e5..f958acd7ce 100644 --- a/gencode/java/udmi/schema/Events.java +++ b/gencode/java/udmi/schema/Events.java @@ -43,23 +43,13 @@ public class Events { @JsonProperty("discovery") @JsonPropertyDescription("[Discovery result](../docs/specs/discovery.md) with implicit discovery") public DiscoveryEvents discovery; - /** - * Streams Events - *

- * Sequential data stream chunks for reliable transport over MQTT (e.g. PCAP traces, firmware blobs, reliable alarms, logs playback). - * - */ - @JsonProperty("streams") - @JsonPropertyDescription("Sequential data stream chunks for reliable transport over MQTT (e.g. PCAP traces, firmware blobs, reliable alarms, logs playback).") - public StreamsEvents streams; @Override public int hashCode() { int result = 1; result = ((result* 31)+((this.pointset == null)? 0 :this.pointset.hashCode())); - result = ((result* 31)+((this.system == null)? 0 :this.system.hashCode())); result = ((result* 31)+((this.discovery == null)? 0 :this.discovery.hashCode())); - result = ((result* 31)+((this.streams == null)? 0 :this.streams.hashCode())); + result = ((result* 31)+((this.system == null)? 0 :this.system.hashCode())); return result; } @@ -72,7 +62,7 @@ public boolean equals(Object other) { return false; } Events rhs = ((Events) other); - return (((((this.pointset == rhs.pointset)||((this.pointset!= null)&&this.pointset.equals(rhs.pointset)))&&((this.system == rhs.system)||((this.system!= null)&&this.system.equals(rhs.system))))&&((this.discovery == rhs.discovery)||((this.discovery!= null)&&this.discovery.equals(rhs.discovery))))&&((this.streams == rhs.streams)||((this.streams!= null)&&this.streams.equals(rhs.streams)))); + return ((((this.pointset == rhs.pointset)||((this.pointset!= null)&&this.pointset.equals(rhs.pointset)))&&((this.discovery == rhs.discovery)||((this.discovery!= null)&&this.discovery.equals(rhs.discovery))))&&((this.system == rhs.system)||((this.system!= null)&&this.system.equals(rhs.system)))); } } diff --git a/gencode/java/udmi/schema/ScanManifest.java b/gencode/java/udmi/schema/ScanManifest.java new file mode 100644 index 0000000000..0e715bebcb --- /dev/null +++ b/gencode/java/udmi/schema/ScanManifest.java @@ -0,0 +1,79 @@ + +package udmi.schema; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyDescription; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + + +/** + * Scan Manifest + *

+ * Metadata describing active discovery scan rounds executed during trace capture + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ScanManifest { + + /** + * Local gateway IPv4 address used during capture + * + */ + @JsonProperty("gateway_ip") + @JsonPropertyDescription("Local gateway IPv4 address used during capture") + public String gateway_ip; + /** + * Network interface captured + * + */ + @JsonProperty("interface") + @JsonPropertyDescription("Network interface captured") + public String _interface; + /** + * BPF packet filter applied during capture + * + */ + @JsonProperty("filter") + @JsonPropertyDescription("BPF packet filter applied during capture") + public String filter; + /** + * RFC 3339 UTC timestamps marking active Who-Is discovery scan rounds + * + */ + @JsonProperty("scan_round_timestamps") + @JsonPropertyDescription("RFC 3339 UTC timestamps marking active Who-Is discovery scan rounds") + public List scan_round_timestamps; + /** + * Routed BACnet DNET numbers discovered via I-Am-Router-To-Network during trace + * + */ + @JsonProperty("discovered_routed_networks") + @JsonPropertyDescription("Routed BACnet DNET numbers discovered via I-Am-Router-To-Network during trace") + public List discovered_routed_networks; + + @Override + public int hashCode() { + int result = 1; + result = ((result* 31)+((this.filter == null)? 0 :this.filter.hashCode())); + result = ((result* 31)+((this.gateway_ip == null)? 0 :this.gateway_ip.hashCode())); + result = ((result* 31)+((this.discovered_routed_networks == null)? 0 :this.discovered_routed_networks.hashCode())); + result = ((result* 31)+((this._interface == null)? 0 :this._interface.hashCode())); + result = ((result* 31)+((this.scan_round_timestamps == null)? 0 :this.scan_round_timestamps.hashCode())); + return result; + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if ((other instanceof ScanManifest) == false) { + return false; + } + ScanManifest rhs = ((ScanManifest) other); + return ((((((this.filter == rhs.filter)||((this.filter!= null)&&this.filter.equals(rhs.filter)))&&((this.gateway_ip == rhs.gateway_ip)||((this.gateway_ip!= null)&&this.gateway_ip.equals(rhs.gateway_ip))))&&((this.discovered_routed_networks == rhs.discovered_routed_networks)||((this.discovered_routed_networks!= null)&&this.discovered_routed_networks.equals(rhs.discovered_routed_networks))))&&((this._interface == rhs._interface)||((this._interface!= null)&&this._interface.equals(rhs._interface))))&&((this.scan_round_timestamps == rhs.scan_round_timestamps)||((this.scan_round_timestamps!= null)&&this.scan_round_timestamps.equals(rhs.scan_round_timestamps)))); + } + +} diff --git a/gencode/java/udmi/schema/StreamsEvents.java b/gencode/java/udmi/schema/StreamsEvents.java deleted file mode 100644 index 4794855dd9..0000000000 --- a/gencode/java/udmi/schema/StreamsEvents.java +++ /dev/null @@ -1,95 +0,0 @@ - -package udmi.schema; - -import java.util.Date; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyDescription; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Streams Events - *

- * Sequential data stream chunks for reliable transport over MQTT (e.g. PCAP traces, firmware blobs, reliable alarms, logs playback). - * - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -public class StreamsEvents { - - /** - * RFC 3339 UTC timestamp the stream chunk event was generated - * - */ - @JsonProperty("timestamp") - @JsonPropertyDescription("RFC 3339 UTC timestamp the stream chunk event was generated") - public Date timestamp; - /** - * Version of the UDMI schema - * - */ - @JsonProperty("version") - @JsonPropertyDescription("Version of the UDMI schema") - public String version; - /** - * Unique session identifier for the continuous stream transmission - * - */ - @JsonProperty("session_id") - @JsonPropertyDescription("Unique session identifier for the continuous stream transmission") - public String session_id; - /** - * Sequence number for this stream event to support reliable sequential delivery and reassembly - * - */ - @JsonProperty("event_no") - @JsonPropertyDescription("Sequence number for this stream event to support reliable sequential delivery and reassembly") - public Integer event_no; - /** - * 0-based index of the transmitted chunk payload within the total session - * - */ - @JsonProperty("chunk_index") - @JsonPropertyDescription("0-based index of the transmitted chunk payload within the total session") - public Integer chunk_index; - /** - * Total number of chunks comprising the complete transmission binary - * - */ - @JsonProperty("total_chunks") - @JsonPropertyDescription("Total number of chunks comprising the complete transmission binary") - public Integer total_chunks; - /** - * Base64-encoded binary chunk payload data - * - */ - @JsonProperty("data") - @JsonPropertyDescription("Base64-encoded binary chunk payload data") - public String data; - - @Override - public int hashCode() { - int result = 1; - result = ((result* 31)+((this.chunk_index == null)? 0 :this.chunk_index.hashCode())); - result = ((result* 31)+((this.data == null)? 0 :this.data.hashCode())); - result = ((result* 31)+((this.event_no == null)? 0 :this.event_no.hashCode())); - result = ((result* 31)+((this.session_id == null)? 0 :this.session_id.hashCode())); - result = ((result* 31)+((this.version == null)? 0 :this.version.hashCode())); - result = ((result* 31)+((this.total_chunks == null)? 0 :this.total_chunks.hashCode())); - result = ((result* 31)+((this.timestamp == null)? 0 :this.timestamp.hashCode())); - return result; - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if ((other instanceof StreamsEvents) == false) { - return false; - } - StreamsEvents rhs = ((StreamsEvents) other); - return ((((((((this.chunk_index == rhs.chunk_index)||((this.chunk_index!= null)&&this.chunk_index.equals(rhs.chunk_index)))&&((this.data == rhs.data)||((this.data!= null)&&this.data.equals(rhs.data))))&&((this.event_no == rhs.event_no)||((this.event_no!= null)&&this.event_no.equals(rhs.event_no))))&&((this.session_id == rhs.session_id)||((this.session_id!= null)&&this.session_id.equals(rhs.session_id))))&&((this.version == rhs.version)||((this.version!= null)&&this.version.equals(rhs.version))))&&((this.total_chunks == rhs.total_chunks)||((this.total_chunks!= null)&&this.total_chunks.equals(rhs.total_chunks))))&&((this.timestamp == rhs.timestamp)||((this.timestamp!= null)&&this.timestamp.equals(rhs.timestamp)))); - } - -} diff --git a/gencode/python/udmi/schema/__init__.py b/gencode/python/udmi/schema/__init__.py index f7e8dd0b75..823027b996 100644 --- a/gencode/python/udmi/schema/__init__.py +++ b/gencode/python/udmi/schema/__init__.py @@ -43,7 +43,6 @@ from .events_discovery import * from .events_pointset import * from .events_pointset_point import * -from .events_streams import * from .events_system import * from .events_udmi import * from .events_validation import * @@ -101,3 +100,4 @@ from .state_validation_feature import * from .state_validation_schema import * from .state_validation_sequence import * +from .upload_discovery import * diff --git a/gencode/python/udmi/schema/envelope.py b/gencode/python/udmi/schema/envelope.py index 08cdb8509e..7a4450dce6 100644 --- a/gencode/python/udmi/schema/envelope.py +++ b/gencode/python/udmi/schema/envelope.py @@ -26,7 +26,6 @@ class SubFolder(Enum): validation = 'validation' blobset = 'blobset' monitoring = 'monitoring' - streams = 'streams' class SubType(Enum): @@ -42,6 +41,7 @@ class SubType(Enum): reply = 'reply' model = 'model' propose = 'propose' + upload = 'upload' @dataclass diff --git a/gencode/python/udmi/schema/events.py b/gencode/python/udmi/schema/events.py index 3ac694d27a..d932e899e5 100644 --- a/gencode/python/udmi/schema/events.py +++ b/gencode/python/udmi/schema/events.py @@ -9,7 +9,6 @@ from ._base import DataModel from .events_discovery import DiscoveryEvents from .events_pointset import PointsetEvents -from .events_streams import StreamsEvents from .events_system import SystemEvents @@ -22,4 +21,3 @@ class Events(DataModel): system: Optional[SystemEvents] = None pointset: Optional[PointsetEvents] = None discovery: Optional[DiscoveryEvents] = None - streams: Optional[StreamsEvents] = None diff --git a/gencode/python/udmi/schema/events_streams.py b/gencode/python/udmi/schema/events_streams.py deleted file mode 100644 index e1f344a814..0000000000 --- a/gencode/python/udmi/schema/events_streams.py +++ /dev/null @@ -1,24 +0,0 @@ -# generated by datamodel-codegen: -# filename: events_streams.json - -from __future__ import annotations - -from dataclasses import dataclass -from typing import Optional - -from ._base import DataModel - - -@dataclass -class StreamsEvents(DataModel): - """ - Sequential data stream chunks for reliable transport over MQTT (e.g. PCAP traces, firmware blobs, reliable alarms, logs playback). - """ - - timestamp: Optional[str] = None - version: Optional[str] = None - session_id: Optional[str] = None - event_no: Optional[int] = None - chunk_index: Optional[int] = None - total_chunks: Optional[int] = None - data: Optional[str] = None diff --git a/gencode/python/udmi/schema/upload_discovery.py b/gencode/python/udmi/schema/upload_discovery.py new file mode 100644 index 0000000000..12b28e257d --- /dev/null +++ b/gencode/python/udmi/schema/upload_discovery.py @@ -0,0 +1,38 @@ +# generated by datamodel-codegen: +# filename: upload_discovery.json + +from __future__ import annotations + +from dataclasses import dataclass +from typing import List, Optional + +from ._base import DataModel + + +@dataclass +class ScanManifest(DataModel): + """ + Metadata describing active discovery scan rounds executed during trace capture + """ + + gateway_ip: Optional[str] = None + interface: Optional[str] = None + filter: Optional[str] = None + scan_round_timestamps: Optional[List[str]] = None + discovered_routed_networks: Optional[List[int]] = None + + +@dataclass +class DiscoveryUpload(DataModel): + """ + Sequential compressed capture chunk transport over MQTT upload/discovery framed by config.discovery and state.discovery. + """ + + timestamp: Optional[str] = None + version: Optional[str] = None + generation: Optional[str] = None + family: Optional[str] = None + event_no: Optional[int] = None + data: Optional[str] = None + sha256: Optional[str] = None + scan_manifest: Optional[ScanManifest] = None diff --git a/schema/envelope.json b/schema/envelope.json index 8dac2d7f1c..239fd4198d 100644 --- a/schema/envelope.json +++ b/schema/envelope.json @@ -68,8 +68,7 @@ "pointset", "validation", "blobset", - "monitoring", - "streams" + "monitoring" ] }, "subType": { @@ -85,7 +84,8 @@ "query", "reply", "model", - "propose" + "propose", + "upload" ] } }, diff --git a/schema/events.json b/schema/events.json index 9ae8ec7de3..3d8d0e387a 100644 --- a/schema/events.json +++ b/schema/events.json @@ -14,9 +14,6 @@ }, "discovery": { "$ref": "file:events_discovery.json#" - }, - "streams": { - "$ref": "file:events_streams.json#" } } } diff --git a/schema/events_streams.json b/schema/events_streams.json deleted file mode 100644 index b9df2fcade..0000000000 --- a/schema/events_streams.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "$udmi_version": "1.5.7", - "title": "Streams Events", - "description": "Sequential data stream chunks for reliable transport over MQTT (e.g. PCAP traces, firmware blobs, reliable alarms, logs playback).", - "$section": "Messages", - "type": "object", - "$schema": "http://json-schema.org/draft-07/schema#", - "additionalProperties": false, - "properties": { - "timestamp": { - "description": "RFC 3339 UTC timestamp the stream chunk event was generated", - "type": "string", - "format": "date-time" - }, - "version": { - "description": "Version of the UDMI schema", - "type": "string" - }, - "session_id": { - "description": "Unique session identifier for the continuous stream transmission", - "type": "string" - }, - "event_no": { - "description": "Sequence number for this stream event to support reliable sequential delivery and reassembly", - "type": "integer" - }, - "chunk_index": { - "description": "0-based index of the transmitted chunk payload within the total session", - "type": "integer" - }, - "total_chunks": { - "description": "Total number of chunks comprising the complete transmission binary", - "type": "integer" - }, - "data": { - "description": "Base64-encoded binary chunk payload data", - "type": "string" - } - } -} diff --git a/schema/upload_discovery.json b/schema/upload_discovery.json new file mode 100644 index 0000000000..ddbcd1b3cf --- /dev/null +++ b/schema/upload_discovery.json @@ -0,0 +1,83 @@ +{ + "$udmi_version": "1.5.7", + "title": "Discovery Upload", + "description": "Sequential compressed capture chunk transport over MQTT upload/discovery framed by config.discovery and state.discovery.", + "$section": "Messages", + "type": "object", + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "properties": { + "timestamp": { + "description": "RFC 3339 UTC timestamp the chunk was emitted", + "type": "string", + "format": "date-time" + }, + "version": { + "description": "Version of the UDMI schema", + "type": "string" + }, + "generation": { + "description": "Trigger timestamp / session generation ID matching config.discovery and state.discovery", + "type": "string", + "format": "date-time" + }, + "family": { + "description": "Protocol family identifier for the trace capture (e.g. bacnet, ether, ipv4)", + "type": "string" + }, + "event_no": { + "description": "0 for start marker, 1..N for gzip-compressed data chunks, and required -(N+1) for stream termination", + "type": "integer" + }, + "data": { + "description": "Base64-encoded gzip-compressed binary PCAP chunk payload (present for event_no > 0)", + "type": "string" + }, + "sha256": { + "description": "Expected SHA-256 hex digest of the complete unencoded PCAP file (required on terminal event_no < 0)", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "scan_manifest": { + "title": "Scan Manifest", + "description": "Metadata describing active discovery scan rounds executed during trace capture", + "type": "object", + "additionalProperties": false, + "properties": { + "gateway_ip": { + "description": "Local gateway IPv4 address used during capture", + "type": "string" + }, + "interface": { + "description": "Network interface captured", + "type": "string" + }, + "filter": { + "description": "BPF packet filter applied during capture", + "type": "string" + }, + "scan_round_timestamps": { + "description": "RFC 3339 UTC timestamps marking active Who-Is discovery scan rounds", + "type": "array", + "items": { + "type": "string" + } + }, + "discovered_routed_networks": { + "description": "Routed BACnet DNET numbers discovered via I-Am-Router-To-Network during trace", + "type": "array", + "items": { + "type": "integer" + } + } + } + } + }, + "required": [ + "timestamp", + "version", + "generation", + "family", + "event_no" + ] +} diff --git a/tests/schemas/envelope/errors1.out b/tests/schemas/envelope/errors1.out index f6f102d6e1..0e3057828b 100644 --- a/tests/schemas/envelope/errors1.out +++ b/tests/schemas/envelope/errors1.out @@ -2,4 +2,4 @@ $.deviceId: does not match the regex pattern ^[A-Z]{2,6}-[1-9][0-9]*$ $.deviceNumId: does not match the regex pattern ^[0-9]+$ $.deviceRegistryId: does not match the regex pattern ^[a-zA-Z][-a-zA-Z0-9._+~%]*[a-zA-Z0-9]$ - $.subType: does not have a value in the enumeration [invalid, local, reflect, events, errors, commands, config, state, query, reply, model, propose] + $.subType: does not have a value in the enumeration [invalid, local, reflect, events, errors, commands, config, state, query, reply, model, propose, upload] diff --git a/tests/schemas/upload_discovery/chunk.json b/tests/schemas/upload_discovery/chunk.json new file mode 100644 index 0000000000..83b66f7508 --- /dev/null +++ b/tests/schemas/upload_discovery/chunk.json @@ -0,0 +1,8 @@ +{ + "version": "1.5.7", + "timestamp": "2026-11-10T14:35:02Z", + "generation": "2026-11-10T14:35:00Z", + "family": "bacnet", + "event_no": 1, + "data": "H4sIAAAAAAAAA9N39Q129XUNdvJ3DQYAaR9LHAwAAAA=" +} diff --git a/tests/schemas/upload_discovery/chunk.out b/tests/schemas/upload_discovery/chunk.out new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/schemas/upload_discovery/eof.json b/tests/schemas/upload_discovery/eof.json new file mode 100644 index 0000000000..2cdbfb5ffd --- /dev/null +++ b/tests/schemas/upload_discovery/eof.json @@ -0,0 +1,22 @@ +{ + "version": "1.5.7", + "timestamp": "2026-11-10T14:36:00Z", + "generation": "2026-11-10T14:35:00Z", + "family": "bacnet", + "event_no": -2, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "scan_manifest": { + "gateway_ip": "192.168.1.50", + "interface": "eth0", + "filter": "udp port 47808", + "scan_round_timestamps": [ + "2026-11-10T14:35:01Z", + "2026-11-10T14:35:20Z", + "2026-11-10T14:35:40Z" + ], + "discovered_routed_networks": [ + 6100, + 9288 + ] + } +} diff --git a/tests/schemas/upload_discovery/eof.out b/tests/schemas/upload_discovery/eof.out new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/schemas/upload_discovery/start.json b/tests/schemas/upload_discovery/start.json new file mode 100644 index 0000000000..0f1a66b258 --- /dev/null +++ b/tests/schemas/upload_discovery/start.json @@ -0,0 +1,7 @@ +{ + "version": "1.5.7", + "timestamp": "2026-11-10T14:35:00Z", + "generation": "2026-11-10T14:35:00Z", + "family": "bacnet", + "event_no": 0 +} diff --git a/tests/schemas/upload_discovery/start.out b/tests/schemas/upload_discovery/start.out new file mode 100644 index 0000000000..e69de29bb2 From 9f4fbda0a0049c341c39d4810224c52aac1a8312 Mon Sep 17 00:00:00 2001 From: Khyati Mahendru Date: Fri, 13 Nov 2026 07:00:49 +0000 Subject: [PATCH 2/8] Route upload/# messages in UDMIS and add publish_upload to Python clientlib - Add --upload_pubsub_topic_id support in MqttToPubSubBridge to route subType='upload' messages to a dedicated Pub/Sub publisher with graceful shutdown draining. - Register uufi_upload flow in UdmiServicePod and udmis/etc/local_pod.json for local upload/# pass-through. - Add publish_upload helper to clientlib BaseManager and include upload/# in MessageConnection default subscribe topics. - Add unit tests in MqttToPubSubBridgeTest covering upload publisher routing and shutdown. --- .../src/udmi/core/managers/base_manager.py | 18 ++++++ .../src/main/python/udmi/common/connection.py | 4 +- udmis/etc/local_pod.json | 4 ++ .../service/bridge/MqttToPubSubBridge.java | 56 +++++++++++++++--- .../bos/udmi/service/pod/UdmiServicePod.java | 1 + .../bridge/MqttToPubSubBridgeTest.java | 57 ++++++++++++++++++- 6 files changed, 131 insertions(+), 9 deletions(-) diff --git a/clientlib/python/src/udmi/core/managers/base_manager.py b/clientlib/python/src/udmi/core/managers/base_manager.py index 7ece646c0e..5213037d03 100644 --- a/clientlib/python/src/udmi/core/managers/base_manager.py +++ b/clientlib/python/src/udmi/core/managers/base_manager.py @@ -102,6 +102,24 @@ def publish_event(self, event_model: DataModel, subfolder: str, self._dispatcher.publish_event(f"events/{subfolder}", event_model, device_id) + def publish_upload(self, upload_model: DataModel, subfolder: str, + device_id: Optional[str] = None) -> None: + """ + Helper method for managers to publish chunked upload messages. + + Args: + upload_model: The UDMI upload data model to publish. + subfolder: The upload subfolder (e.g., 'discovery'). + device_id: (Optional) The device ID to publish for. + """ + if not self._dispatcher: + LOGGER.error("Manager %s cannot publish upload: dispatcher not set.", + self.__class__.__name__) + return + + self._dispatcher.publish_event(f"upload/{subfolder}", upload_model, + device_id) + def trigger_state_update(self, immediate: bool = False) -> None: """ Requests the device to publish its state. diff --git a/common/src/main/python/udmi/common/connection.py b/common/src/main/python/udmi/common/connection.py index 51e552810f..d3218b1304 100644 --- a/common/src/main/python/udmi/common/connection.py +++ b/common/src/main/python/udmi/common/connection.py @@ -161,13 +161,15 @@ def create_mqtt_client(self) -> mqtt.Client: return client def get_default_subscribe_topics(self) -> List[str]: - """Returns standard topic filters for consuming device events and state.""" + """Returns standard topic filters for consuming device events, state, and uploads.""" return [ f"/r/{self.actual_registry}/d/+/#", "/r/+/d/+/#", "/uufi/#", "events/#", "state/#", + "upload/#", + "/devices/+/upload/#", ] def subscribe_mqtt( diff --git a/udmis/etc/local_pod.json b/udmis/etc/local_pod.json index 10b6581621..762175e562 100644 --- a/udmis/etc/local_pod.json +++ b/udmis/etc/local_pod.json @@ -46,6 +46,10 @@ "uufi_events": { "recv_id": "events/#", "send_id": "/uufi/#" + }, + "uufi_upload": { + "recv_id": "upload/#", + "send_id": "/uufi/#" } }, "crons": { diff --git a/udmis/src/main/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridge.java b/udmis/src/main/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridge.java index 339510973c..97cea3e8d2 100644 --- a/udmis/src/main/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridge.java +++ b/udmis/src/main/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridge.java @@ -371,6 +371,7 @@ public static void main(String[] args) { commandLine.getOptionValue("mqtt_subscription_topic", "/r/+/d/#"); String gcpProjectId = commandLine.getOptionValue("gcp_project_id"); String pubsubTopicId = commandLine.getOptionValue("pubsub_topic_id"); + String uploadPubsubTopicId = commandLine.getOptionValue("upload_pubsub_topic_id"); String mqttClientId = commandLine.getOptionValue("mqtt_client_id"); String mqttSessionExpiryInterval = commandLine.getOptionValue("mqtt_session_expiry_interval"); String mqttKeepAliveInterval = commandLine.getOptionValue("mqtt_keep_alive_interval", "15"); @@ -407,6 +408,7 @@ public static void main(String[] args) { } Publisher publisher = null; + Publisher uploadPublisher = null; IMqttClient mqttClient = null; EtcdDataProvider etcdProvider = null; MqttToPubSubBridge bridge = null; @@ -416,6 +418,9 @@ public static void main(String[] args) { try { etcdProvider = createEtcdProvider(etcdTarget, etcdOptions); publisher = createPublisher(gcpProjectId, pubsubTopicId); + if (uploadPubsubTopicId != null && !uploadPubsubTopicId.isEmpty()) { + uploadPublisher = createPublisher(gcpProjectId, uploadPubsubTopicId); + } // Initialize MQTT Client mqttClient = @@ -449,11 +454,13 @@ public static void main(String[] args) { final MqttToPubSubBridge finalBridge = bridge; final IMqttClient finalMqttClient = mqttClient; final Publisher finalPublisher = publisher; + final Publisher finalUploadPublisher = uploadPublisher; final EtcdDataProvider finalEtcdProvider = etcdProvider; Runnable shutdownTask = () -> { if (isShuttingDown.compareAndSet(false, true)) { - gracefulShutdown(finalBridge, finalMqttClient, finalPublisher, finalEtcdProvider); + gracefulShutdown( + finalBridge, finalMqttClient, finalPublisher, finalEtcdProvider, finalUploadPublisher); } }; @@ -467,7 +474,7 @@ public static void main(String[] args) { // Set up MQTT Message Callback bridge.setupBridge(mqttClient, publisher, mqttSubscriptionTopic, - etcdProvider, sourceAttribute, sharedSubscription); + etcdProvider, sourceAttribute, sharedSubscription, uploadPublisher); // Keep the application running while (!bridge.isTripped()) { @@ -490,7 +497,7 @@ public static void main(String[] args) { System.exit(1); } finally { if (isShuttingDown.compareAndSet(false, true)) { - gracefulShutdown(bridge, mqttClient, publisher, etcdProvider); + gracefulShutdown(bridge, mqttClient, publisher, etcdProvider, uploadPublisher); } if (shutdownHook != null) { try { @@ -511,6 +518,8 @@ static CommandLine parseArgs(String[] args) throws ParseException { options.addOption(null, "mqtt_subscription_topic", true, "MQTT subscription topic."); options.addOption(null, "gcp_project_id", true, "Google Cloud Project ID."); options.addOption(null, "pubsub_topic_id", true, "Google Cloud Pub/Sub topic ID."); + options.addOption(null, "upload_pubsub_topic_id", true, + "Dedicated Google Cloud Pub/Sub topic ID for upload/# channel (e.g. udmi_upload)."); options.addOption(null, "mqtt_client_id", true, "MQTT client ID."); options.addOption(null, "mqtt_session_expiry_interval", true, "MQTT session expiry interval (seconds)."); @@ -597,7 +606,7 @@ static String getEtcdOptions(CommandLine commandLine) { */ public void setupBridge(IMqttClient mqttClient, Publisher publisher, String mqttSubscriptionTopic, EtcdDataProvider etcdProvider) throws MqttException { - setupBridge(mqttClient, publisher, mqttSubscriptionTopic, etcdProvider, "zanzara", null); + setupBridge(mqttClient, publisher, mqttSubscriptionTopic, etcdProvider, "zanzara", null, null); } /** @@ -612,7 +621,8 @@ public void setupBridge(IMqttClient mqttClient, Publisher publisher, public void setupBridge(IMqttClient mqttClient, Publisher publisher, String mqttSubscriptionTopic, EtcdDataProvider etcdProvider, String sourceAttribute) throws MqttException { - setupBridge(mqttClient, publisher, mqttSubscriptionTopic, etcdProvider, sourceAttribute, null); + setupBridge(mqttClient, publisher, mqttSubscriptionTopic, etcdProvider, sourceAttribute, null, + null); } /** @@ -622,6 +632,17 @@ public void setupBridge(IMqttClient mqttClient, Publisher publisher, String mqttSubscriptionTopic, EtcdDataProvider etcdProvider, String sourceAttribute, String sharedSubscription) throws MqttException { + setupBridge(mqttClient, publisher, mqttSubscriptionTopic, etcdProvider, sourceAttribute, + sharedSubscription, null); + } + + /** + * Sets up the bridge between MQTT and Pub/Sub with optional dedicated upload publisher. + */ + public void setupBridge(IMqttClient mqttClient, Publisher publisher, + String mqttSubscriptionTopic, EtcdDataProvider etcdProvider, String sourceAttribute, + String sharedSubscription, Publisher uploadPublisher) + throws MqttException { final String actualSubscriptionTopic; if (sharedSubscription != null && !sharedSubscription.isEmpty() @@ -769,8 +790,13 @@ public void messageArrived(String topic, MqttMessage message) { PubsubMessage pubsubMessage = pubsubMessageBuilder.putAllAttributes(attributes).build(); + Publisher targetPublisher = + (uploadPublisher != null && "upload".equals(attributes.get("subType"))) + ? uploadPublisher + : publisher; + // Publish with 5x retry + exponential backoff - publishWithRetry(publisher, pubsubMessage, message, messageKey, + publishWithRetry(targetPublisher, pubsubMessage, message, messageKey, topic, mqttClient, 1); publishInitiated = true; } catch (Exception e) { @@ -1040,6 +1066,11 @@ private static String getDeviceNumId(EtcdDataProvider etcdProvider, String regis static void gracefulShutdown(MqttToPubSubBridge bridge, IMqttClient mqttClient, Publisher publisher, EtcdDataProvider etcdProvider) { + gracefulShutdown(bridge, mqttClient, publisher, etcdProvider, null); + } + + static void gracefulShutdown(MqttToPubSubBridge bridge, IMqttClient mqttClient, + Publisher publisher, EtcdDataProvider etcdProvider, Publisher uploadPublisher) { logger.info("Initiating graceful shutdown of MqttToPubSubBridge..."); // 1. Signal bridge to ignore newly arriving MQTT messages if (bridge != null) { @@ -1057,7 +1088,7 @@ static void gracefulShutdown(MqttToPubSubBridge bridge, IMqttClient mqttClient, } } - // 3. Shut down Pub/Sub publisher and await pending publish futures + // 3. Shut down Pub/Sub publishers and await pending publish futures if (publisher != null) { try { publisher.shutdown(); @@ -1069,6 +1100,17 @@ static void gracefulShutdown(MqttToPubSubBridge bridge, IMqttClient mqttClient, logger.warn("Error shutting down Pub/Sub publisher", e); } } + if (uploadPublisher != null) { + try { + uploadPublisher.shutdown(); + if (!uploadPublisher.awaitTermination(10, TimeUnit.SECONDS)) { + logger.warn("Upload Pub/Sub publisher did not terminate within 10 seconds"); + } + logger.debug("Upload Pub/Sub Publisher shut down."); + } catch (Exception e) { + logger.warn("Error shutting down upload Pub/Sub publisher", e); + } + } // 4. Disconnect MQTT client after in-flight message ACKs have completed if (mqttClient != null && mqttClient.isConnected()) { diff --git a/udmis/src/main/java/com/google/bos/udmi/service/pod/UdmiServicePod.java b/udmis/src/main/java/com/google/bos/udmi/service/pod/UdmiServicePod.java index ec443eb507..84fed35f95 100644 --- a/udmis/src/main/java/com/google/bos/udmi/service/pod/UdmiServicePod.java +++ b/udmis/src/main/java/com/google/bos/udmi/service/pod/UdmiServicePod.java @@ -69,6 +69,7 @@ public class UdmiServicePod extends ContainerBase { PROCESSORS.put("uufi_out", UufiProcessor.class); PROCESSORS.put("uufi_state", UufiProcessor.class); PROCESSORS.put("uufi_events", UufiProcessor.class); + PROCESSORS.put("uufi_upload", UufiProcessor.class); } /** diff --git a/udmis/src/test/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridgeTest.java b/udmis/src/test/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridgeTest.java index a6d50d121e..830f08754b 100644 --- a/udmis/src/test/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridgeTest.java +++ b/udmis/src/test/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridgeTest.java @@ -994,18 +994,73 @@ void testGracefulShutdown() throws Exception { Publisher mockPublisher = mock(Publisher.class); when(mockPublisher.awaitTermination(any(Long.class), any(java.util.concurrent.TimeUnit.class))) .thenReturn(true); + Publisher mockUploadPublisher = mock(Publisher.class); + when(mockUploadPublisher.awaitTermination( + any(Long.class), any(java.util.concurrent.TimeUnit.class))) + .thenReturn(true); EtcdDataProvider mockEtcdProvider = mock(EtcdDataProvider.class); MqttToPubSubBridge bridge = new MqttToPubSubBridge(); MqttToPubSubBridge.gracefulShutdown( - bridge, mockMqttClient, mockPublisher, mockEtcdProvider); + bridge, mockMqttClient, mockPublisher, mockEtcdProvider, mockUploadPublisher); verify(mockMqttClient).disconnect(); verify(mockPublisher).shutdown(); verify(mockPublisher).awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS); + verify(mockUploadPublisher).shutdown(); + verify(mockUploadPublisher).awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS); verify(mockEtcdProvider).shutdown(); } + @Test + void testSetupBridgeRoutesUploadSubTypeToUploadPublisher() throws Exception { + IMqttClient mockMqttClient = mock(IMqttClient.class); + when(mockMqttClient.getClientId()).thenReturn("test-client"); + Publisher mockPublisher = mock(Publisher.class); + Publisher mockUploadPublisher = mock(Publisher.class); + + when(mockPublisher.publish(any(PubsubMessage.class))) + .thenReturn(ApiFutures.immediateFuture("evt-123")); + when(mockUploadPublisher.publish(any(PubsubMessage.class))) + .thenReturn(ApiFutures.immediateFuture("upl-456")); + + MqttToPubSubBridge bridge = new MqttToPubSubBridge(); + bridge.setupBridge( + mockMqttClient, mockPublisher, "/r/+/d/#", null, "zanzara", null, mockUploadPublisher); + + ArgumentCaptor callbackCaptor = + ArgumentCaptor.forClass(MqttCallback.class); + verify(mockMqttClient).setCallback(callbackCaptor.capture()); + MqttCallback callback = callbackCaptor.getValue(); + + // 1. Upload message routes to mockUploadPublisher + String uploadTopic = "/r/ZZ-TRI-FECTA/d/DSN-1/upload/discovery"; + MqttMessage uploadMsg = new MqttMessage("{\"event_no\":0}".getBytes()); + uploadMsg.setId(801); + callback.messageArrived(uploadTopic, uploadMsg); + + ArgumentCaptor uploadCaptor = ArgumentCaptor.forClass(PubsubMessage.class); + verify(mockUploadPublisher, org.mockito.Mockito.timeout(5000)).publish(uploadCaptor.capture()); + Map uploadAttrs = uploadCaptor.getValue().getAttributesMap(); + assertEquals("upload", uploadAttrs.get("subType")); + assertEquals("discovery", uploadAttrs.get("subFolder")); + assertEquals("DSN-1", uploadAttrs.get("deviceId")); + assertEquals("ZZ-TRI-FECTA", uploadAttrs.get("deviceRegistryId")); + verify(mockPublisher, org.mockito.Mockito.never()).publish(any(PubsubMessage.class)); + + // 2. Standard events message routes to mockPublisher + String eventTopic = "/r/ZZ-TRI-FECTA/d/DSN-1/events/discovery"; + MqttMessage eventMsg = new MqttMessage("{\"event_no\":1}".getBytes()); + eventMsg.setId(802); + callback.messageArrived(eventTopic, eventMsg); + + ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(PubsubMessage.class); + verify(mockPublisher, org.mockito.Mockito.timeout(5000)).publish(eventCaptor.capture()); + Map eventAttrs = eventCaptor.getValue().getAttributesMap(); + assertEquals("events", eventAttrs.get("subType")); + assertEquals("discovery", eventAttrs.get("subFolder")); + } + @Test void testBridgeShutdownWithTimeout() { MqttToPubSubBridge bridge = new MqttToPubSubBridge(); From f4b9761329d61841998785c2dda0711bf188a646 Mon Sep 17 00:00:00 2001 From: Khyati Mahendru Date: Fri, 13 Nov 2026 07:01:08 +0000 Subject: [PATCH 3/8] Add Butler PCAP upload reassembly handler and MCP BACnet trace tools - Add PcapUploadHandler to reassemble gzip-compressed upload/discovery chunks in order, verify terminal SHA-256 digests, and archive .pcap and scan_manifest.json artifacts to GCS or local disk. - Exclude subType='upload' messages from RawFallbackHandler so raw PCAP chunks are never persisted in udmi_messages. - Add udmi_pcap_captures table in PostgresManager to track capture lifecycle metadata and URIs. - Add trigger_bacnet_trace and get_pcap_capture tools across Butler discovery, ButlerProvider, ButlerMcpServer, and ButlerClient with unit tests and schema docs. --- butler/README.md | 3 + butler/SCHEMAS.md | 25 ++ butler/src/discovery.py | 56 +++ butler/src/dispatcher.py | 8 +- butler/src/handlers/pcap_upload.py | 381 ++++++++++++++++++ butler/src/handlers/raw_fallback.py | 10 +- butler/src/service.py | 7 +- butler/tests/test_dispatcher.py | 53 +++ butler/tests/test_handlers.py | 135 +++++++ .../main/python/udmi/common/db/postgres.py | 23 ++ mcp/butler/client.py | 39 ++ mcp/butler/provider.py | 163 ++++++++ mcp/butler/server.py | 49 +++ tests/test_mcp_butler.py | 178 ++++++++ 14 files changed, 1127 insertions(+), 3 deletions(-) create mode 100644 butler/src/handlers/pcap_upload.py diff --git a/butler/README.md b/butler/README.md index 435d4718d8..52096fd717 100644 --- a/butler/README.md +++ b/butler/README.md @@ -14,11 +14,13 @@ graph TD SRC["UDMI Stream (MQTT Broker / Stdin)"] --> SVC["ButlerService (service.py)"] SVC --> DISP["MessageDispatcher (dispatcher.py)"] DISP --> H_RAW["RawFallbackHandler"] + DISP --> H_PCAP["PcapUploadHandler (upload/discovery)"] DISP --> H_PT["PointsetEventsHandler"] DISP --> H_ST["PointStateHandler / SystemStateHandler"] DISP --> H_OTH["Discovery / Validation / Alarms / Metadata"] H_RAW --> PG[("PostgreSQL (udmi_messages)")] + H_PCAP --> GCS[("GCS / Local PCAP Archive + udmi_pcap_captures")] H_PT --> INF[("InfluxDB (point_value)")] H_ST --> PG_SPEC[("PostgreSQL (udmi_* state tables)")] H_OTH --> PG_SPEC @@ -50,6 +52,7 @@ butler/ │ ├── dispatcher.py # Message router & handler registry │ └── handlers/ # Specialized database payload handlers │ ├── base.py +│ ├── pcap_upload.py │ ├── pointset_events.py │ ├── point_state.py │ ├── system_state.py diff --git a/butler/SCHEMAS.md b/butler/SCHEMAS.md index 70661c8351..a5470b2be6 100644 --- a/butler/SCHEMAS.md +++ b/butler/SCHEMAS.md @@ -189,6 +189,31 @@ Stores device metadata blocks, physical coordinates, network interface bindings, --- +### Table: `udmi_pcap_captures` (PCAP Trace Reassembly & Archival Status) +Tracks chunked `upload/discovery` packet capture reassembly progress, SHA-256 verification digests, scan manifests, and archived `.pcap` / `scan_manifest.json` URIs (without storing raw PCAP chunk bytes in PostgreSQL). + +| Column | Type | Description | +| :--- | :--- | :--- | +| `id` | `SERIAL PRIMARY KEY` | Auto-incrementing row ID | +| `site` | `VARCHAR(255) NOT NULL` | Site / device registry identifier | +| `device_id` | `VARCHAR(255) NOT NULL` | Gateway / Spotter device identifier | +| `family` | `VARCHAR(50) NOT NULL` | Protocol family (e.g. `bacnet`) | +| `generation` | `VARCHAR(64) NOT NULL` | Discovery trace generation timestamp | +| `status` | `VARCHAR(50)` | Reassembly lifecycle status (`PENDING`, `RECEIVING`, `COMPLETED`, `FAILED`) | +| `chunks_received` | `INTEGER` | Number of data chunks received (`1..N`) | +| `expected_chunks` | `INTEGER` | Total expected chunks `N` derived from terminal `event_no = -(N + 1)` | +| `expected_sha256` | `VARCHAR(64)` | Expected SHA-256 hex digest from terminal EOF message | +| `actual_sha256` | `VARCHAR(64)` | Computed SHA-256 hex digest of reassembled `.pcap` bytes | +| `total_bytes` | `BIGINT` | Total uncompressed `.pcap` size in bytes | +| `pcap_uri` | `TEXT` | Resolved GCS (`gs://...`) or local file URI for the `.pcap` artifact | +| `manifest_uri` | `TEXT` | Resolved GCS (`gs://...`) or local file URI for `scan_manifest.json` | +| `scan_manifest` | `JSONB` | Structured `ScanManifest` metadata from terminal EOF message | +| `bug_id` | `VARCHAR(64)` | Optional issue or ticket identifier associated with the capture | +| `error_message` | `TEXT` | Diagnostic error message if status is `FAILED` | +| `updated_at` | `TIMESTAMP WITH TIME ZONE` | Last status update timestamp (`DEFAULT CURRENT_TIMESTAMP`) | + +--- + ## 3. InfluxDB Time-Series Schema InfluxDB v2 ingests numeric, boolean, and textual point telemetry from `events/pointset` messages. diff --git a/butler/src/discovery.py b/butler/src/discovery.py index 71d98f2ae7..c8813af39a 100644 --- a/butler/src/discovery.py +++ b/butler/src/discovery.py @@ -52,3 +52,59 @@ def run_discovery(conn_spec, registry_id, device_id, target_families, site_model topics = connection.get_discovery_topics(device_id) topic_message_pairs = [(t, msg) for t in topics] connection.publish_messages(topic_message_pairs) + + +def trigger_bacnet_trace( + conn_spec, + registry_id, + device_id, + scan_duration_sec=7200, + max_bytes=268435456, + site_model=None, + generation=None, +): + """Publishes config/discovery (families.bacnet with depth: 'trace') to trigger a Spotter PCAP capture.""" + connection = ButlerConnection(conn_spec, registry_id, site_model, device_id) + actual_registry = connection.actual_registry + + now = generation or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + tx_id = f"TXN-{uuid.uuid4().hex[:8]}" + source_id = "butler" + payload = { + "version": "1.5.7", + "timestamp": now, + "families": { + "bacnet": { + "generation": now, + "scan_duration_sec": int(scan_duration_sec), + "depth": "trace", + "trace": { + "max_bytes": int(max_bytes), + }, + } + }, + } + msg = { + "subType": "config", + "subFolder": "discovery", + "deviceRegistryId": actual_registry, + "deviceId": device_id, + "projectId": connection.project or "vibrant", + "transactionId": tx_id, + "publishTime": now, + "source": source_id, + "principal": source_id, + "payload": payload, + } + + topics = connection.get_discovery_topics(device_id) + topic_message_pairs = [(t, msg) for t in topics] + connection.publish_messages(topic_message_pairs) + return { + "site": actual_registry, + "gateway_id": device_id, + "generation": now, + "scan_duration_sec": int(scan_duration_sec), + "max_bytes": int(max_bytes), + "transaction_id": tx_id, + } diff --git a/butler/src/dispatcher.py b/butler/src/dispatcher.py index 7bcd2abbba..c6972c41f2 100644 --- a/butler/src/dispatcher.py +++ b/butler/src/dispatcher.py @@ -5,6 +5,7 @@ from butler.src.handlers.base import BaseHandler from butler.src.handlers.discovery import DiscoveryHandler from butler.src.handlers.metadata import MetadataHandler +from butler.src.handlers.pcap_upload import PcapUploadHandler from butler.src.handlers.point_state import PointStateHandler from butler.src.handlers.pointset_events import PointsetEventsHandler from butler.src.handlers.raw_fallback import RawFallbackHandler @@ -33,6 +34,7 @@ def __init__( self.handlers = custom_handlers else: self.handlers = [ + PcapUploadHandler(), PointsetEventsHandler(), PointStateHandler(), SystemStateHandler(), @@ -69,7 +71,11 @@ def dispatch(self, envelope: Dict[str, Any], payload: Dict[str, Any]) -> Dict[st envelope, payload, self.postgres_manager, self.influx_manager ) - if self.always_save_raw and matched_handler is not self.raw_fallback: + if ( + self.always_save_raw + and matched_handler is not self.raw_fallback + and sub_type != "upload" + ): self.raw_fallback.process_message( envelope, payload, self.postgres_manager, self.influx_manager ) diff --git a/butler/src/handlers/pcap_upload.py b/butler/src/handlers/pcap_upload.py new file mode 100644 index 0000000000..d0b4b9e611 --- /dev/null +++ b/butler/src/handlers/pcap_upload.py @@ -0,0 +1,381 @@ +"""Handler for UDMI upload/discovery chunk reassembly, SHA-256 verification, and GCS archival.""" + +import base64 +import gzip +import hashlib +import json +import os +import re +import threading +import time +from typing import Any, Dict, Optional, Tuple + +from butler.src.handlers.base import BaseHandler +from udmi.common.db.influx import InfluxManager +from udmi.common.db.postgres import PostgresManager + +GZIP_MAGIC = b"\x1f\x8b" +DEFAULT_SESSION_TTL_SEC = 14400.0 +MAX_COMPLETED_CACHE = 256 + + +def _decode_chunk_payload(b64_data: str) -> bytes: + """Base64-decodes and decompresses a gzip PCAP chunk payload.""" + raw = base64.b64decode(b64_data) + if raw.startswith(GZIP_MAGIC): + return gzip.decompress(raw) + return raw + + +def _sanitize_path_component(val: str) -> str: + """Sanitizes a string for safe filesystem/object path usage.""" + return re.sub(r"[^A-Za-z0-9._-]", "_", str(val or "unknown")) + + +class _PcapSession: + """In-memory reassembly state for a single (site, device_id, family, generation) stream.""" + + def __init__(self, site: str, device_id: str, family: str, generation: str) -> None: + self.site = site + self.device_id = device_id + self.family = family + self.generation = generation + self.created_at = time.monotonic() + self.chunks: Dict[int, bytes] = {} + self.expected_chunks: Optional[int] = None + self.expected_sha256: Optional[str] = None + self.scan_manifest: Optional[Dict[str, Any]] = None + self.completed: bool = False + self.pcap_uri: Optional[str] = None + self.manifest_uri: Optional[str] = None + self.actual_sha256: Optional[str] = None + self.total_bytes: int = 0 + + +class PcapUploadHandler(BaseHandler): + """Reassembles upload/discovery chunks, verifies sha256, and writes standard .pcap + scan_manifest.json.""" + + def __init__( + self, + archive_dir: Optional[str] = None, + gcs_bucket: Optional[str] = None, + gcs_client: Optional[Any] = None, + session_ttl_sec: float = DEFAULT_SESSION_TTL_SEC, + ) -> None: + self.archive_dir = archive_dir or os.environ.get("BUTLER_PCAP_DIR", "out/pcap") + self.gcs_bucket = gcs_bucket or os.environ.get("BUTLER_PCAP_GCS_BUCKET") + self.gcs_client = gcs_client + self.session_ttl_sec = session_ttl_sec + self._sessions: Dict[Tuple[str, str, str, str], _PcapSession] = {} + self._completed_results: Dict[Tuple[str, str, str, str], Dict[str, Any]] = {} + self._lock = threading.Lock() + + def _evict_expired_sessions(self) -> None: + """Evicts incomplete sessions older than session_ttl_sec.""" + now = time.monotonic() + expired_keys = [ + key + for key, sess in self._sessions.items() + if (now - sess.created_at) > self.session_ttl_sec + ] + for key in expired_keys: + self._sessions.pop(key, None) + + def can_handle( + self, + sub_folder: Optional[str], + sub_type: Optional[str], + payload: Dict[str, Any], + ) -> bool: + del payload + return sub_type == "upload" and sub_folder == "discovery" + + def _upsert_capture_metadata( + self, + postgres_manager: Optional[PostgresManager], + session: _PcapSession, + status: str, + error_message: Optional[str] = None, + ) -> None: + """Persists lightweight PCAP capture status and URIs (never raw chunk data) to PostgreSQL.""" + if not postgres_manager: + return + if isinstance(postgres_manager, PostgresManager): + conn = postgres_manager.get_connection() + try: + with conn.cursor() as cur: + manifest_json = ( + json.dumps(session.scan_manifest) + if session.scan_manifest is not None + else None + ) + cur.execute( + """ + INSERT INTO udmi_pcap_captures ( + site, device_id, family, generation, status, + chunks_received, expected_chunks, expected_sha256, + actual_sha256, total_bytes, pcap_uri, manifest_uri, + scan_manifest, error_message, updated_at + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s, CURRENT_TIMESTAMP) + ON CONFLICT (site, device_id, family, generation) + DO UPDATE SET + status = EXCLUDED.status, + chunks_received = EXCLUDED.chunks_received, + expected_chunks = COALESCE(EXCLUDED.expected_chunks, udmi_pcap_captures.expected_chunks), + expected_sha256 = COALESCE(EXCLUDED.expected_sha256, udmi_pcap_captures.expected_sha256), + actual_sha256 = COALESCE(EXCLUDED.actual_sha256, udmi_pcap_captures.actual_sha256), + total_bytes = EXCLUDED.total_bytes, + pcap_uri = COALESCE(EXCLUDED.pcap_uri, udmi_pcap_captures.pcap_uri), + manifest_uri = COALESCE(EXCLUDED.manifest_uri, udmi_pcap_captures.manifest_uri), + scan_manifest = COALESCE(EXCLUDED.scan_manifest, udmi_pcap_captures.scan_manifest), + error_message = EXCLUDED.error_message, + updated_at = CURRENT_TIMESTAMP; + """, + ( + session.site, + session.device_id, + session.family, + session.generation, + status, + len(session.chunks), + session.expected_chunks, + session.expected_sha256, + session.actual_sha256, + session.total_bytes, + session.pcap_uri, + session.manifest_uri, + manifest_json, + error_message, + ), + ) + conn.commit() + finally: + conn.close() + elif hasattr(postgres_manager, "insert_row"): + postgres_manager.insert_row( + "udmi_pcap_captures", + { + "site": session.site, + "device_id": session.device_id, + "family": session.family, + "generation": session.generation, + "status": status, + "chunks_received": len(session.chunks), + "expected_chunks": session.expected_chunks, + "expected_sha256": session.expected_sha256, + "actual_sha256": session.actual_sha256, + "total_bytes": session.total_bytes, + "pcap_uri": session.pcap_uri, + "manifest_uri": session.manifest_uri, + "scan_manifest": session.scan_manifest, + "error_message": error_message, + }, + ) + + def _upload_to_gcs( + self, blob_path: str, content: bytes, content_type: str + ) -> None: + """Uploads a reassembled artifact to GCS when gcs_client is configured.""" + if not self.gcs_bucket or self.gcs_client is None: + return + bucket = self.gcs_client.bucket(self.gcs_bucket) + blob = bucket.blob(blob_path) + blob.upload_from_string(content, content_type=content_type) + + def _finalize_session( + self, + session: _PcapSession, + postgres_manager: Optional[PostgresManager], + ) -> Dict[str, Any]: + """Concatenates chunks 1..N, verifies SHA-256, and writes .pcap + scan_manifest.json.""" + expected_n = session.expected_chunks or 0 + if expected_n <= 0: + err_msg = ( + f"PCAP capture for {session.site}/{session.device_id}/" + f"{session.generation} has 0 expected chunks" + ) + self._upsert_capture_metadata( + postgres_manager, session, status="FAILED", error_message=err_msg + ) + raise ValueError(err_msg) + + assembled = bytearray() + for idx in range(1, expected_n + 1): + assembled.extend(session.chunks[idx]) + + pcap_bytes = bytes(assembled) + if not pcap_bytes: + err_msg = ( + f"PCAP capture for {session.site}/{session.device_id}/" + f"{session.generation} reassembled to 0 bytes" + ) + self._upsert_capture_metadata( + postgres_manager, session, status="FAILED", error_message=err_msg + ) + raise ValueError(err_msg) + + actual_sha256 = hashlib.sha256(pcap_bytes).hexdigest() + session.actual_sha256 = actual_sha256 + session.total_bytes = len(pcap_bytes) + + if session.expected_sha256 and actual_sha256 != session.expected_sha256: + err_msg = ( + f"PCAP SHA-256 digest mismatch for {session.site}/{session.device_id}/" + f"{session.generation}: expected {session.expected_sha256}, got {actual_sha256}" + ) + self._upsert_capture_metadata( + postgres_manager, session, status="FAILED", error_message=err_msg + ) + raise ValueError(err_msg) + + safe_site = _sanitize_path_component(session.site) + safe_gen = _sanitize_path_component(session.generation) + target_dir = os.path.join(self.archive_dir, safe_site) + os.makedirs(target_dir, exist_ok=True) + + local_pcap_path = os.path.abspath( + os.path.join(target_dir, f"{safe_gen}.pcap") + ) + with open(local_pcap_path, "wb") as pf: + pf.write(pcap_bytes) + + local_manifest_path = os.path.abspath( + os.path.join(target_dir, f"{safe_gen}_scan_manifest.json") + ) + manifest_obj = session.scan_manifest or {} + manifest_bytes = json.dumps(manifest_obj, indent=2).encode("utf-8") + with open(local_manifest_path, "wb") as mf: + mf.write(manifest_bytes) + + if self.gcs_bucket: + pcap_blob_path = f"{session.site}/{session.generation}.pcap" + manifest_blob_path = ( + f"{session.site}/{session.generation}_scan_manifest.json" + ) + self._upload_to_gcs( + pcap_blob_path, + pcap_bytes, + content_type="application/vnd.tcpdump.pcap", + ) + self._upload_to_gcs( + manifest_blob_path, + manifest_bytes, + content_type="application/json", + ) + session.pcap_uri = f"gs://{self.gcs_bucket}/{pcap_blob_path}" + session.manifest_uri = f"gs://{self.gcs_bucket}/{manifest_blob_path}" + else: + session.pcap_uri = local_pcap_path + session.manifest_uri = local_manifest_path + + session.completed = True + self._upsert_capture_metadata(postgres_manager, session, status="COMPLETED") + + return { + "target": "gcs", + "table": "udmi_pcap_captures", + "status": "COMPLETED", + "count": 1, + "chunks": expected_n, + "bytes": len(pcap_bytes), + "sha256": actual_sha256, + "pcap_uri": session.pcap_uri, + "manifest_uri": session.manifest_uri, + "local_pcap_path": local_pcap_path, + "local_manifest_path": local_manifest_path, + } + + def process_message( + self, + envelope: Dict[str, Any], + payload: Dict[str, Any], + postgres_manager: PostgresManager, + influx_manager: InfluxManager, + ) -> Dict[str, Any]: + del influx_manager + if ( + isinstance(payload, dict) + and "payload" in payload + and isinstance(payload.get("payload"), dict) + ): + payload = payload["payload"] + + site = str(envelope.get("deviceRegistryId") or "unknown") + device_id = str(envelope.get("deviceId") or "unknown") + family = str(payload.get("family") or "bacnet") + generation = str(payload.get("generation") or "unknown") + event_no = int(payload.get("event_no", 0)) + + session_key = (site, device_id, family, generation) + + with self._lock: + self._evict_expired_sessions() + + if session_key in self._completed_results: + return dict(self._completed_results[session_key]) + + session = self._sessions.get(session_key) + if event_no == 0: + if session is None: + session = _PcapSession(site, device_id, family, generation) + self._sessions[session_key] = session + self._upsert_capture_metadata( + postgres_manager, session, status="RECEIVING" + ) + return { + "target": "gcs", + "table": "udmi_pcap_captures", + "status": "RECEIVING", + "count": 0, + "chunks_received": len(session.chunks), + } + + if session is None: + session = _PcapSession(site, device_id, family, generation) + self._sessions[session_key] = session + + if event_no > 0: + b64_data = payload.get("data") + if not b64_data: + raise ValueError( + f"Missing 'data' in upload/discovery chunk event_no={event_no}" + ) + raw_chunk = _decode_chunk_payload(b64_data) + session.chunks[event_no] = raw_chunk + session.total_bytes = sum(len(c) for c in session.chunks.values()) + else: + # Terminal EOF marker: event_no = -(N + 1) + session.expected_chunks = (-event_no) - 1 + session.expected_sha256 = payload.get("sha256") + if isinstance(payload.get("scan_manifest"), dict): + session.scan_manifest = payload["scan_manifest"] + + if ( + not session.completed + and session.expected_chunks is not None + and all( + idx in session.chunks + for idx in range(1, session.expected_chunks + 1) + ) + ): + try: + result = self._finalize_session(session, postgres_manager) + if len(self._completed_results) >= MAX_COMPLETED_CACHE: + oldest_key = next(iter(self._completed_results)) + self._completed_results.pop(oldest_key, None) + self._completed_results[session_key] = result + return result + finally: + self._sessions.pop(session_key, None) + + self._upsert_capture_metadata( + postgres_manager, session, status="RECEIVING" + ) + return { + "target": "gcs", + "table": "udmi_pcap_captures", + "status": "RECEIVING", + "count": 0, + "chunks_received": len(session.chunks), + } diff --git a/butler/src/handlers/raw_fallback.py b/butler/src/handlers/raw_fallback.py index 7518e2ecb5..091d93e1b8 100644 --- a/butler/src/handlers/raw_fallback.py +++ b/butler/src/handlers/raw_fallback.py @@ -10,7 +10,8 @@ class RawFallbackHandler(BaseHandler): """Saves arbitrary UDMI messages into udmi_messages table as JSONB.""" def can_handle(self, sub_folder: Optional[str], sub_type: Optional[str], payload: Dict[str, Any]) -> bool: - return True + del sub_folder, payload + return sub_type != "upload" def process_message( self, @@ -19,6 +20,13 @@ def process_message( postgres_manager: PostgresManager, influx_manager: InfluxManager, ) -> Dict[str, Any]: + del influx_manager + if envelope.get("subType") == "upload": + return { + "target": "none", + "table": None, + "count": 0, + } row = { "project_id": envelope.get("projectId"), "registry_id": envelope.get("deviceRegistryId"), diff --git a/butler/src/service.py b/butler/src/service.py index bd6798d3c4..573c9fb68c 100644 --- a/butler/src/service.py +++ b/butler/src/service.py @@ -56,7 +56,12 @@ def parse_mqtt_topic(topic: str) -> Dict[str, Optional[str]]: sub_type = parts[r_idx + 2] if r_idx + 3 < len(parts): sub_folder = parts[r_idx + 3] - elif len(parts) > 0 and parts[0] in ("events", "state", "commands", "config"): + elif len(parts) >= 3 and parts[0] == "devices": + device_id = parts[1] + sub_type = parts[2] + if len(parts) > 3: + sub_folder = parts[3] + elif len(parts) > 0 and parts[0] in ("events", "state", "commands", "config", "upload"): sub_type = parts[0] if len(parts) > 1: sub_folder = parts[1] diff --git a/butler/tests/test_dispatcher.py b/butler/tests/test_dispatcher.py index c3ca0cfc5f..05668cbec3 100644 --- a/butler/tests/test_dispatcher.py +++ b/butler/tests/test_dispatcher.py @@ -56,6 +56,59 @@ def test_dispatch_fallback(self): self.assertEqual(res["target"], "postgres") self.assertEqual(res["table"], "udmi_messages") + def test_dispatch_pcap_upload_skips_raw_fallback(self): + import base64 + import gzip + import hashlib + import tempfile + + with tempfile.TemporaryDirectory() as tmpdir: + self.dispatcher.handlers[0].archive_dir = tmpdir + raw_pcap = b"\xa1\xb2\xc3\xd4" + b"\x00" * 20 + b64_chunk = base64.b64encode(gzip.compress(raw_pcap)).decode("ascii") + digest = hashlib.sha256(raw_pcap).hexdigest() + + env = { + "deviceRegistryId": "ZZ-TRI-FECTA", + "deviceId": "DSN-1", + "subType": "upload", + "subFolder": "discovery", + } + self.dispatcher.dispatch( + env, + {"generation": "2026-11-10T12:00:00Z", "family": "bacnet", "event_no": 0}, + ) + self.dispatcher.dispatch( + env, + { + "generation": "2026-11-10T12:00:00Z", + "family": "bacnet", + "event_no": 1, + "data": b64_chunk, + }, + ) + res = self.dispatcher.dispatch( + env, + { + "generation": "2026-11-10T12:00:00Z", + "family": "bacnet", + "event_no": -2, + "sha256": digest, + "scan_manifest": { + "gateway_ip": "192.168.1.50", + "interface": "eth0", + "filter": "udp port 47808", + "scan_round_timestamps": ["2026-11-10T12:00:01Z"], + }, + }, + ) + self.assertEqual(res["status"], "COMPLETED") + self.assertEqual(res["sha256"], digest) + self.assertTrue(os.path.exists(res["local_pcap_path"])) + # Verify raw_fallback never wrote chunk blobs into udmi_messages + for call in self.mock_pg.insert_row.call_args_list: + self.assertNotEqual(call[0][0], "udmi_messages") + if __name__ == "__main__": unittest.main() diff --git a/butler/tests/test_handlers.py b/butler/tests/test_handlers.py index 18df34746b..52b8be016b 100644 --- a/butler/tests/test_handlers.py +++ b/butler/tests/test_handlers.py @@ -181,6 +181,141 @@ def test_raw_fallback_handler(self): self.assertEqual(row["project_id"], "proj-1") self.assertEqual(row["payload"], payload) + # Verify RawFallbackHandler rejects subType == 'upload' + self.assertFalse(handler.can_handle("discovery", "upload", payload)) + upload_res = handler.process_message( + {"subType": "upload", "subFolder": "discovery"}, + payload, + self.mock_pg, + self.mock_influx, + ) + self.assertEqual(upload_res["count"], 0) + self.assertEqual(self.mock_pg.insert_row.call_count, 1) + + def test_pcap_upload_handler_reassembly_and_sha256_verification(self): + import base64 + import gzip + import hashlib + import tempfile + from butler.src.handlers.pcap_upload import PcapUploadHandler + + mock_gcs = MagicMock() + with tempfile.TemporaryDirectory() as tmpdir: + handler = PcapUploadHandler( + archive_dir=tmpdir, + gcs_bucket="udmi-captures", + gcs_client=mock_gcs, + ) + self.assertTrue(handler.can_handle("discovery", "upload", {})) + self.assertFalse(handler.can_handle("discovery", "events", {})) + + c1 = b"\xa1\xb2\xc3\xd4\x00\x02\x00\x04" + c2 = b"BACNET_PACKET_PAYLOAD_BYTES" + full_pcap = c1 + c2 + digest = hashlib.sha256(full_pcap).hexdigest() + + env = { + "deviceRegistryId": "ZZ-TRI-FECTA", + "deviceId": "GAT-1", + "subType": "upload", + "subFolder": "discovery", + } + gen = "2026-11-05T13:00:00Z" + + # Out-of-order arrival: chunk 2, then start (0), then EOF (-3), then chunk 1 + r1 = handler.process_message( + env, + { + "generation": gen, + "family": "bacnet", + "event_no": 2, + "data": base64.b64encode(gzip.compress(c2)).decode("ascii"), + }, + self.mock_pg, + self.mock_influx, + ) + self.assertEqual(r1["status"], "RECEIVING") + + # Out-of-order event_no=0 must NOT wipe chunk 2 + r_start = handler.process_message( + env, + { + "generation": gen, + "family": "bacnet", + "event_no": 0, + }, + self.mock_pg, + self.mock_influx, + ) + self.assertEqual(r_start["status"], "RECEIVING") + self.assertEqual(r_start["chunks_received"], 1) + + r2 = handler.process_message( + env, + { + "generation": gen, + "family": "bacnet", + "event_no": -3, + "sha256": digest, + "scan_manifest": {"gateway_ip": "192.168.1.50"}, + }, + self.mock_pg, + self.mock_influx, + ) + self.assertEqual(r2["status"], "RECEIVING") + + r3 = handler.process_message( + env, + { + "generation": gen, + "family": "bacnet", + "event_no": 1, + "data": base64.b64encode(gzip.compress(c1)).decode("ascii"), + }, + self.mock_pg, + self.mock_influx, + ) + self.assertEqual(r3["status"], "COMPLETED") + self.assertEqual( + r3["pcap_uri"], + "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z.pcap", + ) + self.assertEqual( + r3["manifest_uri"], + "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z_scan_manifest.json", + ) + self.assertEqual(mock_gcs.bucket.return_value.blob.call_count, 2) + with open(r3["local_pcap_path"], "rb") as pf: + self.assertEqual(pf.read(), full_pcap) + + # Verify SHA-256 mismatch raises ValueError and evicts the failed session + with self.assertRaises(ValueError): + handler.process_message( + env, + { + "generation": "2026-11-05T14:00:00Z", + "family": "bacnet", + "event_no": 1, + "data": base64.b64encode(gzip.compress(c1)).decode( + "ascii" + ), + }, + self.mock_pg, + self.mock_influx, + ) + handler.process_message( + env, + { + "generation": "2026-11-05T14:00:00Z", + "family": "bacnet", + "event_no": -2, + "sha256": "0" * 64, + }, + self.mock_pg, + self.mock_influx, + ) + self.assertEqual(len(handler._sessions), 0) + if __name__ == "__main__": unittest.main() diff --git a/common/src/main/python/udmi/common/db/postgres.py b/common/src/main/python/udmi/common/db/postgres.py index b43bce8ba5..016053789f 100644 --- a/common/src/main/python/udmi/common/db/postgres.py +++ b/common/src/main/python/udmi/common/db/postgres.py @@ -236,6 +236,28 @@ def init_default_tables(self, retry_timeout_sec: int = 30) -> None: updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); """ + pcap_captures_sql = """ + CREATE TABLE IF NOT EXISTS udmi_pcap_captures ( + id SERIAL PRIMARY KEY, + site VARCHAR(255) NOT NULL, + device_id VARCHAR(255) NOT NULL, + family VARCHAR(50) NOT NULL, + generation VARCHAR(64) NOT NULL, + status VARCHAR(50) DEFAULT 'PENDING', + chunks_received INTEGER DEFAULT 0, + expected_chunks INTEGER, + expected_sha256 VARCHAR(64), + actual_sha256 VARCHAR(64), + total_bytes BIGINT DEFAULT 0, + pcap_uri TEXT, + manifest_uri TEXT, + scan_manifest JSONB, + bug_id VARCHAR(64), + error_message TEXT, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + UNIQUE(site, device_id, family, generation) + ); + """ tables = [ raw_table_sql, @@ -246,6 +268,7 @@ def init_default_tables(self, retry_timeout_sec: int = 30) -> None: alarms_sql, metadata_sql, rollouts_sql, + pcap_captures_sql, ] try: diff --git a/mcp/butler/client.py b/mcp/butler/client.py index a70f88c51f..2a5b22fbba 100644 --- a/mcp/butler/client.py +++ b/mcp/butler/client.py @@ -253,6 +253,45 @@ def update_rollout( params["failed_devices"] = failed_devices return self.call_rpc("update_rollout", params) + def trigger_bacnet_trace( + self, + site: str, + gateway_id: str, + scan_duration_sec: int = 7200, + max_bytes: int = 268435456, + bug_id: Optional[str] = None, + conn_spec: Optional[str] = None, + site_model: Optional[str] = None, + ) -> Dict[str, Any]: + """Trigger a depth: 'trace' BACnet packet capture on the target gateway.""" + params: Dict[str, Any] = { + "site": site, + "gateway_id": gateway_id, + "scan_duration_sec": scan_duration_sec, + "max_bytes": max_bytes, + } + if bug_id is not None: + params["bug_id"] = bug_id + if conn_spec is not None: + params["conn_spec"] = conn_spec + if site_model is not None: + params["site_model"] = site_model + return self.call_rpc("trigger_bacnet_trace", params) + + def get_pcap_capture( + self, + site: str, + gateway_id: Optional[str] = None, + generation: Optional[str] = None, + ) -> Optional[Dict[str, Any]]: + """Query PCAP chunk reassembly status and resolved GCS/file URIs.""" + params: Dict[str, Any] = {"site": site} + if gateway_id is not None: + params["gateway_id"] = gateway_id + if generation is not None: + params["generation"] = generation + return self.call_rpc("get_pcap_capture", params) + def tools_list(self) -> List[Dict[str, Any]]: """List all available MCP tools.""" res = self.call_rpc("tools/list", {}) diff --git a/mcp/butler/provider.py b/mcp/butler/provider.py index da364a7818..16f37febec 100644 --- a/mcp/butler/provider.py +++ b/mcp/butler/provider.py @@ -57,6 +57,7 @@ def __init__( influx_port: Optional[Union[str, int]] = None, ): """Initializes ButlerProvider with relational and timeseries managers.""" + self.project_spec = project_spec if pg_manager is not None: self.pg_manager = pg_manager elif PostgresManager is not None: @@ -921,3 +922,165 @@ def update_rollout( failed_devices=failed_devices, ) + def trigger_bacnet_trace( + self, + site: str, + gateway_id: str, + scan_duration_sec: int = 7200, + max_bytes: int = 268435456, + bug_id: Optional[str] = None, + conn_spec: Optional[str] = None, + site_model: Optional[str] = None, + ) -> Dict[str, Any]: + """Triggers a depth: 'trace' BACnet packet capture on the target gateway and tracks reassembly.""" + generation = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + gcs_bucket = os.environ.get("BUTLER_PCAP_GCS_BUCKET") + archive_dir = os.environ.get("BUTLER_PCAP_DIR", "out/pcap") + if gcs_bucket: + pcap_uri = f"gs://{gcs_bucket}/{site}/{generation}.pcap" + manifest_uri = ( + f"gs://{gcs_bucket}/{site}/{generation}_scan_manifest.json" + ) + else: + safe_site = re.sub(r"[^A-Za-z0-9._-]", "_", site) + safe_gen = re.sub(r"[^A-Za-z0-9._-]", "_", generation) + pcap_uri = os.path.abspath( + os.path.join(archive_dir, safe_site, f"{safe_gen}.pcap") + ) + manifest_uri = os.path.abspath( + os.path.join( + archive_dir, safe_site, f"{safe_gen}_scan_manifest.json" + ) + ) + + effective_spec = ( + conn_spec or self.project_spec or os.environ.get("BUTLER_CONN_SPEC") + ) + if effective_spec: + from butler.src.discovery import trigger_bacnet_trace as publish_trace + + publish_trace( + conn_spec=effective_spec, + registry_id=site, + device_id=gateway_id, + scan_duration_sec=int(scan_duration_sec), + max_bytes=int(max_bytes), + site_model=site_model or os.environ.get("BUTLER_SITE_MODEL"), + generation=generation, + ) + + if self.pg_manager and hasattr(self.pg_manager, "insert_row"): + self.pg_manager.insert_row( + "udmi_pcap_captures", + { + "site": site, + "device_id": gateway_id, + "family": "bacnet", + "generation": generation, + "status": "PENDING", + "chunks_received": 0, + "pcap_uri": pcap_uri, + "manifest_uri": manifest_uri, + "bug_id": str(bug_id) if bug_id is not None else None, + }, + ) + + return { + "status": "PENDING", + "site": site, + "gateway_id": gateway_id, + "generation": generation, + "scan_duration_sec": int(scan_duration_sec), + "max_bytes": int(max_bytes), + "bug_id": str(bug_id) if bug_id is not None else None, + "pcap_uri": pcap_uri, + "manifest_uri": manifest_uri, + } + + def get_pcap_capture( + self, + site: str, + gateway_id: Optional[str] = None, + generation: Optional[str] = None, + ) -> Optional[Dict[str, Any]]: + """Retrieves chunk reassembly status and resolved GCS/file URIs for a PCAP capture.""" + if not self.pg_manager: + return None + try: + conn = self.pg_manager.get_connection() + try: + with conn.cursor() as cur: + clauses = ["site = %s"] + params: List[Any] = [site] + if gateway_id: + clauses.append("device_id = %s") + params.append(gateway_id) + if generation: + clauses.append("generation = %s") + params.append(generation) + where_sql = " AND ".join(clauses) + cur.execute( + f""" + SELECT site, device_id, family, generation, status, + chunks_received, expected_chunks, expected_sha256, + actual_sha256, total_bytes, pcap_uri, manifest_uri, + scan_manifest, bug_id, error_message, updated_at + FROM udmi_pcap_captures + WHERE {where_sql} + ORDER BY updated_at DESC, id DESC + LIMIT 1; + """, + tuple(params), + ) + row = cur.fetchone() + finally: + conn.close() + + if not row: + return None + + ( + r_site, + r_dev, + r_fam, + r_gen, + r_status, + r_chunks, + r_expected, + r_exp_sha, + r_act_sha, + r_bytes, + r_pcap_uri, + r_manifest_uri, + r_manifest, + r_bug_id, + r_err, + r_updated, + ) = row + if isinstance(r_manifest, str): + r_manifest = json.loads(r_manifest) + return { + "site": r_site, + "gateway_id": r_dev, + "family": r_fam, + "generation": r_gen, + "status": r_status, + "chunks_received": r_chunks, + "expected_chunks": r_expected, + "expected_sha256": r_exp_sha, + "actual_sha256": r_act_sha, + "total_bytes": r_bytes, + "pcap_uri": r_pcap_uri, + "manifest_uri": r_manifest_uri, + "scan_manifest": r_manifest, + "bug_id": r_bug_id, + "error_message": r_err, + "updated_at": _format_iso(r_updated), + } + except Exception as err: + print( + f"ButlerProvider error fetching pcap capture status: {err}", + file=sys.stderr, + ) + return None + diff --git a/mcp/butler/server.py b/mcp/butler/server.py index 3e04c733cd..a08597fe0e 100644 --- a/mcp/butler/server.py +++ b/mcp/butler/server.py @@ -310,6 +310,39 @@ "required": ["rollout_id"], }, }, + { + "name": "trigger_bacnet_trace", + "description": ( + "Trigger a depth: 'trace' BACnet packet capture on the target gateway, " + "track chunk reassembly status, and return target GCS/file URIs." + ), + "inputSchema": { + "type": "object", + "properties": { + "site": {"type": "string", "description": "Target site / device registry identifier"}, + "gateway_id": {"type": "string", "description": "Target gateway / Spotter device identifier"}, + "scan_duration_sec": {"type": "integer", "default": 7200, "description": "Capture duration in seconds"}, + "max_bytes": {"type": "integer", "default": 268435456, "description": "Maximum PCAP byte cap"}, + "bug_id": {"type": "string", "description": "Optional issue or ticket identifier"}, + "conn_spec": {"type": "string", "description": "Optional UDMI connection specification (e.g. //mqtt/localhost)"}, + "site_model": {"type": "string", "description": "Optional path to the UDMI site model directory"}, + }, + "required": ["site", "gateway_id"], + }, + }, + { + "name": "get_pcap_capture", + "description": "Track chunk reassembly status and resolve the GCS/file URI for a PCAP capture.", + "inputSchema": { + "type": "object", + "properties": { + "site": {"type": "string", "description": "Target site / device registry identifier"}, + "gateway_id": {"type": "string", "description": "Optional gateway device identifier"}, + "generation": {"type": "string", "description": "Optional capture generation timestamp"}, + }, + "required": ["site"], + }, + }, ] @@ -515,6 +548,22 @@ def _dispatch_tool(self, name: str, args: Dict[str, Any]) -> Any: converged_devices=args.get("converged_devices"), failed_devices=args.get("failed_devices"), ) + if name == "trigger_bacnet_trace": + return self.provider.trigger_bacnet_trace( + site=args["site"], + gateway_id=args["gateway_id"], + scan_duration_sec=int(args.get("scan_duration_sec", 7200)), + max_bytes=int(args.get("max_bytes", 268435456)), + bug_id=args.get("bug_id"), + conn_spec=args.get("conn_spec"), + site_model=args.get("site_model"), + ) + if name == "get_pcap_capture": + return self.provider.get_pcap_capture( + site=args["site"], + gateway_id=args.get("gateway_id"), + generation=args.get("generation"), + ) raise ValueError(f"Unknown tool or method: {name}") def run_stdio(self) -> None: diff --git a/tests/test_mcp_butler.py b/tests/test_mcp_butler.py index 762fe6c783..1179e592e5 100644 --- a/tests/test_mcp_butler.py +++ b/tests/test_mcp_butler.py @@ -353,6 +353,82 @@ def test_rollout_lifecycle(self): self.assertIsNone(self.provider.get_rollout(999)) self.assertIsNone(self.provider.update_rollout(999, status="PAUSED")) + @patch.dict(os.environ, {"BUTLER_PCAP_GCS_BUCKET": "udmi-captures"}) + @patch("butler.src.discovery.trigger_bacnet_trace") + def test_pcap_trace_and_get_capture(self, mock_publish_trace): + # 1. trigger_bacnet_trace with GCS bucket and conn_spec + res = self.provider.trigger_bacnet_trace( + site="ZZ-TRI-FECTA", + gateway_id="GAT-1", + scan_duration_sec=3600, + max_bytes=1048576, + bug_id="ISSUE-101", + conn_spec="//mqtt/localhost:18833", + ) + self.assertEqual(res["status"], "PENDING") + self.assertEqual(res["site"], "ZZ-TRI-FECTA") + self.assertEqual(res["gateway_id"], "GAT-1") + gen = res["generation"] + self.assertEqual( + res["pcap_uri"], + f"gs://udmi-captures/ZZ-TRI-FECTA/{gen}.pcap", + ) + self.assertEqual( + res["manifest_uri"], + f"gs://udmi-captures/ZZ-TRI-FECTA/{gen}_scan_manifest.json", + ) + mock_publish_trace.assert_called_once() + self.mock_pg.insert_row.assert_called_with( + "udmi_pcap_captures", + { + "site": "ZZ-TRI-FECTA", + "device_id": "GAT-1", + "family": "bacnet", + "generation": gen, + "status": "PENDING", + "chunks_received": 0, + "pcap_uri": res["pcap_uri"], + "manifest_uri": res["manifest_uri"], + "bug_id": "ISSUE-101", + }, + ) + + # 2. get_pcap_capture querying udmi_pcap_captures + mock_conn = MagicMock() + mock_cur = MagicMock() + mock_conn.cursor.return_value.__enter__.return_value = mock_cur + mock_cur.fetchone.return_value = ( + "ZZ-TRI-FECTA", + "GAT-1", + "bacnet", + gen, + "COMPLETED", + 3, + 3, + "abc123", + "abc123", + 4096, + res["pcap_uri"], + res["manifest_uri"], + json.dumps({"gateway_ip": "192.168.1.50"}), + "ISSUE-101", + None, + "2026-11-11T05:00:00Z", + ) + self.mock_pg.get_connection.return_value = mock_conn + + cap = self.provider.get_pcap_capture( + site="ZZ-TRI-FECTA", gateway_id="GAT-1", generation=gen + ) + self.assertIsNotNone(cap) + self.assertEqual(cap["status"], "COMPLETED") + self.assertEqual(cap["chunks_received"], 3) + self.assertEqual(cap["expected_chunks"], 3) + self.assertEqual(cap["actual_sha256"], "abc123") + self.assertEqual(cap["pcap_uri"], res["pcap_uri"]) + self.assertEqual(cap["manifest_uri"], res["manifest_uri"]) + self.assertEqual(cap["scan_manifest"], {"gateway_ip": "192.168.1.50"}) + class TestButlerMcpServer(unittest.TestCase): """Tests for ButlerMcpServer handling JSON-RPC 2.0 requests.""" @@ -397,10 +473,71 @@ def test_tools_list(self): "list_rollouts", "get_rollout", "update_rollout", + "trigger_bacnet_trace", + "get_pcap_capture", ] for exp in expected: self.assertIn(exp, tool_names) + def test_tools_call_pcap_trace_methods(self): + self.mock_provider.trigger_bacnet_trace.return_value = { + "status": "PENDING", + "site": "ZZ-TRI-FECTA", + "gateway_id": "GAT-1", + "generation": "2026-11-05T13:00:00Z", + "pcap_uri": "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z.pcap", + "manifest_uri": "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z_scan_manifest.json", + } + req = { + "jsonrpc": "2.0", + "id": 20, + "method": "tools/call", + "params": { + "name": "trigger_bacnet_trace", + "arguments": { + "site": "ZZ-TRI-FECTA", + "gateway_id": "GAT-1", + "scan_duration_sec": 7200, + }, + }, + } + resp = self.server.handle_request(req) + self.assertFalse(resp["result"]["isError"]) + data = json.loads(resp["result"]["content"][0]["text"]) + self.assertEqual(data["status"], "PENDING") + self.assertIn(".pcap", data["pcap_uri"]) + self.assertIn("_scan_manifest.json", data["manifest_uri"]) + + self.mock_provider.get_pcap_capture.return_value = { + "site": "ZZ-TRI-FECTA", + "gateway_id": "GAT-1", + "generation": "2026-11-05T13:00:00Z", + "status": "COMPLETED", + "pcap_uri": "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z.pcap", + "manifest_uri": "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z_scan_manifest.json", + } + req_get = { + "jsonrpc": "2.0", + "id": 21, + "method": "tools/call", + "params": { + "name": "get_pcap_capture", + "arguments": { + "site": "ZZ-TRI-FECTA", + "gateway_id": "GAT-1", + "generation": "2026-11-05T13:00:00Z", + }, + }, + } + resp_get = self.server.handle_request(req_get) + self.assertFalse(resp_get["result"]["isError"]) + get_data = json.loads(resp_get["result"]["content"][0]["text"]) + self.assertEqual(get_data["status"], "COMPLETED") + self.assertEqual( + get_data["manifest_uri"], + "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z_scan_manifest.json", + ) + def test_tools_call_rollout_methods(self): # 1. create_rollout tool self.mock_provider.create_rollout.return_value = {"id": 1, "status": "RUNNING", "name": "Rollout 1"} @@ -599,6 +736,47 @@ def test_client_rollouts(self): up = self.client.update_rollout(1, status="PAUSED") self.assertEqual(up["status"], "PAUSED") + def test_client_pcap_trace_and_get_capture(self): + self.mock_provider.trigger_bacnet_trace.return_value = { + "status": "PENDING", + "site": "ZZ-TRI-FECTA", + "gateway_id": "GAT-1", + "generation": "2026-11-05T13:00:00Z", + "pcap_uri": "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z.pcap", + "manifest_uri": "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z_scan_manifest.json", + } + trig = self.client.trigger_bacnet_trace( + site="ZZ-TRI-FECTA", + gateway_id="GAT-1", + scan_duration_sec=3600, + max_bytes=1048576, + bug_id="ISSUE-101", + ) + self.assertEqual(trig["status"], "PENDING") + self.assertEqual( + trig["manifest_uri"], + "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z_scan_manifest.json", + ) + + self.mock_provider.get_pcap_capture.return_value = { + "site": "ZZ-TRI-FECTA", + "gateway_id": "GAT-1", + "generation": "2026-11-05T13:00:00Z", + "status": "COMPLETED", + "pcap_uri": "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z.pcap", + "manifest_uri": "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z_scan_manifest.json", + } + cap = self.client.get_pcap_capture( + site="ZZ-TRI-FECTA", + gateway_id="GAT-1", + generation="2026-11-05T13:00:00Z", + ) + self.assertEqual(cap["status"], "COMPLETED") + self.assertEqual( + cap["pcap_uri"], + "gs://udmi-captures/ZZ-TRI-FECTA/2026-11-05T13:00:00Z.pcap", + ) + class TestButlerMcpStdioRunner(unittest.TestCase): """Test running bin/mcp_butler in stdio mode via subprocess.""" From cf60027c0532baab2ffb166e6fc1b0c0262e99a6 Mon Sep 17 00:00:00 2001 From: Khyati Mahendru Date: Fri, 13 Nov 2026 07:01:33 +0000 Subject: [PATCH 4/8] Overhaul Spotter for UDMI discovery compliance and upload/discovery PCAP streaming - Enforce strict UDMI discovery depth compliance ('buckets', 'entries', 'system', 'details', 'trace') across Spotter providers and fail fast on non-canonical legacy depths. - Emit canonical '/' BACnet refs, hyphenated object types and ancillary keys, explicit families.ipv4.port (47808), ARP-resolved families.ethmac, and routed MS/TP ':' bindings. - Decode BACnet/IP BVLL Forwarded-NPDU real controller IPs/ports behind BBMDs, NPDU SNET/SADR MS/TP headers, and I-Am-Router-To-Network DNET lists in PassiveFamilyProvider. - Implement raw-socket (SOCK_RAW) BACnet Who-Is and Who-Is-Router-To-Network discovery rounds during depth: 'trace' without binding UDP 47808, and stream gzipped DiscoveryUpload chunks with SHA-256 and ScanManifest over upload/discovery. - Update reassemble_pcap, compare_field_parity, Spotter documentation, and unit/integration test suites. --- docs/tools/spotter.md | 28 +- edge/spotter/GEMINI.md | 6 +- edge/spotter/README.md | 52 +- edge/spotter/bin/compare_field_parity | 352 +++++-- edge/spotter/bin/reassemble_pcap | 171 +++- edge/spotter/bin/run_spotter_tests | 17 +- edge/spotter/bin/test_container | 14 +- edge/spotter/bin/test_fault_injection | 2 +- edge/spotter/bin/test_parity | 323 ++++--- edge/spotter/bin/test_pcap | 45 +- edge/spotter/src/agent.py | 156 ++-- edge/spotter/src/config_generator.py | 39 +- edge/spotter/src/manager/discovery.py | 862 ++++++++++++++---- edge/spotter/src/manager/system.py | 75 +- edge/spotter/src/pcap.py | 329 ++++++- edge/spotter/src/providers/bacnet.py | 744 ++++++++++++--- edge/spotter/src/providers/ether.py | 609 ++++++++++--- edge/spotter/src/providers/passive.py | 421 ++++++++- edge/spotter/tests/test_agent.py | 347 ++++--- edge/spotter/tests/test_config_generator.py | 20 +- edge/spotter/tests/test_pcap.py | 140 +++ edge/spotter/tests/test_providers.py | 572 ++++++++++-- .../spotter/tests/test_resource_contention.py | 10 +- 23 files changed, 4239 insertions(+), 1095 deletions(-) diff --git a/docs/tools/spotter.md b/docs/tools/spotter.md index 0d8c274160..a5756c77aa 100644 --- a/docs/tools/spotter.md +++ b/docs/tools/spotter.md @@ -13,10 +13,10 @@ Spotter runs as a single unified process using the UDMI Python Client Library (` 1. **`LocalnetManager` & Pluggable Family Providers**: - **`BacnetFamilyProvider`**: Performs active BACnet Who-Is / I-Am discovery, object enumeration, and UDP port extraction. - **`EtherFamilyProvider`**: Performs Layer-2 Ethernet / ARP, nmap XML host parsing, and ICMP ping sweeps. - - **`PassiveFamilyProvider`**: Listens for passive broadcast network traffic and extracts discovered device metadata. + - **`PassiveFamilyProvider`**: Listens for passive broadcast network traffic, decodes BACnet/IP BVLL (`Forwarded-NPDU` real controller IP/port behind BBMDs) and NPDU (`SNET`/`SADR` routed MS/TP frames and `I-Am-Router-To-Network` DNET lists), and extracts discovered device metadata. 2. **`SpotterDiscoveryManager`**: - Manages scheduled and on-demand discovery sweeps. - - Streams live remote packet capture traces (`events/streams`) buffered in volatile memory with circuit-breaker protection (zero-disk streaming). + - Streams live remote packet capture traces (`upload/discovery`) buffered in volatile memory with circuit-breaker protection (zero-disk streaming). 3. **`SpotterSystemManager`**: - Collects host metrics (CPU load, memory, OS distribution) and emits periodic telemetry (`events/system`). - Evaluates memory usage against safety thresholds (`check_safety_circuit_breaker`), throttling active discovery and packet captures to protect edge devices from kernel OOM termination. @@ -43,12 +43,12 @@ graph TD end subgraph "Messaging & Field Network" - MB["MQTT Broker / UDMIS"] + MB["MQTT Broker / UDMIS / Butler"] DEV["Field OT Devices / BACnet Controllers"] end SYS -->|"state.system / events/system"| MB - DISC -->|"events/discovery & events/streams"| MB + DISC -->|"events/discovery & upload/discovery"| MB LOC -->|"Scans & Probes"| DEV ``` @@ -58,18 +58,22 @@ graph TD Spotter processes diagnostic packet capture triggers sent declaratively over the UDMI discovery configuration channel (`config.discovery.families.` with `depth: "trace"`): -1. **Capture Worker ([pcap.py](../../edge/spotter/src/pcap.py))**: Spawns `tcpdump` with configurable interface filters, enforcing strict execution bounds (maximum duration and byte quotas). -2. **Streaming MQTT Egress Transport**: - - **Zero-Disk Streaming**: Packets are buffered dynamically in volatile memory (RAM) and sequentially published as reliable base64 chunks (`StreamsEvents`) over the universal streaming MQTT event topic (`events/streams`). +1. **Capture Worker & Active BACnet Trace Rounds ([pcap.py](../../edge/spotter/src/pcap.py))**: + - Spawns `tcpdump` with configurable interface filters (defaulting to `"udp port 47808"` for `bacnet`), enforcing strict execution bounds (maximum duration and byte quotas). + - For `families.bacnet` with `depth: "trace"`, skips `BAC0.lite()` socket binding so UDP port `47808` remains unbound and executes paced raw-socket (`SOCK_RAW, IPPROTO_UDP`) `Who-Is` and `Who-Is-Router-To-Network` rounds during the capture window. +2. **Streaming MQTT Egress Transport (`upload/discovery`)**: + - **Zero-Disk Streaming**: Packets are buffered dynamically in volatile memory (RAM), gzip-compressed per chunk, and sequentially published as `DiscoveryUpload` chunks over the `upload/discovery` MQTT topic (`event_no = 0` start marker, `1..N` gzipped base64 chunks, and `-(N+1)` terminal marker with uncompressed `sha256` and `scan_manifest`). - **Zero Secret Distribution**: Leverages the existing mTLS hardware key/certificate connection directly, avoiding external network credentials or outbound HTTP rules at the edge. -3. **Ad-hoc PCAP Reassembly ([bin/reassemble_pcap](../../edge/spotter/bin/reassemble_pcap))**: - Reassembles chunked `events/streams` messages (from JSON, JSONL, or `mosquitto_sub`) back into a valid `.pcap` binary capture file: +3. **Cloud & Local PCAP Reassembly**: + - **Butler Service (`PcapUploadHandler`)**: Subscribes to `upload/discovery` (or `uufi_upload`), gunzips and reassembles chunks in order, validates the terminal `sha256` digest, and writes the `.pcap` and `scan_manifest.json` to GCS (`gs:////.pcap`) or local disk without persisting raw chunks to PostgreSQL. + - **Ad-hoc CLI Reassembly ([bin/reassemble_pcap](../../edge/spotter/bin/reassemble_pcap))**: + Reassembles chunked `upload/discovery` messages (from JSON, JSONL, or `mosquitto_sub`) back into a valid `.pcap` binary capture file and `scan_manifest.json`: ```bash - # Reassemble stream events file into a pcap file: - ./edge/spotter/bin/reassemble_pcap stream_events.json capture.pcap + # Reassemble upload/discovery chunks file into a pcap file: + ./edge/spotter/bin/reassemble_pcap discovery_upload.json capture.pcap # Or stream directly from mosquitto subscriber: - mosquitto_sub -h $BROKER -t '/r/+/d/+/events/streams' | ./edge/spotter/bin/reassemble_pcap - live.pcap + mosquitto_sub -h $BROKER -t '/r/+/d/+/upload/discovery' | ./edge/spotter/bin/reassemble_pcap - live.pcap ``` --- diff --git a/edge/spotter/GEMINI.md b/edge/spotter/GEMINI.md index e43c7fc5d8..010f324ace 100644 --- a/edge/spotter/GEMINI.md +++ b/edge/spotter/GEMINI.md @@ -143,11 +143,11 @@ device:on_ready Connection successful. --- -## 5. Engineering Standards & Parity Verification +## 5. Engineering Standards & UDMI Specification Compliance To maintain technical integrity and ensure non-regression: -- **Functional Parity**: Spotter must maintain functional parity with legacy discovery nodes for existing protocol sweeps. -- **Differential Verification**: Run `bin/test_parity` against simulated device fixtures before changes are committed. +- **Strict UDMI Specification Compliance**: Spotter strictly adheres to `docs/specs/discovery.md`, `docs/specs/discovery_bacnet.md`, and `schema/*_discovery.json` (canonical `/` BACnet refs, hyphenated object types, `families.ipv4.port`, top-level `system.name`/`description`, hyphenated `system.ancillary` keys, canonical `Depth` enum enforcement, and zero `null` fields). Where the legacy discovery node deviated from the UDMI specification, Spotter enforces the authoritative UDMI specification. +- **Compliance & Co-Existence Verification**: Run `bin/test_parity` against simulated device fixtures before changes are committed. - **Negative Verification**: Confirm reproduction of any failure signatures before declaring a defect repaired. --- diff --git a/edge/spotter/README.md b/edge/spotter/README.md index 78bb4cbd79..4176b2b7e5 100644 --- a/edge/spotter/README.md +++ b/edge/spotter/README.md @@ -11,10 +11,10 @@ Spotter runs as a single unified process using the UDMI Python Client Library (` 1. **`LocalnetManager` & Pluggable Family Providers**: - **`BacnetFamilyProvider`**: Performs active BACnet Who-Is / I-Am discovery, object enumeration, and UDP port extraction. - **`EtherFamilyProvider`**: Performs Layer-2 Ethernet / ARP, nmap XML host parsing, and ICMP ping sweeps. - - **`PassiveFamilyProvider`**: Listens for passive broadcast network traffic and extracts discovered device metadata. + - **`PassiveFamilyProvider`**: Listens for passive broadcast network traffic, decodes BACnet/IP BVLL (`Forwarded-NPDU` real controller IP/port behind BBMDs) and NPDU (`SNET`/`SADR` routed MS/TP frames and `I-Am-Router-To-Network` DNET lists), and extracts discovered device metadata. 2. **`SpotterDiscoveryManager`**: - Manages scheduled and on-demand discovery sweeps. - - Streams live remote packet capture traces (`events/streams`) buffered in volatile memory with circuit-breaker protection (zero-disk streaming). + - Streams live remote packet capture traces (`upload/discovery`) buffered in volatile memory with circuit-breaker protection (zero-disk streaming). 3. **`SpotterSystemManager`**: - Collects host metrics (CPU load, memory, OS distribution) and emits periodic telemetry (`events/system`). - Evaluates memory usage against safety thresholds (`check_safety_circuit_breaker`), throttling active discovery and packet captures to protect edge devices from kernel OOM termination. @@ -41,12 +41,12 @@ graph TD end subgraph "Messaging & Field Network" - MB["MQTT Broker / UDMIS"] + MB["MQTT Broker / UDMIS / Butler"] DEV["Field OT Devices / BACnet Controllers"] end SYS -->|"state.system / events/system"| MB - DISC -->|"events/discovery & events/streams"| MB + DISC -->|"events/discovery & upload/discovery"| MB LOC -->|"Scans & Probes"| DEV ``` @@ -64,11 +64,12 @@ When `configs_dir` is specified in the primary configuration (e.g. `/opt/discove - **Ethernet Concurrency**: `ether.ping_concurrency` configures the maximum parallel ICMP ping worker threads (default: `4`). - **Passive Sniffing & Subnet Exclusions**: `ip.subnet_filter` (CIDR format, e.g. `192.168.1.10/24`) and `ip.interface` configure the network capture interface and BPF exclusion filters for broadcast, gateway, and host addresses. -### 3. Transparent Legacy Depth Normalization -To maintain backward compatibility with legacy edge schedules without polluting the abstract UDMI schema, Spotter normalizes legacy strings at the edge ingestion boundary: -- `"ping"` $\rightarrow$ `"entries"` (Host presence / IP addresses) -- `"ports"` $\rightarrow$ `"details"` (Open TCP/UDP ports and attributes) -- `"services"` $\rightarrow$ `"parts"` (Detailed service and point definitions) +### 3. Strict UDMI Specification Compliance +Spotter strictly enforces canonical UDMI discovery depths (`"buckets"`, `"entries"`, `"parts"`, `"system"`, `"refs"`, `"details"`, `"trace"`) and fails fast on non-canonical legacy depth strings (`"ping"`, `"ports"`, `"services"`), reporting a configuration error in `state.system.status`. All emitted `events/discovery` payloads conform to `docs/specs/discovery.md` and `docs/specs/discovery_bacnet.md`: +- Canonical `/` BACnet point references (e.g. `AI/0`, `AV/1`, `BV/2`), hyphenated object types (`analog-input`), boolean `writable` flags, and `present-value` ancillary values. +- Explicit `families.ipv4.port` (default `47808`), ARP-resolved `families.ethmac`, and MS/TP `:` routing (`network` + `families.mstp.addr`). +- Top-level `system.name`, `system.description`, `system.serial_no`, `system.hardware`, and hyphenated `system.ancillary` keys (`firmware-revision`, `application-software-version`, `location`). +- Self-enumeration via `config.discovery.generation` and `config.discovery.enumerations` (`families`, `features`, `points`). --- @@ -76,18 +77,22 @@ To maintain backward compatibility with legacy edge schedules without polluting Spotter processes diagnostic packet capture triggers sent declaratively over the UDMI discovery configuration channel (`config.discovery.families` with `depth: "trace"`): -1. **Capture Worker ([pcap.py](src/pcap.py))**: Spawns `tcpdump` with configurable interface filters, enforcing strict execution bounds (maximum duration and byte quotas). -2. **Streaming MQTT Egress Transport**: - - **Zero-Disk Streaming**: Packets are buffered dynamically in volatile memory (RAM) and sequentially published as reliable base64 chunks (`StreamsEvents`) over the universal streaming MQTT event topic (`events/streams`). +1. **Capture Worker & Active BACnet Trace Rounds ([pcap.py](src/pcap.py))**: + - Spawns `tcpdump` with configurable interface filters (defaulting to `"udp port 47808"` for `bacnet`), enforcing strict execution bounds (maximum duration and byte quotas). + - For `families.bacnet` with `depth: "trace"`, skips `BAC0.lite()` socket binding so UDP port `47808` remains unbound and executes paced raw-socket (`SOCK_RAW, IPPROTO_UDP`) `Who-Is` and `Who-Is-Router-To-Network` rounds during the capture window. +2. **Streaming MQTT Egress Transport (`upload/discovery`)**: + - **Zero-Disk Streaming**: Packets are buffered dynamically in volatile memory (RAM), gzip-compressed per chunk, and sequentially published as `DiscoveryUpload` chunks over the `upload/discovery` MQTT topic (`event_no = 0` start marker, `1..N` gzipped base64 chunks, and `-(N+1)` terminal marker with uncompressed `sha256` and `scan_manifest`). - **Zero Secret Distribution**: Leverages the existing mTLS hardware key/certificate connection directly, avoiding external network credentials or outbound HTTP rules at the edge. -3. **Ad-hoc PCAP Reassembly ([bin/reassemble_pcap](bin/reassemble_pcap))**: - Reassembles chunked `events/streams` messages (from JSON, JSONL, or `mosquitto_sub`) back into a valid `.pcap` binary capture file: +3. **Cloud & Local PCAP Reassembly**: + - **Butler Service (`PcapUploadHandler`)**: Subscribes to `upload/discovery` (or `uufi_upload`), gunzips and reassembles chunks in order, validates the terminal `sha256` digest, and writes the `.pcap` and `scan_manifest.json` to GCS (`gs:////.pcap`) or local disk without persisting raw chunks to PostgreSQL. + - **Ad-hoc CLI Reassembly ([bin/reassemble_pcap](bin/reassemble_pcap))**: + Reassembles chunked `upload/discovery` messages (from JSON, JSONL, or `mosquitto_sub`) back into a valid `.pcap` binary capture file and `scan_manifest.json`: ```bash - # Reassemble stream events file into a pcap file: - ./edge/spotter/bin/reassemble_pcap stream_events.json capture.pcap + # Reassemble upload/discovery chunks file into a pcap file: + ./edge/spotter/bin/reassemble_pcap discovery_upload.json capture.pcap # Or stream directly from mosquitto subscriber: - mosquitto_sub -h $BROKER -t '/r/+/d/+/events/streams' | ./edge/spotter/bin/reassemble_pcap - live.pcap + mosquitto_sub -h $BROKER -t '/r/+/d/+/upload/discovery' | ./edge/spotter/bin/reassemble_pcap - live.pcap ``` --- @@ -98,12 +103,12 @@ Spotter processes diagnostic packet capture triggers sent declaratively over the | :--- | :--- | | **[bin/spotter](../../bin/spotter)** | Unified CLI orchestrator for starting (local/container) and stopping instances | | **[bin/run_spotter_tests](bin/run_spotter_tests)** | Unified verification test runner for unit and integration suites | -| **[bin/reassemble_pcap](bin/reassemble_pcap)** | Ad-hoc CLI utility to reassemble `events/streams` chunks into `.pcap` files | +| **[bin/reassemble_pcap](bin/reassemble_pcap)** | Ad-hoc CLI utility to reassemble `upload/discovery` chunks into `.pcap` files | | **[bin/compare_field_parity](bin/compare_field_parity)** | Automated CLI tool to verify functional parity between legacy node and Spotter | | **[src/agent.py](src/agent.py)** | Main Spotter agent entry point, manager wiring, and command dispatcher | | **[src/providers/](src/providers/)** | Modular protocol discovery providers (BACnet, Ether, Passive) | | **[src/host_telemetry.py](src/host_telemetry.py)** | Host OS and performance telemetry probes | -| **[src/pcap.py](src/pcap.py)** | Safe `tcpdump` wrapper yielding binary streams with duration and size caps | +| **[src/pcap.py](src/pcap.py)** | Safe `tcpdump` wrapper and raw-socket BACnet `Who-Is` trace generator | | **[container/Dockerfile](container/Dockerfile)** | Multi-stage Docker image build specification | | **[spotter_config.json](spotter_config.json)** | Sample configuration file for endpoint and BACnet parameters | | **[GEMINI.md](GEMINI.md)** | Detailed testing standards, execution matrices, and triage guidelines | @@ -177,7 +182,7 @@ To prove byte-for-byte discovery parity on an actual field testbed machine witho ```bash # Automated live scan comparison (back-to-back sequential execution): -sudo ./edge/spotter/bin/compare_field_parity --config /etc/udmi_discovery/config.json --duration 20 +./edge/spotter/bin/compare_field_parity --config /etc/udmi_discovery/config.json --duration 20 # Or offline diff of previously collected discovery event files: ./edge/spotter/bin/compare_field_parity --diff legacy_events.json spotter_events.json -v @@ -189,7 +194,6 @@ sudo ./edge/spotter/bin/compare_field_parity --config /etc/udmi_discovery/config The following capabilities are tracked as future milestones: -1. **UDMIS Native PCAP Ingestion Pipeline**: Native service-side ingestion and reassembly in UDMIS to automatically collect and persist `events/streams` PCAP chunks directly into Cloud Storage (GCS) or BigQuery blob storage. -2. **Ephemeral Secret Delivery**: Architectural mechanism for delivering transient, authenticated operational credentials (e.g., vendor device credentials, BACnet network encryption keys, or REST API bearer tokens) strictly in volatile RAM without disk persistence. A dedicated architectural discussion will finalize the delivery transport (such as non-persisted command channels e.g. `commands/secret` vs encrypted `config.blobset`), memory scrubbing lifecycles, and cryptographic envelope validation before implementation. -3. **Key Rotation & Lifecycle**: End-to-end device private/public key rotation with automated cloud IoT registry coordination, backup verification, and zero-downtime reconnection. -4. **Expanded Host Observability Metrics**: Network adapter error/drop counters, hardware temperature, storage/inode thresholds, and edge-to-cloud roundtrip latency. +1. **Ephemeral Secret Delivery**: Architectural mechanism for delivering transient, authenticated operational credentials (e.g., vendor device credentials, BACnet network encryption keys, or REST API bearer tokens) strictly in volatile RAM without disk persistence. A dedicated architectural discussion will finalize the delivery transport (such as non-persisted command channels e.g. `commands/secret` vs encrypted `config.blobset`), memory scrubbing lifecycles, and cryptographic envelope validation before implementation. +2. **Key Rotation & Lifecycle**: End-to-end device private/public key rotation with automated cloud IoT registry coordination, backup verification, and zero-downtime reconnection. +3. **Expanded Host Observability Metrics**: Network adapter error/drop counters, hardware temperature, storage/inode thresholds, and edge-to-cloud roundtrip latency. diff --git a/edge/spotter/bin/compare_field_parity b/edge/spotter/bin/compare_field_parity index 31194c0e60..0290acd0c2 100755 --- a/edge/spotter/bin/compare_field_parity +++ b/edge/spotter/bin/compare_field_parity @@ -1,8 +1,9 @@ #!/usr/bin/env python3 -"""Spotter Field Parity Verification Tool. +"""Spotter Specification Compliance & Field Parity Verification Tool. -Compares BACnet discovery outputs between the legacy discoverynode and the new -Spotter node. Supports both direct live testbed execution (automated sequential +Compares BACnet discovery outputs between the legacy discoverynode and the +Spotter node while enforcing strict UDMI specification compliance on Spotter +payloads. Supports both direct live testbed execution (automated sequential scans) and offline file diffing of captured discovery events. """ @@ -10,11 +11,21 @@ import argparse import difflib import json import os +import re import shutil import subprocess import sys import time -from typing import Any, Dict, List +from typing import Any, Dict, List, Tuple + + +CAMEL_TO_HYPHEN_RE = re.compile(r"([a-z0-9])([A-Z])") +BACNET_REF_RE = re.compile(r"^([A-Z]{2,4})/(0|[1-9][0-9]*)(#[_a-z]+)?$") + + +def camel_to_hyphen(val: str) -> str: + """Converts camelCase strings (e.g. analogInput) to hyphenated lowercase.""" + return CAMEL_TO_HYPHEN_RE.sub(r"\1-\2", val).lower() def remove_none_fields(d: Any) -> Any: @@ -26,6 +37,17 @@ def remove_none_fields(d: Any) -> Any: return d +def has_null_fields(d: Any) -> bool: + """Returns True if any dictionary key or list element has a None value.""" + if d is None: + return True + if isinstance(d, dict): + return any(v is None or has_null_fields(v) for v in d.values()) + if isinstance(d, list): + return any(v is None or has_null_fields(v) for v in d) + return False + + def clean_event(event: Dict[str, Any]) -> Dict[str, Any]: """Cleans dynamic timestamps, versions, and generations for comparison.""" evt = json.loads(json.dumps(event)) @@ -45,7 +67,157 @@ def clean_event(event: Dict[str, Any]) -> Dict[str, Any]: return evt -def load_events_from_file(filepath: str) -> List[Dict[str, Any]]: +def normalize_legacy_event(event: Dict[str, Any]) -> Dict[str, Any]: + """Normalizes known legacy discoverynode spec violations to canonical UDMI. + + Allows semantic comparison of discovered devices and points against Spotter's + strict UDMI specification-compliant output. + """ + evt = clean_event(event) + if evt.get("event_no", 0) <= 0: + return evt + + # 1. Normalize families.ipv4.port (omitted by legacy discoverynode) + families = evt.get("families") + if isinstance(families, dict): + ipv4 = families.get("ipv4") + if isinstance(ipv4, dict) and ipv4.get("addr") and "port" not in ipv4: + ipv4["port"] = 47808 + + # 2. Normalize system.ancillary -> system.name/description and hyphenated keys + system = evt.get("system") + if isinstance(system, dict): + ancillary = system.get("ancillary") + if isinstance(ancillary, dict): + if "name" in ancillary and "name" not in system: + system["name"] = ancillary.pop("name") + else: + ancillary.pop("name", None) + if "description" in ancillary and "description" not in system: + system["description"] = ancillary.pop("description") + else: + ancillary.pop("description", None) + if "firmware" in ancillary and "firmware-revision" not in ancillary: + ancillary["firmware-revision"] = ancillary.pop("firmware") + if ( + "application_version" in ancillary + and "application-software-version" not in ancillary + ): + ancillary["application-software-version"] = ancillary.pop( + "application_version" + ) + + # 3. Normalize colon-delimited refs ("AI:0" -> "AI/0") and point metadata + refs = evt.get("refs") + if isinstance(refs, dict): + normalized_refs = {} + for ref_key, ref_val in refs.items(): + norm_key = ref_key.replace(":", "/", 1) if ":" in ref_key else ref_key + if isinstance(ref_val, dict): + ref_copy = dict(ref_val) + if isinstance(ref_copy.get("type"), str): + ref_copy["type"] = camel_to_hyphen(ref_copy["type"]) + if "writable" not in ref_copy: + rtype = ref_copy.get("type", "") + ref_copy["writable"] = ("output" in rtype) or ("value" in rtype) + if "possible_values" not in ref_copy and ref_copy.get("type", "").startswith("binary-"): + ref_copy["possible_values"] = ["inactive", "active"] + ref_anc = ref_copy.get("ancillary") + if isinstance(ref_anc, dict) and "present_value" in ref_anc: + pv = ref_anc.pop("present_value") + if isinstance(pv, str): + try: + pv = int(pv) if pv.isdigit() else float(pv) + except ValueError: + pass + ref_anc["present-value"] = pv + normalized_refs[norm_key] = ref_copy + else: + normalized_refs[norm_key] = ref_val + evt["refs"] = normalized_refs + + return evt + + +def validate_spotter_spec_compliance( + raw_events: List[Dict[str, Any]], +) -> List[str]: + """Validates that Spotter discovery events strictly adhere to the UDMI spec.""" + violations: List[str] = [] + for idx, evt in enumerate(raw_events): + if has_null_fields(evt): + violations.append(f"Event #{idx} contains explicit null fields") + event_no = evt.get("event_no") + if not isinstance(event_no, int): + violations.append(f"Event #{idx} missing integer event_no") + continue + if event_no <= 0: + continue + + if evt.get("family") == "bacnet": + families = evt.get("families", {}) + ipv4 = families.get("ipv4") + mstp = families.get("mstp") + if isinstance(ipv4, dict): + if not isinstance(ipv4.get("port"), int): + violations.append( + f"Event #{idx} (addr={evt.get('addr')}) missing integer" + " families.ipv4.port" + ) + elif not isinstance(mstp, dict) and not evt.get("network"): + violations.append( + f"Event #{idx} (addr={evt.get('addr')}) missing families.ipv4 or" + " families.mstp" + ) + + system = evt.get("system") + if isinstance(system, dict): + anc = system.get("ancillary", {}) + if isinstance(anc, dict): + for legacy_key in ( + "name", + "description", + "firmware", + "application_version", + ): + if legacy_key in anc: + violations.append( + f"Event #{idx} has non-standard key '{legacy_key}' in" + " system.ancillary" + ) + + refs = evt.get("refs") + if isinstance(refs, dict): + for ref_key, ref_val in refs.items(): + if not BACNET_REF_RE.match(ref_key): + violations.append( + f"Event #{idx} has non-canonical BACnet ref key '{ref_key}'" + " (expected '/')" + ) + if isinstance(ref_val, dict): + rtype = ref_val.get("type", "") + if rtype and rtype != rtype.lower(): + violations.append( + f"Event #{idx} ref '{ref_key}' has non-hyphenated type" + f" '{rtype}'" + ) + if not isinstance(ref_val.get("writable"), bool): + violations.append( + f"Event #{idx} ref '{ref_key}' missing boolean 'writable'" + ) + ref_anc = ref_val.get("ancillary", {}) + if isinstance(ref_anc, dict) and "present_value" in ref_anc: + violations.append( + f"Event #{idx} ref '{ref_key}' uses underscore" + " 'present_value' instead of 'present-value'" + ) + + return violations + + +def load_events_from_file( + filepath: str, include_raw: bool = False +) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: """Loads discovery events from JSON array, JSONL, or mosquitto_sub logs.""" if not os.path.isfile(filepath): raise FileNotFoundError(f"Event file not found: {filepath}") @@ -54,55 +226,55 @@ def load_events_from_file(filepath: str) -> List[Dict[str, Any]]: content = f.read().strip() if not content: - return [] + return ([], []) if include_raw else [] # type: ignore[return-value] + raw_events: List[Dict[str, Any]] = [] # Attempt 1: Full JSON array if content.startswith("["): try: data = json.loads(content) if isinstance(data, list): - return [clean_event(e) for e in data if isinstance(e, dict)] + raw_events = [e for e in data if isinstance(e, dict)] except json.JSONDecodeError: pass # Attempt 2: Line-delimited JSON or mosquitto_sub topic-payload lines - events = [] - for line in content.splitlines(): - line = line.strip() - if not line: - continue - # Check for mosquitto_sub prefix (e.g. "/r/.../events/discovery { ... }") - if " " in line and line.startswith("/") and "{" in line: - _, json_str = line.split(" ", 1) - line = json_str.strip() - - try: - parsed = json.loads(line) - if isinstance(parsed, dict): - events.append(clean_event(parsed)) - except json.JSONDecodeError: - continue - - return events + if not raw_events: + for line in content.splitlines(): + line = line.strip() + if not line: + continue + if " " in line and line.startswith("/") and "{" in line: + _, json_str = line.split(" ", 1) + line = json_str.strip() + + try: + parsed = json.loads(line) + if isinstance(parsed, dict): + raw_events.append(parsed) + except json.JSONDecodeError: + continue + + cleaned = [clean_event(e) for e in raw_events] + if include_raw: + return cleaned, raw_events + return cleaned # type: ignore[return-value] def extract_summary(events: List[Dict[str, Any]]) -> Dict[str, Any]: """Extracts high-level summary metrics from a sequence of discovery events.""" start_events = [e for e in events if e.get("event_no") == 0] - stop_events = [e for e in events if e.get("event_no") == -1] + stop_events = [ + e + for e in events + if isinstance(e.get("event_no"), int) and e.get("event_no", 0) < 0 + ] discovered_devices = {} for e in events: event_no = e.get("event_no") - if event_no not in (0, -1): - # Identification key: addr, id, or device hash - dev_key = str(event_no) - if "families" in e and isinstance(e["families"], dict): - for fam, f_data in e["families"].items(): - if isinstance(f_data, dict) and "addr" in f_data: - addr_val = f_data["addr"] - dev_key = f"{fam}:{addr_val}" - break + if isinstance(event_no, int) and event_no > 0: + dev_key = f"{e.get('family', 'unknown')}:{e.get('addr', event_no)}" discovered_devices[dev_key] = e return { @@ -116,14 +288,23 @@ def extract_summary(events: List[Dict[str, Any]]) -> Dict[str, Any]: def compare_events( legacy_events: List[Dict[str, Any]], spotter_events: List[Dict[str, Any]], + raw_spotter_events: List[Dict[str, Any]] | None = None, verbose: bool = False, ) -> bool: - """Performs deep parity comparison between legacy and Spotter discovery.""" - legacy_summary = extract_summary(legacy_events) + """Performs UDMI spec validation and semantic parity comparison.""" + normalized_legacy = [normalize_legacy_event(e) for e in legacy_events] + # For comparison against legacy (which lacks ethmac ARP resolution when run on + # different sockets), compare canonical fields while validating Spotter spec. + legacy_summary = extract_summary(normalized_legacy) spotter_summary = extract_summary(spotter_events) + spec_violations = ( + validate_spotter_spec_compliance(raw_spotter_events) + if raw_spotter_events is not None + else validate_spotter_spec_compliance(spotter_events) + ) print("\n" + "=" * 64) - print(" UDMI DISCOVERY NODE PARITY VERIFICATION REPORT") + print(" UDMI SPOTTER SPEC COMPLIANCE & PARITY VERIFICATION REPORT") print("=" * 64) print("\n[1] Event Volume & Sequencing:") @@ -140,7 +321,7 @@ def compare_events( has_stop_leg = legacy_summary["has_stop_event"] has_stop_spt = spotter_summary["has_stop_event"] print( - f" - Stop Event (event_no: -1): Legacy={has_stop_leg} | " + f" - Stop Event (event_no < 0): Legacy={has_stop_leg} | " f"Spotter={has_stop_spt}" ) @@ -169,15 +350,21 @@ def compare_events( f"{len(extra_in_spotter)} ({extra_str})" ) - # Deep payload diff on matched events + # Deep payload diff on matched events (ignoring ethmac if legacy omitted it) attribute_mismatches = 0 for dev in sorted(matched_devices): - leg_dev = legacy_summary["devices"][dev] - spt_dev = spotter_summary["devices"][dev] + leg_dev = json.loads(json.dumps(legacy_summary["devices"][dev])) + spt_dev = json.loads(json.dumps(spotter_summary["devices"][dev])) + if ( + isinstance(spt_dev.get("families"), dict) + and "ethmac" in spt_dev["families"] + and "ethmac" not in leg_dev.get("families", {}) + ): + spt_dev["families"].pop("ethmac", None) if leg_dev != spt_dev: attribute_mismatches += 1 if verbose: - print(f"\n [!] Attribute diff on device \"{dev}\":") + print(f'\n [!] Attribute diff on device "{dev}":') leg_str = json.dumps(leg_dev, indent=2, sort_keys=True).splitlines() spt_str = json.dumps(spt_dev, indent=2, sort_keys=True).splitlines() diff = difflib.unified_diff( @@ -186,31 +373,39 @@ def compare_events( for line in diff: print(f" {line}") - print("\n[3] Payload Attribute Integrity:") + print("\n[3] UDMI Specification Compliance & Attribute Integrity:") + print(f" - Spotter Spec Violations : {len(spec_violations)}") + for v in spec_violations: + print(f" * {v}") print(f" - Attribute Mismatches : {attribute_mismatches}") - # Final Parity Verdict is_parity = ( legacy_summary["has_start_event"] == spotter_summary["has_start_event"] and legacy_summary["has_stop_event"] == spotter_summary["has_stop_event"] and len(missing_in_spotter) == 0 + and len(spec_violations) == 0 and attribute_mismatches == 0 and len(legacy_events) > 0 ) print("\n" + "=" * 64) if is_parity: - print("VERDICT: [PASS] FUNCTIONAL PARITY ACHIEVED!") - print("Spotter produces identical telemetry payloads and sequencing.") + print("VERDICT: [PASS] SPEC COMPLIANCE & FUNCTIONAL PARITY ACHIEVED!") + print("Spotter produces UDMI spec-compliant discovery payloads.") else: - print("VERDICT: [FAIL] DISCOVERY PARITY NOT ACHIEVED.") + print("VERDICT: [FAIL] VERIFICATION FAILED.") if len(legacy_events) == 0: print("Reason: No events were collected to compare.") + elif spec_violations: + print( + f"Reason: Spotter had {len(spec_violations)} UDMI specification" + " violations." + ) elif missing_in_spotter: num_missing = len(missing_in_spotter) print( f"Reason: Spotter failed to discover {num_missing} devices found by " - f"legacy." + "legacy." ) elif attribute_mismatches > 0: print( @@ -234,7 +429,7 @@ def run_live_parity( spotter_output = os.path.join(output_dir, "spotter_discovery.jsonl") if not os.path.isfile(config_file): - print(f"ERROR: Config file not found at \"{config_file}\".") + print(f'ERROR: Config file not found at "{config_file}".') return False with open(config_file, "r", encoding="utf-8") as f: @@ -248,9 +443,15 @@ def run_live_parity( ca_file = mqtt_cfg.get("ca_file", "") topic = f"/r/{registry_id}/d/{device_id}/events/discovery" - # Build mosquitto_sub command base sub_cmd = [ - "mosquitto_sub", "-h", str(host), "-p", str(port), "-t", topic, "-v" + "mosquitto_sub", + "-h", + str(host), + "-p", + str(port), + "-t", + topic, + "-v", ] if ca_file and os.path.isfile(ca_file): sub_cmd.extend(["--cafile", ca_file]) @@ -285,10 +486,16 @@ def run_live_parity( check=False, ) if res.stdout.strip() == "active": + if os.geteuid() != 0: + raise RuntimeError( + f"Systemd service '{svc_candidate}' is active, but" + " compare_field_parity is running as non-root. Stop the service" + " or run as root." + ) active_service = svc_candidate print(f"Stopping systemd service '{active_service}'...") subprocess.run( - ["sudo", "systemctl", "stop", active_service], check=False + ["systemctl", "stop", active_service], check=False ) time.sleep(2) break @@ -299,7 +506,10 @@ def run_live_parity( if shutil.which("podman") and not shutil.which("docker") else "docker" ) - print(f"\n--- Phase 3: Launching Spotter Node ({spotter_image}) via {engine} ---") + print( + f"\n--- Phase 3: Launching Spotter Node ({spotter_image}) via {engine}" + " ---" + ) config_dir = os.path.dirname(os.path.abspath(config_file)) config_basename = os.path.basename(config_file) container_cmd = [ @@ -358,26 +568,32 @@ def run_live_parity( check=False, ) - # Restore Legacy Service if it was running - if active_service: + if active_service and os.geteuid() == 0: print(f"Restoring legacy '{active_service}' service...") subprocess.run( - ["sudo", "systemctl", "start", active_service], check=False + ["systemctl", "start", active_service], check=False ) # Step 6: Evaluate Parity print("\n--- Phase 6: Analyzing & Comparing Collected Events ---") - legacy_events = load_events_from_file(legacy_output) - spotter_events = load_events_from_file(spotter_output) - return compare_events(legacy_events, spotter_events, verbose=verbose) + legacy_events, _ = load_events_from_file(legacy_output, include_raw=True) + spotter_events, raw_spotter = load_events_from_file( + spotter_output, include_raw=True + ) + return compare_events( + legacy_events, + spotter_events, + raw_spotter_events=raw_spotter, + verbose=verbose, + ) def main(): """Main CLI entrypoint for field parity comparison.""" parser = argparse.ArgumentParser( description=( - "Verify BACnet discovery parity between legacy discoverynode and" - " Spotter." + "Verify UDMI discovery spec compliance and functional parity between" + " legacy discoverynode and Spotter." ) ) parser.add_argument( @@ -423,10 +639,15 @@ def main(): args = parser.parse_args() if args.diff: - legacy_events = load_events_from_file(args.diff[0]) - spotter_events = load_events_from_file(args.diff[1]) + legacy_events, _ = load_events_from_file(args.diff[0], include_raw=True) + spotter_events, raw_spotter = load_events_from_file( + args.diff[1], include_raw=True + ) success = compare_events( - legacy_events, spotter_events, verbose=args.verbose + legacy_events, + spotter_events, + raw_spotter_events=raw_spotter, + verbose=args.verbose, ) else: success = run_live_parity( @@ -442,4 +663,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/edge/spotter/bin/reassemble_pcap b/edge/spotter/bin/reassemble_pcap index a542d9b34a..7afaafb2e2 100755 --- a/edge/spotter/bin/reassemble_pcap +++ b/edge/spotter/bin/reassemble_pcap @@ -1,21 +1,24 @@ #!/usr/bin/env python3 -"""Utility to reassemble UDMI events/streams chunks into a valid PCAP file. +"""Utility to reassemble UDMI upload/discovery chunks into a valid PCAP file and scan manifest. Usage: - bin/reassemble_pcap + bin/reassemble_pcap [--manifest ] Supported input formats: - - Raw JSON array of StreamsEvents: [ {"event_no": 0, "data": "..."}, ... ] - - JSON Lines (JSONL): One StreamsEvents JSON object per line + - Raw JSON array of DiscoveryUpload messages: [ {"event_no": 0, ...}, {"event_no": 1, "data": "..."}, ... ] + - JSON Lines (JSONL): One DiscoveryUpload JSON object per line - mosquitto_sub output: " " - Standard input (specify "-" as input file) """ import argparse import base64 +import gzip +import hashlib import json import os import sys +from typing import Any, Dict, List, Optional PCAP_MAGIC_NUMBERS = [ b"\xa1\xb2\xc3\xd4", # Standard pcap (same-endian) @@ -24,9 +27,11 @@ PCAP_MAGIC_NUMBERS = [ b"\x4d\x3c\xb2\xa1", # Nanosecond pcap (swapped-endian) ] +GZIP_MAGIC = b"\x1f\x8b" -def parse_stream_events(raw_text: str): - """Parse StreamsEvents objects from JSON array, JSONL, or mosquitto_sub.""" + +def parse_upload_messages(raw_text: str) -> List[Dict[str, Any]]: + """Parses DiscoveryUpload objects from JSON array, JSONL, or mosquitto_sub.""" raw_text = raw_text.strip() if not raw_text: return [] @@ -36,21 +41,30 @@ def parse_stream_events(raw_text: str): try: data = json.loads(raw_text) if isinstance(data, list): - return [item.get("payload", item) if (isinstance(item, dict) and "payload" in item and isinstance(item["payload"], dict)) else item for item in data] + return [ + item.get("payload", item) + if ( + isinstance(item, dict) + and "payload" in item + and isinstance(item["payload"], dict) + ) + else item + for item in data + if isinstance(item, dict) + ] if isinstance(data, dict): - if "payload" in data and isinstance(data["payload"], dict) and "data" in data["payload"]: + if "payload" in data and isinstance(data["payload"], dict): return [data["payload"]] return [data] except json.JSONDecodeError: pass # Case 2: Line by line (JSONL or mosquitto_sub format: " ") - events = [] + messages: List[Dict[str, Any]] = [] for line in raw_text.splitlines(): line = line.strip() if not line: continue - # Strip topic prefix if present if " " in line and not line.startswith("{"): _, _, payload = line.partition(" ") else: @@ -59,17 +73,33 @@ def parse_stream_events(raw_text: str): try: obj = json.loads(payload) if isinstance(obj, dict): - inner = obj.get("payload") if (isinstance(obj.get("payload"), dict) and "data" in obj["payload"]) else obj - if "data" in inner: - events.append(inner) + inner = ( + obj.get("payload") + if isinstance(obj.get("payload"), dict) + else obj + ) + if "event_no" in inner or "data" in inner: + messages.append(inner) except json.JSONDecodeError: continue - return events + return messages + +def decode_chunk_bytes(b64_str: str) -> bytes: + """Base64-decodes and gunzips a PCAP chunk payload.""" + raw_bytes = base64.b64decode(b64_str) + if raw_bytes.startswith(GZIP_MAGIC): + return gzip.decompress(raw_bytes) + return raw_bytes -def reassemble_pcap(input_source: str, output_path: str) -> None: - """Reassembles chunked events into a binary pcap capture file.""" + +def reassemble_pcap( + input_source: str, + output_path: str, + manifest_output_path: Optional[str] = None, +) -> Dict[str, Any]: + """Reassembles chunked upload/discovery messages into a binary .pcap file and verifies sha256.""" if input_source == "-": raw_content = sys.stdin.read() else: @@ -78,77 +108,128 @@ def reassemble_pcap(input_source: str, output_path: str) -> None: with open(input_source, "r", encoding="utf-8", errors="replace") as f: raw_content = f.read() - events = parse_stream_events(raw_content) - if not events: - sys.exit("Error: No valid StreamsEvents records with 'data' found in input.") - - # Filter out records missing data - valid_events = [e for e in events if e.get("data")] - if not valid_events: - sys.exit("Error: Found stream records but none contained base64 'data'.") - - # Sort primarily by chunk_index, fallback to event_no - def sort_key(e): - return ( - e.get("chunk_index", 0) - if e.get("chunk_index") is not None - else e.get("event_no", 0) - ) - - sorted_events = sorted(valid_events, key=sort_key) - session_id = sorted_events[0].get("session_id", "unknown") + messages = parse_upload_messages(raw_content) + if not messages: + sys.exit("Error: No valid upload/discovery records found in input.") + + data_events = [ + m + for m in messages + if m.get("data") and int(m.get("event_no", 1)) > 0 + ] + if not data_events: + sys.exit("Error: Found upload records but none contained base64 'data'.") + + eof_events = [m for m in messages if int(m.get("event_no", 0)) < 0] + expected_sha256: Optional[str] = None + expected_chunks: Optional[int] = None + scan_manifest: Optional[Dict[str, Any]] = None + + if eof_events: + terminal = eof_events[-1] + expected_sha256 = terminal.get("sha256") + expected_chunks = (-int(terminal["event_no"])) - 1 + if isinstance(terminal.get("scan_manifest"), dict): + scan_manifest = terminal["scan_manifest"] + + def sort_key(e: Dict[str, Any]) -> int: + return int(e.get("event_no", 0)) + + sorted_events = sorted(data_events, key=sort_key) + generation = sorted_events[0].get("generation") or "unknown" + family = sorted_events[0].get("family", "bacnet") total_chunks = len(sorted_events) - # Reconstruct binary payload + if expected_chunks is not None and total_chunks != expected_chunks: + sys.exit( + f"Error: Chunk count mismatch (received {total_chunks}, expected" + f" {expected_chunks} from terminal event_no)." + ) + pcap_data = bytearray() for idx, evt in enumerate(sorted_events): b64_str = evt["data"] try: - chunk_bytes = base64.b64decode(b64_str) + chunk_bytes = decode_chunk_bytes(b64_str) pcap_data.extend(chunk_bytes) except Exception as err: # pylint: disable=broad-exception-caught - sys.exit(f"Error: Failed to decode base64 chunk at index {idx}: {err}") + sys.exit(f"Error: Failed to decode/decompress chunk at index {idx}: {err}") - # Validate output if not pcap_data: sys.exit("Error: Reassembled PCAP payload is empty (0 bytes).") + actual_sha256 = hashlib.sha256(pcap_data).hexdigest() + if expected_sha256 and actual_sha256 != expected_sha256: + sys.exit( + f"Error: SHA-256 digest mismatch! Expected {expected_sha256}, got" + f" {actual_sha256}." + ) + magic = bytes(pcap_data[:4]) is_valid_magic = any(magic == m for m in PCAP_MAGIC_NUMBERS) - # Write to destination file os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True) with open(output_path, "wb") as f: f.write(pcap_data) + resolved_manifest_path = manifest_output_path + if scan_manifest is not None: + if not resolved_manifest_path: + resolved_manifest_path = os.path.join( + os.path.dirname(os.path.abspath(output_path)), "scan_manifest.json" + ) + os.makedirs( + os.path.dirname(os.path.abspath(resolved_manifest_path)), exist_ok=True + ) + with open(resolved_manifest_path, "w", encoding="utf-8") as mf: + json.dump(scan_manifest, mf, indent=2) + magic_status = "VALID" if is_valid_magic else "WARNING: Unexpected header" print("========================================") print("PCAP Reassembly Completed Successfully") print("========================================") - print(f"Session ID : {session_id}") + print(f"Generation : {generation}") + print(f"Family : {family}") print(f"Chunks Decoded : {total_chunks}") print(f"Total Bytes : {len(pcap_data)}") + print(f"SHA-256 Digest : {actual_sha256}") print(f"Magic Bytes : {magic.hex()} ({magic_status})") print(f"Output File : {output_path}") + if resolved_manifest_path and os.path.exists(resolved_manifest_path): + print(f"Scan Manifest : {resolved_manifest_path}") + + return { + "generation": generation, + "family": family, + "chunks": total_chunks, + "bytes": len(pcap_data), + "sha256": actual_sha256, + "output_path": output_path, + "manifest_path": resolved_manifest_path, + } def main(): """CLI entry point for PCAP reassembly.""" parser = argparse.ArgumentParser( - description="Reassemble UDMI stream events into PCAP file" + description="Reassemble UDMI upload/discovery chunks into PCAP file" ) parser.add_argument( "input", - help="Input file containing stream event data (or '-' for stdin)", + help="Input file containing upload/discovery data (or '-' for stdin)", ) parser.add_argument( "output", help="Destination file path for reassembled .pcap" ) + parser.add_argument( + "--manifest", + default=None, + help="Optional destination path for scan_manifest.json", + ) args = parser.parse_args() - reassemble_pcap(args.input, args.output) + reassemble_pcap(args.input, args.output, manifest_output_path=args.manifest) if __name__ == "__main__": main() - diff --git a/edge/spotter/bin/run_spotter_tests b/edge/spotter/bin/run_spotter_tests index 74bd880be2..08629b2d3f 100755 --- a/edge/spotter/bin/run_spotter_tests +++ b/edge/spotter/bin/run_spotter_tests @@ -47,6 +47,12 @@ if [[ "$MODE" == "integration" || "$MODE" == "all" ]]; then fi fi export CONTAINER_ENGINE + if [[ ! -f "${WORKSPACE_DIR}/sites/udmi_site_model/reflector/ca.crt" ]]; then + "${WORKSPACE_DIR}/bin/setup_ca" "${WORKSPACE_DIR}/sites/udmi_site_model" localhost >/dev/null + fi + if [[ ! -f "${WORKSPACE_DIR}/sites/udmi_site_model/devices/AHU-1/rsa_private.crt" ]]; then + "${WORKSPACE_DIR}/bin/keygen" CERT "${WORKSPACE_DIR}/sites/udmi_site_model/devices/AHU-1" >/dev/null + fi ${CONTAINER_ENGINE} build -t udmi-spotter:latest -f "${WORKSPACE_DIR}/edge/spotter/container/Dockerfile" "${WORKSPACE_DIR}" >/dev/null echo "--- Step 4: Running Container Lifecycle Integration Tests (test_container) ---" @@ -70,9 +76,14 @@ if [[ "$MODE" == "integration" || "$MODE" == "all" ]]; then if ${CONTAINER_ENGINE} network inspect parity-spotter-net >/dev/null 2>&1 || ${CONTAINER_ENGINE} network create --subnet=192.168.12.0/24 --gateway=192.168.12.254 parity-spotter-net >/dev/null 2>&1; then echo "--- Step 8: Running Discovery Parity Tests (test_parity) ---" - echo "Building legacy discovery node container and simulated BACnet device image..." - "${WORKSPACE_DIR}/misc/discoverynode/bin/build_container" test-discovery_node >/dev/null - bash "${WORKSPACE_DIR}/misc/discoverynode/testing/docker/bacnet_device/build.sh" >/dev/null + if ! ${CONTAINER_ENGINE} image inspect test-discovery_node:latest >/dev/null 2>&1; then + echo "Building legacy discovery node container..." + "${WORKSPACE_DIR}/misc/discoverynode/bin/build_container" test-discovery_node >/dev/null + fi + if ! ${CONTAINER_ENGINE} image inspect test-bacnet-device:latest >/dev/null 2>&1; then + echo "Building simulated BACnet device image..." + bash "${WORKSPACE_DIR}/misc/discoverynode/testing/docker/bacnet_device/build.sh" >/dev/null + fi ( cd "${WORKSPACE_DIR}" PYTHONPATH=clientlib/python/src:gencode/python:. "${SPOTTER_PYTHON}" "${SCRIPT_DIR}/test_parity" diff --git a/edge/spotter/bin/test_container b/edge/spotter/bin/test_container index 0ab77fbf78..b01348a908 100755 --- a/edge/spotter/bin/test_container +++ b/edge/spotter/bin/test_container @@ -125,7 +125,19 @@ class TestContainer(unittest.TestCase): with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) as proc: - time.sleep(2.5) + deadline = time.time() + 10.0 + while time.time() < deadline: + logs_res = subprocess.run( + [self.engine, "logs", container_name], + capture_output=True, + text=True, + check=False, + ) + if "Starting UDMI Spotter Unified Agent" in ( + logs_res.stdout + logs_res.stderr + ): + break + time.sleep(0.2) print( f" Sending SIGTERM via '{self.engine} stop' to {container_name}...", flush=True, diff --git a/edge/spotter/bin/test_fault_injection b/edge/spotter/bin/test_fault_injection index 10b36f9dca..db54ad92f7 100755 --- a/edge/spotter/bin/test_fault_injection +++ b/edge/spotter/bin/test_fault_injection @@ -13,7 +13,7 @@ fi echo "=== Spotter Network Resilience & Fault Injection Test Suite ===" -echo "--- Step 1: Verifying StreamsEvents transport structure and sequence ordering ---" +echo "--- Step 1: Verifying DiscoveryUpload (upload/discovery) transport structure and sequence ordering ---" ( cd "${WORKSPACE_DIR}" PYTHONPATH=clientlib/python/src:gencode/python:. "${WORKSPACE_DIR}/edge/spotter/venv/bin/python3" -m unittest edge.spotter.tests.test_agent.TestSpotterDiscoveryManager -v diff --git a/edge/spotter/bin/test_parity b/edge/spotter/bin/test_parity index 9ad1cfef82..7219f28049 100755 --- a/edge/spotter/bin/test_parity +++ b/edge/spotter/bin/test_parity @@ -1,9 +1,10 @@ #!/usr/bin/env python3 -"""Multi-device discovery parity tests between discoverynode & Spotter.""" +"""Multi-device discovery & UDMI spec compliance tests for Spotter.""" import datetime import json import os +import re import shutil import subprocess import sys @@ -25,6 +26,9 @@ import paho.mqtt.client as mqtt # pylint: disable=g-import-not-at-top sys.path.insert(0, os.path.join(_workspace_dir, "clientlib/python/src")) sys.path.insert(0, _workspace_dir) +BACNET_POINT_REF_REGEX = re.compile(r"^([A-Z]{2,4})/(0|[1-9][0-9]*)(#[_a-z]+)?$") + + def get_container_engine(): if os.environ.get("CONTAINER_ENGINE"): return os.environ["CONTAINER_ENGINE"] @@ -57,38 +61,18 @@ def datetime_now_iso(): ) -def remove_none_fields(d): - """Recursively removes keys/items with None values.""" - if isinstance(d, dict): - return {k: remove_none_fields(v) for k, v in d.items() if v is not None} - if isinstance(d, list): - return [remove_none_fields(v) for v in d if v is not None] - return d - - -def clean_events(events): - """Normalizes timestamps and generations for payload comparison.""" - cleaned = [] - for event in events: - evt = json.loads(json.dumps(event)) - evt = remove_none_fields(evt) - if "timestamp" in evt: - evt["timestamp"] = "CLEANED" - if "generation" in evt: - evt["generation"] = "CLEANED" - if "version" in evt: - evt["version"] = "CLEANED" - if evt.get("families") and isinstance(evt["families"], dict): - for _, data in evt["families"].items(): - if isinstance(data, dict) and "generation" in data: - data["generation"] = "CLEANED" - # Legacy discovery_node lacked DiscoverySystem name/description fields, - # populating them only in system.ancillary. Strip them for parity comparison. - if evt.get("system") and isinstance(evt["system"], dict): - evt["system"].pop("name", None) - evt["system"].pop("description", None) - cleaned.append(evt) - return cleaned +def find_null_paths(obj, path="$"): + """Recursively finds any JSON paths with None (null) values.""" + nulls = [] + if obj is None: + nulls.append(path) + elif isinstance(obj, dict): + for k, v in obj.items(): + nulls.extend(find_null_paths(v, f"{path}.{k}")) + elif isinstance(obj, list): + for idx, v in enumerate(obj): + nulls.extend(find_null_paths(v, f"{path}[{idx}]")) + return nulls def sort_discovery_events(events): @@ -107,7 +91,7 @@ def sort_discovery_events(events): class TestParity(unittest.TestCase): - """Validates parity between discoverynode and Spotter container scans.""" + """Validates UDMI spec compliance of Spotter and co-existence with legacy node.""" @classmethod def setUpClass(cls): @@ -166,7 +150,6 @@ class TestParity(unittest.TestCase): self.mqtt_port = 18883 self.mqtt_plain_port = 18884 - # 1. Get workspace paths for certificates workspace_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), "../../../") ) @@ -179,7 +162,6 @@ class TestParity(unittest.TestCase): ahu_crt_src = os.path.join(ahu_dir, "rsa_private.crt") ahu_pkcs8_src = os.path.join(ahu_dir, "rsa_private.pkcs8") - # Copy client certs for AHU-1 to config dir for cert_path in [ ca_src, server_crt_src, @@ -206,7 +188,6 @@ class TestParity(unittest.TestCase): ahu_crt_src, os.path.join(self.test_dir.name, "rsa_private.crt") ) - # 2. Start local Mosquitto broker on unprivileged ports self.mosquitto_conf = os.path.join(self.test_dir.name, "mosquitto.conf") with open(self.mosquitto_conf, "w", encoding="utf-8") as f: f.write(f""" @@ -239,7 +220,6 @@ allow_anonymous true log_content = f.read() raise RuntimeError(f"Mosquitto failed to start:\n{log_content}") - # 3. Ensure network exists res = subprocess.run( [CONTAINER_ENGINE, "network", "inspect", "parity-spotter-net"], stdout=subprocess.DEVNULL, @@ -262,7 +242,6 @@ allow_anonymous true except subprocess.CalledProcessError: pass - # 4. Start N simulated BACnet devices self.simulated_devices = [] print( f"\n[TestParity] Starting {PARITY_TEST_NUM_DEVICES} simulated BACnet" @@ -300,7 +279,6 @@ allow_anonymous true time.sleep(3) def tearDown(self): - # Stop simulated devices for cname, proc, _, _ in getattr(self, "simulated_devices", []): subprocess.run( [CONTAINER_ENGINE, "stop", cname], @@ -338,7 +316,7 @@ allow_anonymous true scan_duration_sec=6, settle_time=12, ): - """Executes a container discovery run and collects emitted events.""" + """Executes a container discovery run and collects emitted events & states.""" if self.mosquitto_proc.poll() is not None: self.mosquitto_log_file.close() with open(self.mosquitto_log_path, "r", encoding="utf-8") as f: @@ -346,6 +324,7 @@ allow_anonymous true raise RuntimeError(f"Mosquitto broker died:\n{log_content}") messages = [] + states = [] client = create_mqtt_client() state_received = threading.Event() connected = threading.Event() @@ -353,6 +332,7 @@ allow_anonymous true def on_message(client, userdata, message): # pylint: disable=unused-argument if message.topic.endswith("/state"): + states.append(json.loads(message.payload.decode())) state_received.set() elif message.topic.endswith("/events/discovery"): payload = json.loads(message.payload.decode()) @@ -373,7 +353,6 @@ allow_anonymous true client.subscribe(f"/r/ZZ-TRI-FECTA/d/{client_id}/events/discovery") client.subscribe(f"/r/ZZ-TRI-FECTA/d/{client_id}/state") - # Clean existing container name if running subprocess.run( [CONTAINER_ENGINE, "stop", container_name], stdout=subprocess.DEVNULL, @@ -463,7 +442,7 @@ allow_anonymous true client.loop_stop() client.disconnect() - return messages + return messages, states def _prepare_configs(self): legacy_config = { @@ -516,11 +495,12 @@ allow_anonymous true f.write(json.dumps(spotter_config)) def test_01_bacnet_multi_device_discovery_parity(self): - """Verifies BACnet system discovery parity across N simulated devices.""" + """Verifies BACnet system discovery coverage and UDMI spec compliance.""" self._prepare_configs() - expected_dev_ids = [ - str(dev_id) for _, _, dev_id, _ in self.simulated_devices - ] + expected_devs = { + str(dev_id): ip for _, _, dev_id, ip in self.simulated_devices + } + expected_dev_ids = sorted(expected_devs.keys()) num_devs = len(self.simulated_devices) scan_dur = max(6, 2 + num_devs * 2) @@ -530,7 +510,7 @@ allow_anonymous true f"\n--- [Test 1] Running Legacy Discovery: BACnet depth=system" f" (devices={num_devs}, scan={scan_dur}s, settle={settle_t}s) ---" ) - legacy_events = self.run_discovery_test( + legacy_events, _ = self.run_discovery_test( "test-discovery_node:latest", "parity-legacy-node-system", "DSN-1", @@ -545,7 +525,7 @@ allow_anonymous true f"\n--- [Test 1] Running Spotter Discovery: BACnet depth=system" f" (devices={num_devs}, scan={scan_dur}s, settle={settle_t}s) ---" ) - spotter_events = self.run_discovery_test( + spotter_events, spotter_states = self.run_discovery_test( "udmi-spotter:latest", "parity-spotter-node-system", "DSN-1", @@ -556,35 +536,72 @@ allow_anonymous true settle_time=settle_t, ) - legacy_clean = sort_discovery_events(clean_events(legacy_events)) - spotter_clean = sort_discovery_events(clean_events(spotter_events)) + # 1. Verify zero null fields in raw Spotter state and event payloads + for s_idx, st in enumerate(spotter_states): + null_paths = find_null_paths(st) + self.assertEqual( + null_paths, [], f"Spotter state[{s_idx}] contains nulls: {null_paths}" + ) + for e_idx, evt in enumerate(spotter_events): + null_paths = find_null_paths(evt) + self.assertEqual( + null_paths, + [], + f"Spotter event[{e_idx}] contains nulls: {null_paths}", + ) + + legacy_sorted = sort_discovery_events(legacy_events) + spotter_sorted = sort_discovery_events(spotter_events) print(f"\nDiscovered simulated BACnet device IDs: {expected_dev_ids}") - print(f"Legacy total events: {len(legacy_clean)}") - print(f"Spotter total events: {len(spotter_clean)}") - - # 1. Verify start & stop markers + print(f"Legacy total events: {len(legacy_sorted)}") + print(f"Spotter total events: {len(spotter_sorted)}") + if spotter_states: + print("\n[Spotter Final State Payload]:") + print(json.dumps(spotter_states[-1], indent=2)) + print("\n[Spotter Emitted Discovery Events (depth=system)]:") + print(json.dumps(spotter_sorted, indent=2)) + + # 2. Verify start & stop markers and final state phase/active_count + self.assertTrue(len(spotter_states) > 0, "No Spotter states captured") + final_bacnet_state = ( + spotter_states[-1] + .get("discovery", {}) + .get("families", {}) + .get("bacnet", {}) + ) + self.assertEqual( + final_bacnet_state.get("phase"), + "stopped", + f"Expected final Spotter phase 'stopped', got {final_bacnet_state}", + ) + self.assertEqual( + final_bacnet_state.get("active_count"), + len(expected_devs), + f"Expected final active_count {len(expected_devs)}, got {final_bacnet_state}", + ) self.assertTrue( - any(e.get("event_no") == 0 for e in legacy_clean), + any(e.get("event_no") == 0 for e in legacy_sorted), "Legacy missing start marker 0", ) self.assertTrue( - any(e.get("event_no") == 0 for e in spotter_clean), + any(e.get("event_no") == 0 for e in spotter_sorted), "Spotter missing start marker 0", ) self.assertTrue( - any(e.get("event_no", 0) < 0 for e in legacy_clean), + any(e.get("event_no", 0) < 0 for e in legacy_sorted), "Legacy missing finish marker < 0", ) self.assertTrue( - any(e.get("event_no", 0) < 0 for e in spotter_clean), + any(e.get("event_no", 0) < 0 for e in spotter_sorted), "Spotter missing finish marker < 0", ) + self.assertEqual(len(legacy_sorted), len(spotter_sorted)) - # 2. Verify all simulated devices are present in both - for dev_id in expected_dev_ids: - leg_match = [e for e in legacy_clean if e.get("addr") == dev_id] - spt_match = [e for e in spotter_clean if e.get("addr") == dev_id] + # 3. Verify all simulated devices are discovered and Spotter adheres to spec + for dev_id, expected_ip in expected_devs.items(): + leg_match = [e for e in legacy_sorted if e.get("addr") == dev_id] + spt_match = [e for e in spotter_sorted if e.get("addr") == dev_id] self.assertEqual( len(leg_match), 1, f"Legacy failed to discover device {dev_id}" ) @@ -592,24 +609,43 @@ allow_anonymous true len(spt_match), 1, f"Spotter failed to discover device {dev_id}" ) - # Verify system metadata parity - leg_sys = leg_match[0].get("system", {}) - spt_sys = spt_match[0].get("system", {}) + spt_evt = spt_match[0] + leg_evt = leg_match[0] + + # Verify Spotter families.ipv4 includes both addr and UDP port 47808 + self.assertEqual( + spt_evt.get("families", {}).get("ipv4", {}).get("addr"), expected_ip + ) + self.assertEqual( + spt_evt.get("families", {}).get("ipv4", {}).get("port"), 47808 + ) + + # Verify system block per docs/specs/discovery_bacnet.md Section 3.3 + leg_sys = leg_evt.get("system", {}) + spt_sys = spt_evt.get("system", {}) self.assertEqual(leg_sys.get("hardware"), spt_sys.get("hardware")) - self.assertEqual(leg_sys.get("ancillary"), spt_sys.get("ancillary")) + self.assertIsNotNone(spt_sys.get("name")) + self.assertEqual( + spt_sys.get("name"), leg_sys.get("ancillary", {}).get("name") + ) + self.assertNotIn("name", spt_sys.get("ancillary", {})) + self.assertNotIn("description", spt_sys.get("ancillary", {})) + self.assertIn("firmware-revision", spt_sys.get("ancillary", {})) + self.assertIn( + "application-software-version", spt_sys.get("ancillary", {}) + ) - # 3. Verify total event parity - self.assertEqual( - legacy_clean, spotter_clean, "System discovery events do not match!" + print( + "\nSUCCESS: BACnet multi-device system discovery and UDMI spec" + " compliance verified!" ) - print("\nSUCCESS: BACnet multi-device system discovery parity achieved!") def test_02_bacnet_point_enumeration_parity(self): - """Verifies BACnet point reference enumeration parity across N devices.""" + """Verifies BACnet point reference enumeration and UDMI spec compliance.""" self._prepare_configs() - expected_dev_ids = [ + expected_dev_ids = sorted( str(dev_id) for _, _, dev_id, _ in self.simulated_devices - ] + ) num_devs = len(self.simulated_devices) scan_dur = max(7, 3 + num_devs * 2) @@ -619,7 +655,7 @@ allow_anonymous true f"\n--- [Test 2] Running Legacy Discovery: BACnet depth=refs" f" (devices={num_devs}, scan={scan_dur}s, settle={settle_t}s) ---" ) - legacy_events = self.run_discovery_test( + legacy_events, _ = self.run_discovery_test( "test-discovery_node:latest", "parity-legacy-node-refs", "DSN-1", @@ -631,87 +667,144 @@ allow_anonymous true ) print( - f"\n--- [Test 2] Running Spotter Discovery: BACnet depth=refs" + f"\n--- [Test 2] Running Spotter Discovery: BACnet depth=details" f" (devices={num_devs}, scan={scan_dur}s, settle={settle_t}s) ---" ) - spotter_events = self.run_discovery_test( + spotter_events, spotter_states = self.run_discovery_test( "udmi-spotter:latest", - "parity-spotter-node-refs", + "parity-spotter-node-details", "DSN-1", "/config_dir/spotter_config.json", family="bacnet", - depth="refs", + depth="details", scan_duration_sec=scan_dur, settle_time=settle_t, ) - legacy_clean = sort_discovery_events(clean_events(legacy_events)) - spotter_clean = sort_discovery_events(clean_events(spotter_events)) - - print(f"\nLegacy refs events: {len(legacy_clean)}") - print(f"Spotter refs events: {len(spotter_clean)}") + for s_idx, st in enumerate(spotter_states): + null_paths = find_null_paths(st) + self.assertEqual( + null_paths, + [], + f"Spotter details state[{s_idx}] contains nulls: {null_paths}", + ) + for e_idx, evt in enumerate(spotter_events): + null_paths = find_null_paths(evt) + self.assertEqual( + null_paths, + [], + f"Spotter details event[{e_idx}] contains nulls: {null_paths}", + ) - # 1. Verify markers - self.assertTrue(any(e.get("event_no") == 0 for e in legacy_clean)) - self.assertTrue(any(e.get("event_no") == 0 for e in spotter_clean)) - self.assertTrue(any(e.get("event_no", 0) < 0 for e in legacy_clean)) - self.assertTrue(any(e.get("event_no", 0) < 0 for e in spotter_clean)) + legacy_sorted = sort_discovery_events(legacy_events) + spotter_sorted = sort_discovery_events(spotter_events) + + print(f"\nLegacy refs events: {len(legacy_sorted)}") + print(f"Spotter details events: {len(spotter_sorted)}") + print("\n[Spotter Emitted Discovery Events (depth=details)]:") + print(json.dumps(spotter_sorted, indent=2)) + if spotter_states: + print("\n[Spotter Final State (depth=details)]:") + print(json.dumps(spotter_states[-1], indent=2)) + + # 1. Verify markers and final state phase/active_count + self.assertTrue(len(spotter_states) > 0, "No Spotter states captured") + final_details_state = ( + spotter_states[-1] + .get("discovery", {}) + .get("families", {}) + .get("bacnet", {}) + ) + self.assertEqual( + final_details_state.get("phase"), + "stopped", + f"Expected final Spotter phase 'stopped', got {final_details_state}", + ) + self.assertEqual( + final_details_state.get("active_count"), + len(expected_dev_ids), + f"Expected final active_count {len(expected_dev_ids)}, got {final_details_state}", + ) + self.assertTrue(any(e.get("event_no") == 0 for e in legacy_sorted)) + self.assertTrue(any(e.get("event_no") == 0 for e in spotter_sorted)) + self.assertTrue(any(e.get("event_no", 0) < 0 for e in legacy_sorted)) + self.assertTrue(any(e.get("event_no", 0) < 0 for e in spotter_sorted)) + + # 2. Verify all simulated devices and canonical BACnet refs + expected_spotter_points = { + "AI/0": ("AI:0", "analog-input", False), + "AV/0": ("AV:0", "analog-value", True), + "BI/0": ("BI:0", "binary-input", False), + "MSV/0": ("MSV:0", "multi-state-value", True), + } - # 2. Verify all simulated devices are present and have points enumerated - expected_points = {"AI:0", "AV:0", "BI:0", "MSV:0"} for dev_id in expected_dev_ids: - leg_match = [e for e in legacy_clean if e.get("addr") == dev_id] - spt_match = [e for e in spotter_clean if e.get("addr") == dev_id] + leg_match = [e for e in legacy_sorted if e.get("addr") == dev_id] + spt_match = [e for e in spotter_sorted if e.get("addr") == dev_id] self.assertEqual(len(leg_match), 1, f"Legacy missing device {dev_id}") self.assertEqual(len(spt_match), 1, f"Spotter missing device {dev_id}") leg_refs = leg_match[0].get("refs", {}) spt_refs = spt_match[0].get("refs", {}) + for ref_key in spt_refs: + self.assertRegex( + ref_key, + BACNET_POINT_REF_REGEX, + f"Spotter ref key {ref_key} violates canonical / format", + ) + self.assertTrue( - expected_points.issubset(set(leg_refs.keys())), - f"Legacy missing expected points on {dev_id}", - ) - self.assertTrue( - expected_points.issubset(set(spt_refs.keys())), - f"Spotter missing expected points on {dev_id}", + set(expected_spotter_points.keys()).issubset(set(spt_refs.keys())), + f"Spotter missing expected points on {dev_id}: {set(spt_refs.keys())}", ) - # Verify point attributes parity (name, type, description, units, possible_values) - for pt_id in expected_points: - lp = leg_refs[pt_id] - sp = spt_refs[pt_id] + for spt_id, (leg_id, exp_type, exp_writable) in ( + expected_spotter_points.items() + ): + lp = leg_refs[leg_id] + sp = spt_refs[spt_id] self.assertEqual( lp.get("name"), sp.get("name"), - f"Point {pt_id} name mismatch on {dev_id}", + f"Point {spt_id} name mismatch on {dev_id}", ) self.assertEqual( - lp.get("type"), sp.get("type"), - f"Point {pt_id} type mismatch on {dev_id}", + exp_type, + f"Point {spt_id} type mismatch on {dev_id}", + ) + self.assertEqual( + sp.get("writable"), + exp_writable, + f"Point {spt_id} writable mismatch on {dev_id}", ) self.assertEqual( lp.get("description"), sp.get("description"), - f"Point {pt_id} description mismatch on {dev_id}", + f"Point {spt_id} description mismatch on {dev_id}", + ) + self.assertIn( + "present-value", + sp.get("ancillary", {}), + f"Point {spt_id} missing present-value in ancillary", ) if "units" in lp: self.assertEqual( lp.get("units"), sp.get("units"), - f"Point {pt_id} units mismatch on {dev_id}", + f"Point {spt_id} units mismatch on {dev_id}", ) - if "possible_values" in lp: - self.assertEqual( - lp.get("possible_values"), - sp.get("possible_values"), - f"Point {pt_id} possible_values mismatch on {dev_id}", + if spt_id in ("BI/0", "MSV/0"): + self.assertTrue( + isinstance(sp.get("possible_values"), list) + and len(sp["possible_values"]) >= 2, + f"Point {spt_id} missing possible_values list on {dev_id}", ) print( - "\nSUCCESS: BACnet point reference enumeration parity achieved across" - " all devices!" + "\nSUCCESS: BACnet point reference enumeration and UDMI spec" + " compliance verified across all devices!" ) diff --git a/edge/spotter/bin/test_pcap b/edge/spotter/bin/test_pcap index db43346f6a..4187e50bda 100755 --- a/edge/spotter/bin/test_pcap +++ b/edge/spotter/bin/test_pcap @@ -7,10 +7,10 @@ WORKSPACE_DIR=$(realpath "$SCRIPT_DIR/../../../") if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then echo "Usage: ./test_pcap" echo "" - echo "Validates remote-triggered PCAP packet capture diagnostics over MQTT streaming:" + echo "Validates remote-triggered PCAP packet capture diagnostics over MQTT upload/discovery streaming:" echo "1. Starts Mosquitto broker and udmi-spotter container." echo "2. Generates dummy traffic and publishes a Discovery TRACE configuration (depth: 'trace')." - echo "3. Asserts sequential StreamsEvents chunks over events/streams and parses PCAP magic headers." + echo "3. Asserts sequential DiscoveryUpload chunks (0, 1..N, -(N+1)) over upload/discovery and verifies sha256 & PCAP magic headers." echo "4. Verifies Level 200 status reports in the container's discovery state." echo "" echo "Prerequisites:" @@ -109,7 +109,7 @@ cp "$AHU_CRT_SRC" "$TEST_DIR/rsa_private.crt" echo "Starting mosquitto broker with dual listeners" MOSQ_CONF="$TEST_DIR/mosquitto.conf" cat < "$MOSQ_CONF" -listener 1883 0.0.0.0 +listener 18884 127.0.0.1 allow_anonymous true listener 18883 0.0.0.0 @@ -120,7 +120,9 @@ require_certificate true allow_anonymous true EOF -sudo systemctl stop mosquitto >/dev/null 2>&1 || true +if [[ $(id -u) == 0 ]]; then + systemctl stop mosquitto >/dev/null 2>&1 || true +fi pkill -9 mosquitto >/dev/null 2>&1 || true sleep 0.5 @@ -157,12 +159,12 @@ cat < "$TEST_DIR/spotter_config.json" } EOF -echo "Setting up MQTT subscriber on port 1883 for state and stream event messages" +echo "Setting up MQTT subscriber on port 18884 for state and upload/discovery messages" MQTT_OUT="$TEST_DIR/mqtt.out" touch "$MQTT_OUT" -mosquitto_sub -h 127.0.0.1 -p 1883 \ +mosquitto_sub -h 127.0.0.1 -p 18884 \ -t "/r/ZZ-TRI-FECTA/d/DSN-1/state" \ - -t "/r/ZZ-TRI-FECTA/d/DSN-1/events/streams" \ + -t "/r/ZZ-TRI-FECTA/d/DSN-1/upload/discovery" \ -F "%t %p" > "$MQTT_OUT" & MOSQ_SUB_PID=$! @@ -194,7 +196,7 @@ if [[ $DEVICE_ONLINE -eq 0 ]]; then fi echo "Preparing discovery TRACE trigger config" -TIMESTAMP="2026-07-08T14:35:00Z" +TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ") cat < "$TEST_DIR/config_payload.json" { @@ -202,13 +204,11 @@ cat < "$TEST_DIR/config_payload.json" "version": "1.5.7", "discovery": { "families": { - "ether": { + "bacnet": { "generation": "$TIMESTAMP", "depth": "trace", "scan_duration_sec": 4, "trace": { - "interface": "any", - "filter": "udp port 47808", "max_bytes": 100000 } } @@ -229,9 +229,9 @@ echo "Starting dummy UDP traffic thread" TRAFFIC_PID=$! echo "Publishing discovery TRACE config to trigger packet capture over MQTT..." -mosquitto_pub -h 127.0.0.1 -p 1883 -t "/r/ZZ-TRI-FECTA/d/DSN-1/config" -f "$TEST_DIR/config_payload.json" -q 1 +mosquitto_pub -h 127.0.0.1 -p 18884 -t "/r/ZZ-TRI-FECTA/d/DSN-1/config" -f "$TEST_DIR/config_payload.json" -q 1 -echo "Waiting for discovery state 'stopped' and stream transfers" +echo "Waiting for discovery state 'stopped' and upload/discovery terminal EOF marker" END_TIME=$((SECONDS + 25)) STATE_STOPPED=0 PCAP_DONE=0 @@ -243,10 +243,9 @@ while [[ $SECONDS -lt $END_TIME ]]; do fi fi - if grep -q '/events/streams' "$MQTT_OUT"; then - TOTAL=$(grep '/events/streams' "$MQTT_OUT" | head -n 1 | sed 's|^[^ ]* ||' | jq -r '.total_chunks') - COUNT=$(grep '/events/streams' "$MQTT_OUT" | wc -l) - if [[ -n "$TOTAL" && "$TOTAL" != "null" && $COUNT -ge $TOTAL ]]; then + if grep -q '/upload/discovery' "$MQTT_OUT"; then + LAST_EVT_NO=$(grep '/upload/discovery' "$MQTT_OUT" | tail -n 1 | sed 's|^[^ ]* ||' | jq -r '.event_no') + if [[ -n "$LAST_EVT_NO" && "$LAST_EVT_NO" != "null" && "$LAST_EVT_NO" -lt 0 ]]; then PCAP_DONE=1 fi fi @@ -265,20 +264,20 @@ if [[ $STATE_STOPPED -eq 0 ]]; then exit 1 fi if [[ $PCAP_DONE -eq 0 ]]; then - echo "ERROR: Test timed out waiting for PCAP streaming chunks over MQTT events/streams" + echo "ERROR: Test timed out waiting for PCAP streaming chunks over MQTT upload/discovery" exit 1 fi echo "Validating state and payload" -if grep '/state' "$MQTT_OUT" | tail -n 1 | sed 's|^[^ ]* ||' | jq -e '.discovery.families.ether.status.level != 200' >/dev/null 2>&1; then - STATUS_VAL=$(grep '/state' "$MQTT_OUT" | tail -n 1 | sed 's|^[^ ]* ||' | jq -r '.discovery.families.ether.status') - echo "ERROR: Discovery family state reported non-200 level: $STATUS_VAL" +if grep '/state' "$MQTT_OUT" | tail -n 1 | sed 's|^[^ ]* ||' | jq -e '.discovery.families.bacnet.status.level != 200 or .discovery.families.bacnet.status.category != "discovery.family.scan"' >/dev/null 2>&1; then + STATUS_VAL=$(grep '/state' "$MQTT_OUT" | tail -n 1 | sed 's|^[^ ]* ||' | jq -r '.discovery.families.bacnet.status') + echo "ERROR: Discovery family state reported invalid status: $STATUS_VAL" exit 1 fi echo "Reassembling pcap payload using reassemble_pcap utility" -grep '/events/streams' "$MQTT_OUT" | sed 's|^[^ ]* ||' > "$TEST_DIR/stream_events.json" -"${SCRIPT_DIR}/reassemble_pcap" "$TEST_DIR/stream_events.json" "$TEST_DIR/assembled.pcap" +grep '/upload/discovery' "$MQTT_OUT" | sed 's|^[^ ]* ||' > "$TEST_DIR/upload_discovery_events.json" +"${SCRIPT_DIR}/reassemble_pcap" "$TEST_DIR/upload_discovery_events.json" "$TEST_DIR/assembled.pcap" --manifest "$TEST_DIR/scan_manifest.json" echo "Validating pcap payload size" SIZE=$(stat -c%s "$TEST_DIR/assembled.pcap") diff --git a/edge/spotter/src/agent.py b/edge/spotter/src/agent.py index 8a87f7409d..e3697ef46f 100644 --- a/edge/spotter/src/agent.py +++ b/edge/spotter/src/agent.py @@ -5,6 +5,7 @@ """ import argparse +from datetime import datetime, timezone import hashlib import json import logging @@ -16,13 +17,30 @@ import time from typing import Any, Dict, Optional +def _early_signal_handler(signum: int, frame: Any) -> None: + """Handles SIGINT/SIGTERM even if received during initial module imports in PID 1.""" + del frame + print( + f"Starting UDMI Spotter Unified Agent - Signal {signum} received. Shutting down Spotter...", + flush=True, + ) + sys.exit(0) + + +if __name__ == "__main__": + signal.signal(signal.SIGINT, _early_signal_handler) + signal.signal(signal.SIGTERM, _early_signal_handler) + from udmi.core.factory import ClientConfig, create_device from udmi.core.managers import LocalnetManager from udmi.core.messaging.mqtt_messaging_client import TlsConfig from udmi.schema import ( AuthProvider, Basic, + Config, + Depth, EndpointConfiguration, + Entry, Jwt, Protocol, StateSystemHardware, @@ -36,7 +54,7 @@ ) from manager.discovery import SpotterDiscoveryManager from manager.system import SpotterSystemManager - from providers.bacnet import BacnetFamilyProvider + from providers.bacnet import BACNET_DEVICE_ID, BacnetFamilyProvider from providers.ether import EtherFamilyProvider from providers.passive import PassiveFamilyProvider except ImportError: @@ -46,13 +64,18 @@ ) from edge.spotter.src.manager.discovery import SpotterDiscoveryManager from edge.spotter.src.manager.system import SpotterSystemManager - from edge.spotter.src.providers.bacnet import BacnetFamilyProvider + from edge.spotter.src.providers.bacnet import ( + BACNET_DEVICE_ID, + BacnetFamilyProvider, + ) from edge.spotter.src.providers.ether import EtherFamilyProvider from edge.spotter.src.providers.passive import PassiveFamilyProvider LOGGER = logging.getLogger("spotter_agent") +VALID_UDMI_DEPTHS = frozenset(d.value for d in Depth) + def merge_dicts( base: Dict[str, Any], override: Dict[str, Any] @@ -82,6 +105,9 @@ def load_config(config_file: str) -> Dict[str, Any]: Returns: The merged configuration dictionary. + + Raises: + ValueError: If an overlay JSON file is malformed. """ with open(config_file, "r", encoding="utf-8") as f: config = json.load(f) @@ -105,31 +131,29 @@ def load_config(config_file: str) -> Dict[str, Any]: overlay = json.load(f) config = merge_dicts(config, overlay) except (json.JSONDecodeError, OSError) as err: - LOGGER.warning( + LOGGER.error( "Failed to load config overlay from %s: %s", extra_file, err ) + raise ValueError( + f"Failed to load config overlay from {extra_file}: {err}" + ) from err return config -LEGACY_DEPTH_MAP: Dict[str, str] = { - "ping": "entries", - "ports": "details", - "services": "parts", -} +def validate_discovery_config(payload: Dict[str, Any]) -> Dict[str, Any]: + """Validates that discovery depths strictly conform to canonical UDMI Depth enums. - -def normalize_discovery_config(payload: Dict[str, Any]) -> Dict[str, Any]: - """Normalizes legacy discovery depths from discovery_node configs. - - Maps legacy depth strings ('ping', 'ports', 'services') to canonical - UDMI depth enums ('entries', 'details', 'parts') for families and - enumerations. + Rejects non-canonical or legacy depth strings (such as 'ping', 'ports', + 'services') rather than silently remapping them. Args: payload: Raw configuration dictionary from MQTT config channel. Returns: - The normalized dictionary with canonical depth enums. + The validated configuration dictionary. + + Raises: + ValueError: If any family or enumeration specifies a non-canonical depth. """ if not isinstance(payload, dict): return payload @@ -138,37 +162,32 @@ def normalize_discovery_config(payload: Dict[str, Any]) -> Dict[str, Any]: families = discovery.get("families") if isinstance(families, dict): for fam_name, fam_conf in families.items(): - if isinstance(fam_conf, dict) and "depth" in fam_conf: + if isinstance(fam_conf, dict) and fam_conf.get("depth") is not None: raw_depth = fam_conf["depth"] + depth_str = getattr(raw_depth, "value", raw_depth) if ( - isinstance(raw_depth, str) - and raw_depth.lower() in LEGACY_DEPTH_MAP + not isinstance(depth_str, str) + or depth_str not in VALID_UDMI_DEPTHS ): - canonical = LEGACY_DEPTH_MAP[raw_depth.lower()] - LOGGER.info( - "Normalizing legacy discovery depth '%s' -> '%s' for family" - " '%s'", - raw_depth, - canonical, - fam_name, + raise ValueError( + f"Invalid discovery depth {raw_depth!r} for family" + f" '{fam_name}'. Allowed canonical UDMI depths:" + f" {sorted(VALID_UDMI_DEPTHS)}" ) - fam_conf["depth"] = canonical enumerations = discovery.get("enumerations") if isinstance(enumerations, dict): for enum_field, enum_val in enumerations.items(): - if ( - isinstance(enum_val, str) - and enum_val.lower() in LEGACY_DEPTH_MAP - ): - canonical = LEGACY_DEPTH_MAP[enum_val.lower()] - LOGGER.info( - "Normalizing legacy discovery depth '%s' -> '%s' for" - " enumeration '%s'", - enum_val, - canonical, - enum_field, - ) - enumerations[enum_field] = canonical + if enum_val is not None: + depth_str = getattr(enum_val, "value", enum_val) + if ( + not isinstance(depth_str, str) + or depth_str not in VALID_UDMI_DEPTHS + ): + raise ValueError( + f"Invalid enumeration depth {enum_val!r} for" + f" '{enum_field}'. Allowed canonical UDMI depths:" + f" {sorted(VALID_UDMI_DEPTHS)}" + ) return payload @@ -189,7 +208,6 @@ def resolve_config_path( if base_dir and not os.path.isabs(path): return os.path.normpath(os.path.join(base_dir, path)) if base_dir and os.path.isabs(path) and not os.path.exists(path): - # Check if basename or relative sub-path exists under base_dir rel_candidate = os.path.normpath( os.path.join(base_dir, os.path.basename(path)) ) @@ -406,12 +424,9 @@ def handle_signal(signum, frame): client_config = ClientConfig(tls_config=tls_config) # Initialize Managers with cleanly constructed SystemState - metrics_rate_sec = int( - config.get("system", {}).get("metrics_rate_sec", 300) - ) - circuit_breaker_mem_pct = float( - config.get("system", {}).get("circuit_breaker_mem_pct", 85.0) - ) + sys_cfg = config.get("system", {}) + metrics_rate_sec = int(sys_cfg.get("metrics_rate_sec", 300)) + circuit_breaker_mem_pct = float(sys_cfg.get("circuit_breaker_mem_pct", 85.0)) os_info = get_host_os_info() os_name = ( @@ -426,12 +441,16 @@ def handle_signal(signum, frame): or "unknown" ) if os_info else "unknown" - hw_config = config.get("system", {}).get("hardware", {}) + hw_config = sys_cfg.get("hardware", {}) hw_probed = get_host_hardware_info() make = hw_config.get("make") or hw_probed.get("make") or "UDMI" model = hw_config.get("model") or hw_probed.get("model") or "Spotter" + serial_no = sys_cfg.get("serial_no") or ( + args.serial_no if args.serial_no and args.serial_no != "NA" else None + ) initial_system_state = SystemState( + serial_no=serial_no, hardware=StateSystemHardware(make=make, model=model), software={"os": os_name, "os_version": os_version}, ) @@ -457,14 +476,21 @@ def is_truthy(val: Any) -> bool: ipv4_enabled = is_truthy(discovery_cfg.get("ipv4", True)) localnet_manager = LocalnetManager() + ip_cfg = config.get("ip", {}) + subnet_filter = ip_cfg.get("subnet_filter") if bacnet_enabled: bacnet_cfg = config.get("bacnet", {}) bacnet_ip = bacnet_cfg.get("ip") bacnet_port = bacnet_cfg.get("port") + bacnet_dev_id = int(bacnet_cfg.get("device_id") or BACNET_DEVICE_ID) localnet_manager.register_provider( "bacnet", - BacnetFamilyProvider(bacnet_ip=bacnet_ip, bacnet_port=bacnet_port), + BacnetFamilyProvider( + bacnet_ip=bacnet_ip, + bacnet_port=bacnet_port, + bacnet_device_id=bacnet_dev_id, + ), ) if ether_enabled: @@ -473,14 +499,16 @@ def is_truthy(val: Any) -> bool: ping_concurrency = int(ether_cfg.get("ping_concurrency", 4)) except (ValueError, TypeError): ping_concurrency = 4 + ether_subnet = ether_cfg.get("ip") or subnet_filter localnet_manager.register_provider( "ether", - EtherFamilyProvider(ping_concurrency=ping_concurrency), + EtherFamilyProvider( + ping_concurrency=ping_concurrency, + subnet_filter=ether_subnet, + ), ) if ipv4_enabled: - ip_cfg = config.get("ip", {}) - subnet_filter = ip_cfg.get("subnet_filter") interface = ip_cfg.get("interface") localnet_manager.register_provider( "ipv4", @@ -501,14 +529,31 @@ def is_truthy(val: Any) -> bool: key_file=key_file, ) - # Intercept and normalize legacy discovery depths from legacy - # discovery_node configs. raw_handle_config = device.handle_config def spotter_handle_config( device_id: str, channel: str, payload: Dict[str, Any] ) -> None: - normalize_discovery_config(payload) + try: + validate_discovery_config(payload) + Config.from_dict(payload) + if system_manager.system_state.status is not None: + system_manager.system_state.status = None + except (ValueError, TypeError) as err: + LOGGER.error("Rejected invalid UDMI configuration: %s", err) + now_str = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + if isinstance(payload, dict) and payload.get("timestamp"): + # pylint: disable=protected-access + system_manager._last_config_ts = payload["timestamp"] + system_manager.system_state.status = Entry( + category="system.config.parse", + level=500, + message=str(err), + timestamp=now_str, + ) + device.trigger_state_update(immediate=True) + return + raw_handle_config(device_id, channel, payload) device.handle_config = spotter_handle_config @@ -545,4 +590,3 @@ def spotter_handle_config( if __name__ == "__main__": main() - diff --git a/edge/spotter/src/config_generator.py b/edge/spotter/src/config_generator.py index eb1d3f028b..3523fdc586 100644 --- a/edge/spotter/src/config_generator.py +++ b/edge/spotter/src/config_generator.py @@ -148,28 +148,31 @@ def find_key_cert(target_dir): algorithm = "ES256" if is_ec else "RS256" # Inspect device metadata if available + bacnet_device_id = None metadata_path = os.path.join(device_dir, "metadata.json") if os.path.isfile(metadata_path): try: with open(metadata_path, "r", encoding="utf-8") as f: meta = json.load(f) - auth_type = meta.get("cloud", {}).get("auth_type") or meta.get( - "auth_type" - ) - if auth_type: - if "ES256" in auth_type: - algorithm = "ES256" - elif "RS256" in auth_type: - algorithm = "RS256" - if not bacnet_ip: - bacnet_ip = ( - meta.get("localnet", {}) - .get("families", {}) - .get("bacnet", {}) - .get("ip") - ) - except Exception: # pylint: disable=broad-exception-caught - pass + except (json.JSONDecodeError, OSError) as err: + raise ValueError( + f"Failed to parse device metadata at {metadata_path}: {err}" + ) from err + + auth_type = meta.get("cloud", {}).get("auth_type") or meta.get("auth_type") + if auth_type: + if "ES256" in auth_type: + algorithm = "ES256" + elif "RS256" in auth_type: + algorithm = "RS256" + bacnet_meta = meta.get("localnet", {}).get("families", {}).get("bacnet", {}) + if not bacnet_ip: + bacnet_ip = bacnet_meta.get("ip") + raw_bacnet_addr = bacnet_meta.get("addr") + if raw_bacnet_addr is not None and str(raw_bacnet_addr).isdigit(): + addr_int = int(raw_bacnet_addr) + if 1 <= addr_int <= 4194303: + bacnet_device_id = addr_int ca_file = None if parsed_spec["iot_provider"] == "mqtt": @@ -178,6 +181,8 @@ def find_key_cert(target_dir): bacnet_section = {} if bacnet_ip: bacnet_section["ip"] = bacnet_ip + if bacnet_device_id is not None: + bacnet_section["device_id"] = bacnet_device_id config = { "log_level": "INFO", diff --git a/edge/spotter/src/manager/discovery.py b/edge/spotter/src/manager/discovery.py index 91185b9c01..744ae7b8af 100644 --- a/edge/spotter/src/manager/discovery.py +++ b/edge/spotter/src/manager/discovery.py @@ -1,42 +1,92 @@ """Spotter Unified Discovery Manager. -Extends standard DiscoveryManager to natively handle both active protocol sweeps -(BACnet, Ether, Passive) and TRACE-level packet streaming (PCAP) over -events/streams. +Extends standard DiscoveryManager to natively handle active protocol sweeps +(BACnet, Ether), passive network monitoring (IPv4), self-enumeration, and +TRACE-level packet streaming (PCAP) over upload/discovery. """ import base64 +import copy from datetime import datetime, timedelta, timezone +import gzip +import hashlib +import json import logging +import threading import time -from typing import Any, Dict, Optional +from typing import Any, Dict, List, Optional, Set from udmi.constants import UDMI_VERSION from udmi.core.managers import DiscoveryManager from udmi.schema import ( Config, + DataModel, + DiscoveryConfig, DiscoveryEvents, + DiscoveryUpload, Entry, + Enumerations, + FamilyDiscovery, FamilyDiscoveryConfig, FamilyDiscoveryState, - StreamsEvents, + FeatureDiscovery, + ScanManifest, + State, ) -from udmi.schema.common import Depth +from udmi.schema.common import Depth, Stage from udmi.schema.state_discovery_family import Phase as DiscoveryPhase try: from host_telemetry import check_safety_circuit_breaker - from pcap import capture_packets + from pcap import ( + capture_packets, + extract_routed_networks_from_pcap_chunk, + resolve_gateway_ip, + run_bacnet_trace_whois_rounds, + ) except ImportError: from edge.spotter.src.host_telemetry import check_safety_circuit_breaker - from edge.spotter.src.pcap import capture_packets + from edge.spotter.src.pcap import ( + capture_packets, + extract_routed_networks_from_pcap_chunk, + resolve_gateway_ip, + run_bacnet_trace_whois_rounds, + ) LOGGER = logging.getLogger("spotter_agent") +# Clock skew tolerance (in seconds) for newly issued 'now' scan generations +GENERATION_PAST_TOLERANCE_SEC = 15.0 + + +def strip_none_fields(obj: Any) -> Any: + """Recursively strips None values from dictionaries and lists.""" + if isinstance(obj, dict): + return { + k: strip_none_fields(v) + for k, v in obj.items() + if v is not None + } + if isinstance(obj, list): + return [strip_none_fields(v) for v in obj if v is not None] + return obj + + +if not getattr(DataModel, "_spotter_none_stripping_patched", False): + _orig_to_json = DataModel.to_json + + def _clean_to_json(self: DataModel, *args: Any, **kwargs: Any) -> str: + raw_json = _orig_to_json(self, *args, **kwargs) + cleaned = strip_none_fields(json.loads(raw_json)) + return json.dumps(cleaned) + + DataModel.to_json = _clean_to_json # type: ignore[method-assign] + setattr(DataModel, "_spotter_none_stripping_patched", True) + def _parse_generation(gen_str: Optional[str]) -> Optional[datetime]: """Parses ISO-8601 generation timestamp into timezone-aware datetime.""" - if not gen_str: + if not gen_str or not isinstance(gen_str, str): return None try: clean_str = gen_str.replace("Z", "+00:00") @@ -57,99 +107,381 @@ def _format_generation(dt: datetime) -> str: return dt.strftime("%Y-%m-%dT%H:%M:%SZ") +def _should_enumerate_depth(depth: Any) -> bool: + """Returns True if the enumeration depth is 'entries' or 'details'.""" + if depth is None: + return False + val = getattr(depth, "value", depth) + return str(val).lower() in ("entries", "details") + + class SpotterDiscoveryManager(DiscoveryManager): """Unified Discovery Manager for Spotter. - Extends standard DiscoveryManager to handle active protocol sweeps and - TRACE packet streaming over events/streams with safety circuit breaker checks - and UDMI discovery phase lifecycle tracking (pending/active/stopped). + Handles active protocol sweeps, passive monitoring, self-enumeration, and + TRACE packet streaming over upload/discovery with safety circuit breaker checks + and strict UDMI discovery phase lifecycle tracking (pending/active/stopped). """ def __init__(self, max_mem_pct: float = 85.0) -> None: super().__init__() self.max_mem_pct = max_mem_pct + self._start_time = datetime.now(timezone.utc) self._active_event_counts: Dict[str, int] = {} + self._applied_family_configs: Dict[str, Any] = {} + self._family_providers: Dict[str, Any] = {} + self._trace_stop_events: Dict[str, threading.Event] = {} + + def _stop_family_scan(self, family: str) -> None: + """Stops an active provider scan for the specified family, if running.""" + trace_stop = self._trace_stop_events.pop(family, None) + if trace_stop is not None: + trace_stop.set() + provider = self._family_providers.pop(family, None) + if provider is not None: + try: + provider.stop_scan() + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("Error stopping provider for '%s': %s", family, err) + if provider in self._active_providers: + self._active_providers.remove(provider) + + def _stop_all_family_scans(self) -> None: + """Stops all currently running family scans.""" + for trace_stop in list(self._trace_stop_events.values()): + trace_stop.set() + self._trace_stop_events.clear() + for family in list(self._family_providers.keys()): + self._stop_family_scan(family) + for provider in list(self._active_providers): + try: + provider.stop_scan() + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("Error stopping active provider: %s", err) + self._active_providers.clear() + + def _has_registered_provider(self, family: str) -> bool: + """Checks if a FamilyProvider is registered in LocalnetManager (when wired).""" + if not self._device or not hasattr(self._device, "get_manager"): + return True + # pylint: disable=import-outside-toplevel + from udmi.core.managers.localnet_manager import LocalnetManager + + localnet = self._device.get_manager(LocalnetManager) + if not localnet or not hasattr(localnet, "get_provider"): + return True + return localnet.get_provider(family) is not None + + def _handle_self_enumeration( + self, discovery_cfg: DiscoveryConfig + ) -> bool: + """Handles self-enumeration triggered by config.discovery.generation.""" + enum_gen = getattr(discovery_cfg, "generation", None) + if enum_gen is None: + if self._discovery_state.generation is not None: + self._discovery_state.generation = None + return True + return False + + cur_gen = self._discovery_state.generation + if enum_gen == cur_gen: + return False + + enum_dt = _parse_generation(enum_gen) + cur_dt = _parse_generation(cur_gen) + if cur_dt is not None and enum_dt is not None and enum_dt <= cur_dt: + return False + + self._discovery_state.generation = enum_gen + self._enumerate_capabilities( + generation=enum_gen, + depths=getattr(discovery_cfg, "enumerations", None), + ) + return True + + def _enumerate_capabilities( + self, + generation: Optional[str] = None, + depths: Optional[Enumerations] = None, + ) -> None: + """Publishes a self-enumeration DiscoveryEvents payload per UDMI spec.""" + # pylint: disable=import-outside-toplevel + from udmi.core.managers.localnet_manager import LocalnetManager + + localnet: Optional[LocalnetManager] = None + if self._device and hasattr(self._device, "get_manager"): + localnet = self._device.get_manager(LocalnetManager) + + families_map: Optional[Dict[str, FamilyDiscovery]] = None + features_map: Optional[Dict[str, FeatureDiscovery]] = None + points_map: Optional[Dict[str, Any]] = None + + if depths is not None: + if _should_enumerate_depth(getattr(depths, "families", None)): + reg_families = ( + localnet.get_registered_families() if localnet else [] + ) + families_map = {f: FamilyDiscovery() for f in reg_families} + + if _should_enumerate_depth(getattr(depths, "features", None)): + features_map = { + "discovery.scan": FeatureDiscovery(stage=Stage.stable), + "enumeration": FeatureDiscovery(stage=Stage.stable), + "enumeration.families": FeatureDiscovery(stage=Stage.stable), + "enumeration.features": FeatureDiscovery(stage=Stage.stable), + "system": FeatureDiscovery(stage=Stage.stable), + } + + if _should_enumerate_depth(getattr(depths, "points", None)): + points_map = {} + + event = DiscoveryEvents( + timestamp=_format_generation(datetime.now(timezone.utc)), + version=UDMI_VERSION, + generation=generation, + families=families_map, + features=features_map, + points=points_map, + ) + LOGGER.info( + "Publishing self-enumeration event (generation: %s)", generation + ) + self.publish_event(event, "discovery") def handle_config(self, config: Config) -> None: - """Handles discovery config and marks upcoming generations as pending.""" - super().handle_config(config) - if not self._config or not self._config.families: + """Reconciles discovery configuration, self-enumeration, and family scans.""" + if not config or config.discovery is None: + self._stop_all_family_scans() + self._config = None + self._applied_family_configs.clear() + self._discovery_state.generation = None + self._discovery_state.families = None + self.trigger_state_update() + return + + self._config = config.discovery + if self._discovery_state.families is None: + self._discovery_state.families = {} + + state_updated = self._handle_self_enumeration(config.discovery) + + if config.discovery.families is None: + if self._discovery_state.families: + self._stop_all_family_scans() + self._applied_family_configs.clear() + self._discovery_state.families = {} + state_updated = True + if state_updated: + self.trigger_state_update() return + # Remove families that disappeared from config.discovery.families + configured_keys = set(config.discovery.families.keys()) + for existing_fam in list(self._discovery_state.families.keys()): + if existing_fam not in configured_keys: + self._stop_family_scan(existing_fam) + self._applied_family_configs.pop(existing_fam, None) + self._discovery_state.families.pop(existing_fam, None) + state_updated = True + now_dt = datetime.now(timezone.utc) - state_updated = False - for family, fam_config in self._config.families.items(): + for family, fam_config in config.discovery.families.items(): + prev_cfg = self._applied_family_configs.get(family) f_state = self._discovery_state.families.get(family) - state_gen = f_state.generation if f_state else None + + # Empty or cleared family config stops active/pending scan + if not fam_config or ( + not getattr(fam_config, "generation", None) + and not getattr(fam_config, "scan_interval_sec", None) + and not getattr(fam_config, "passive_sec", None) + ): + if f_state and f_state.phase in ( + DiscoveryPhase.active, + DiscoveryPhase.pending, + ): + self._stop_family_scan(family) + f_state.phase = DiscoveryPhase.stopped + state_updated = True + self._applied_family_configs[family] = copy.deepcopy(fam_config) + continue + + # No-op if family config is unchanged and already tracked in state + if prev_cfg == fam_config and f_state is not None: + continue + + # Config changed for this family: stop any currently running scan first + if f_state and f_state.phase == DiscoveryPhase.active: + self._stop_family_scan(family) + + prev_state_gen = f_state.generation if f_state else None + if not f_state: + f_state = FamilyDiscoveryState() + self._discovery_state.families[family] = f_state + + self._applied_family_configs[family] = copy.deepcopy(fam_config) + + # Validate provider availability if device LocalnetManager is wired + if not self._has_registered_provider(family): + f_state.phase = DiscoveryPhase.stopped + f_state.generation = getattr(fam_config, "generation", None) + f_state.status = Entry( + category="discovery.family.scan", + level=500, + message=f"No provider registered for family '{family}'", + timestamp=_format_generation(now_dt), + ) + state_updated = True + continue + + interval_sec = getattr(fam_config, "scan_interval_sec", None) + duration_sec = getattr(fam_config, "scan_duration_sec", None) if ( - fam_config - and fam_config.generation - and fam_config.generation != state_gen + interval_sec is not None + and duration_sec is not None + and interval_sec > 0 + and duration_sec > interval_sec ): - if not f_state: - f_state = FamilyDiscoveryState() - self._discovery_state.families[family] = f_state - if ( - getattr(f_state, "phase", None) != DiscoveryPhase.active - and not getattr(f_state, "active", False) + f_state.phase = DiscoveryPhase.stopped + f_state.generation = getattr(fam_config, "generation", None) + f_state.status = Entry( + category="discovery.family.scan", + level=500, + message=( + f"scan_duration_sec ({duration_sec}) cannot exceed" + f" scan_interval_sec ({interval_sec})" + ), + timestamp=_format_generation(now_dt), + ) + state_updated = True + continue + + gen_str = getattr(fam_config, "generation", None) + passive_sec = getattr(fam_config, "passive_sec", None) + + # Case 1: Purely passive scan (no generation marker) + if not gen_str and passive_sec and passive_sec > 0: + f_state.generation = None + f_state.status = None + f_state.phase = DiscoveryPhase.pending + state_updated = True + continue + + gen_dt = _parse_generation(gen_str) + if gen_str and gen_dt is None: + f_state.phase = DiscoveryPhase.stopped + f_state.generation = gen_str + f_state.status = Entry( + category="discovery.family.scan", + level=500, + message=f"Invalid generation timestamp: {gen_str!r}", + timestamp=_format_generation(now_dt), + ) + state_updated = True + continue + + # Case 2: Periodic / Recurring scan (generation + scan_interval_sec > 0) + if interval_sec and interval_sec > 0 and gen_dt: + f_state.status = None + if gen_dt > now_dt: + f_state.generation = gen_str + f_state.phase = DiscoveryPhase.pending + else: + elapsed = (now_dt - gen_dt).total_seconds() + cycles = int(elapsed // interval_sec) + target_dt = gen_dt + timedelta(seconds=interval_sec * cycles) + if (now_dt - target_dt).total_seconds() > GENERATION_PAST_TOLERANCE_SEC: + target_dt += timedelta(seconds=interval_sec) + f_state.generation = _format_generation(target_dt) + f_state.phase = DiscoveryPhase.pending + state_updated = True + continue + + # Case 3: Sporadic / One-time active scan + if gen_dt: + prev_gen_dt = _parse_generation(prev_state_gen) + min_allowed_dt = self._start_time - timedelta( + seconds=GENERATION_PAST_TOLERANCE_SEC + ) + if gen_dt < min_allowed_dt or ( + prev_gen_dt is not None and gen_dt < prev_gen_dt ): - gen_dt = _parse_generation(fam_config.generation) - interval_sec = getattr(fam_config, "scan_interval_sec", None) - if gen_dt and gen_dt > now_dt: - f_state.phase = DiscoveryPhase.pending - f_state.generation = fam_config.generation - state_updated = True - elif interval_sec and interval_sec > 0 and gen_dt: - elapsed = (now_dt - gen_dt).total_seconds() - cycles = int(elapsed // interval_sec) - target_dt = gen_dt + timedelta(seconds=interval_sec * cycles) - if (now_dt - target_dt).total_seconds() > 10.0: - target_dt += timedelta(seconds=interval_sec) - f_state.generation = _format_generation(target_dt) - f_state.phase = DiscoveryPhase.pending - state_updated = True - else: - f_state.phase = DiscoveryPhase.pending - f_state.generation = fam_config.generation - state_updated = True + LOGGER.info( + "Skipping stale past generation %s for family '%s' (start_time:" + " %s)", + gen_str, + family, + _format_generation(self._start_time), + ) + f_state.generation = gen_str + f_state.phase = DiscoveryPhase.stopped + f_state.status = None + state_updated = True + continue + + f_state.status = None + f_state.phase = DiscoveryPhase.pending + f_state.generation = gen_str + state_updated = True + + if self._scan_wake_event: + self._scan_wake_event.set() if state_updated: self.trigger_state_update() + def update_state(self, state: State) -> None: + """Contributes discovery state to device state.""" + if self._discovery_state and self._discovery_state.families: + for fam, provider in list(self._family_providers.items()): + f_state = self._discovery_state.families.get(fam) + if f_state is not None: + passive_holdoff = getattr(provider, "passive_holdoff_count", 0) + if passive_holdoff: + f_state.passive_count = passive_holdoff + if self._discovery_state and ( + self._discovery_state.generation is not None + or self._discovery_state.families is not None + ): + state.discovery = self._discovery_state + def _get_check_interval(self) -> float: """Calculates check interval from pending generations and intervals.""" min_wait = 60.0 now_dt = datetime.now(timezone.utc) if self._config and self._config.families: for family, fam_config in self._config.families.items(): - f_state = self._discovery_state.families.get(family) - if ( - f_state - and f_state.phase == DiscoveryPhase.pending - and f_state.generation - ): - target_dt = _parse_generation(f_state.generation) - if target_dt: - diff = (target_dt - now_dt).total_seconds() - if diff > 0: - min_wait = min(min_wait, diff) - else: - min_wait = min(min_wait, 1.0) + f_state = ( + self._discovery_state.families.get(family) + if self._discovery_state.families + else None + ) + if f_state and f_state.phase == DiscoveryPhase.pending: + if f_state.generation: + target_dt = _parse_generation(f_state.generation) + if target_dt: + diff = (target_dt - now_dt).total_seconds() + if diff > 0: + min_wait = min(min_wait, diff) + else: + min_wait = min(min_wait, 1.0) + else: + min_wait = min(min_wait, 1.0) if ( fam_config and fam_config.scan_interval_sec and fam_config.scan_interval_sec > 0 ): min_wait = min(min_wait, float(fam_config.scan_interval_sec)) - return max(1.0, min_wait) + return max(0.5, min_wait) def _update_family_state(self, family: str, active: bool) -> None: - """Updates family active flag and sets UDMI discovery phase.""" + """Updates family UDMI discovery phase and schedules next periodic cycle.""" + if self._discovery_state.families is None: + self._discovery_state.families = {} if family not in self._discovery_state.families: self._discovery_state.families[family] = FamilyDiscoveryState() f_state = self._discovery_state.families[family] - f_state.active = active if active: f_state.phase = DiscoveryPhase.active @@ -169,7 +501,7 @@ def _update_family_state(self, family: str, active: bool) -> None: ) if interval_sec and interval_sec > 0 and not is_error: - # Schedule next recurring generation per UDMI specification + # Schedule next recurring generation per UDMI specification (Ts = Tc + N*Ti) current_dt = _parse_generation(f_state.generation) or datetime.now( timezone.utc ) @@ -189,22 +521,31 @@ def _handle_scan_result(self, device_id: str, event: DiscoveryEvents) -> None: device_id: Discovered device address or identifier. event: Discovered entity event payload. """ - del device_id # Unused; events are published to the local gateway topic. + del device_id # Events are published to the local discovery node's topic. LOGGER.info( - "Discovery event received for device: %s", event.addr or "unknown" + "Discovery event received for device: %s", + event.addr or event.network or "marker", ) if not event.timestamp: - event.timestamp = datetime.now(timezone.utc).isoformat() + event.timestamp = _format_generation(datetime.now(timezone.utc)) if not event.version: event.version = UDMI_VERSION - # Track active count per family (ignoring boundary markers: event_no <= 0) fam = event.family - if fam: + if fam and self._discovery_state.families: + f_state = self._discovery_state.families.get(fam) + if f_state and f_state.generation and event.generation != f_state.generation: + event.generation = f_state.generation + + provider = self._family_providers.get(fam) + if provider is not None and f_state is not None: + passive_holdoff = getattr(provider, "passive_holdoff_count", 0) + if passive_holdoff: + f_state.passive_count = passive_holdoff + if event.event_no is not None: if event.event_no > 0: self._active_event_counts[fam] = event.event_no - f_state = self._discovery_state.families.get(fam) if f_state: f_state.active_count = self._active_event_counts[fam] self.trigger_state_update() @@ -212,7 +553,6 @@ def _handle_scan_result(self, device_id: str, event: DiscoveryEvents) -> None: self._active_event_counts[fam] = ( self._active_event_counts.get(fam, 0) + 1 ) - f_state = self._discovery_state.families.get(fam) if f_state: f_state.active_count = self._active_event_counts[fam] self.trigger_state_update() @@ -221,44 +561,55 @@ def _handle_scan_result(self, device_id: str, event: DiscoveryEvents) -> None: def _should_scan(self, family: str, config: FamilyDiscoveryConfig) -> bool: """Determines whether a discovery scan is due for the given family.""" + if not config: + return False + if self._discovery_state.families is None: + self._discovery_state.families = {} f_state = self._discovery_state.families.get(family) if not f_state: f_state = FamilyDiscoveryState() self._discovery_state.families[family] = f_state + if f_state.phase == DiscoveryPhase.active: + return False + if ( - f_state.phase == DiscoveryPhase.active - or getattr(f_state, "active", False) + f_state.status + and f_state.status.level + and f_state.status.level >= 500 + and f_state.phase == DiscoveryPhase.stopped ): return False gen_str = getattr(config, "generation", None) + passive_sec = getattr(config, "passive_sec", None) now_dt = datetime.now(timezone.utc) gen_dt = _parse_generation(gen_str) state_gen = getattr(f_state, "generation", None) if f_state else None state_gen_dt = _parse_generation(state_gen) - # Standard Protocol sweeps (BACnet, Ether, IPv4) + # Purely passive scan (no generation marker) + if not gen_str and passive_sec and passive_sec > 0: + return f_state.phase != DiscoveryPhase.stopped + + # Periodic / Recurring scan interval_sec = getattr(config, "scan_interval_sec", None) if interval_sec and interval_sec > 0: - # Recurring / Periodic scan if f_state and f_state.phase == DiscoveryPhase.pending and state_gen_dt: return now_dt >= state_gen_dt elif not state_gen_dt: if gen_dt and gen_dt > now_dt: - if f_state: - f_state.generation = gen_str - f_state.phase = DiscoveryPhase.pending + f_state.generation = gen_str + f_state.phase = DiscoveryPhase.pending return False elif gen_dt: elapsed = (now_dt - gen_dt).total_seconds() cycles = int(elapsed // interval_sec) target_dt = gen_dt + timedelta(seconds=interval_sec * cycles) - if (now_dt - target_dt).total_seconds() > 10.0: + if (now_dt - target_dt).total_seconds() > GENERATION_PAST_TOLERANCE_SEC: target_dt += timedelta(seconds=interval_sec) - if f_state: - f_state.generation = _format_generation(target_dt) - f_state.phase = DiscoveryPhase.pending + f_state.generation = _format_generation(target_dt) + f_state.phase = DiscoveryPhase.pending return now_dt >= target_dt else: last_run = self._last_scan_times.get(family, 0) @@ -268,18 +619,23 @@ def _should_scan(self, family: str, config: FamilyDiscoveryConfig) -> bool: return (time.time() - last_run) >= interval_sec # Sporadic / One-off scan - if not gen_str: + if not gen_str or not gen_dt: return False - if ( - gen_str == state_gen - and f_state - and f_state.phase == DiscoveryPhase.stopped - ): + if f_state.phase == DiscoveryPhase.stopped and gen_str == state_gen: return False - if gen_dt and gen_dt > now_dt: - if f_state: - f_state.phase = DiscoveryPhase.pending - f_state.generation = gen_str + + # Reject stale past generations prior to device start window + min_allowed_dt = self._start_time - timedelta( + seconds=GENERATION_PAST_TOLERANCE_SEC + ) + if gen_dt < min_allowed_dt and f_state.phase != DiscoveryPhase.pending: + f_state.generation = gen_str + f_state.phase = DiscoveryPhase.stopped + return False + + if gen_dt > now_dt: + f_state.phase = DiscoveryPhase.pending + f_state.generation = gen_str return False return True @@ -290,6 +646,9 @@ def _run_scan(self, family: str, provider: Any) -> None: family: Discovery family identifier (e.g. 'bacnet', 'ether', 'ipv4'). provider: FamilyProvider instance to execute the scan. """ + if self._discovery_state.families is None: + self._discovery_state.families = {} + if check_safety_circuit_breaker(self.max_mem_pct): LOGGER.warning( "Safety circuit breaker active: Host memory exceeds %.1f%% threshold." @@ -301,20 +660,21 @@ def _run_scan(self, family: str, provider: Any) -> None: if not f_state: f_state = FamilyDiscoveryState() self._discovery_state.families[family] = f_state - f_state.active = False f_state.phase = DiscoveryPhase.stopped f_state.status = Entry( - category="discovery.family", + category="discovery.family.scan", level=400, message=( f"Scan throttled by safety circuit breaker (memory usage exceeds" f" {self.max_mem_pct}%)" ), + timestamp=_format_generation(datetime.now(timezone.utc)), ) if provider in self._active_providers: self._active_providers.remove(provider) + self._family_providers.pop(family, None) self._update_family_state(family, False) - self.trigger_state_update() + self.trigger_state_update(immediate=True) return fam_config = None @@ -328,8 +688,9 @@ def _run_scan(self, family: str, provider: Any) -> None: finally: if provider in self._active_providers: self._active_providers.remove(provider) + self._family_providers.pop(family, None) self._update_family_state(family, False) - self.trigger_state_update() + self.trigger_state_update(immediate=True) return # Standard Protocol Scan @@ -338,33 +699,60 @@ def _run_scan(self, family: str, provider: Any) -> None: f_state = FamilyDiscoveryState() self._discovery_state.families[family] = f_state - f_state.active = True + if ( + not f_state.generation + and fam_config + and getattr(fam_config, "generation", None) + ): + f_state.generation = fam_config.generation + f_state.phase = DiscoveryPhase.active f_state.active_count = 0 self._active_event_counts[family] = 0 - self.trigger_state_update() + self._family_providers[family] = provider + self.trigger_state_update(immediate=True) - LOGGER.info("Scanning family '%s'...", family) + # Build effective scan config carrying the current loop generation and duration + effective_config = copy.copy(fam_config) if fam_config else None + if effective_config is not None: + if f_state.generation: + effective_config.generation = f_state.generation + if ( + getattr(effective_config, "scan_duration_sec", None) is None + and getattr(effective_config, "scan_interval_sec", None) + ): + effective_config.scan_duration_sec = effective_config.scan_interval_sec + + LOGGER.info( + "Scanning family '%s' (generation: %s)...", family, f_state.generation + ) try: - provider.start_scan(fam_config, self._handle_scan_result) + provider.start_scan(effective_config, self._handle_scan_result) LOGGER.info("Scan finished for '%s'.", family) f_state.status = None + passive_holdoff = getattr(provider, "passive_holdoff_count", 0) + if passive_holdoff: + f_state.passive_count = passive_holdoff except Exception as e: # pylint: disable=broad-exception-caught LOGGER.error("Scan failed for '%s': %s", family, e, exc_info=True) err_msg = str(e).strip() or type(e).__name__ f_state.status = Entry( - category="discovery.error", + category="discovery.family.scan", level=500, message=err_msg, + timestamp=_format_generation(datetime.now(timezone.utc)), ) finally: if provider in self._active_providers: self._active_providers.remove(provider) + self._family_providers.pop(family, None) self._update_family_state(family, False) - self.trigger_state_update() + self.trigger_state_update(immediate=True) def _run_trace_capture(self, family: str, fam_config: Any) -> None: - """Executes PCAP capture and streams chunks over events/streams.""" + """Executes PCAP capture, runs raw-socket BACnet Who-Is rounds, and streams chunks over upload/discovery.""" + if self._discovery_state.families is None: + self._discovery_state.families = {} f_state = self._discovery_state.families.get(family) if not f_state: f_state = FamilyDiscoveryState() @@ -375,12 +763,12 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: "Safety circuit breaker active: Throttling trace capture for '%s'.", family, ) - f_state.active = False f_state.phase = DiscoveryPhase.stopped f_state.status = Entry( - category="discovery.family", + category="discovery.family.scan", level=400, message="Trace capture throttled by safety circuit breaker", + timestamp=_format_generation(datetime.now(timezone.utc)), ) return @@ -391,15 +779,23 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: ) if target_gen: f_state.generation = target_gen + if not f_state.generation: + f_state.generation = _format_generation(datetime.now(timezone.utc)) + generation = f_state.generation - f_state.active = True f_state.phase = DiscoveryPhase.active + f_state.active_count = 0 f_state.status = Entry( - category="discovery.family", + category="discovery.family.scan", level=200, message=f"Starting trace capture for family '{family}'...", + timestamp=_format_generation(datetime.now(timezone.utc)), ) - self.trigger_state_update() + self.trigger_state_update(immediate=True) + + whois_stop_event = threading.Event() + self._trace_stop_events[family] = whois_stop_event + whois_thread: Optional[threading.Thread] = None try: trace_cfg = getattr(fam_config, "trace", None) @@ -417,33 +813,12 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: getattr(trace_cfg, "max_bytes", None) or (10 * 1024 * 1024) ) else: - interface = ( - getattr(fam_config, "interface", None) - or ( - fam_config.get("interface") - if isinstance(fam_config, dict) - else None - ) - or "any" - ) - filter_str = ( - getattr(fam_config, "filter", None) - or ( - fam_config.get("filter") - if isinstance(fam_config, dict) - else None - ) - or "" - ) - max_bytes = int( - getattr(fam_config, "max_bytes", None) - or ( - fam_config.get("max_bytes") - if isinstance(fam_config, dict) - else None - ) - or (10 * 1024 * 1024) - ) + interface = "any" + filter_str = "" + max_bytes = 10 * 1024 * 1024 + + if not filter_str and family == "bacnet": + filter_str = "udp port 47808" max_duration_sec = int( getattr(fam_config, "scan_duration_sec", None) @@ -464,80 +839,197 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: max_bytes, ) + # 1. Emit start marker (event_no: 0) over upload/discovery + start_msg = DiscoveryUpload( + timestamp=_format_generation(datetime.now(timezone.utc)), + version=UDMI_VERSION, + generation=generation, + family=family, + event_no=0, + ) + self.publish_upload(start_msg, "discovery") + + discovered_routed_networks: Set[int] = set() + discovered_routers: Set[str] = set() + scan_round_timestamps: List[str] = [] + gateway_ip = resolve_gateway_ip(interface) + + # 2. For BACnet trace, launch paced raw-socket Who-Is discovery rounds + if family == "bacnet": + whois_thread = threading.Thread( + target=run_bacnet_trace_whois_rounds, + kwargs={ + "discovered_routed_networks": discovered_routed_networks, + "scan_round_timestamps": scan_round_timestamps, + "stop_event": whois_stop_event, + "max_duration_sec": max_duration_sec, + "interface": interface, + "src_ip": gateway_ip, + "discovered_routers": discovered_routers, + }, + name="BACnet-Trace-WhoIs", + daemon=True, + ) + whois_thread.start() + + # 3. Stream compressed PCAP chunks incrementally over upload/discovery + chunk_size = 128 * 1024 # 128KB raw chunk threshold before gzip + pending_buf = bytearray() + sha256_hasher = hashlib.sha256() + chunk_count = 0 + total_bytes = 0 + circuit_breaker_tripped = False + + def _emit_compressed_chunk(raw_bytes: bytes) -> None: + nonlocal chunk_count + sha256_hasher.update(raw_bytes) + compressed = gzip.compress(raw_bytes) + b64_data = base64.b64encode(compressed).decode("ascii") + chunk_count += 1 + chunk_msg = DiscoveryUpload( + timestamp=_format_generation(datetime.now(timezone.utc)), + version=UDMI_VERSION, + generation=generation, + family=family, + event_no=chunk_count, + data=b64_data, + ) + self.publish_upload(chunk_msg, "discovery") + f_state.active_count = chunk_count + self.trigger_state_update() + LOGGER.info( + "Published upload/discovery chunk %d (event_no: %d, %d raw bytes ->" + " %d gzip bytes)", + chunk_count, + chunk_count, + len(raw_bytes), + len(compressed), + ) + data_generator = capture_packets( interface=interface, filter_str=filter_str, max_duration_sec=max_duration_sec, max_bytes=max_bytes, + stop_event=whois_stop_event, ) - captured_chunks = [] - for chunk in data_generator: - if check_safety_circuit_breaker(self.max_mem_pct): - LOGGER.warning( - "Safety circuit breaker triggered during trace capture. Halting" - " capture loop." - ) - break - captured_chunks.append(chunk) - full_data = b"".join(captured_chunks) + try: + for chunk in data_generator: + if check_safety_circuit_breaker(self.max_mem_pct): + LOGGER.warning( + "Safety circuit breaker triggered during trace capture. Halting" + " capture loop." + ) + circuit_breaker_tripped = True + break + if not chunk: + continue + total_bytes += len(chunk) + if family == "bacnet": + routed = extract_routed_networks_from_pcap_chunk( + chunk, discovered_routers=discovered_routers + ) + if routed: + discovered_routed_networks.update(routed) + pending_buf.extend(chunk) + while len(pending_buf) >= chunk_size: + slice_bytes = bytes(pending_buf[:chunk_size]) + del pending_buf[:chunk_size] + _emit_compressed_chunk(slice_bytes) + finally: + close_fn = getattr(data_generator, "close", None) + if callable(close_fn): + close_fn() - LOGGER.info( - "Capture complete (%d bytes). Emitting StreamsEvents...", - len(full_data), - ) - chunk_size = 128 * 1024 # 128KB chunks - total_bytes = len(full_data) - total_chunks = ( - (total_bytes + chunk_size - 1) // chunk_size if total_bytes > 0 else 1 - ) - session_id = f"trace-{family}-{int(time.time())}" + if pending_buf: + _emit_compressed_chunk(bytes(pending_buf)) + pending_buf.clear() - for idx in range(total_chunks): - start = idx * chunk_size - end = min(start + chunk_size, total_bytes) - chunk_data = full_data[start:end] - b64_data = base64.b64encode(chunk_data).decode() + whois_stop_event.set() + if whois_thread and whois_thread.is_alive(): + whois_thread.join(timeout=2.0) - chunk_event = StreamsEvents( - timestamp=datetime.now(timezone.utc).isoformat(), - version=UDMI_VERSION, - session_id=session_id, - event_no=idx, - chunk_index=idx, - total_chunks=total_chunks, - data=b64_data, + if circuit_breaker_tripped and chunk_count == 0: + f_state.phase = DiscoveryPhase.stopped + f_state.active_count = 0 + f_state.status = Entry( + category="discovery.family.scan", + level=400, + message="Trace capture throttled by safety circuit breaker", + timestamp=_format_generation(datetime.now(timezone.utc)), ) - self.publish_event(chunk_event, "streams") - LOGGER.info( - "Published stream chunk %d/%d (event_no: %d, %d bytes)", - idx + 1, - total_chunks, - idx, - len(chunk_data), + return + + if total_bytes == 0: + raise RuntimeError( + f"Packet capture on '{interface}' (filter: '{filter_str}') produced" + " 0 bytes" ) - f_state.phase = DiscoveryPhase.stopped - f_state.active_count = total_chunks - f_state.status = Entry( - category="discovery.family", - level=200, - message=( - f"Trace capture complete. {total_chunks} stream chunks emitted." - ), + # 4. Emit mandatory EOF marker (event_no: -(N + 1)) with sha256 and scan_manifest + digest = sha256_hasher.hexdigest() + manifest = ScanManifest( + gateway_ip=gateway_ip, + interface=interface, + filter=filter_str, + scan_round_timestamps=scan_round_timestamps, + discovered_routed_networks=sorted(discovered_routed_networks), + ) + eof_msg = DiscoveryUpload( + timestamp=_format_generation(datetime.now(timezone.utc)), + version=UDMI_VERSION, + generation=generation, + family=family, + event_no=-(chunk_count + 1), + sha256=digest, + scan_manifest=manifest, ) + self.publish_upload(eof_msg, "discovery") + LOGGER.info( + "Capture complete (%d bytes, %d chunks, sha256=%s).", + total_bytes, + chunk_count, + digest, + ) + + f_state.phase = DiscoveryPhase.stopped + f_state.active_count = chunk_count + if circuit_breaker_tripped: + f_state.status = Entry( + category="discovery.family.scan", + level=400, + message=( + "Trace capture throttled by safety circuit breaker after" + f" {chunk_count} upload/discovery chunks." + ), + timestamp=_format_generation(datetime.now(timezone.utc)), + ) + else: + f_state.status = Entry( + category="discovery.family.scan", + level=200, + message=( + f"Trace capture complete. {chunk_count} upload/discovery chunks" + " emitted." + ), + timestamp=_format_generation(datetime.now(timezone.utc)), + ) except Exception as e: # pylint: disable=broad-exception-caught + whois_stop_event.set() + if whois_thread and whois_thread.is_alive(): + whois_thread.join(timeout=1.0) LOGGER.error( "Trace capture failed for family '%s': %s", family, e, exc_info=True ) f_state.phase = DiscoveryPhase.stopped f_state.status = Entry( - category="discovery.family", + category="discovery.family.scan", level=500, message=str(e), + timestamp=_format_generation(datetime.now(timezone.utc)), ) finally: - f_state.active = False + self._trace_stop_events.pop(family, None) self.trigger_state_update() - diff --git a/edge/spotter/src/manager/system.py b/edge/spotter/src/manager/system.py index 6373bd3c5b..5497d11384 100644 --- a/edge/spotter/src/manager/system.py +++ b/edge/spotter/src/manager/system.py @@ -1,6 +1,7 @@ """Spotter custom SystemManager. -Integrates host telemetry and safety circuit breaker. +Integrates host telemetry and safety circuit breaker while ensuring strict +UDMI schema compliance for system state and event payloads. """ from datetime import datetime, timezone @@ -9,7 +10,16 @@ from udmi.constants import UDMI_VERSION from udmi.core.managers import SystemManager -from udmi.schema import Metrics, StateSystemHardware, SystemEvents, SystemState +from udmi.schema import ( + BlobsetState, + Entry, + Metrics, + State, + StateSystemHardware, + StateSystemOperation, + SystemEvents, + SystemState, +) try: import psutil @@ -30,6 +40,15 @@ LOGGER = logging.getLogger("spotter_agent") +def _format_rfc3339(dt: datetime) -> str: + """Formats a datetime into an RFC 3339 UTC string.""" + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + else: + dt = dt.astimezone(timezone.utc) + return dt.strftime("%Y-%m-%dT%H:%M:%SZ") + + class SpotterSystemManager(SystemManager): """Spotter SystemManager incorporating host telemetry. @@ -91,10 +110,57 @@ def set_hardware_info( if model: self._system_state.hardware.model = model + def update_state(self, state: State) -> None: + """Updates the system and blobset blocks in the state object.""" + state.timestamp = _format_rfc3339(datetime.now(timezone.utc)) + self._system_state.last_config = self._last_config_ts + if self._system_state.operation is None: + self._system_state.operation = StateSystemOperation() + self._system_state.operation.operational = True + self._system_state.operation.restart_count = self._restart_count + self._system_state.operation.last_start = _format_rfc3339(self._start_time) + + state.system = self._system_state + + if self._blob_states: + state.blobset = BlobsetState(blobs=self._blob_states) + + def _publish_startup_event(self) -> None: + """Publishes a schema-valid system startup event log.""" + try: + now_str = _format_rfc3339(datetime.now(timezone.utc)) + log_entry = Entry( + category="system.base.ready", + message="Device has started", + level=200, + timestamp=now_str, + ) + startup_event = SystemEvents( + timestamp=now_str, + version=UDMI_VERSION, + logentries=[log_entry], + ) + self.publish_event(startup_event, "system") + except Exception as e: # pylint: disable=broad-exception-caught + LOGGER.error("Failed to publish startup event: %s", e) + + def _report_status( + self, + level: int, + message: str, + category: str = "system.config.apply", + ) -> None: + """Updates the system status entry with required category and timestamp.""" + self._system_state.status = Entry( + category=category, + message=message, + level=level, + timestamp=_format_rfc3339(datetime.now(timezone.utc)), + ) + def publish_metrics(self) -> None: """Publishes system metrics using host telemetry with circuit breaker.""" try: - # Evaluate memory usage against safety threshold if check_safety_circuit_breaker(self.max_mem_pct): LOGGER.warning( "Safety circuit breaker: Memory usage exceeds %.1f%% threshold" @@ -120,11 +186,10 @@ def publish_metrics(self) -> None: ) system_event = SystemEvents( - timestamp=datetime.now(timezone.utc).isoformat(), + timestamp=_format_rfc3339(datetime.now(timezone.utc)), version=UDMI_VERSION, metrics=metrics, ) self.publish_event(system_event, "system") except Exception as e: # pylint: disable=broad-exception-caught LOGGER.error("Failed to publish host metrics: %s", e) - diff --git a/edge/spotter/src/pcap.py b/edge/spotter/src/pcap.py index 28338f18f6..2b7440096c 100644 --- a/edge/spotter/src/pcap.py +++ b/edge/spotter/src/pcap.py @@ -1,11 +1,16 @@ -"""PCAP packet capture wrapper for Spotter.""" +"""PCAP packet capture wrapper and raw-socket BACnet trace scanner for Spotter.""" +from datetime import datetime, timezone +import fcntl import logging import os import select +import socket +import struct import subprocess +import threading import time -from typing import Iterator +from typing import Iterator, List, Optional, Set try: from host_telemetry import check_safety_circuit_breaker @@ -15,14 +20,287 @@ except ImportError: check_safety_circuit_breaker = None +try: + from providers.passive import decode_bacnet_bvll +except ImportError: + try: + from edge.spotter.src.providers.passive import decode_bacnet_bvll + except ImportError: + decode_bacnet_bvll = None + LOGGER = logging.getLogger("spotter_pcap") +BACNET_UDP_PORT = 47808 +GLOBAL_BACNET_DNET = 0xFFFF + + +def build_whois_router_to_network_bvll(unicast: bool = False) -> bytes: + """Builds an unconfirmed BACnet/IP BVLL Who-Is-Router-To-Network frame.""" + # BVLL Type 0x81, Function 0x0a (Unicast) or 0x0b (Broadcast), Length 7 + # NPDU Version 0x01, Control 0x80 (Network Layer Message), MsgType 0x00 (Who-Is-Router-To-Network) + bvlc_func = 0x0A if unicast else 0x0B + return bytes([0x81, bvlc_func, 0x00, 0x07, 0x01, 0x80, 0x00]) + + +def build_whois_bvll(dnet: Optional[int] = None, unicast: bool = False) -> bytes: + """Builds an unconfirmed BACnet/IP BVLL Who-Is frame (local, per-DNET, or global).""" + apdu = b"\x10\x08" # Unconfirmed-Request PDU (0x10), Service Choice 8 (Who-Is) + if dnet is None: + npdu = b"\x01\x00" + else: + if not (1 <= int(dnet) <= 0xFFFF): + raise ValueError(f"Invalid BACnet DNET {dnet!r}: expected 1..65535") + # Control 0x20 (Destination Specifier present), DNET (2B), DLEN=0 (broadcast), HopCount=255 + npdu = b"\x01\x20" + int(dnet).to_bytes(2, "big") + b"\x00\xff" + total_len = 4 + len(npdu) + len(apdu) + bvlc_func = 0x0A if unicast else 0x0B + return bytes([0x81, bvlc_func]) + total_len.to_bytes(2, "big") + npdu + apdu + + +def _compute_udp_checksum( + src_ip: str, dst_ip: str, udp_header_and_payload: bytes +) -> int: + """Computes the RFC 768 16-bit one's complement UDP checksum over IPv4 pseudo-header.""" + if src_ip in ("0.0.0.0", "") or ( + src_ip == "127.0.0.1" and dst_ip != "127.0.0.1" + ): + return 0 + try: + src_packed = socket.inet_aton(src_ip) + dst_packed = socket.inet_aton(dst_ip) + except OSError: + return 0 + if src_packed == b"\x00\x00\x00\x00": + return 0 + + udp_len = len(udp_header_and_payload) + pseudo_header = struct.pack( + "!4s4sBBH", src_packed, dst_packed, 0, socket.IPPROTO_UDP, udp_len + ) + data = pseudo_header + udp_header_and_payload + if len(data) % 2 == 1: + data += b"\x00" + + total = 0 + for i in range(0, len(data), 2): + total += (data[i] << 8) + data[i + 1] + while total >> 16: + total = (total & 0xFFFF) + (total >> 16) + checksum = ~total & 0xFFFF + return 0xFFFF if checksum == 0 else checksum + + +def resolve_gateway_ip(interface: Optional[str] = None) -> str: + """Resolves the local IPv4 address for the gateway or target capture interface.""" + if interface and interface != "any": + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + ifreq = struct.pack("256s", interface[:15].encode("utf-8")) + res = fcntl.ioctl(s.fileno(), 0x8915, ifreq) # SIOCGIFADDR + ip = socket.inet_ntoa(res[20:24]) + if ip and ip != "0.0.0.0": + return ip + except OSError: + pass + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("10.255.255.255", 1)) + return s.getsockname()[0] + except OSError: + return "127.0.0.1" + + +def send_raw_bvll( + pdu: bytes, + dst_ip: str = "255.255.255.255", + src_ip: str = "0.0.0.0", + src_port: int = BACNET_UDP_PORT, + dst_port: int = BACNET_UDP_PORT, + interface: Optional[str] = None, +) -> bool: + """Transmits a BACnet BVLL frame with source port 47808 via raw socket without binding UDP 47808.""" + udp_len = 8 + len(pdu) + header_zero_csum = struct.pack("!HHHH", src_port, dst_port, udp_len, 0) + checksum = _compute_udp_checksum(src_ip, dst_ip, header_zero_csum + pdu) + udp_frame = ( + struct.pack("!HHHH", src_port, dst_port, udp_len, checksum) + pdu + ) + + try: + with socket.socket( + socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP + ) as raw_sock: + raw_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) + if interface and interface != "any" and hasattr(socket, "SO_BINDTODEVICE"): + raw_sock.setsockopt( + socket.SOL_SOCKET, + socket.SO_BINDTODEVICE, + interface.encode("utf-8") + b"\x00", + ) + raw_sock.sendto(udp_frame, (dst_ip, dst_port)) + return True + except OSError as err: + LOGGER.debug("Raw UDP transmit skipped/failed: %s", err) + return False + + +def extract_routed_networks_from_pcap_chunk( + chunk: bytes, + discovered_routers: Optional[Set[str]] = None, +) -> Set[int]: + """Extracts BACnet DNETs and router IPs from I-Am-Router-To-Network and NPDU SNET frames.""" + discovered: Set[int] = set() + if not chunk or decode_bacnet_bvll is None: + return discovered + + idx = 0 + while True: + pos = chunk.find(b"\x81", idx) + if pos < 0 or pos + 7 > len(chunk): + break + bvlc_func = chunk[pos + 1] + if bvlc_func in (0x04, 0x0A, 0x0B): + bvlc_len = int.from_bytes(chunk[pos + 2 : pos + 4], "big") + if 7 <= bvlc_len <= 1500 and pos + bvlc_len <= len(chunk): + outer_ip: Optional[str] = None + outer_port: int = BACNET_UDP_PORT + if ( + pos >= 28 + and (chunk[pos - 28] >> 4) == 4 + and chunk[pos - 19] == socket.IPPROTO_UDP + ): + try: + outer_ip = socket.inet_ntoa(chunk[pos - 16 : pos - 12]) + outer_port = int.from_bytes(chunk[pos - 8 : pos - 6], "big") + except OSError: + outer_ip = None + decoded = decode_bacnet_bvll( + chunk[pos : pos + bvlc_len], + outer_ip=outer_ip, + outer_port=outer_port, + ) + if decoded: + if decoded.iam_router_networks: + discovered.update(decoded.iam_router_networks) + if discovered_routers is not None and decoded.orig_ip: + discovered_routers.add(decoded.orig_ip) + if decoded.snet is not None: + discovered.add(decoded.snet) + if discovered_routers is not None and decoded.orig_ip: + discovered_routers.add(decoded.orig_ip) + idx = pos + 1 + return discovered + + +def run_bacnet_trace_whois_rounds( + discovered_routed_networks: Set[int], + scan_round_timestamps: List[str], + stop_event: threading.Event, + max_duration_sec: int = 7200, + interface: Optional[str] = None, + dst_ip: str = "255.255.255.255", + src_ip: str = "0.0.0.0", + rounds: int = 3, + discovered_routers: Optional[Set[str]] = None, +) -> None: + """Executes paced rounds of raw-socket broadcast and unicast Who-Is-Router-To-Network and Who-Is.""" + scale = min(1.0, max(0.02, float(max_duration_sec) / 60.0)) + router_wait_sec = 2.0 * scale + dnet_pace_sec = 1.0 * scale + global_wait_sec = 15.0 * scale + + for _ in range(rounds): + if stop_event.is_set(): + break + round_ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + scan_round_timestamps.append(round_ts) + + # 1. Local broadcast + unicast Who-Is-Router-To-Network + send_raw_bvll( + pdu=build_whois_router_to_network_bvll(unicast=False), + dst_ip=dst_ip, + src_ip=src_ip, + src_port=BACNET_UDP_PORT, + interface=interface, + ) + for router_ip in sorted(list(discovered_routers or ())): + send_raw_bvll( + pdu=build_whois_router_to_network_bvll(unicast=True), + dst_ip=router_ip, + src_ip=src_ip, + src_port=BACNET_UDP_PORT, + interface=interface, + ) + if stop_event.wait(timeout=router_wait_sec): + break + + # 2. Local Who-Is + paced per-DNET Who-Is (broadcast and unicast to routers) + send_raw_bvll( + pdu=build_whois_bvll(dnet=None, unicast=False), + dst_ip=dst_ip, + src_ip=src_ip, + src_port=BACNET_UDP_PORT, + interface=interface, + ) + for router_ip in sorted(list(discovered_routers or ())): + send_raw_bvll( + pdu=build_whois_bvll(dnet=None, unicast=True), + dst_ip=router_ip, + src_ip=src_ip, + src_port=BACNET_UDP_PORT, + interface=interface, + ) + + for dnet in sorted(list(discovered_routed_networks)): + if stop_event.is_set(): + break + send_raw_bvll( + pdu=build_whois_bvll(dnet=dnet, unicast=False), + dst_ip=dst_ip, + src_ip=src_ip, + src_port=BACNET_UDP_PORT, + interface=interface, + ) + for router_ip in sorted(list(discovered_routers or ())): + send_raw_bvll( + pdu=build_whois_bvll(dnet=dnet, unicast=True), + dst_ip=router_ip, + src_ip=src_ip, + src_port=BACNET_UDP_PORT, + interface=interface, + ) + if stop_event.wait(timeout=dnet_pace_sec): + break + + if stop_event.is_set(): + break + + # 3. Global Who-Is (broadcast and unicast to routers) + send_raw_bvll( + pdu=build_whois_bvll(dnet=GLOBAL_BACNET_DNET, unicast=False), + dst_ip=dst_ip, + src_ip=src_ip, + src_port=BACNET_UDP_PORT, + interface=interface, + ) + for router_ip in sorted(list(discovered_routers or ())): + send_raw_bvll( + pdu=build_whois_bvll(dnet=GLOBAL_BACNET_DNET, unicast=True), + dst_ip=router_ip, + src_ip=src_ip, + src_port=BACNET_UDP_PORT, + interface=interface, + ) + if stop_event.wait(timeout=global_wait_sec): + break + def capture_packets( interface: str, filter_str: str, max_duration_sec: int, max_bytes: int, + stop_event: Optional[threading.Event] = None, ) -> Iterator[bytes]: """Spawns tcpdump to capture packets, yielding chunks of bytes. @@ -63,6 +341,7 @@ def capture_packets( start_time = time.time() total_bytes = 0 stderr_chunks = [] + stopped_by_limit = False # Configure non-blocking I/O if running with real OS file descriptors is_real_fd = False @@ -89,12 +368,16 @@ def capture_packets( rlist.append(proc.stderr) while rlist: + if stop_event is not None and stop_event.is_set(): + stopped_by_limit = True + break elapsed = time.time() - start_time if elapsed >= max_duration_sec: LOGGER.info( "Capture duration limit reached (%ss). Stopping tcpdump...", max_duration_sec, ) + stopped_by_limit = True break remaining_time = max(0.0, max_duration_sec - elapsed) @@ -108,6 +391,7 @@ def capture_packets( "Safety circuit breaker triggered: Throttling packet capture loop" " under memory pressure." ) + stopped_by_limit = True break # 1. Drain stderr to prevent pipe buffer deadlock (>64KB) @@ -137,6 +421,7 @@ def capture_packets( "Capture size limit reached (%s bytes). Stopping tcpdump...", max_bytes, ) + stopped_by_limit = True break elif chunk == b"": rlist.remove(proc.stdout) @@ -147,12 +432,16 @@ def capture_packets( else: # Fallback path for mocked execution environments while True: + if stop_event is not None and stop_event.is_set(): + stopped_by_limit = True + break elapsed = time.time() - start_time if elapsed >= max_duration_sec: LOGGER.info( "Capture duration limit reached (%ss). Stopping tcpdump...", max_duration_sec, ) + stopped_by_limit = True break if check_safety_circuit_breaker and check_safety_circuit_breaker(): @@ -160,6 +449,7 @@ def capture_packets( "Safety circuit breaker triggered: Throttling packet capture" " fallback loop under memory pressure." ) + stopped_by_limit = True break chunk = proc.stdout.read(65536) @@ -177,8 +467,31 @@ def capture_packets( "Capture size limit reached (%s bytes). Stopping tcpdump...", max_bytes, ) + stopped_by_limit = True break + if not stopped_by_limit: + rc = proc.poll() + if rc is None: + try: + rc = proc.wait(timeout=3) + except subprocess.TimeoutExpired: + rc = None + if isinstance(rc, int) and rc != 0: + try: + rem_err = proc.stderr.read() + if rem_err and len(stderr_chunks) < 16: + stderr_chunks.append(rem_err) + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("Error reading remaining tcpdump stderr: %s", err) + full_stderr = b"".join(stderr_chunks) + err_detail = ( + full_stderr.decode(errors="replace").strip() + if isinstance(full_stderr, bytes) and full_stderr + else f"exit code {rc}" + ) + raise RuntimeError(f"tcpdump failed (exit code {rc}): {err_detail}") + finally: # Clean shutdown of subprocess if proc.poll() is None: @@ -196,16 +509,16 @@ def capture_packets( rem_err = proc.stderr.read() if rem_err and len(stderr_chunks) < 16: stderr_chunks.append(rem_err) - except Exception: # pylint: disable=broad-exception-caught - pass + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("Error reading remaining tcpdump stderr: %s", err) try: - if proc.stdout and not proc.stdout.closed: + if proc.stdout: proc.stdout.close() - if proc.stderr and not proc.stderr.closed: + if proc.stderr: proc.stderr.close() - except Exception: # pylint: disable=broad-exception-caught - pass + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("Error closing tcpdump pipes: %s", err) full_stderr = b"".join(stderr_chunks) if full_stderr: diff --git a/edge/spotter/src/providers/bacnet.py b/edge/spotter/src/providers/bacnet.py index bc449526d3..dc00d109f9 100644 --- a/edge/spotter/src/providers/bacnet.py +++ b/edge/spotter/src/providers/bacnet.py @@ -1,20 +1,27 @@ """BACnet Protocol Family Provider for UDMI Spotter.""" import concurrent.futures -import copy +from datetime import datetime, timezone +import ipaddress import logging +import os import re import threading +import time from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple try: import BAC0 from BAC0.core.devices.Device import DeviceDisconnected - from BAC0.core.io.IOExceptions import NoResponseFromController + from BAC0.core.io.IOExceptions import ( + NoResponseFromController, + SegmentationNotSupported, + ) except ImportError: BAC0 = None DeviceDisconnected = () NoResponseFromController = RuntimeError + SegmentationNotSupported = RuntimeError from udmi.core.managers.providers.family_provider import FamilyProvider from udmi.schema import ( @@ -29,41 +36,267 @@ LOGGER = logging.getLogger(__name__) BACNET_DEVICE_ID = 4194300 -_IP_ADDRESS_REGEX = r"([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})" +MAX_BACNET_DEVICE_ID = 4194303 +MAX_BACNET_NETWORK = 65534 +DEFAULT_BACNET_PORT = 47808 +_POSITIVE_INT_REGEX = re.compile(r"^[1-9][0-9]*$") if BAC0: BAC0.log_level("silence") - for name in logging.getLogger().manager.loggerDict: - if name.startswith("BAC0"): - logging.getLogger(name).setLevel(logging.CRITICAL) + for _logger_name in logging.getLogger().manager.loggerDict: + if _logger_name.startswith("BAC0"): + logging.getLogger(_logger_name).setLevel(logging.CRITICAL) -BACNET_ACRONYMS = { +BACNET_ACRONYMS: Dict[str, str] = { "analogInput": "AI", + "analog-input": "AI", "analogOutput": "AO", + "analog-output": "AO", "analogValue": "AV", + "analog-value": "AV", "binaryInput": "BI", + "binary-input": "BI", "binaryOutput": "BO", + "binary-output": "BO", "binaryValue": "BV", + "binary-value": "BV", "loop": "LP", "multiStateInput": "MSI", + "multi-state-input": "MSI", "multiStateOutput": "MSO", + "multi-state-output": "MSO", "multiStateValue": "MSV", + "multi-state-value": "MSV", "characterstringValue": "CSV", + "characterstring-value": "CSV", + "datetimeValue": "DTV", + "datetime-value": "DTV", + "largeAnalogValue": "LAV", + "large-analog-value": "LAV", + "integerValue": "IV", + "integer-value": "IV", + "positiveIntegerValue": "PIV", + "positive-integer-value": "PIV", } +BACNET_STANDARD_TYPES: Dict[str, str] = { + "analogInput": "analog-input", + "analogOutput": "analog-output", + "analogValue": "analog-value", + "binaryInput": "binary-input", + "binaryOutput": "binary-output", + "binaryValue": "binary-value", + "loop": "loop", + "multiStateInput": "multi-state-input", + "multiStateOutput": "multi-state-output", + "multiStateValue": "multi-state-value", + "characterstringValue": "characterstring-value", + "datetimeValue": "datetime-value", + "largeAnalogValue": "large-analog-value", + "integerValue": "integer-value", + "positiveIntegerValue": "positive-integer-value", +} -def _future_wait_and_count_outstanding( - futures: Iterable[concurrent.futures.Future], timeout: int = 1 -) -> int: - """Waits for futures up to timeout and returns incomplete count.""" - _, outstanding = concurrent.futures.wait(futures, timeout) - return len(outstanding) - +OUTPUT_OBJECT_ACRONYMS = frozenset({ + "AO", + "BO", + "MSO", +}) + +VALUE_OBJECT_ACRONYMS = frozenset({ + "AV", + "BV", + "MSV", + "CSV", + "DTV", + "LAV", + "IV", + "PIV", +}) + +WRITABLE_OBJECT_ACRONYMS = OUTPUT_OBJECT_ACRONYMS | VALUE_OBJECT_ACRONYMS + +VALID_BACNET_DEPTHS = frozenset({ + "buckets", + "entries", + "system", + "details", + "refs", + "parts", + "trace", +}) + +BACNET_ANCILLARY_PROP_MAP: Dict[str, str] = { + "statusFlags": "status-flags", + "status-flags": "status-flags", + "status_flags": "status-flags", + "eventState": "event-state", + "event-state": "event-state", + "event_state": "event-state", + "outOfService": "out-of-service", + "out-of-service": "out-of-service", + "out_of_service": "out-of-service", + "reliability": "reliability", + "covIncrement": "cov-increment", + "cov-increment": "cov-increment", + "cov_increment": "cov-increment", + "minPresValue": "min-pres-value", + "min-pres-value": "min-pres-value", + "min_pres_value": "min-pres-value", + "maxPresValue": "max-pres-value", + "max-pres-value": "max-pres-value", + "max_pres_value": "max-pres-value", + "resolution": "resolution", +} DEFAULT_UNCHANGED_THRESHOLD_SEC = 300 +def _now_rfc3339() -> str: + """Returns the current UTC time formatted as RFC 3339 string.""" + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _camel_to_kebab(name: str) -> str: + """Converts a camelCase BACnet identifier into standard hyphenated form.""" + if not name: + return name + return re.sub(r"([a-z0-9])([A-Z])", r"\1-\2", name).lower() + + +def _get_mac_for_ip(ip: str, arp_file: str = "/proc/net/arp") -> Optional[str]: + """Resolves Layer-2 MAC address for a local IPv4 address from ARP table.""" + try: + if os.path.exists(arp_file): + with open(arp_file, "r", encoding="utf-8") as f: + for line in f: + parts = line.split() + if len(parts) >= 4 and parts[0] == ip: + mac = parts[3].upper() + if mac != "00:00:00:00:00:00": + return mac + except OSError as err: + LOGGER.debug("Failed to read ARP cache %s: %s", arp_file, err) + return None + + +def _parse_bacnet_networks( + networks: Optional[Iterable[Any]], +) -> List[int]: + """Validates and parses BACnet network numbers ('1'..'65534').""" + if not networks: + return [] + parsed: List[int] = [] + for net in networks: + net_str = str(net).strip() + if not _POSITIVE_INT_REGEX.match(net_str): + raise ValueError( + f"Invalid BACnet network number {net!r}: must be 1..{MAX_BACNET_NETWORK} with no leading zeroes" + ) + net_val = int(net_str) + if net_val < 1 or net_val > MAX_BACNET_NETWORK: + raise ValueError( + f"BACnet network number {net_val} out of range (1..{MAX_BACNET_NETWORK})" + ) + if net_val not in parsed: + parsed.append(net_val) + return parsed + + +def _parse_bacnet_addrs( + addrs: Optional[Iterable[Any]], +) -> List[Tuple[int, int]]: + """Validates and parses BACnet Device Object Instance numbers or ranges. + + Per docs/specs/discovery_bacnet.md Section 2, each element in `addrs` must be: + - An exact Device Object Instance number ('', 1..4194303), or + - An inclusive hyphen-separated range ('-', 1 <= low <= high <= 4194303) + with no leading zeroes. + """ + if not addrs: + return [] + ranges: List[Tuple[int, int]] = [] + for addr in addrs: + addr_str = str(addr).strip() + if "-" in addr_str: + parts = addr_str.split("-", 1) + if len(parts) != 2 or not ( + _POSITIVE_INT_REGEX.match(parts[0]) + and _POSITIVE_INT_REGEX.match(parts[1]) + ): + raise ValueError( + f"Invalid BACnet target address range {addr!r}: expected '-' (1..{MAX_BACNET_DEVICE_ID})" + ) + low, high = int(parts[0]), int(parts[1]) + if low < 1 or high > MAX_BACNET_DEVICE_ID or low > high: + raise ValueError( + f"Invalid BACnet target address range {addr!r}: must satisfy 1 <= low <= high <= {MAX_BACNET_DEVICE_ID}" + ) + ranges.append((low, high)) + else: + if not _POSITIVE_INT_REGEX.match(addr_str): + raise ValueError( + f"Invalid BACnet target device instance {addr!r}: must be 1..{MAX_BACNET_DEVICE_ID} with no leading zeroes" + ) + inst = int(addr_str) + if inst < 1 or inst > MAX_BACNET_DEVICE_ID: + raise ValueError( + f"BACnet device instance {inst} out of range (1..{MAX_BACNET_DEVICE_ID})" + ) + ranges.append((inst, inst)) + return ranges + + +def _parse_bacnet_device_address( + device_address: Any, + default_port: int = DEFAULT_BACNET_PORT, + arp_file: str = "/proc/net/arp", +) -> Tuple[Optional[str], Dict[str, FamilyDiscovery]]: + """Parses BAC0 device address into (network, families_map). + + Distinguishes BACnet/IP ('' or ':') from routed BACnet + MS/TP or subnetwork addresses (':', e.g. '6100:10'). + """ + raw_addr = str(device_address).strip() + if not raw_addr: + return None, {} + + host_part = raw_addr.split(":", 1)[0] if ":" in raw_addr else raw_addr + suffix = raw_addr.split(":", 1)[1] if ":" in raw_addr else None + + # Case 1: BACnet/IP address ( or :) + try: + ipaddress.IPv4Address(host_part) + port = default_port + if suffix is not None: + try: + port = int(suffix) + except ValueError: + port = default_port + families_map: Dict[str, FamilyDiscovery] = { + "ipv4": FamilyDiscovery(addr=host_part, port=port) + } + mac = _get_mac_for_ip(host_part, arp_file=arp_file) + if mac: + families_map["ethmac"] = FamilyDiscovery(addr=mac) + return None, families_map + except ValueError: + pass + + # Case 2: Routed BACnet address (:, e.g. '6100:10') + if suffix is not None: + network = None + if _POSITIVE_INT_REGEX.match(host_part): + net_val = int(host_part) + if 1 <= net_val <= MAX_BACNET_NETWORK: + network = host_part + families_map = {"mstp": FamilyDiscovery(addr=suffix)} + return network, families_map + + return None, {} + + class BacnetFamilyProvider(FamilyProvider): """Pluggable BACnet protocol discovery provider for Spotter.""" @@ -90,11 +323,11 @@ def __init__( self._lock = threading.Lock() self._devices_published: Set[Tuple[str, Any]] = set() - self._targeted_devices_found: Set[Tuple[str, Any]] = set() self._cancelled = threading.Event() self._scan_thread: Optional[threading.Thread] = None - self._resolver_thread: Optional[threading.Thread] = None self._event_count = 0 + self._active_instance_ranges: List[Tuple[int, int]] = [] + self._active_networks: List[int] = [] def _ensure_bacnet_client(self) -> Any: """Returns cached or new BAC0 client instance in a thread-safe manner.""" @@ -115,6 +348,21 @@ def _ensure_bacnet_client(self) -> Any: ) return self._bacnet + @staticmethod + def _resolve_depth(discovery_config: Any) -> str: + """Resolves and validates the canonical BACnet scan depth.""" + raw_depth = getattr(discovery_config, "depth", None) + depth_val = getattr(raw_depth, "value", raw_depth) + addrs = getattr(discovery_config, "addrs", None) + if depth_val is None: + return "details" if addrs else "entries" + depth_str = str(depth_val).strip().lower() + if depth_str not in VALID_BACNET_DEPTHS: + raise ValueError( + f"Unsupported BACnet discovery depth {depth_val!r}: expected one of {sorted(VALID_BACNET_DEPTHS)}" + ) + return depth_str + def start_scan( self, discovery_config: Any, @@ -123,23 +371,30 @@ def start_scan( """Starts a discovery scan for the BACnet protocol family.""" self._cancelled.clear() self._devices_published.clear() - self._targeted_devices_found.clear() self._event_count = 0 - client = self._ensure_bacnet_client() generation = getattr(discovery_config, "generation", None) - depth = getattr(discovery_config, "depth", "system") + depth_val = self._resolve_depth(discovery_config) addrs = getattr(discovery_config, "addrs", None) + networks = getattr(discovery_config, "networks", None) scan_duration_sec = getattr(discovery_config, "scan_duration_sec", None) + self._active_networks = _parse_bacnet_networks(networks) + self._active_instance_ranges = _parse_bacnet_addrs(addrs) + + client = self._ensure_bacnet_client() + LOGGER.info( "Starting BACnet discovery scan (generation: %s, depth: %s," - " addrs: %s)...", + " networks: %s, addrs: %s)...", generation, - depth, + depth_val, + self._active_networks, addrs, ) + scan_start_mono = time.monotonic() + # Emit start event (event_no: 0) publish_func( "self", @@ -150,40 +405,56 @@ def start_scan( ), ) - if not addrs: - # Reset cached Who-Is results so subsequent scans on the shared BAC0 stack do not replay stale devices. - client.discover(global_broadcast=True, reset=True) - device_producer = self._global_device_producer + if depth_val == "buckets": + self._discover_buckets(client, generation, publish_func) + self.stop_scan() + publish_func( + "self", + DiscoveryEvents( + generation=generation, + family="bacnet", + event_no=-(self._event_count + 1), + ), + ) + return + + # Issue Who-Is discovery according to network and instance range filters + if not self._active_instance_ranges: + if self._active_networks: + client.discover( + networks=self._active_networks, + global_broadcast=True, + reset=True, + ) + else: + client.discover(global_broadcast=True, reset=True) else: - for addr in addrs: - if not re.match(_IP_ADDRESS_REGEX, addr.split(":", maxsplit=1)[0]): - raise RuntimeError( - f"Unsupported BACnet target address format: {addr}" - ) - - self._resolver_thread = threading.Thread( - target=self._resolve_targeted_ips, - args=(copy.copy(addrs),), - name="BACnet-Resolver", - daemon=True, + target_nets: Any = ( + self._active_networks if self._active_networks else "known" + ) + min_low = min(low for low, _ in self._active_instance_ranges) + max_high = max(high for _, high in self._active_instance_ranges) + client.discover( + networks=target_nets, + limits=(min_low, max_high), + global_broadcast=True, + reset=True, ) - self._resolver_thread.start() - device_producer = self._targeted_device_producer self._scan_thread = threading.Thread( target=self._devices_consumer, - args=(device_producer, discovery_config, publish_func), + args=(self._global_device_producer, discovery_config, publish_func), name="BACnet-Consumer", daemon=True, ) self._scan_thread.start() if scan_duration_sec and float(scan_duration_sec) > 0: - timeout = float(scan_duration_sec) + elapsed = time.monotonic() - scan_start_mono + remaining = max(0.5, float(scan_duration_sec) - elapsed) if self._scan_thread: - self._scan_thread.join(timeout=timeout) + self._scan_thread.join(timeout=remaining) else: - # Match legacy discovery node: run until unchanged threshold is reached if self._scan_thread: self._scan_thread.join() @@ -199,53 +470,101 @@ def start_scan( ), ) + def _discover_buckets( + self, + client: Any, + generation: Optional[str], + publish_func: Callable[[str, DiscoveryEvents], None], + ) -> None: + """Discovers available BACnet network buckets and correlated UDP ports.""" + for probe_fn in ("what_is_network_number", "whois_router_to_network"): + fn = getattr(client, probe_fn, None) + if callable(fn): + try: + fn() + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("BACnet bucket probe %s failed: %s", probe_fn, err) + + discovered_nets: List[int] = [] + known = getattr(client, "known_network_numbers", None) + if isinstance(known, (list, set, tuple)): + for net in known: + try: + net_int = int(net) + if 1 <= net_int <= MAX_BACNET_NETWORK and net_int not in discovered_nets: + discovered_nets.append(net_int) + except (ValueError, TypeError): + continue + + if self._active_networks: + if discovered_nets: + discovered_nets = [ + n for n in discovered_nets if n in self._active_networks + ] + else: + discovered_nets = list(self._active_networks) + + default_port = int(self.bacnet_port or DEFAULT_BACNET_PORT) + for net_num in sorted(discovered_nets): + if self._cancelled.is_set(): + break + self._event_count += 1 + event = DiscoveryEvents( + generation=generation, + family="bacnet", + network=str(net_num), + event_no=self._event_count, + families={"ipv4": FamilyDiscovery(port=default_port)}, + ) + publish_func(f"network-{net_num}", event) + def stop_scan(self) -> None: """Stops any active BACnet scan immediately.""" LOGGER.info("Stopping BACnet discovery scan...") self._cancelled.set() - if self._resolver_thread and self._resolver_thread.is_alive(): - self._resolver_thread.join(timeout=1.0) if self._scan_thread and self._scan_thread.is_alive(): self._scan_thread.join(timeout=1.0) - def _resolve_targeted_ips(self, target_ips: List[str]) -> None: - """Resolves BACnet device IDs for targets using thread pool.""" - with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: - futures = [ - executor.submit(self._resolve_single_ip, ip) for ip in target_ips - ] - while _future_wait_and_count_outstanding(futures, timeout=1) > 0: - if self._cancelled.is_set(): - executor.shutdown(wait=True, cancel_futures=True) - break - - def _resolve_single_ip(self, ip_address: str) -> None: - """Queries single IP address for BACnet device object identifier.""" - client = self._ensure_bacnet_client() + def _matches_active_filters(self, address: Any, device_id: Any) -> bool: + """Checks if a discovered BACnet device matches configured scope filters.""" try: - res = client.read( - f"{ip_address} device 4194303 objectIdentifier", None, 0, None, 3 - ) - dev_id = ( - res[1] if isinstance(res, (tuple, list)) and len(res) >= 2 else res - ) - if dev_id: - LOGGER.debug("Resolved BACnet device %s at %s", dev_id, ip_address) - self._targeted_devices_found.add((ip_address, dev_id)) - except Exception: # pylint: disable=broad-exception-caught - pass + dev_id_int = int(device_id) + except (ValueError, TypeError): + return False + + # Never report Spotter's own BACnet client instance ID as a discovered peer + if dev_id_int == int(self.bacnet_device_id): + return False + + if dev_id_int < 1 or dev_id_int > MAX_BACNET_DEVICE_ID: + return False + + if self._active_instance_ranges: + if not any( + low <= dev_id_int <= high + for low, high in self._active_instance_ranges + ): + return False + + if self._active_networks: + net_str, _ = _parse_bacnet_device_address(address) + if net_str is not None and int(net_str) not in self._active_networks: + return False + + return True def _global_device_producer(self) -> Set[Tuple[str, Any]]: - """Returns newly discovered devices from global broadcast.""" + """Returns newly discovered devices matching configured scope filters.""" client = self._ensure_bacnet_client() if client.discoveredDevices is not None: - return set(client.discoveredDevices.keys()) - self._devices_published + candidates = set(client.discoveredDevices.keys()) - self._devices_published + return { + (str(addr), dev_id) + for addr, dev_id in candidates + if self._matches_active_filters(addr, dev_id) + } return set() - def _targeted_device_producer(self) -> Set[Tuple[str, Any]]: - """Returns newly resolved targeted devices.""" - return self._targeted_devices_found - self._devices_published - def _devices_consumer( self, producer: Callable[[], Set[Tuple[str, Any]]], @@ -269,7 +588,7 @@ def _devices_consumer( continue unchanged_seconds = 0 - for device in new_devices: + for device in sorted(new_devices, key=lambda d: int(d[1])): if self._cancelled.is_set(): return address, device_id = device @@ -289,53 +608,86 @@ def _devices_consumer( return self._cancelled.wait(timeout=1.0) + def _read_device_properties( + self, client: Any, device_address: str, device_id: Any + ) -> List[Any]: + """Reads Device Object properties via ReadPropertyMultiple with RP fallback.""" + prop_names = [ + "objectName", + "vendorName", + "firmwareRevision", + "modelName", + "serialNumber", + "description", + "location", + "applicationSoftwareVersion", + "vendorIdentifier", + "protocolVersion", + "protocolRevision", + ] + try: + props = client.readMultiple( + f"{device_address} device {device_id} " + " ".join(prop_names) + ) + if not isinstance(props, (list, tuple)): + props = [props] + padded = list(props) + [None] * max(0, len(prop_names) - len(props)) + return [None if isinstance(x, Exception) else x for x in padded[:11]] + except Exception as err: # pylint: disable=broad-exception-caught + is_seg_err = isinstance(err, SegmentationNotSupported) or ( + "segmentation" in str(err).lower() + ) + if not is_seg_err: + raise + LOGGER.info( + "ReadPropertyMultiple unsupported/segmented on %s/%s; falling back" + " to individual ReadProperty requests.", + device_address, + device_id, + ) + results: List[Any] = [] + any_success = False + last_err: Optional[Exception] = None + for prop in prop_names: + try: + val = client.read(f"{device_address} device {device_id} {prop}") + results.append(val) + any_success = True + except Exception as rp_err: # pylint: disable=broad-exception-caught + last_err = rp_err + results.append(None) + if not any_success and last_err is not None: + raise last_err + return results + def discover_device( self, device_address: str, device_id: Any, discovery_config: Any ) -> DiscoveryEvents: - """Discovers and inspects a single BACnet device.""" + """Discovers and inspects a single BACnet device across configured depth.""" client = self._ensure_bacnet_client() generation = getattr(discovery_config, "generation", None) - depth = getattr(discovery_config, "depth", "system") - depth_val = getattr(depth, "value", depth) + depth_val = self._resolve_depth(discovery_config) - raw_addr = str(device_address) - ip_part = ( - raw_addr.split(":", maxsplit=1)[0] if ":" in raw_addr else raw_addr + default_port = int(self.bacnet_port or DEFAULT_BACNET_PORT) + network, families_map = _parse_bacnet_device_address( + device_address, default_port=default_port ) - port_part = None - if ":" in raw_addr: - try: - port_part = int(raw_addr.split(":", maxsplit=1)[1]) - except ValueError: - port_part = None - - families_map = {"ipv4": FamilyDiscovery(addr=ip_part)} - if port_part and port_part != 47808: - families_map["bacnet"] = FamilyDiscovery(addr=raw_addr, port=port_part) + if network is None and len(self._active_networks) == 1: + network = str(self._active_networks[0]) event = DiscoveryEvents( generation=generation, family="bacnet", addr=str(device_id), - families=families_map, + network=network, + families=families_map if families_map else None, ) - if depth_val in ("system", "refs", "details", "parts"): + if depth_val == "entries": + return event + + if depth_val in ("system", "details", "refs", "parts"): try: - props = client.readMultiple( - f"{device_address} device {device_id}" - " objectName" - " vendorName" - " firmwareRevision" - " modelName" - " serialNumber" - " description" - " location" - " applicationSoftwareVersion" - ) - if not isinstance(props, (list, tuple)): - props = [props] - padded = list(props) + [None] * max(0, 8 - len(props)) ( object_name, vendor_name, @@ -345,28 +697,72 @@ def discover_device( description, location, application_version, - ) = [None if isinstance(x, Exception) else x for x in padded[:8]] - - ancillary_dict = {} - if description: - ancillary_dict["description"] = str(description) - if location: + vendor_identifier, + protocol_version, + protocol_revision, + ) = self._read_device_properties(client, device_address, device_id) + + ancillary_dict: Dict[str, Any] = {} + if firmware_version is not None and str(firmware_version) != "": + ancillary_dict["firmware-revision"] = str(firmware_version) + if application_version is not None and str(application_version) != "": + ancillary_dict["application-software-version"] = str( + application_version + ) + if location is not None and str(location) != "": ancillary_dict["location"] = str(location) - if application_version: - ancillary_dict["application_version"] = str(application_version) - if firmware_version: - ancillary_dict["firmware"] = str(firmware_version) - if object_name: - ancillary_dict["name"] = str(object_name) + if vendor_identifier is not None and str(vendor_identifier) != "": + ancillary_dict["vendor-identifier"] = ( + vendor_identifier + if isinstance(vendor_identifier, (int, float, bool)) + else str(vendor_identifier) + ) + if protocol_version is not None and str(protocol_version) != "": + ancillary_dict["protocol-version"] = ( + protocol_version + if isinstance(protocol_version, (int, float, bool)) + else str(protocol_version) + ) + if protocol_revision is not None and str(protocol_revision) != "": + ancillary_dict["protocol-revision"] = ( + protocol_revision + if isinstance(protocol_revision, (int, float, bool)) + else str(protocol_revision) + ) + + make_str = ( + str(vendor_name) + if vendor_name is not None and str(vendor_name) != "" + else None + ) + model_str = ( + str(model_name) + if model_name is not None and str(model_name) != "" + else None + ) + hw_block = ( + StateSystemHardware(make=make_str, model=model_str) + if (make_str is not None or model_str is not None) + else None + ) event.system = System( - name=str(object_name) if object_name else None, - description=str(description) if description else None, - serial_no=str(serial_number) if serial_number else None, - hardware=StateSystemHardware( - make=str(vendor_name) if vendor_name else "Unknown", - model=str(model_name) if model_name else "Unknown", + name=( + str(object_name) + if object_name is not None and str(object_name) != "" + else None + ), + description=( + str(description) + if description is not None and str(description) != "" + else None + ), + serial_no=( + str(serial_number) + if serial_number is not None and str(serial_number) != "" + else None ), + hardware=hw_block, ancillary=ancillary_dict if ancillary_dict else None, ) except Exception as err: # pylint: disable=broad-exception-caught @@ -378,13 +774,14 @@ def discover_device( ) err_msg = str(err).strip() or type(err).__name__ event.status = Entry( - category="discovery.error", + category="discovery.device.enumerate", level=500, message=f"Property read failed: {err_msg}", + timestamp=_now_rfc3339(), ) return event - if depth_val in ("refs", "parts"): + if depth_val in ("details", "refs", "parts"): try: refs = self.enumerate_refs(f"{device_address} {device_id}") if refs: @@ -398,9 +795,10 @@ def discover_device( ) err_msg = str(err).strip() or type(err).__name__ event.status = Entry( - category="discovery.error", + category="discovery.device.enumerate", level=500, message=f"Point enumeration failed: {err_msg}", + timestamp=_now_rfc3339(), ) return event @@ -417,32 +815,87 @@ def enumerate_refs(self, addr: str) -> Dict[str, RefDiscovery]: device_address, device_id = parts[0], parts[1] try: dev = BAC0.device(device_address, int(device_id), client, poll=0) - # BAC0.device swallows APDU timeouts into DeviceDisconnected or an empty objects_list instead of raising. if isinstance(dev, DeviceDisconnected) or not dev.properties.objects_list: raise NoResponseFromController( f"Failed to connect or read objectList for {device_address}/{device_id}" ) for point in dev.points: + raw_type = str(point.properties.type or "") + point_acronym = BACNET_ACRONYMS.get(raw_type, raw_type.upper()) + std_type = BACNET_STANDARD_TYPES.get(raw_type) or _camel_to_kebab( + raw_type + ) + present_val = getattr(point, "lastValue", None) - ancillary = {} + ancillary: Dict[str, Any] = {} if present_val is not None: - ancillary["present_value"] = str(present_val) + if isinstance(present_val, (int, float, bool, str)): + ancillary["present-value"] = present_val + else: + ancillary["present-value"] = str(present_val) + + bacnet_props = getattr(point.properties, "bacnet_properties", None) + if isinstance(bacnet_props, dict): + for raw_k, canonical_k in BACNET_ANCILLARY_PROP_MAP.items(): + if raw_k in bacnet_props and bacnet_props[raw_k] is not None: + val = bacnet_props[raw_k] + ancillary[canonical_k] = ( + val + if isinstance(val, (int, float, bool, str, list, dict)) + else str(val) + ) + + explicit_writable = getattr(point.properties, "writable", None) + if isinstance(explicit_writable, bool): + writable = explicit_writable + elif point_acronym in OUTPUT_OBJECT_ACRONYMS: + writable = True + elif point_acronym in VALUE_OBJECT_ACRONYMS: + if isinstance(bacnet_props, dict) and any( + k in bacnet_props + for k in ("priorityArray", "priority-array", "priority_array") + ): + pa_val = ( + bacnet_props.get("priorityArray") + if "priorityArray" in bacnet_props + else ( + bacnet_props.get("priority-array") + if "priority-array" in bacnet_props + else bacnet_props.get("priority_array") + ) + ) + writable = pa_val is not None + else: + writable = True + else: + writable = False + desc = point.properties.description ref = RefDiscovery( - name=point.properties.name, - description=point.properties.description, - type=point.properties.type, + name=str(point.properties.name) if point.properties.name else None, + description=( + str(desc) if desc is not None and str(desc) != "" else None + ), + type=std_type if std_type else None, + writable=writable, ancillary=ancillary if ancillary else None, ) - if isinstance(point.properties.units_state, list): - ref.possible_values = point.properties.units_state - elif isinstance(point.properties.units_state, str): - ref.units = point.properties.units_state - point_acronym = BACNET_ACRONYMS.get( - point.properties.type, point.properties.type - ) - point_id = f"{point_acronym}:{point.properties.address}" + units_state = point.properties.units_state + if isinstance(units_state, (list, tuple)): + possible_vals = [ + str(v) for v in units_state if v is not None and str(v) != "" + ] + if possible_vals: + ref.possible_values = possible_vals + elif point_acronym in ("BI", "BO", "BV"): + ref.possible_values = ["inactive", "active"] + elif isinstance(units_state, str) and units_state: + ref.units = units_state + elif point_acronym in ("BI", "BO", "BV"): + ref.possible_values = ["inactive", "active"] + + point_id = f"{point_acronym}/{point.properties.address}" refs[point_id] = ref except Exception as err: LOGGER.warning( @@ -458,10 +911,9 @@ def close(self) -> None: if self._bacnet: try: self._bacnet.disconnect() - except Exception: # pylint: disable=broad-exception-caught - pass + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("Error disconnecting BAC0 client: %s", err) self._bacnet = None def __del__(self) -> None: self.close() - diff --git a/edge/spotter/src/providers/ether.py b/edge/spotter/src/providers/ether.py index 1c9d75e558..72439fa850 100644 --- a/edge/spotter/src/providers/ether.py +++ b/edge/spotter/src/providers/ether.py @@ -2,12 +2,14 @@ import concurrent.futures import dataclasses +import ipaddress import logging import os +import socket import subprocess import threading import time -from typing import Any, Callable, Dict, List, Optional +from typing import Any, Callable, Dict, Iterator, List, Optional import xml.etree.ElementTree as ET from udmi.core.managers.providers.family_provider import FamilyProvider @@ -15,10 +17,23 @@ DiscoveryEvents, FamilyDiscovery, RefDiscovery, + StateSystemHardware, + System, ) LOGGER = logging.getLogger(__name__) +VALID_ETHER_DEPTHS = frozenset({ + "buckets", + "entries", + "system", + "details", + "parts", + "refs", +}) +MIN_VLAN_ID = 1 +MAX_VLAN_ID = 4094 + @dataclasses.dataclass class PortInfo: @@ -39,72 +54,141 @@ class HostInfo: ip: str mac: Optional[str] = None + mac_vendor: Optional[str] = None + hostname: Optional[str] = None + os_name: Optional[str] = None ports: List[PortInfo] = dataclasses.field(default_factory=list) -def parse_nmap_xml(xml_content: str) -> List[HostInfo]: - """Parses nmap XML output into structured HostInfo dataclasses.""" - hosts = [] - try: - root = ET.fromstring(xml_content) - for host_elem in root.findall("host"): - status_elem = host_elem.find("status") - if status_elem is not None and status_elem.get("state") != "up": - continue - - address_elem = host_elem.find("address[@addrtype='ipv4']") - if address_elem is None: - continue - ip = address_elem.get("addr") - - mac_elem = host_elem.find("address[@addrtype='mac']") - mac = ( - mac_elem.get("addr").lower() - if mac_elem is not None and mac_elem.get("addr") - else None +def _parse_host_element(host_elem: ET.Element) -> Optional[HostInfo]: + """Extracts a HostInfo record from a completed XML element.""" + status_elem = host_elem.find("status") + if status_elem is not None and status_elem.get("state") != "up": + return None + + address_elem = host_elem.find("address[@addrtype='ipv4']") + if address_elem is None: + address_elem = host_elem.find("address") + if address_elem is None or not address_elem.get("addr"): + return None + ip = address_elem.get("addr") + + mac_elem = host_elem.find("address[@addrtype='mac']") + mac = ( + mac_elem.get("addr").lower() + if mac_elem is not None and mac_elem.get("addr") + else None + ) + mac_vendor = ( + mac_elem.get("vendor") + if mac_elem is not None and mac_elem.get("vendor") + else None + ) + + hostname_elem = host_elem.find("hostnames/hostname") + if hostname_elem is None: + hostname_elem = host_elem.find("hostname") + hostname = ( + hostname_elem.get("name") + if hostname_elem is not None and hostname_elem.get("name") + else None + ) + + osmatch_elem = host_elem.find("os/osmatch") + os_name = ( + osmatch_elem.get("name") + if osmatch_elem is not None and osmatch_elem.get("name") + else None + ) + + ports: List[PortInfo] = [] + ports_elem = host_elem.find("ports") + if ports_elem is not None: + for port_elem in ports_elem.findall("port"): + port_id = int(port_elem.get("portid")) + protocol = port_elem.get("protocol") or "tcp" + state_elem = port_elem.find("state") + state = ( + state_elem.get("state") + if state_elem is not None and state_elem.get("state") + else "unknown" ) - ports = [] - ports_elem = host_elem.find("ports") - if ports_elem is not None: - for port_elem in ports_elem.findall("port"): - port_id = int(port_elem.get("portid")) - protocol = port_elem.get("protocol") - state_elem = port_elem.find("state") - state = ( - state_elem.get("state") - if state_elem is not None - else "unknown" + service_elem = port_elem.find("service") + service_name = None + product = None + version = None + if service_elem is not None: + service_name = service_elem.get("name") + product = service_elem.get("product") + version = service_elem.get("version") + + banner = None + script_elem = port_elem.find("script[@id='banner']") + if script_elem is not None: + banner = script_elem.get("output") + + ports.append( + PortInfo( + port_number=port_id, + protocol=protocol, + state=state, + service_name=service_name, + product=product, + version=version, + banner=banner, ) + ) + return HostInfo( + ip=ip, + mac=mac, + mac_vendor=mac_vendor, + hostname=hostname, + os_name=os_name, + ports=ports, + ) + + +def parse_nmap_xml( + xml_content: str, allow_partial: bool = False +) -> List[HostInfo]: + """Parses nmap XML output into structured HostInfo dataclasses. + + Args: + xml_content: Nmap XML output string. + allow_partial: If True, extracts completed elements from truncated + XML output (e.g. when Nmap is terminated at scan_duration_sec deadline). + + Raises: + ValueError: If xml_content is not valid XML and allow_partial is False. + """ + hosts: List[HostInfo] = [] + if not allow_partial: + try: + root = ET.fromstring(xml_content) + except ET.ParseError as err: + LOGGER.error("Failed to parse nmap XML: %s", err) + raise ValueError(f"Failed to parse nmap XML: {err}") from err - service_elem = port_elem.find("service") - service_name = None - product = None - version = None - if service_elem is not None: - service_name = service_elem.get("name") - product = service_elem.get("product") - version = service_elem.get("version") - - banner = None - script_elem = port_elem.find("script[@id='banner']") - if script_elem is not None: - banner = script_elem.get("output") - - ports.append( - PortInfo( - port_number=port_id, - protocol=protocol, - state=state, - service_name=service_name, - product=product, - version=version, - banner=banner, - ) - ) - hosts.append(HostInfo(ip=ip, mac=mac, ports=ports)) - except Exception as err: # pylint: disable=broad-exception-caught - LOGGER.error("Failed to parse nmap XML: %s", err) + for host_elem in root.findall("host"): + host_info = _parse_host_element(host_elem) + if host_info is not None: + hosts.append(host_info) + return hosts + + parser = ET.XMLPullParser(events=("end",)) + try: + parser.feed(xml_content) + except ET.ParseError: + pass + try: + for _, elem in parser.read_events(): + if elem.tag == "host": + host_info = _parse_host_element(elem) + if host_info is not None: + hosts.append(host_info) + except ET.ParseError: + pass return hosts @@ -119,43 +203,116 @@ def get_mac_for_ip(ip: str, arp_file: str = "/proc/net/arp") -> Optional[str]: mac = parts[3].lower() if mac != "00:00:00:00:00:00": return mac - except Exception: # pylint: disable=broad-exception-caught - pass + except OSError as err: + LOGGER.debug("Could not read ARP cache %s: %s", arp_file, err) return None +def get_hostname_for_ip(ip: str) -> Optional[str]: + """Attempts reverse DNS lookup for a target IP address.""" + try: + host = socket.gethostbyaddr(ip)[0] + if host and host != ip: + return host + except (socket.herror, socket.gaierror, OSError): + return None + return None + + +def expand_ip_targets( + targets: List[str], fallback_subnet: Optional[str] = None +) -> Iterator[str]: + """Expands a list of IP addresses, CIDR netblocks, or VLAN IDs into host IPs.""" + for target in targets: + target_str = str(target).strip() + if not target_str: + continue + if target_str.isdigit(): + vlan_id = int(target_str) + if MIN_VLAN_ID <= vlan_id <= MAX_VLAN_ID: + if fallback_subnet: + yield from expand_ip_targets([fallback_subnet]) + continue + raise ValueError( + f"Ether VLAN network ID {target_str!r} must be between" + f" {MIN_VLAN_ID} and {MAX_VLAN_ID}" + ) + if "/" in target_str: + net = ipaddress.ip_network(target_str, strict=False) + if net.prefixlen >= 31: + for ip in net: + yield str(ip) + else: + for host in net.hosts(): + yield str(host) + else: + yield str(ipaddress.ip_address(target_str)) + + class EtherFamilyProvider(FamilyProvider): """Pluggable Ethernet protocol discovery provider (Ping & Nmap).""" - def __init__(self, ping_concurrency: int = 4) -> None: + def __init__( + self, + ping_concurrency: int = 4, + subnet_filter: Optional[str] = None, + ) -> None: """Initializes EtherFamilyProvider. Args: ping_concurrency: Maximum number of concurrent ping worker threads. Guaranteed to be at least 1. + subnet_filter: Default CIDR subnet to scan when neither addrs nor + networks is provided in discovery_config. """ self.ping_concurrency = max(1, int(ping_concurrency)) + self.subnet_filter = subnet_filter self._cancelled = threading.Event() self._active_proc: Optional[subprocess.Popen] = None self._lock = threading.Lock() self._event_count = 0 self._event_lock = threading.Lock() + def _resolve_targets(self, discovery_config: Any) -> List[str]: + """Resolves scan targets from addrs, networks, or configured subnet_filter.""" + addrs = getattr(discovery_config, "addrs", None) + if addrs: + return [str(a).strip() for a in addrs if str(a).strip()] + networks = getattr(discovery_config, "networks", None) + if networks: + return [str(n).strip() for n in networks if str(n).strip()] + if self.subnet_filter: + return [str(self.subnet_filter).strip()] + return [] + + @staticmethod + def _resolve_depth(discovery_config: Any) -> str: + """Resolves and validates the canonical UDMI discovery depth.""" + raw_depth = getattr(discovery_config, "depth", None) + depth_val = getattr(raw_depth, "value", raw_depth) + if depth_val is None: + return "entries" + depth_str = str(depth_val).strip().lower() + if depth_str not in VALID_ETHER_DEPTHS: + raise ValueError( + f"Unsupported discovery depth for ether scan: {depth_val!r}. " + f"Expected one of {sorted(VALID_ETHER_DEPTHS)}" + ) + return depth_str + def start_scan( self, discovery_config: Any, publish_func: Callable[[str, DiscoveryEvents], None], ) -> None: - """Executes ping or nmap scan based on depth configuration.""" + """Executes bucket, ping, or nmap scan based on canonical UDMI depth.""" self._cancelled.clear() with self._event_lock: self._event_count = 0 generation = getattr(discovery_config, "generation", None) - raw_depth = getattr(discovery_config, "depth", "entries") - depth_val = getattr(raw_depth, "value", raw_depth) - depth = str(depth_val).lower() if depth_val else "entries" - addrs = getattr(discovery_config, "addrs", None) or [] + depth = self._resolve_depth(discovery_config) + targets = self._resolve_targets(discovery_config) scan_duration_sec = getattr(discovery_config, "scan_duration_sec", None) deadline = ( (time.time() + float(scan_duration_sec)) @@ -168,7 +325,7 @@ def start_scan( " targets: %s, duration: %s)...", depth, generation, - addrs, + targets, scan_duration_sec, ) @@ -182,8 +339,8 @@ def start_scan( ), ) - if not addrs: - LOGGER.warning("No target addresses provided for ether scan.") + if not targets: + LOGGER.warning("No target addresses or subnets provided for ether scan.") publish_func( "self", DiscoveryEvents( @@ -194,17 +351,28 @@ def start_scan( ) return - if depth in ("entries", "ping"): - self._run_ping_scan(addrs, generation, publish_func, deadline=deadline) - elif depth in ("details", "ports", "services", "parts"): + if depth == "buckets": + self._run_buckets_scan(targets, generation, publish_func) + elif depth == "entries": + self._run_ping_scan(targets, generation, publish_func, deadline=deadline) + elif depth == "system": self._run_nmap_scan( - addrs, depth, generation, publish_func, deadline=deadline + targets, + depth, + generation, + publish_func, + include_refs=False, + deadline=deadline, ) - else: - LOGGER.warning( - "Unrecognized ether scan depth: '%s'. Defaulting to ping.", depth + else: # details, parts, refs + self._run_nmap_scan( + targets, + depth, + generation, + publish_func, + include_refs=True, + deadline=deadline, ) - self._run_ping_scan(addrs, generation, publish_func, deadline=deadline) with self._event_lock: count = self._event_count @@ -225,8 +393,53 @@ def stop_scan(self) -> None: if self._active_proc and self._active_proc.poll() is None: try: self._active_proc.terminate() - except Exception: # pylint: disable=broad-exception-caught - pass + except OSError as err: + LOGGER.debug("Error terminating ether scan subprocess: %s", err) + + def _run_buckets_scan( + self, + targets: List[str], + generation: Any, + publish_func: Callable[[str, DiscoveryEvents], None], + ) -> None: + """Emits discovered Ethernet VLAN buckets per EtherFamilyProvider spec.""" + seen_vlans = set() + + for target in targets: + if self._cancelled.is_set(): + break + target_str = str(target).strip() + if not target_str: + continue + + if target_str.isdigit(): + vlan_id = int(target_str) + if not (MIN_VLAN_ID <= vlan_id <= MAX_VLAN_ID): + raise ValueError( + f"Ether network VLAN ID {target_str!r} must be between" + f" {MIN_VLAN_ID} and {MAX_VLAN_ID}" + ) + vlan_str = str(vlan_id) + else: + # Validate IPv4 subnet/address target and report untagged native VLAN 1 + ipaddress.ip_network(target_str, strict=False) + vlan_str = "1" + + if vlan_str in seen_vlans: + continue + seen_vlans.add(vlan_str) + + with self._event_lock: + self._event_count += 1 + event_no = self._event_count + + event = DiscoveryEvents( + generation=generation, + family="ether", + network=vlan_str, + event_no=event_no, + ) + publish_func(vlan_str, event) def _run_ping_scan( self, @@ -235,35 +448,62 @@ def _run_ping_scan( publish_func: Callable[[str, DiscoveryEvents], None], deadline: Optional[float] = None, ) -> None: - """Performs concurrent ICMP ping sweeps across target IP addresses.""" + """Performs bounded concurrent ICMP ping sweeps across target IPs/CIDRs.""" ping_bin = ( "/usr/bin/ping" if os.path.exists("/usr/bin/ping") else "/bin/ping" ) if not os.path.exists(ping_bin): raise RuntimeError("Ping binary not found at /usr/bin/ping or /bin/ping") + hosts_iter = expand_ip_targets(targets, fallback_subnet=self.subnet_filter) + max_in_flight = max(self.ping_concurrency * 2, 1) + with concurrent.futures.ThreadPoolExecutor( max_workers=self.ping_concurrency ) as executor: - futures = { - executor.submit( - self._ping_target, ip, generation, publish_func - ): ip - for ip in targets - } - for future in concurrent.futures.as_completed(futures): + in_flight: Dict[concurrent.futures.Future, str] = {} + exhausted = False + + while not exhausted or in_flight: if self._cancelled.is_set() or (deadline and time.time() >= deadline): LOGGER.info( "Ping scan interrupted by cancellation or duration timeout." ) executor.shutdown(wait=False, cancel_futures=True) break - try: - future.result() - except Exception as e: # pylint: disable=broad-exception-caught - LOGGER.debug( - "Ping worker exception for %s: %s", futures[future], e + + while not exhausted and len(in_flight) < max_in_flight: + if self._cancelled.is_set() or ( + deadline and time.time() >= deadline + ): + break + try: + ip = next(hosts_iter) + except StopIteration: + exhausted = True + break + fut = executor.submit( + self._ping_target, ip, generation, publish_func ) + in_flight[fut] = ip + + if not in_flight: + break + + return_when = ( + concurrent.futures.ALL_COMPLETED + if exhausted + else concurrent.futures.FIRST_COMPLETED + ) + done, _ = concurrent.futures.wait( + in_flight.keys(), timeout=0.5, return_when=return_when + ) + for fut in done: + ip = in_flight.pop(fut, "unknown") + try: + fut.result() + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("Ping worker exception for %s: %s", ip, err) def _ping_target( self, @@ -289,6 +529,12 @@ def _ping_target( ) if res.returncode == 0: mac = get_mac_for_ip(target_ip) + hostname = get_hostname_for_ip(target_ip) + families_map: Dict[str, FamilyDiscovery] = { + "ipv4": FamilyDiscovery(addr=target_ip) + } + if hostname: + families_map["host"] = FamilyDiscovery(addr=hostname) with self._event_lock: self._event_count += 1 event_no = self._event_count @@ -296,7 +542,7 @@ def _ping_target( generation=generation, family="ether", addr=mac, - families={"ipv4": FamilyDiscovery(addr=target_ip)}, + families=families_map, event_no=event_no, ) publish_func(target_ip, event) @@ -310,6 +556,79 @@ def _ping_target( raise RuntimeError(f"Ping binary not found at {ping_bin}") from err return False + def _publish_nmap_hosts( + self, + hosts: List[HostInfo], + depth: str, + generation: Any, + publish_func: Callable[[str, DiscoveryEvents], None], + *, + include_refs: bool = True, + ) -> None: + """Emits DiscoveryEvents for each parsed Nmap HostInfo record.""" + for host in hosts: + refs: Dict[str, RefDiscovery] = {} + if include_refs: + for p in host.ports: + adjunct = { + "port_number": str(p.port_number), + "protocol": str(p.protocol), + "state": str(p.state), + } + if p.service_name: + adjunct["service"] = str(p.service_name) + if p.product: + adjunct["product"] = str(p.product) + if p.version: + adjunct["version"] = str(p.version) + if p.banner: + adjunct["banner"] = str(p.banner) + + refs[f"{p.port_number}"] = RefDiscovery( + name=f"port_{p.port_number}", + description=( + f"{p.protocol} service" + f' {p.service_name or "unknown"}' + ), + adjunct=adjunct, + ) + + mac = host.mac or get_mac_for_ip(host.ip) + hostname = host.hostname or get_hostname_for_ip(host.ip) + families_map: Dict[str, FamilyDiscovery] = { + "ipv4": FamilyDiscovery(addr=host.ip) + } + if hostname: + families_map["host"] = FamilyDiscovery(addr=hostname) + + sys_block: Optional[System] = None + if host.os_name or host.mac_vendor or hostname or depth == "system": + ancillary = {"os": host.os_name} if host.os_name else None + hardware = ( + StateSystemHardware(make=host.mac_vendor) + if host.mac_vendor + else None + ) + sys_block = System( + name=hostname, + hardware=hardware, + ancillary=ancillary, + ) + + with self._event_lock: + self._event_count += 1 + event_no = self._event_count + event = DiscoveryEvents( + generation=generation, + family="ether", + addr=mac, + families=families_map, + system=sys_block, + refs=refs if refs else None, + event_no=event_no, + ) + publish_func(host.ip, event) + def _run_nmap_scan( self, targets: List[str], @@ -317,16 +636,17 @@ def _run_nmap_scan( generation: Any, publish_func: Callable[[str, DiscoveryEvents], None], *, + include_refs: bool = True, deadline: Optional[float] = None, ) -> None: - """Executes an Nmap port/service scan subprocess across target addresses.""" + """Executes an Nmap scan subprocess across target addresses.""" if not os.path.exists("/usr/bin/nmap"): raise RuntimeError("nmap binary not found at /usr/bin/nmap") cmd = ["/usr/bin/nmap"] - if depth in ("services", "parts"): + if depth in ("system", "details", "parts", "refs"): cmd.extend(["--script", "banner", "-sV"]) - cmd.extend(["-p-", "-T3", "-oX", "-"]) + cmd.extend(["-p-", "-T4", "--max-hostgroup", "32", "-oX", "-"]) cmd.extend(targets) try: @@ -339,86 +659,79 @@ def _run_nmap_scan( ) self._active_proc = proc - stdout_chunks = [] + stdout_chunks: List[str] = [] + timed_out = False with proc: while True: - if self._cancelled.is_set() or (deadline and time.time() >= deadline): - LOGGER.info( - "Nmap scan timed out or cancelled; terminating subprocess." - ) + if self._cancelled.is_set(): + LOGGER.info("Nmap scan cancelled; terminating subprocess.") proc.terminate() try: proc.wait(timeout=2.0) except subprocess.TimeoutExpired: proc.kill() return + if deadline and time.time() >= deadline: + LOGGER.info( + "Nmap scan reached scan_duration_sec deadline; flushing" + " completed hosts and terminating subprocess." + ) + timed_out = True + proc.terminate() + try: + rem_stdout, _ = proc.communicate(timeout=2.0) + if rem_stdout: + stdout_chunks.append(rem_stdout) + except subprocess.TimeoutExpired: + proc.kill() + break + wait_sec = ( + min(1.0, max(0.01, deadline - time.time())) + if deadline + else 1.0 + ) try: - stdout, _ = proc.communicate(timeout=1.0) + stdout, _ = proc.communicate(timeout=wait_sec) if stdout: stdout_chunks.append(stdout) break - except subprocess.TimeoutExpired: + except subprocess.TimeoutExpired as exc: + if getattr(exc, "output", None): + chunk = ( + exc.output.decode("utf-8", errors="replace") + if isinstance(exc.output, bytes) + else str(exc.output) + ) + stdout_chunks.append(chunk) continue if self._cancelled.is_set(): return - if proc.returncode != 0: + if not timed_out and proc.returncode != 0: raise RuntimeError( f"Nmap process failed with exit code {proc.returncode}" ) full_stdout = "".join(stdout_chunks) if full_stdout: - hosts = parse_nmap_xml(full_stdout) - for host in hosts: - refs = {} - for p in host.ports: - adjunct = { - "port_number": str(p.port_number), - "protocol": str(p.protocol), - "state": str(p.state), - } - if p.service_name: - adjunct["service"] = str(p.service_name) - if p.product: - adjunct["product"] = str(p.product) - if p.version: - adjunct["version"] = str(p.version) - if p.banner: - adjunct["banner"] = str(p.banner) - - refs[f"{p.port_number}"] = RefDiscovery( - name=f"port_{p.port_number}", - description=( - f"{p.protocol} service" - f' {p.service_name or "unknown"}' - ), - adjunct=adjunct, - ) - mac = host.mac or get_mac_for_ip(host.ip) - with self._event_lock: - self._event_count += 1 - event_no = self._event_count - event = DiscoveryEvents( - generation=generation, - family="ether", - addr=mac, - families={"ipv4": FamilyDiscovery(addr=host.ip)}, - refs=refs if refs else None, - event_no=event_no, - ) - publish_func(host.ip, event) + hosts = parse_nmap_xml(full_stdout, allow_partial=timed_out) + self._publish_nmap_hosts( + hosts, + depth, + generation, + publish_func, + include_refs=include_refs, + ) except FileNotFoundError as err: LOGGER.error("nmap binary not found at /usr/bin/nmap: %s", err) raise RuntimeError("nmap binary not found at /usr/bin/nmap") from err - except Exception as e: # pylint: disable=broad-exception-caught - LOGGER.error("Nmap scan failed: %s", e) + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.error("Nmap scan failed: %s", err) raise def enumerate_refs(self, addr: str) -> Dict[str, RefDiscovery]: """Enumerates references for target address (unused for ether).""" del addr return {} - diff --git a/edge/spotter/src/providers/passive.py b/edge/spotter/src/providers/passive.py index 108eaf9577..6ec45eaa3e 100644 --- a/edge/spotter/src/providers/passive.py +++ b/edge/spotter/src/providers/passive.py @@ -3,7 +3,9 @@ import dataclasses import ipaddress import logging +import os import queue +import socket import threading import time from typing import Any, Callable, Dict, Optional, Set @@ -26,6 +28,7 @@ BACNET_BVLC_MARKER = b"\x81" BACNET_APDU_I_AM_START = b"\x10\x00\xc4" +BACNET_INSTANCE_MASK = 0x3FFFFF PRIVATE_IP_BPF_FILTER = ( @@ -39,11 +42,157 @@ ) +@dataclasses.dataclass(eq=True, frozen=True) +class DecodedBacnetPacket: + """Parsed BACnet/IP BVLL + NPDU + APDU metadata from a captured UDP frame.""" + + device_id: Optional[int] = None + orig_ip: Optional[str] = None + orig_port: Optional[int] = None + snet: Optional[int] = None + sadr: Optional[str] = None + iam_router_networks: tuple[int, ...] = () + + @dataclasses.dataclass(eq=True, frozen=True) class PassiveScanRecord: + """Discovered host record from passive network packet inspection.""" + addr: str mac: Optional[str] = None hostname: Optional[str] = None + bacnet_id: Optional[int] = None + bacnet_port: Optional[int] = None + snet: Optional[int] = None + sadr: Optional[str] = None + + +def decode_bacnet_bvll( + payload: bytes, + outer_ip: Optional[str] = None, + outer_port: Optional[int] = None, +) -> Optional[DecodedBacnetPacket]: + """Decodes a BACnet/IP BVLL payload into originating IP, MS/TP routing, and I-Am metadata.""" + if not payload or len(payload) < 4 or payload[0:1] != BACNET_BVLC_MARKER: + return None + + bvlc_func = payload[1] + orig_ip = outer_ip + orig_port = outer_port + npdu_offset = 4 + + if bvlc_func == 0x04: # Forwarded-NPDU (6-byte originating B/IP address) + if len(payload) < 10: + return None + try: + orig_ip = socket.inet_ntoa(payload[4:8]) + orig_port = int.from_bytes(payload[8:10], byteorder="big") + except OSError: + orig_ip = outer_ip + npdu_offset = 10 + + if len(payload) >= npdu_offset + 2 and payload[npdu_offset] == 0x01: + control = payload[npdu_offset + 1] + pos = npdu_offset + 2 + + # Bit 5 (0x20): Destination Specifier (DNET + DLEN + DADR) + if control & 0x20: + if pos + 3 > len(payload): + return None + dlen = payload[pos + 2] + pos += 3 + dlen + + # Bit 3 (0x08): Source Specifier (SNET + SLEN + SADR -> routed MS/TP device) + snet: Optional[int] = None + sadr: Optional[str] = None + if control & 0x08: + if pos + 3 > len(payload): + return None + raw_snet = int.from_bytes(payload[pos : pos + 2], byteorder="big") + slen = payload[pos + 2] + if pos + 3 + slen > len(payload): + return None + sadr_bytes = payload[pos + 3 : pos + 3 + slen] + if 1 <= raw_snet <= 65534: + snet = raw_snet + if slen == 1: + sadr = str(sadr_bytes[0]) + elif slen > 1: + sadr = sadr_bytes.hex() + pos += 3 + slen + + # Hop count is present when Destination Specifier bit is set + if control & 0x20: + pos += 1 + + if pos <= len(payload): + if control & 0x80: + # Network Layer Message: 0x01 is I-Am-Router-To-Network + if pos < len(payload) and payload[pos] == 0x01: + dnets = [] + rem = payload[pos + 1 :] + for i in range(0, len(rem) - 1, 2): + dnet = int.from_bytes(rem[i : i + 2], byteorder="big") + if 1 <= dnet <= 65534 and dnet not in dnets: + dnets.append(dnet) + return DecodedBacnetPacket( + orig_ip=orig_ip, + orig_port=orig_port, + snet=snet, + sadr=sadr, + iam_router_networks=tuple(dnets), + ) + if snet is not None: + return DecodedBacnetPacket( + orig_ip=orig_ip, + orig_port=orig_port, + snet=snet, + sadr=sadr, + ) + else: + # Application Layer APDU: Unconfirmed-Request (0x10) I-Am (0x00) ObjectId tag (0xc4) + if ( + pos + 7 <= len(payload) + and payload[pos : pos + 3] == BACNET_APDU_I_AM_START + ): + obj_id = int.from_bytes(payload[pos + 3 : pos + 7], byteorder="big") + inst = obj_id & BACNET_INSTANCE_MASK + if 1 <= inst <= BACNET_INSTANCE_MASK: + return DecodedBacnetPacket( + device_id=inst, + orig_ip=orig_ip, + orig_port=orig_port, + snet=snet, + sadr=sadr, + ) + if snet is not None: + return DecodedBacnetPacket( + orig_ip=orig_ip, + orig_port=orig_port, + snet=snet, + sadr=sadr, + ) + else: + # Fallback scan for simplified/synthetic BVLC I-Am frames without standard NPDU v1 + index = payload.find(BACNET_APDU_I_AM_START, 4, 32) + if index > 0 and len(payload) >= index + 7: + obj_id = int.from_bytes(payload[index + 3 : index + 7], byteorder="big") + inst = obj_id & BACNET_INSTANCE_MASK + if 1 <= inst <= BACNET_INSTANCE_MASK: + return DecodedBacnetPacket( + device_id=inst, + orig_ip=orig_ip, + orig_port=orig_port, + ) + return None + + +def extract_bacnet_iam( + payload: bytes, +) -> Optional[int]: + """Extracts 22-bit BACnet Device Object Instance from a BVLC I-Am payload.""" + decoded = decode_bacnet_bvll(payload) + return decoded.device_id if decoded is not None else None class PassiveFamilyProvider(FamilyProvider): @@ -61,6 +210,7 @@ def __init__( self._queue: queue.SimpleQueue = queue.SimpleQueue() self._addresses_seen: Set[str] = set() + self._last_published_at: Dict[str, float] = {} self._device_records: Set[PassiveScanRecord] = set() self._records_published: Set[PassiveScanRecord] = set() self._records_lock = threading.Lock() @@ -72,6 +222,43 @@ def __init__( self._publisher_thread: Optional[threading.Thread] = None self._event_count = 0 self._event_lock = threading.Lock() + self.packets_seen = 0 + self.ip_packets_seen = 0 + self.bacnet_packets_seen = 0 + self.passive_holdoff_count = 0 + self.discovered_routed_networks: Set[int] = set() + self.bacnet_ip_devices_seen: Set[int] = set() + self.routed_mstp_devices_seen: Set[int] = set() + self._packet_count_start: Optional[int] = None + + def _get_packet_counter_total(self) -> Optional[int]: + """Reads total rx+tx packets for configured interface from sysfs.""" + if not self.interface: + return None + try: + rx_path = f"/sys/class/net/{self.interface}/statistics/rx_packets" + tx_path = f"/sys/class/net/{self.interface}/statistics/tx_packets" + if not (os.path.exists(rx_path) and os.path.exists(tx_path)): + return None + with open(rx_path, "r", encoding="utf-8") as f: + rx = int(f.read().strip()) + with open(tx_path, "r", encoding="utf-8") as f: + tx = int(f.read().strip()) + return rx + tx + except (OSError, ValueError) as err: + LOGGER.debug("Could not read interface packet statistics: %s", err) + return None + + @staticmethod + def _get_host(ip: str) -> Optional[str]: + """Attempts reverse DNS lookup for a passively observed IP address.""" + try: + host = socket.gethostbyaddr(ip)[0] + if host and host != ip: + return host + except (socket.herror, socket.gaierror, OSError): + return None + return None def build_bpf_filter(self, subnet_filter: Optional[str] = None) -> str: """Constructs the BPF filter string for Scapy packet capture. @@ -84,12 +271,17 @@ def build_bpf_filter(self, subnet_filter: Optional[str] = None) -> str: Returns: BPF filter string for Scapy sniffer. + + Raises: + ValueError: If subnet_filter is not a valid IPv4 interface/network CIDR. """ if not subnet_filter: return PRIVATE_IP_BPF_FILTER try: iface = ipaddress.ip_interface(subnet_filter) + if not isinstance(iface, ipaddress.IPv4Interface): + raise ValueError(f"Expected IPv4 subnet filter, got {subnet_filter!r}") network = iface.network bpf_filter = ( f"ip and src net {network} and (dst net {network} or" @@ -103,12 +295,9 @@ def build_bpf_filter(self, subnet_filter: Optional[str] = None) -> str: if iface.ip not in (network.network_address, first_host): bpf_filter += f" and not src host {iface.ip}" return bpf_filter - except ValueError: - LOGGER.warning("Invalid subnet filter: %s", subnet_filter) - return ( - f"ip and src net {subnet_filter} and (dst net {subnet_filter} or" - " broadcast or multicast)" - ) + except ValueError as err: + LOGGER.error("Invalid subnet filter %s: %s", subnet_filter, err) + raise ValueError(f"Invalid subnet filter: {subnet_filter}") from err def start_scan( self, @@ -123,19 +312,33 @@ def start_scan( self._sniffer_started.clear() with self._records_lock: self._addresses_seen.clear() + self._last_published_at.clear() self._device_records.clear() self._records_published.clear() + self.passive_holdoff_count = 0 + self.discovered_routed_networks.clear() + self.bacnet_ip_devices_seen.clear() + self.routed_mstp_devices_seen.clear() with self._event_lock: self._event_count = 0 + self.packets_seen = 0 + self.ip_packets_seen = 0 + self.bacnet_packets_seen = 0 + generation = getattr(discovery_config, "generation", None) scan_duration_sec = getattr(discovery_config, "scan_duration_sec", None) + passive_sec = getattr(discovery_config, "passive_sec", None) + + bpf_filter = self.build_bpf_filter(self.subnet_filter) LOGGER.info( - "Starting Passive discovery scan (iface: %s, dur: %s, gen: %s)...", + "Starting Passive discovery scan (iface: %s, dur: %s, gen: %s," + " passive_sec: %s)...", self.interface, scan_duration_sec, generation, + passive_sec, ) # Emit start event (event_no: 0) @@ -148,10 +351,9 @@ def start_scan( ), ) - bpf_filter = self.build_bpf_filter(self.subnet_filter) - self._queue_thread = threading.Thread( target=self._queue_worker, + args=(passive_sec,), name="Passive-QueueWorker", daemon=True, ) @@ -177,10 +379,14 @@ def start_scan( is_mock = hasattr(self._sniffer, "_mock_call") if not is_mock and not self._sniffer_started.wait(timeout=5.0): + sniffer_err = getattr(self._sniffer, "exception", None) raise RuntimeError( f"Failed to initiate packet capture on interface {self.interface}" + + (f": {sniffer_err}" if sniffer_err else "") ) + self._packet_count_start = self._get_packet_counter_total() + if scan_duration_sec and int(scan_duration_sec) > 0: self._cancelled.wait(timeout=float(scan_duration_sec)) else: @@ -208,35 +414,181 @@ def stop_scan(self) -> None: if self._sniffer: try: self._sniffer.stop() - except Exception: # pylint: disable=broad-exception-caught - pass + except Exception as err: # pylint: disable=broad-exception-caught + LOGGER.debug("Error stopping Scapy sniffer: %s", err) self._sniffer = None + packet_count_end = self._get_packet_counter_total() + if self._queue_thread and self._queue_thread.is_alive(): self._queue_thread.join(timeout=1.0) if self._publisher_thread and self._publisher_thread.is_alive(): self._publisher_thread.join(timeout=1.0) - def _queue_worker(self) -> None: - """Worker thread reading packets from queue and extracting IPs/MACs.""" + if ( + self.interface + and packet_count_end is not None + and self._packet_count_start is not None + ): + LOGGER.info( + "Passive scan stats: packets seen by scapy=%d, interface delta=%d," + " devices seen=%d", + self.packets_seen, + packet_count_end - self._packet_count_start, + len(self._addresses_seen), + ) + + def _queue_worker(self, passive_sec: Optional[int] = None) -> None: + """Worker thread reading packets from queue and extracting IPs/MACs/BACnet headers.""" while not self._cancelled.is_set(): try: packet = self._queue.get(timeout=0.5) + self.packets_seen += 1 if scapy and scapy.layers.inet.IP in packet: + self.ip_packets_seen += 1 ip_layer = packet[scapy.layers.inet.IP] - src_ip = ip_layer.src - if src_ip and src_ip not in self._addresses_seen: - mac = None - if scapy.layers.inet.Ether in packet: - mac = packet[scapy.layers.inet.Ether].src - with self._records_lock: - self._addresses_seen.add(src_ip) - self._device_records.add( - PassiveScanRecord(addr=src_ip, mac=mac) + src_ip = getattr(ip_layer, "src", None) + if not src_ip: + continue + + effective_ip = src_ip + bacnet_id: Optional[int] = None + bacnet_port: Optional[int] = None + snet: Optional[int] = None + sadr: Optional[str] = None + if scapy.layers.inet.UDP in packet: + udp_layer = packet[scapy.layers.inet.UDP] + sport = getattr(udp_layer, "sport", None) + dport = getattr(udp_layer, "dport", None) + if sport == 47808 or dport == 47808: + self.bacnet_packets_seen += 1 + raw_payload = bytes(udp_layer.payload) + decoded = decode_bacnet_bvll( + raw_payload, + outer_ip=src_ip, + outer_port=int(sport or 47808), ) + if decoded is not None: + if decoded.orig_ip: + effective_ip = decoded.orig_ip + if decoded.iam_router_networks: + with self._records_lock: + self.discovered_routed_networks.update( + decoded.iam_router_networks + ) + if decoded.snet is not None: + with self._records_lock: + self.discovered_routed_networks.add(decoded.snet) + if decoded.device_id is not None: + bacnet_id = decoded.device_id + bacnet_port = int(decoded.orig_port or sport or 47808) + snet = decoded.snet + sadr = decoded.sadr + with self._records_lock: + if snet is not None: + self.routed_mstp_devices_seen.add(bacnet_id) + else: + self.bacnet_ip_devices_seen.add(bacnet_id) + LOGGER.debug( + "Passively observed BACnet I-Am device %d at %s:%d" + " (snet=%s, sadr=%s)", + bacnet_id, + effective_ip, + bacnet_port, + snet, + sadr, + ) + + now = time.monotonic() + record_key = ( + f"{effective_ip}:{snet}:{sadr}:{bacnet_id}" + if snet is not None + else effective_ip + ) + with self._records_lock: + if passive_sec and int(passive_sec) > 0: + last_pub = self._last_published_at.get(record_key) + if last_pub is not None and (now - last_pub) < float(passive_sec): + self.passive_holdoff_count += 1 + continue + self._last_published_at[record_key] = now + if snet is None: + self._records_published = { + r + for r in self._records_published + if not (r.addr == effective_ip and r.snet is None) + } + self._device_records = { + r + for r in self._device_records + if not (r.addr == effective_ip and r.snet is None) + } + elif effective_ip in self._addresses_seen and bacnet_id is None: + continue + + mac = None + if effective_ip == src_ip and scapy.layers.inet.Ether in packet: + raw_mac = getattr(packet[scapy.layers.inet.Ether], "src", None) + if raw_mac: + mac = str(raw_mac).upper() + + hostname = self._get_host(effective_ip) + record = PassiveScanRecord( + addr=effective_ip, + mac=mac, + hostname=hostname, + bacnet_id=bacnet_id, + bacnet_port=bacnet_port, + snet=snet, + sadr=sadr, + ) + with self._records_lock: + self._addresses_seen.add(effective_ip) + self._device_records.add(record) except queue.Empty: continue + def _flush_pending_records( + self, + generation: Any, + publish_func: Callable[[str, DiscoveryEvents], None], + ) -> None: + """Publishes any newly collected passive scan records.""" + with self._records_lock: + new_records = sorted( + self._device_records - self._records_published, + key=lambda r: (r.addr, r.snet or 0, r.sadr or "", r.bacnet_id or 0), + ) + for record in new_records: + families_map: Dict[str, FamilyDiscovery] = {} + if record.mac: + families_map["ethmac"] = FamilyDiscovery(addr=record.mac) + if record.hostname: + families_map["host"] = FamilyDiscovery(addr=record.hostname) + if record.bacnet_id is not None: + families_map["bacnet"] = FamilyDiscovery( + addr=str(record.bacnet_id), port=record.bacnet_port + ) + if record.sadr: + families_map["mstp"] = FamilyDiscovery(addr=record.sadr) + + with self._event_lock: + self._event_count += 1 + event_no = self._event_count + event = DiscoveryEvents( + generation=generation, + family="ipv4", + addr=record.addr, + network=str(record.snet) if record.snet is not None else None, + families=families_map if families_map else None, + event_no=event_no, + ) + publish_func(record.addr, event) + with self._records_lock: + self._records_published.add(record) + if record.addr not in self._last_published_at: + self._last_published_at[record.addr] = time.monotonic() + def _publisher_worker( self, generation: Any, @@ -244,28 +596,9 @@ def _publisher_worker( ) -> None: """Worker thread periodically publishing new passive records.""" while not self._cancelled.is_set(): - with self._records_lock: - new_records = set(self._device_records) - self._records_published - for record in new_records: - with self._event_lock: - self._event_count += 1 - event_no = self._event_count - event = DiscoveryEvents( - generation=generation, - family="ipv4", - addr=record.addr, - families=( - {"ether": FamilyDiscovery(addr=record.mac)} - if record.mac - else None - ), - event_no=event_no, - ) - publish_func(record.addr, event) - with self._records_lock: - self._records_published.add(record) - - time.sleep(self.publish_interval_sec) + self._flush_pending_records(generation, publish_func) + self._cancelled.wait(timeout=self.publish_interval_sec) + self._flush_pending_records(generation, publish_func) def enumerate_refs(self, addr: str) -> Dict[str, RefDiscovery]: del addr # Unused diff --git a/edge/spotter/tests/test_agent.py b/edge/spotter/tests/test_agent.py index 713006941b..b5bb7ab073 100644 --- a/edge/spotter/tests/test_agent.py +++ b/edge/spotter/tests/test_agent.py @@ -13,8 +13,8 @@ from edge.spotter.src.agent import calculate_local_password from edge.spotter.src.agent import load_config from edge.spotter.src.agent import merge_dicts -from edge.spotter.src.agent import normalize_discovery_config from edge.spotter.src.agent import resolve_config_path +from edge.spotter.src.agent import validate_discovery_config from edge.spotter.src.agent import wait_for_broker_readiness from edge.spotter.src.manager.discovery import SpotterDiscoveryManager from edge.spotter.src.manager.system import SpotterSystemManager @@ -22,9 +22,12 @@ from udmi.schema import Depth from udmi.schema import DiscoveryConfig from udmi.schema import DiscoveryEvents +from udmi.schema import Enumerations +from udmi.schema import FamilyDiscovery from udmi.schema import FamilyDiscoveryConfig from udmi.schema import FamilyDiscoveryState from udmi.schema import Protocol +from udmi.schema import State from udmi.schema import SystemConfig from udmi.schema import TraceDiscoveryConfig from udmi.schema.state_discovery_family import Phase as DiscoveryPhase @@ -37,12 +40,10 @@ def setUp(self): # pylint: disable=consider-using-with self.test_dir = tempfile.TemporaryDirectory() - # Create a mock private key self.key_file = os.path.join(self.test_dir.name, "rsa_private.pem") with open(self.key_file, "wb") as f: f.write(b"MOCK PRIVATE KEY DATA") - # Create pkcs8 version as well self.pkcs8_file = os.path.join(self.test_dir.name, "rsa_private.pkcs8") with open(self.pkcs8_file, "wb") as f: f.write(b"MOCK PKCS8 KEY DATA") @@ -186,93 +187,81 @@ def test_merge_dicts(self): self.assertEqual(result["nested"]["k2"], "v2_new") self.assertEqual(result["nested"]["k3"], "v3") - def test_normalize_discovery_config_legacy_depths(self): - """Verifies legacy discovery depths normalize to schema enums.""" + def test_validate_discovery_config_canonical_depths(self): + """Verifies canonical UDMI discovery depths pass validation.""" payload = { - "timestamp": "2026-09-11T08:00:00Z", + "timestamp": "2026-11-10T08:00:00Z", "version": "1.5.7", "discovery": { "families": { - "ether": {"generation": "gen-1", "depth": "ping"}, - "nmap": {"generation": "gen-2", "depth": "ports"}, - "services_scan": {"generation": "gen-3", "depth": "services"}, - "bacnet": {"generation": "gen-4", "depth": "system"}, + "bacnet": {"generation": "gen-1", "depth": "buckets"}, + "ether": {"generation": "gen-2", "depth": "entries"}, + "ipv4": {"generation": "gen-3", "depth": "details"}, }, "enumerations": { - "families": "ping", - "devices": "ports", - "points": "services", + "families": "entries", + "devices": "details", + "points": "parts", + "features": "system", }, }, } - normalized = normalize_discovery_config(payload) - - # Families normalized - self.assertEqual( - normalized["discovery"]["families"]["ether"]["depth"], "entries" - ) - self.assertEqual( - normalized["discovery"]["families"]["nmap"]["depth"], "details" - ) - self.assertEqual( - normalized["discovery"]["families"]["services_scan"]["depth"], "parts" - ) - self.assertEqual( - normalized["discovery"]["families"]["bacnet"]["depth"], "system" - ) - - # Enumerations normalized + validated = validate_discovery_config(payload) + parsed = Config.from_dict(validated) self.assertEqual( - normalized["discovery"]["enumerations"]["families"], "entries" + parsed.discovery.families["bacnet"].depth, Depth.buckets ) - self.assertEqual( - normalized["discovery"]["enumerations"]["devices"], "details" - ) - self.assertEqual( - normalized["discovery"]["enumerations"]["points"], "parts" - ) - - # Verifies that Config.from_dict() parses cleanly without ValueError - parsed = Config.from_dict(normalized) self.assertEqual( parsed.discovery.families["ether"].depth, Depth.entries ) self.assertEqual( - parsed.discovery.families["nmap"].depth, Depth.details - ) - self.assertEqual( - parsed.discovery.families["services_scan"].depth, Depth.parts - ) + parsed.discovery.families["ipv4"].depth, Depth.details + ) + + def test_validate_discovery_config_rejects_legacy_non_canonical_depths(self): + """Verifies non-canonical depths ('ping', 'ports', 'services') fail fast.""" + self.assertIsNone(validate_discovery_config(None)) + self.assertEqual(validate_discovery_config("not-a-dict"), "not-a-dict") + + for legacy_depth in ("ping", "ports", "services", "custom_depth"): + fam_payload = { + "discovery": {"families": {"ether": {"depth": legacy_depth}}} + } + with self.assertRaises(ValueError): + validate_discovery_config(fam_payload) + + enum_payload = { + "discovery": {"enumerations": {"families": legacy_depth}} + } + with self.assertRaises(ValueError): + validate_discovery_config(enum_payload) + + def test_datamodel_to_json_strips_none_fields(self): + """Verifies serialized UDMI payloads omit None fields for schema validity.""" + event = DiscoveryEvents( + timestamp="2026-11-10T12:00:00Z", + version="1.5.7", + generation="2026-11-10T12:00:00Z", + family="bacnet", + addr="1234", + event_no=1, + families={"ipv4": FamilyDiscovery(addr="192.168.1.10", port=47808)}, + ) + serialized = json.loads(event.to_json()) self.assertEqual( - parsed.discovery.families["bacnet"].depth, Depth.system - ) - - def test_normalize_discovery_config_edge_cases(self): - """Verifies normalize_discovery_config handles non-dicts and case.""" - # Non-dict inputs are preserved without error - self.assertIsNone(normalize_discovery_config(None)) - self.assertEqual(normalize_discovery_config("not-a-dict"), "not-a-dict") - - # Case insensitivity and unrecognized depths - payload = { - "discovery": { + serialized, + { + "timestamp": "2026-11-10T12:00:00Z", + "version": "1.5.7", + "generation": "2026-11-10T12:00:00Z", + "family": "bacnet", + "addr": "1234", + "event_no": 1, "families": { - "ether": {"depth": "PING"}, - "nmap": {"depth": "Ports"}, - "custom": {"depth": "custom_depth"}, - } - } - } - normalized = normalize_discovery_config(payload) - self.assertEqual( - normalized["discovery"]["families"]["ether"]["depth"], "entries" - ) - self.assertEqual( - normalized["discovery"]["families"]["nmap"]["depth"], "details" - ) - self.assertEqual( - normalized["discovery"]["families"]["custom"]["depth"], "custom_depth" + "ipv4": {"addr": "192.168.1.10", "port": 47808} + }, + }, ) def test_load_config_with_configs_dir_overlay(self): @@ -305,13 +294,18 @@ def test_load_config_with_configs_dir_overlay(self): self.assertEqual(merged["ether"]["ping_concurrency"], 10) self.assertEqual(merged["ip"]["subnet_filter"], "10.0.0.0/24") + # Corrupted overlay fails fast + bad_overlay = os.path.join(extra_dir, "02-corrupt.json") + with open(bad_overlay, "w", encoding="utf-8") as f: + f.write("{invalid json") + with self.assertRaises(ValueError): + load_config(base_config_path) + def test_resolve_config_path_container_remapping(self): """Verifies resolve_config_path handles container volume remapping.""" - # 1. Relative path res = resolve_config_path("/app/config", "certs/key.pem") self.assertEqual(res, "/app/config/certs/key.pem") - # 2. Existing file test_file = os.path.join(self.test_dir.name, "test.pem") with open(test_file, "w", encoding="utf-8") as f: f.write("key") @@ -319,29 +313,36 @@ def test_resolve_config_path_container_remapping(self): resolve_config_path(self.test_dir.name, test_file), test_file ) - # 3. Missing host path remapped to container base_dir non_existent_host_path = "/opt/discovery_node/configs/test.pem" remapped = resolve_config_path(self.test_dir.name, non_existent_host_path) self.assertEqual(remapped, test_file) def test_metrics_rate_sec_default_and_override(self): - """Verifies system metrics rate default and dynamic update.""" + """Verifies system metrics rate default, RFC 3339 last_start, and startup event.""" # pylint: disable=protected-access - # 1. Default initialization (300s, 85% memory threshold) mgr_default = SpotterSystemManager() self.assertEqual(mgr_default._metrics_rate_sec, 300) self.assertEqual(mgr_default.max_mem_pct, 85.0) - # 2. Custom initialization override mgr_custom = SpotterSystemManager(max_mem_pct=75.0, metrics_rate_sec=15) self.assertEqual(mgr_custom._metrics_rate_sec, 15) self.assertEqual(mgr_custom.max_mem_pct, 75.0) - # 3. Dynamic update via UDMI Config message config_update = Config(system=SystemConfig(metrics_rate_sec=60)) mgr_custom.handle_config(config_update) self.assertEqual(mgr_custom._metrics_rate_sec, 60) + state = State() + mgr_custom.update_state(state) + self.assertTrue(state.system.operation.last_start.endswith("Z")) + self.assertIn("T", state.system.operation.last_start) + + mgr_custom.publish_event = MagicMock() + mgr_custom._publish_startup_event() + startup_evt, channel = mgr_custom.publish_event.call_args[0] + self.assertEqual(channel, "system") + self.assertEqual(startup_evt.logentries[0].category, "system.base.ready") + @patch("edge.spotter.src.manager.system.get_cpu_and_memory_metrics") def test_spotter_system_manager_publish_metrics(self, mock_metrics): """Verifies metrics publishing with host resource metrics.""" @@ -431,41 +432,72 @@ def setUp(self): self.mock_device = MagicMock() self.mock_dispatcher = MagicMock() self.mock_device.dispatcher = self.mock_dispatcher + self.mock_device.get_manager.return_value = None self.manager._device = self.mock_device self.manager._dispatcher = self.mock_dispatcher + @patch("edge.spotter.src.manager.discovery.run_bacnet_trace_whois_rounds") @patch("edge.spotter.src.manager.discovery.capture_packets") - def test_run_trace_worker_streaming(self, mock_capture): - """Verifies packet streaming chunk emission during trace capture.""" - mock_capture.return_value = [b"MOCK_PACKET_HEADER", b"MOCK_PACKET_BODY"] + def test_run_trace_worker_streaming(self, mock_capture, mock_whois): + """Verifies gzip-compressed upload/discovery streaming, start/EOF markers, sha256, and scan_manifest.""" + import base64 + import gzip + + raw_chunks = [b"MOCK_PACKET_HEADER", b"MOCK_PACKET_BODY"] + mock_capture.return_value = raw_chunks + + def fake_whois(**kwargs): + kwargs["scan_round_timestamps"].append("2026-11-10T14:35:01Z") + kwargs["discovered_routed_networks"].add(6100) + + mock_whois.side_effect = fake_whois fam_config = FamilyDiscoveryConfig( - generation="2026-07-08T14:35:00Z", + generation="2026-11-10T14:35:00Z", depth=Depth.trace, - trace=TraceDiscoveryConfig( - interface="any", - filter="udp port 47808", - ), scan_duration_sec=2, ) - self.manager._discovery_state.families["ether"] = MagicMock() - self.manager._run_trace_capture("ether", fam_config) - - self.assertTrue(self.mock_dispatcher.publish_event.called) - call_args = self.mock_dispatcher.publish_event.call_args[0] - channel = call_args[0] - event_model = call_args[1] + self.manager._discovery_state.families["bacnet"] = FamilyDiscoveryState() + self.manager._run_trace_capture("bacnet", fam_config) - self.assertEqual(channel, "events/streams") - self.assertEqual(event_model.event_no, 0) - self.assertEqual(event_model.chunk_index, 0) - self.assertEqual(event_model.total_chunks, 1) - self.assertIn("trace-ether-", event_model.session_id) + # Expect 3 publishes on upload/discovery: start (0), data chunk (1), EOF (-2) + self.assertEqual(self.mock_dispatcher.publish_event.call_count, 3) + calls = self.mock_dispatcher.publish_event.call_args_list + + start_ch, start_msg, _ = calls[0][0] + self.assertEqual(start_ch, "upload/discovery") + self.assertEqual(start_msg.event_no, 0) + self.assertEqual(start_msg.generation, "2026-11-10T14:35:00Z") + self.assertEqual(start_msg.family, "bacnet") + self.assertIsNone(start_msg.data) + + data_ch, data_msg, _ = calls[1][0] + self.assertEqual(data_ch, "upload/discovery") + self.assertEqual(data_msg.event_no, 1) + decompressed = gzip.decompress(base64.b64decode(data_msg.data)) + self.assertEqual(decompressed, b"MOCK_PACKET_HEADERMOCK_PACKET_BODY") + + eof_ch, eof_msg, _ = calls[2][0] + self.assertEqual(eof_ch, "upload/discovery") + self.assertEqual(eof_msg.event_no, -2) + expected_sha = hashlib.sha256( + b"MOCK_PACKET_HEADERMOCK_PACKET_BODY" + ).hexdigest() + self.assertEqual(eof_msg.sha256, expected_sha) + self.assertIsNotNone(eof_msg.scan_manifest) + self.assertEqual(eof_msg.scan_manifest.filter, "udp port 47808") + self.assertEqual( + eof_msg.scan_manifest.scan_round_timestamps, ["2026-11-10T14:35:01Z"] + ) + self.assertEqual(eof_msg.scan_manifest.discovered_routed_networks, [6100]) - f_state = self.manager._discovery_state.families["ether"] + f_state = self.manager._discovery_state.families["bacnet"] self.assertEqual(f_state.phase, DiscoveryPhase.stopped) + self.assertEqual(f_state.active_count, 1) self.assertEqual(f_state.status.level, 200) + self.assertEqual(f_state.status.category, "discovery.family.scan") + self.assertIsNotNone(f_state.status.timestamp) @patch("edge.spotter.src.manager.discovery.capture_packets") def test_run_trace_worker_failure(self, mock_capture): @@ -473,7 +505,7 @@ def test_run_trace_worker_failure(self, mock_capture): mock_capture.side_effect = RuntimeError("Network interface down") fam_config = FamilyDiscoveryConfig( - generation="2026-07-08T14:35:00Z", + generation="2026-11-10T14:35:00Z", depth=Depth.trace, trace=TraceDiscoveryConfig( interface="eth0", @@ -482,27 +514,29 @@ def test_run_trace_worker_failure(self, mock_capture): scan_duration_sec=2, ) - self.manager._discovery_state.families["ether"] = MagicMock() + self.manager._discovery_state.families["ether"] = FamilyDiscoveryState() self.manager._run_trace_capture("ether", fam_config) f_state = self.manager._discovery_state.families["ether"] self.assertEqual(f_state.phase, DiscoveryPhase.stopped) self.assertEqual(f_state.status.level, 500) + self.assertEqual(f_state.status.category, "discovery.family.scan") self.assertIn("Network interface down", f_state.status.message) @patch("edge.spotter.src.manager.discovery.capture_packets") def test_run_scan_trace_cleans_up_active_providers(self, mock_capture): - """Verifies provider eviction and active state reset after trace scan.""" + """Verifies provider eviction and phase reset after trace scan.""" mock_capture.return_value = [b"TRACE_DATA"] mock_provider = MagicMock() self.manager._active_providers.append(mock_provider) - old_state = FamilyDiscoveryState(generation="old-gen") - old_state.active = True + old_state = FamilyDiscoveryState( + generation="old-gen", phase=DiscoveryPhase.active + ) self.manager._discovery_state.families["ether"] = old_state fam_config = FamilyDiscoveryConfig( - generation="new-gen-2026", + generation="2026-11-10T15:00:00Z", depth=Depth.trace, trace=TraceDiscoveryConfig(interface="any", filter=""), scan_duration_sec=1, @@ -516,8 +550,7 @@ def test_run_scan_trace_cleans_up_active_providers(self, mock_capture): mock_provider.stop_scan.assert_not_called() f_state = self.manager._discovery_state.families["ether"] - self.assertFalse(f_state.active) - self.assertEqual(f_state.generation, "new-gen-2026") + self.assertEqual(f_state.generation, "2026-11-10T15:00:00Z") self.assertEqual(f_state.phase, DiscoveryPhase.stopped) @patch("edge.spotter.src.manager.discovery.check_safety_circuit_breaker") @@ -533,9 +566,9 @@ def test_run_scan_circuit_breaker_throttles_execution(self, mock_cb): self.assertNotIn(mock_provider, self.manager._active_providers) f_state = self.manager._discovery_state.families["bacnet"] - self.assertFalse(f_state.active) self.assertEqual(f_state.phase, DiscoveryPhase.stopped) self.assertEqual(f_state.status.level, 400) + self.assertEqual(f_state.status.category, "discovery.family.scan") self.assertIn( "Scan throttled by safety circuit breaker", f_state.status.message ) @@ -548,22 +581,27 @@ def test_run_trace_capture_circuit_breaker_throttles( """Verifies trace capture throttling when circuit breaker trips.""" mock_cb.return_value = True fam_config = FamilyDiscoveryConfig( - generation="gen-trace", depth=Depth.trace, scan_duration_sec=5 + generation="2026-11-10T15:00:00Z", + depth=Depth.trace, + scan_duration_sec=5, ) self.manager._run_trace_capture("bacnet", fam_config) mock_capture.assert_not_called() f_state = self.manager._discovery_state.families["bacnet"] - self.assertFalse(f_state.active) self.assertEqual(f_state.phase, DiscoveryPhase.stopped) self.assertEqual(f_state.status.level, 400) + self.assertEqual(f_state.status.category, "discovery.family.scan") self.assertIn("throttled by safety circuit breaker", f_state.status.message) def test_handle_config_marks_new_generation_as_pending(self): """Verifies new generation in discovery config marks phase as pending.""" + gen_str = (datetime.now(timezone.utc) + timedelta(seconds=5)).strftime( + "%Y-%m-%dT%H:%M:%SZ" + ) fam_cfg = FamilyDiscoveryConfig( - generation="2026-09-14T13:00:00Z", + generation=gen_str, depth=Depth.system, ) config = Config(discovery=DiscoveryConfig(families={"bacnet": fam_cfg})) @@ -573,9 +611,61 @@ def test_handle_config_marks_new_generation_as_pending(self): f_state = self.manager._discovery_state.families.get("bacnet") self.assertIsNotNone(f_state) self.assertEqual(f_state.phase, DiscoveryPhase.pending) - self.assertEqual(f_state.generation, "2026-09-14T13:00:00Z") + self.assertEqual(f_state.generation, gen_str) self.mock_device.trigger_state_update.assert_called() + def test_stale_past_generation_rejected_as_stopped(self): + """Verifies sporadic scan scheduled in the distant past never starts.""" + stale_gen = "2020-10-18T12:02:01Z" + fam_cfg = FamilyDiscoveryConfig( + generation=stale_gen, + depth=Depth.system, + ) + config = Config(discovery=DiscoveryConfig(families={"bacnet": fam_cfg})) + + self.manager.handle_config(config) + + f_state = self.manager._discovery_state.families.get("bacnet") + self.assertIsNotNone(f_state) + self.assertEqual(f_state.phase, DiscoveryPhase.stopped) + self.assertEqual(f_state.generation, stale_gen) + self.assertFalse(self.manager._should_scan("bacnet", fam_cfg)) + + def test_self_enumeration_lifecycle(self): + """Verifies self-enumeration generation tracking and event emission.""" + gen_str = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + config = Config( + discovery=DiscoveryConfig( + generation=gen_str, + enumerations=Enumerations( + families=Depth.entries, + features=Depth.entries, + points=Depth.buckets, + ), + ) + ) + self.manager.handle_config(config) + + self.assertEqual(self.manager._discovery_state.generation, gen_str) + self.assertTrue(self.mock_dispatcher.publish_event.called) + call_args = self.mock_dispatcher.publish_event.call_args[0] + channel = call_args[0] + evt = call_args[1] + self.assertEqual(channel, "events/discovery") + self.assertEqual(evt.generation, gen_str) + self.assertIsNotNone(evt.families) + self.assertIsNotNone(evt.features) + self.assertIn("discovery.scan", evt.features) + self.assertIn("enumeration.families", evt.features) + self.assertIn("enumeration.features", evt.features) + self.assertNotIn("discovery_scan", evt.features) + self.assertIsNone(evt.points) + + # Clearing generation resets state.discovery.generation + clear_cfg = Config(discovery=DiscoveryConfig(generation=None)) + self.manager.handle_config(clear_cfg) + self.assertIsNone(self.manager._discovery_state.generation) + def test_update_family_state_transitions_active_and_stopped(self): """Verifies that _update_family_state transitions active/stopped phases.""" self.manager._update_family_state("bacnet", True) @@ -595,7 +685,6 @@ def test_future_generation_held_in_pending_phase(self): ) self.manager._config = DiscoveryConfig(families={"bacnet": fam_cfg}) - # _should_scan must return False because generation is in the future self.assertFalse(self.manager._should_scan("bacnet", fam_cfg)) f_state = self.manager._discovery_state.families.get("bacnet") self.assertIsNotNone(f_state) @@ -603,8 +692,8 @@ def test_future_generation_held_in_pending_phase(self): self.assertEqual(f_state.generation, future_gen_str) def test_past_generation_triggers_when_due(self): - """Verifies that past/due generation timestamps trigger scanning.""" - past_time = datetime.now(timezone.utc) - timedelta(seconds=10) + """Verifies that recent past/due generation timestamps trigger scanning.""" + past_time = datetime.now(timezone.utc) - timedelta(seconds=5) past_gen_str = past_time.strftime("%Y-%m-%dT%H:%M:%SZ") fam_cfg = FamilyDiscoveryConfig( generation=past_gen_str, @@ -616,7 +705,7 @@ def test_past_generation_triggers_when_due(self): def test_trace_generation_triggers_when_due(self): """Verifies that trace capture triggers when due after config update.""" - past_time = datetime.now(timezone.utc) - timedelta(seconds=10) + past_time = datetime.now(timezone.utc) - timedelta(seconds=5) past_gen_str = past_time.strftime("%Y-%m-%dT%H:%M:%SZ") fam_cfg = FamilyDiscoveryConfig( generation=past_gen_str, @@ -626,10 +715,8 @@ def test_trace_generation_triggers_when_due(self): config = Config(discovery=DiscoveryConfig(families={"ether": fam_cfg})) self.manager.handle_config(config) - # After handle_config, the scan is pending and due, so _should_scan is True self.assertTrue(self.manager._should_scan("ether", fam_cfg)) - # Once the scan runs and stops, it should not trigger again f_state = self.manager._discovery_state.families.get("ether") self.assertIsNotNone(f_state) f_state.phase = DiscoveryPhase.stopped @@ -638,35 +725,32 @@ def test_trace_generation_triggers_when_due(self): def test_recurring_interval_advances_generation_and_pending(self): """Verifies recurring interval advances generation and marks pending.""" fam_cfg = FamilyDiscoveryConfig( - generation="2026-09-14T10:00:00Z", + generation="2026-11-10T10:00:00Z", scan_interval_sec=300, depth=Depth.system, ) self.manager._config = DiscoveryConfig(families={"bacnet": fam_cfg}) f_state = FamilyDiscoveryState( - generation="2026-09-14T10:00:00Z", + generation="2026-11-10T10:00:00Z", phase=DiscoveryPhase.active, ) self.manager._discovery_state.families["bacnet"] = f_state - # When scan finishes, _update_family_state advances generation by 300s self.manager._update_family_state("bacnet", False) - self.assertFalse(f_state.active) self.assertEqual(f_state.phase, DiscoveryPhase.pending) - self.assertEqual(f_state.generation, "2026-09-14T10:05:00Z") + self.assertEqual(f_state.generation, "2026-11-10T10:05:00Z") self.assertEqual(f_state.active_count, 0) def test_active_count_increments_on_scan_results(self): """Verifies active_count dynamically tracks discovered devices in state.""" f_state = FamilyDiscoveryState( - generation="2026-09-14T10:00:00Z", + generation="2026-11-10T10:00:00Z", phase=DiscoveryPhase.active, active_count=0, ) self.manager._discovery_state.families["bacnet"] = f_state - # Start marker (event_no: 0) should not increment active_count start_evt = DiscoveryEvents(family="bacnet", event_no=0) self.manager._handle_scan_result("self", start_evt) self.assertEqual(f_state.active_count, 0) @@ -674,12 +758,12 @@ def test_active_count_increments_on_scan_results(self): evt1 = DiscoveryEvents(family="bacnet", addr="dev-1") self.manager._handle_scan_result("dev-1", evt1) self.assertEqual(f_state.active_count, 1) + self.assertEqual(evt1.generation, "2026-11-10T10:00:00Z") evt2 = DiscoveryEvents(family="bacnet", addr="dev-2", event_no=2) self.manager._handle_scan_result("dev-2", evt2) self.assertEqual(f_state.active_count, 2) - # Finish marker (event_no: -3) should not increment active_count finish_evt = DiscoveryEvents(family="bacnet", event_no=-3) self.manager._handle_scan_result("self", finish_evt) self.assertEqual(f_state.active_count, 2) @@ -691,7 +775,7 @@ def test_provider_exception_propagates_status_500_and_stopped(self): self.manager._active_providers.append(mock_provider) fam_cfg = FamilyDiscoveryConfig( - generation="2026-09-14T10:00:00Z", depth=Depth.system + generation="2026-11-10T10:00:00Z", depth=Depth.system ) self.manager._config = DiscoveryConfig(families={"bacnet": fam_cfg}) @@ -699,16 +783,13 @@ def test_provider_exception_propagates_status_500_and_stopped(self): f_state = self.manager._discovery_state.families.get("bacnet") self.assertIsNotNone(f_state) - self.assertFalse(f_state.active) self.assertEqual(f_state.phase, DiscoveryPhase.stopped) self.assertIsNotNone(f_state.status) self.assertEqual(f_state.status.level, 500) - self.assertEqual(f_state.status.category, "discovery.error") + self.assertEqual(f_state.status.category, "discovery.family.scan") + self.assertIsNotNone(f_state.status.timestamp) self.assertIn("BACnet socket failure", f_state.status.message) if __name__ == "__main__": unittest.main() - - - diff --git a/edge/spotter/tests/test_config_generator.py b/edge/spotter/tests/test_config_generator.py index 3575767bad..148f1813c8 100644 --- a/edge/spotter/tests/test_config_generator.py +++ b/edge/spotter/tests/test_config_generator.py @@ -119,20 +119,20 @@ def test_generate_spotter_config_bacnet_ip_override(self): self.assertEqual(config["bacnet"]["ip"], "192.168.1.5") def test_generate_spotter_config_bacnet_ip_from_metadata(self): - """Verifies bacnet IP extraction from device metadata.json.""" + """Verifies bacnet IP and device_id extraction from device metadata.json.""" device_dir = os.path.join(self.site_path, "devices", "DSN-1") metadata = { "localnet": { "families": { "bacnet": { - "ip": "10.0.0.42" + "ip": "10.0.0.42", + "addr": "291842", } } } } - with open( - os.path.join(device_dir, "metadata.json"), "w", encoding="utf-8" - ) as f: + metadata_file = os.path.join(device_dir, "metadata.json") + with open(metadata_file, "w", encoding="utf-8") as f: json.dump(metadata, f) config = generate_spotter_config( @@ -141,6 +141,16 @@ def test_generate_spotter_config_bacnet_ip_from_metadata(self): device_id="DSN-1", ) self.assertEqual(config["bacnet"]["ip"], "10.0.0.42") + self.assertEqual(config["bacnet"]["device_id"], 291842) + + with open(metadata_file, "w", encoding="utf-8") as f: + f.write("{corrupted_json") + with self.assertRaises(ValueError): + generate_spotter_config( + site_path=self.site_path, + project_spec="//mqtt/localhost:18883", + device_id="DSN-1", + ) if __name__ == "__main__": diff --git a/edge/spotter/tests/test_pcap.py b/edge/spotter/tests/test_pcap.py index a8a5bc2375..5da97dd569 100644 --- a/edge/spotter/tests/test_pcap.py +++ b/edge/spotter/tests/test_pcap.py @@ -177,6 +177,146 @@ def test_capture_packets_circuit_breaker_throttles( self.assertEqual(chunks, []) mock_popen.assert_not_called() + def test_build_whois_and_router_bvll_frames(self): + """Verifies binary encoding of BACnet BVLL Who-Is-Router-To-Network and Who-Is frames.""" + from edge.spotter.src.pcap import ( + GLOBAL_BACNET_DNET, + build_whois_bvll, + build_whois_router_to_network_bvll, + ) + + router_pdu = build_whois_router_to_network_bvll() + self.assertEqual(router_pdu, b"\x81\x0b\x00\x07\x01\x80\x00") + + local_whois = build_whois_bvll(dnet=None) + self.assertEqual(local_whois, b"\x81\x0b\x00\x08\x01\x00\x10\x08") + + dnet_whois = build_whois_bvll(dnet=6100) + self.assertEqual( + dnet_whois, + b"\x81\x0b\x00\x0c\x01\x20" + (6100).to_bytes(2, "big") + b"\x00\xff\x10\x08", + ) + + global_whois = build_whois_bvll(dnet=GLOBAL_BACNET_DNET) + self.assertEqual( + global_whois, b"\x81\x0b\x00\x0c\x01\x20\xff\xff\x00\xff\x10\x08" + ) + + @patch("socket.socket") + def test_send_raw_bvll_uses_raw_socket_without_binding_47808( + self, mock_socket_cls + ): + """Verifies send_raw_bvll sends UDP source port 47808 via SOCK_RAW without binding.""" + import socket as py_socket + import struct + from edge.spotter.src.pcap import ( + BACNET_UDP_PORT, + build_whois_bvll, + send_raw_bvll, + ) + + mock_raw_sock = MagicMock() + mock_socket_cls.return_value.__enter__.return_value = mock_raw_sock + + pdu = build_whois_bvll(dnet=None) + ok = send_raw_bvll( + pdu=pdu, + dst_ip="255.255.255.255", + src_ip="192.168.1.50", + src_port=BACNET_UDP_PORT, + interface="eth0", + ) + self.assertTrue(ok) + mock_socket_cls.assert_called_once_with( + py_socket.AF_INET, py_socket.SOCK_RAW, py_socket.IPPROTO_UDP + ) + mock_raw_sock.bind.assert_not_called() + mock_raw_sock.sendto.assert_called_once() + udp_frame, addr = mock_raw_sock.sendto.call_args[0] + self.assertEqual(addr, ("255.255.255.255", 47808)) + sport, dport, ulen, csum = struct.unpack("!HHHH", udp_frame[:8]) + self.assertEqual(sport, 47808) + self.assertEqual(dport, 47808) + self.assertEqual(ulen, 8 + len(pdu)) + self.assertNotEqual(csum, 0) + self.assertEqual(udp_frame[8:], pdu) + + @patch("edge.spotter.src.pcap.send_raw_bvll", return_value=True) + def test_run_bacnet_trace_whois_rounds_and_routed_extraction(self, mock_send): + """Verifies 3 paced rounds of raw-socket broadcast/unicast Who-Is and I-Am-Router / SNET extraction.""" + import threading + from edge.spotter.src.pcap import ( + extract_routed_networks_from_pcap_chunk, + run_bacnet_trace_whois_rounds, + ) + + # 1. BVLL Original-Broadcast-NPDU carrying I-Am-Router-To-Network for DNETs 6100 and 9288 + iam_router_frame = ( + b"\x81\x0b\x00\x0b\x01\x80\x01" + + (6100).to_bytes(2, "big") + + (9288).to_bytes(2, "big") + ) + # 2. BVLL Forwarded-NPDU (0x04) from router 192.168.50.12 with NPDU SNET=7700, SLEN=1, SADR=5 + routed_snet_frame = ( + b"\x81\x04\x00\x16" + + bytes([192, 168, 50, 12]) + + (47808).to_bytes(2, "big") + + b"\x01\x08" + + (7700).to_bytes(2, "big") + + b"\x01\x05" + + b"\x00\x05\x01\x0c\x0c" + ) + routers = set() + routed = extract_routed_networks_from_pcap_chunk( + b"PCAP_HDR" + iam_router_frame + routed_snet_frame + b"TRAILING", + discovered_routers=routers, + ) + self.assertEqual(routed, {6100, 9288, 7700}) + self.assertEqual(routers, {"192.168.50.12"}) + + timestamps = [] + stop_evt = threading.Event() + run_bacnet_trace_whois_rounds( + discovered_routed_networks={6100, 9288}, + scan_round_timestamps=timestamps, + stop_event=stop_evt, + max_duration_sec=1, + interface="eth0", + src_ip="192.168.1.50", + rounds=3, + discovered_routers=routers, + ) + self.assertEqual(len(timestamps), 3) + # Per round (with 1 router and 2 DNETs): + # - Who-Is-Router: 1 bcast + 1 unicast = 2 + # - Local Who-Is: 1 bcast + 1 unicast = 2 + # - 2 DNETs: 2 * (1 bcast + 1 unicast) = 4 + # - Global Who-Is: 1 bcast + 1 unicast = 2 + # Total per round = 10 * 3 rounds = 30 + self.assertEqual(mock_send.call_count, 30) + + @patch("subprocess.Popen") + def test_capture_packets_raises_on_tcpdump_nonzero_exit(self, mock_popen): + """Verifies capture_packets raises RuntimeError if tcpdump exits with an error.""" + mock_proc = MagicMock() + mock_proc.stdout.fileno.side_effect = AttributeError("mock pipe") + mock_proc.stdout.read.return_value = b"" + mock_proc.stderr.read.return_value = b"tcpdump: syntax error in filter expression" + mock_proc.poll.return_value = 1 + mock_proc.returncode = 1 + mock_popen.return_value = mock_proc + + with self.assertRaises(RuntimeError) as ctx: + list( + capture_packets( + interface="eth0", + filter_str="invalid_bpf_syntax", + max_duration_sec=5, + max_bytes=10000, + ) + ) + self.assertIn("tcpdump failed (exit code 1)", str(ctx.exception)) + if __name__ == "__main__": unittest.main() diff --git a/edge/spotter/tests/test_providers.py b/edge/spotter/tests/test_providers.py index 094fc2fb27..071acd2462 100644 --- a/edge/spotter/tests/test_providers.py +++ b/edge/spotter/tests/test_providers.py @@ -1,27 +1,112 @@ #!/usr/bin/env python3 """Unit tests for discovery family providers: BACnet, Ether, and Passive.""" +import subprocess import tempfile +import threading +import time import unittest from unittest.mock import MagicMock, patch from BAC0.core.devices.Device import DeviceDisconnected +from BAC0.core.io.IOExceptions import SegmentationNotSupported from edge.spotter.src.providers.bacnet import BacnetFamilyProvider from edge.spotter.src.providers.ether import EtherFamilyProvider +from edge.spotter.src.providers.ether import expand_ip_targets from edge.spotter.src.providers.ether import get_mac_for_ip from edge.spotter.src.providers.ether import parse_nmap_xml from edge.spotter.src.providers.passive import PassiveFamilyProvider from edge.spotter.src.providers.passive import PassiveScanRecord from edge.spotter.src.providers.passive import PRIVATE_IP_BPF_FILTER +from edge.spotter.src.providers.passive import extract_bacnet_iam from udmi.schema import FamilyDiscoveryConfig class TestBacnetFamilyProvider(unittest.TestCase): - """Unit tests for BacnetFamilyProvider.""" + """Unit tests for BacnetFamilyProvider across UDMI BACnet spec depths.""" @patch("edge.spotter.src.providers.bacnet.BAC0") - def test_global_bacnet_scan(self, mock_bac0): - """Verifies BAC0 device discovery and metadata attribute extraction.""" + def test_bacnet_depth_buckets(self, mock_bac0): + """Verifies buckets depth emits network and UDP port without device addr.""" + mock_client = MagicMock() + mock_bac0.lite.return_value = mock_client + mock_client.known_network_numbers = [9288, 6100] + + provider = BacnetFamilyProvider(bacnet_ip="127.0.0.1", bacnet_port=47808) + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", depth="buckets" + ) + + published = [] + provider.start_scan( + config, lambda dev_id, evt: published.append((dev_id, evt)) + ) + + # Start (0), 2 buckets (1, 2), Stop (-3) + self.assertEqual(len(published), 4) + self.assertEqual(published[0][1].event_no, 0) + b1 = published[1][1] + self.assertEqual(b1.family, "bacnet") + self.assertEqual(b1.network, "6100") + self.assertEqual(b1.families["ipv4"].port, 47808) + self.assertIsNone(b1.addr) + self.assertIsNone(b1.system) + self.assertIsNone(b1.refs) + + b2 = published[2][1] + self.assertEqual(b2.network, "9288") + self.assertEqual(b2.families["ipv4"].port, 47808) + self.assertIsNone(b2.addr) + self.assertEqual(published[3][1].event_no, -3) + + @patch("edge.spotter.src.providers.bacnet._get_mac_for_ip") + @patch("edge.spotter.src.providers.bacnet.BAC0") + def test_bacnet_depth_entries_ipv4_port_and_ethmac( + self, mock_bac0, mock_get_mac + ): + """Verifies entries depth populates addr, ipv4 addr/port, and ethmac.""" + mock_client = MagicMock() + mock_bac0.lite.return_value = mock_client + mock_get_mac.return_value = "82:CC:18:9A:45:1C" + + provider = BacnetFamilyProvider(bacnet_ip="127.0.0.1", bacnet_port=47808) + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", depth="entries" + ) + + event = provider.discover_device("192.168.10.45", 291842, config) + + self.assertEqual(event.addr, "291842") + self.assertEqual(event.family, "bacnet") + self.assertEqual(event.families["ipv4"].addr, "192.168.10.45") + self.assertEqual(event.families["ipv4"].port, 47808) + self.assertEqual(event.families["ethmac"].addr, "82:CC:18:9A:45:1C") + self.assertIsNone(event.system) + self.assertIsNone(event.refs) + mock_client.readMultiple.assert_not_called() + + @patch("edge.spotter.src.providers.bacnet.BAC0") + def test_bacnet_depth_entries_routed_mstp(self, mock_bac0): + """Verifies routed MS/TP address '6100:10' sets network and mstp family.""" + mock_client = MagicMock() + mock_bac0.lite.return_value = mock_client + + provider = BacnetFamilyProvider() + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", depth="entries" + ) + + event = provider.discover_device("6100:10", 200011, config) + + self.assertEqual(event.addr, "200011") + self.assertEqual(event.network, "6100") + self.assertNotIn("ipv4", event.families) + self.assertNotIn("bacnet", event.families) + self.assertEqual(event.families["mstp"].addr, "10") + + @patch("edge.spotter.src.providers.bacnet.BAC0") + def test_global_bacnet_scan_system_depth(self, mock_bac0): + """Verifies BAC0 device discovery and spec-compliant system properties.""" mock_client = MagicMock() mock_bac0.lite.return_value = mock_client mock_client.discoveredDevices = {("192.168.1.50", 1234): "Device"} @@ -34,58 +119,191 @@ def test_global_bacnet_scan(self, mock_bac0): "Air Handler", "Roof", "App-4.0", + 8, + 1, + 14, ) provider = BacnetFamilyProvider(bacnet_ip="127.0.0.1", bacnet_port=47808) config = FamilyDiscoveryConfig( - generation="2026-09-01T12:00:00Z", depth="system" + generation="2026-11-10T12:00:00Z", depth="system" ) - # Run discovery event = provider.discover_device("192.168.1.50:47808", 1234, config) self.assertEqual(event.addr, "1234") self.assertEqual(event.family, "bacnet") self.assertEqual(event.families["ipv4"].addr, "192.168.1.50") + self.assertEqual(event.families["ipv4"].port, 47808) self.assertEqual(event.system.name, "Main-AHU") self.assertEqual(event.system.description, "Air Handler") - self.assertEqual(event.system.ancillary["name"], "Main-AHU") - self.assertEqual(event.system.ancillary["description"], "Air Handler") - self.assertEqual(event.system.ancillary["location"], "Roof") - self.assertEqual(event.system.ancillary["application_version"], "App-4.0") + self.assertEqual(event.system.serial_no, "SN-9999") self.assertEqual(event.system.hardware.make, "Delta") self.assertEqual(event.system.hardware.model, "DSC-1212") - self.assertEqual(event.system.serial_no, "SN-9999") + self.assertEqual(event.system.ancillary["firmware-revision"], "v1.2.3") + self.assertEqual( + event.system.ancillary["application-software-version"], "App-4.0" + ) + self.assertEqual(event.system.ancillary["location"], "Roof") + self.assertEqual(event.system.ancillary["vendor-identifier"], 8) + self.assertEqual(event.system.ancillary["protocol-version"], 1) + self.assertEqual(event.system.ancillary["protocol-revision"], 14) + self.assertNotIn("name", event.system.ancillary) + self.assertNotIn("description", event.system.ancillary) + + @patch("edge.spotter.src.providers.bacnet.BAC0") + def test_bacnet_system_segmentation_fallback(self, mock_bac0): + """Verifies ReadPropertyMultiple falls back to ReadProperty on segmentation error.""" + mock_client = MagicMock() + mock_bac0.lite.return_value = mock_client + mock_client.readMultiple.side_effect = SegmentationNotSupported( + "segmentation-not-supported" + ) + prop_values = { + "objectName": "AHU-Seg", + "vendorName": "Trane", + "firmwareRevision": "2.0", + "modelName": "UC400", + "serialNumber": "SN-400", + "description": "Segmented Controller", + "location": "Basement", + "applicationSoftwareVersion": "1.1", + "vendorIdentifier": 2, + "protocolVersion": 1, + "protocolRevision": 12, + } + mock_client.read.side_effect = ( + lambda req: prop_values.get(req.split()[-1]) + ) + + provider = BacnetFamilyProvider() + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", depth="system" + ) + event = provider.discover_device("192.168.1.60", 4001, config) + + self.assertIsNone(event.status) + self.assertEqual(event.system.name, "AHU-Seg") + self.assertEqual(event.system.hardware.make, "Trane") + self.assertEqual(event.system.hardware.model, "UC400") + self.assertEqual(event.system.ancillary["firmware-revision"], "2.0") + self.assertEqual(event.system.ancillary["vendor-identifier"], 2) @patch("edge.spotter.src.providers.bacnet.BAC0") - def test_bacnet_refs_enumeration(self, mock_bac0): - """Verifies BACnet point reference extraction.""" + def test_bacnet_details_refs_enumeration(self, mock_bac0): + """Verifies BACnet point reference extraction at details depth.""" mock_client = MagicMock() mock_bac0.lite.return_value = mock_client mock_dev = MagicMock() - mock_point = MagicMock() - mock_point.properties.name = "zone_temp" - mock_point.properties.description = "Zone Temperature" - mock_point.properties.type = "analogValue" - mock_point.properties.address = "1" - mock_point.properties.units_state = "degC" - mock_point.lastValue = 22.5 - mock_dev.points = [mock_point] + av_point = MagicMock() + av_point.properties.name = "zone_temp_sp" + av_point.properties.description = "Zone Temperature Setpoint" + av_point.properties.type = "analogValue" + av_point.properties.address = "1" + av_point.properties.units_state = "degrees-celsius" + av_point.properties.writable = None + av_point.properties.bacnet_properties = { + "outOfService": False, + "priorityArray": [None] * 16, + } + av_point.lastValue = 22.5 + + bi_point = MagicMock() + bi_point.properties.name = "fan_status" + bi_point.properties.description = "Supply Fan Status" + bi_point.properties.type = "binaryInput" + bi_point.properties.address = "2" + bi_point.properties.units_state = ("Off", "On") + bi_point.properties.writable = None + bi_point.properties.bacnet_properties = {} + bi_point.lastValue = "On" + + bv_point = MagicMock() + bv_point.properties.name = "damper_cmd" + bv_point.properties.description = "Damper Command" + bv_point.properties.type = "binaryValue" + bv_point.properties.address = "3" + bv_point.properties.units_state = (None, None) + bv_point.properties.writable = None + bv_point.properties.bacnet_properties = {"priorityArray": None} + bv_point.lastValue = "active" + + mock_dev.points = [av_point, bi_point, bv_point] mock_bac0.device.return_value = mock_dev provider = BacnetFamilyProvider() refs = provider.enumerate_refs("192.168.1.50 1234") - self.assertIn("AV:1", refs) - self.assertEqual(refs["AV:1"].name, "zone_temp") - self.assertEqual(refs["AV:1"].units, "degC") - self.assertIsNotNone(refs["AV:1"].ancillary) - self.assertEqual(refs["AV:1"].ancillary["present_value"], "22.5") + self.assertIn("AV/1", refs) + self.assertEqual(refs["AV/1"].name, "zone_temp_sp") + self.assertEqual(refs["AV/1"].type, "analog-value") + self.assertEqual(refs["AV/1"].units, "degrees-celsius") + self.assertTrue(refs["AV/1"].writable) + self.assertEqual(refs["AV/1"].ancillary["present-value"], 22.5) + self.assertIs(refs["AV/1"].ancillary["out-of-service"], False) + + self.assertIn("BI/2", refs) + self.assertEqual(refs["BI/2"].name, "fan_status") + self.assertEqual(refs["BI/2"].type, "binary-input") + self.assertFalse(refs["BI/2"].writable) + self.assertEqual(refs["BI/2"].possible_values, ["Off", "On"]) + self.assertEqual(refs["BI/2"].ancillary["present-value"], "On") + + self.assertIn("BV/3", refs) + self.assertEqual(refs["BV/3"].type, "binary-value") + # BV/3 has priorityArray=None so it is non-commandable (writable=False) + self.assertFalse(refs["BV/3"].writable) + self.assertEqual(refs["BV/3"].possible_values, ["inactive", "active"]) + + @patch("edge.spotter.src.providers.bacnet.BAC0") + def test_bacnet_addrs_instance_and_range_filtering(self, mock_bac0): + """Verifies BACnet addrs instance and range filtering and self-exclusion.""" + mock_client = MagicMock() + mock_bac0.lite.return_value = mock_client + mock_client.discoveredDevices = { + ("192.168.1.10", 1005): "Device", + ("192.168.1.11", 2500): "Device", + ("192.168.1.12", 291842): "Device", + ("192.168.1.99", 4194300): "SelfDevice", + } + + provider = BacnetFamilyProvider(unchanged_threshold_sec=1) + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", + depth="entries", + addrs=["1000-1999", "291842", "4194300"], + ) + + published = [] + provider.start_scan( + config, lambda dev_id, evt: published.append((dev_id, evt)) + ) + + addrs_found = [evt.addr for _, evt in published if evt.addr is not None] + self.assertEqual(addrs_found, ["1005", "291842"]) + + @patch("edge.spotter.src.providers.bacnet.BAC0") + def test_bacnet_invalid_addrs_and_networks_fail_fast(self, mock_bac0): + """Verifies invalid BACnet addrs or networks raise ValueError.""" + provider = BacnetFamilyProvider() + for bad_addr in ("0123", "2000-1000", "192.168.1.1", "5000000"): + cfg = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", addrs=[bad_addr] + ) + with self.assertRaises(ValueError): + provider.start_scan(cfg, MagicMock()) + + for bad_net in ("0", "65535", "010", "net-1"): + cfg = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", networks=[bad_net] + ) + with self.assertRaises(ValueError): + provider.start_scan(cfg, MagicMock()) @patch("edge.spotter.src.providers.bacnet.BAC0") def test_bacnet_refs_disconnected_fails_fast(self, mock_bac0): - """Verifies silent BAC0.device timeouts surface as discovery.error status.""" + """Verifies silent BAC0.device timeouts surface as discovery.device.enumerate status.""" mock_client = MagicMock() mock_bac0.lite.return_value = mock_client mock_client.readMultiple.return_value = ( @@ -110,7 +328,7 @@ def test_bacnet_refs_disconnected_fails_fast(self, mock_bac0): provider = BacnetFamilyProvider() config = FamilyDiscoveryConfig( - generation="2026-09-01T12:00:00Z", depth="refs" + generation="2026-11-10T12:00:00Z", depth="details" ) for timed_out_dev in (disconnected_dev, empty_objlist_dev): @@ -118,8 +336,9 @@ def test_bacnet_refs_disconnected_fails_fast(self, mock_bac0): event = provider.discover_device("192.168.1.50", 12341, config) self.assertIsNone(event.refs) self.assertIsNotNone(event.status) - self.assertEqual(event.status.category, "discovery.error") + self.assertEqual(event.status.category, "discovery.device.enumerate") self.assertEqual(event.status.level, 500) + self.assertIsNotNone(event.status.timestamp) self.assertIn("Point enumeration failed", event.status.message) @patch("edge.spotter.src.providers.bacnet.BAC0") @@ -141,7 +360,7 @@ def test_bacnet_scan_unchanged_threshold(self, mock_bac0): provider = BacnetFamilyProvider(unchanged_threshold_sec=1) config = FamilyDiscoveryConfig( - generation="2026-09-01T12:00:00Z", depth="system" + generation="2026-11-10T12:00:00Z", depth="system" ) published = [] @@ -153,13 +372,10 @@ def test_bacnet_scan_unchanged_threshold(self, mock_bac0): global_broadcast=True, reset=True ) self.assertEqual(len(published), 3) - # Start marker self.assertEqual(published[0][1].event_no, 0) - # Discovered device self.assertEqual(published[1][0], "1234") self.assertEqual(published[1][1].addr, "1234") self.assertEqual(published[1][1].event_no, 1) - # Finish marker self.assertEqual(published[2][1].event_no, -2) @@ -175,8 +391,8 @@ def test_ping_scan_duration_timeout(self, mock_subproc_run): provider = EtherFamilyProvider(ping_concurrency=1) config = FamilyDiscoveryConfig( - generation="2026-09-01T12:00:00Z", - depth="ping", + generation="2026-11-10T12:00:00Z", + depth="entries", addrs=["10.0.0.1", "10.0.0.2", "10.0.0.3"], scan_duration_sec=0.001, ) @@ -190,16 +406,20 @@ def test_ping_scan_duration_timeout(self, mock_subproc_run): self.assertEqual(published[0][1].event_no, 0) self.assertLess(published[-1][1].event_no, 0) + @patch("edge.spotter.src.providers.ether.get_hostname_for_ip") @patch("subprocess.run") - def test_ping_scan_success(self, mock_subproc_run): - """Verifies ICMP ping sweep emission of discovery events.""" + def test_ping_scan_success(self, mock_subproc_run, mock_hostname): + """Verifies ICMP ping sweep emission of discovery events at entries depth.""" mock_res = MagicMock() mock_res.returncode = 0 mock_subproc_run.return_value = mock_res + mock_hostname.return_value = None provider = EtherFamilyProvider(ping_concurrency=2) config = FamilyDiscoveryConfig( - generation="2026-09-01T12:00:00Z", depth="ping", addrs=["10.0.0.1"] + generation="2026-11-10T12:00:00Z", + depth="entries", + addrs=["10.0.0.1"], ) published = [] @@ -217,20 +437,106 @@ def test_ping_scan_success(self, mock_subproc_run): self.assertEqual(event.event_no, 1) self.assertEqual(published[2][1].event_no, -2) + @patch("edge.spotter.src.providers.ether.get_hostname_for_ip") + @patch("subprocess.run") + def test_ping_cidr_expansion_and_subnet_fallback( + self, mock_subproc_run, mock_hostname + ): + """Verifies CIDR netblock expansion and subnet_filter fallback.""" + mock_res = MagicMock() + mock_res.returncode = 0 + mock_subproc_run.return_value = mock_res + mock_hostname.return_value = None + + self.assertEqual( + list(expand_ip_targets(["192.168.1.0/30", "10.0.0.5"])), + ["192.168.1.1", "192.168.1.2", "10.0.0.5"], + ) + + # Fallback to configured subnet_filter when addrs and networks are omitted + provider = EtherFamilyProvider( + ping_concurrency=2, subnet_filter="192.168.2.0/30" + ) + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", depth="entries" + ) + published = [] + provider.start_scan( + config, lambda dev_id, evt: published.append((dev_id, evt)) + ) + found_ips = sorted( + evt.families["ipv4"].addr + for _, evt in published + if evt.families and "ipv4" in evt.families + ) + self.assertEqual(found_ips, ["192.168.2.1", "192.168.2.2"]) + + def test_ether_buckets_depth(self): + """Verifies buckets depth emits numeric VLAN network IDs per EtherFamilyProvider.""" + provider = EtherFamilyProvider(subnet_filter="10.20.30.5/24") + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", depth="buckets" + ) + published = [] + provider.start_scan( + config, lambda dev_id, evt: published.append((dev_id, evt)) + ) + self.assertEqual(len(published), 3) + self.assertEqual(published[1][1].network, "1") + self.assertIsNone(published[1][1].addr) + + # VLAN ID in networks sets event.network to the VLAN ID + vlan_cfg = FamilyDiscoveryConfig( + generation="2026-11-10T12:05:00Z", + depth="buckets", + networks=["100"], + ) + vlan_pub = [] + provider.start_scan( + vlan_cfg, lambda dev_id, evt: vlan_pub.append((dev_id, evt)) + ) + self.assertEqual(len(vlan_pub), 3) + self.assertEqual(vlan_pub[1][1].network, "100") + + # Invalid VLAN ID (> 4094) fails fast + bad_vlan_cfg = FamilyDiscoveryConfig( + generation="2026-11-10T12:10:00Z", + depth="buckets", + networks=["5000"], + ) + with self.assertRaises(ValueError): + provider.start_scan(bad_vlan_cfg, MagicMock()) + + def test_ether_rejects_legacy_non_canonical_depths(self): + """Verifies legacy depths ('ping', 'ports', 'services') fail fast.""" + provider = EtherFamilyProvider() + for bad_depth in ("ping", "ports", "services", "invalid"): + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", + depth=bad_depth, + addrs=["10.0.0.1"], + ) + with self.assertRaises(ValueError): + provider.start_scan(config, MagicMock()) + + @patch("edge.spotter.src.providers.ether.get_hostname_for_ip") @patch("edge.spotter.src.providers.ether.get_mac_for_ip") @patch("subprocess.run") def test_ping_scan_with_arp_resolution( - self, mock_subproc_run, mock_get_mac + self, mock_subproc_run, mock_get_mac, mock_hostname ): """Verifies ARP resolution attaches MAC address to ether discovery.""" mock_res = MagicMock() mock_res.returncode = 0 mock_subproc_run.return_value = mock_res mock_get_mac.return_value = "00:50:b6:ed:5f:77" + mock_hostname.return_value = "ahu-1.local" provider = EtherFamilyProvider(ping_concurrency=2) config = FamilyDiscoveryConfig( - generation="2026-09-01T12:00:00Z", depth="ping", addrs=["10.0.0.1"] + generation="2026-11-10T12:00:00Z", + depth="entries", + addrs=["10.0.0.1"], ) published = [] @@ -245,6 +551,7 @@ def test_ping_scan_with_arp_resolution( self.assertEqual(event.family, "ether") self.assertEqual(event.addr, "00:50:b6:ed:5f:77") self.assertEqual(event.families["ipv4"].addr, "10.0.0.1") + self.assertEqual(event.families["host"].addr, "ahu-1.local") self.assertEqual(event.event_no, 1) self.assertEqual(published[2][1].event_no, -2) @@ -272,13 +579,15 @@ def test_get_mac_for_ip(self): self.assertIsNone(get_mac_for_ip("192.168.1.99", arp_file=f.name)) def test_parse_nmap_xml(self): - """Verifies nmap XML output parsing for host IP, MAC, and open ports.""" + """Verifies nmap XML output parsing for host IP, MAC, OS, and open ports.""" sample_xml = """

-
+
+ + @@ -297,6 +606,9 @@ def test_parse_nmap_xml(self): self.assertEqual(len(hosts), 1) self.assertEqual(hosts[0].ip, "192.168.1.10") self.assertEqual(hosts[0].mac, "00:11:22:33:44:55") + self.assertEqual(hosts[0].mac_vendor, "Delta") + self.assertEqual(hosts[0].hostname, "controller-1.local") + self.assertEqual(hosts[0].os_name, "Linux 5.15") self.assertEqual(len(hosts[0].ports), 2) self.assertEqual(hosts[0].ports[0].port_number, 80) self.assertEqual(hosts[0].ports[0].service_name, "http") @@ -304,6 +616,61 @@ def test_parse_nmap_xml(self): self.assertEqual(hosts[0].ports[0].version, "2.4.41") self.assertEqual(hosts[0].ports[0].banner, "Apache/2.4.41") + with self.assertRaises(ValueError): + parse_nmap_xml("' + '
' + '' + ) + partial_hosts = parse_nmap_xml(truncated_xml, allow_partial=True) + self.assertEqual(len(partial_hosts), 1) + self.assertEqual(partial_hosts[0].ip, "10.0.0.15") + + @patch("os.path.exists", return_value=True) + @patch("subprocess.Popen") + def test_nmap_scan_deadline_flushes_partial_hosts( + self, mock_popen, _mock_exists + ): + """Verifies Nmap scan flushes completed hosts when scan_duration_sec expires.""" + truncated_xml = ( + '' + '
' + '
' + '' + ) + mock_proc = MagicMock() + mock_proc.__enter__.return_value = mock_proc + calls = [] + + def fake_communicate(timeout=1.0): + calls.append(timeout) + if len(calls) == 1: + time.sleep(0.02) + raise subprocess.TimeoutExpired(cmd="nmap", timeout=timeout) + return (truncated_xml, "") + + mock_proc.communicate.side_effect = fake_communicate + mock_popen.return_value = mock_proc + + provider = EtherFamilyProvider() + config = FamilyDiscoveryConfig( + generation="2026-11-10T12:00:00Z", + depth="system", + addrs=["10.0.0.25", "10.0.0.26"], + scan_duration_sec=0.01, + ) + published = [] + provider.start_scan( + config, lambda dev_id, evt: published.append((dev_id, evt)) + ) + mock_proc.terminate.assert_called() + self.assertEqual(len(published), 3) + self.assertEqual(published[1][1].addr, "aa:bb:cc:dd:ee:ff") + self.assertEqual(published[1][1].families["ipv4"].addr, "10.0.0.25") + self.assertEqual(published[2][1].event_no, -2) + def test_ping_concurrency_clamping(self): """Verifies ping_concurrency clamps to at least 1.""" provider_zero = EtherFamilyProvider(ping_concurrency=0) @@ -321,8 +688,8 @@ def test_nmap_scan_fails_fast_when_binary_missing(self, mock_exists): mock_exists.return_value = False provider = EtherFamilyProvider() config = FamilyDiscoveryConfig( - generation="2026-09-01T12:00:00Z", - depth="ports", + generation="2026-11-10T12:00:00Z", + depth="details", addrs=["10.0.0.1"], ) with self.assertRaises(RuntimeError) as ctx: @@ -340,6 +707,54 @@ def test_passive_record_deduplication(self): records = {r1, r2} self.assertEqual(len(records), 1) + def test_extract_bacnet_iam(self): + """Verifies BACnet I-Am 22-bit instance extraction from BVLC UDP payload.""" + # BVLC 0x81, Original-Broadcast-NPDU, APDU I-Am \x10\x00\xc4, ObjectIdentifier (device=8, instance=291842 = 0x047402) + obj_id_bytes = ((8 << 22) | 291842).to_bytes(4, byteorder="big") + payload = b"\x81\x0b\x00\x0c\x01\x20\xff\xff\x00\xff\x10\x00\xc4" + obj_id_bytes + self.assertEqual(extract_bacnet_iam(payload), 291842) + self.assertIsNone(extract_bacnet_iam(b"\x00\x01\x02")) + + def test_decode_bacnet_bvll_bbmd_and_routed_mstp(self): + """Verifies Forwarded-NPDU real IP extraction, routed MS/TP SNET/SADR, and I-Am-Router DNETs.""" + from edge.spotter.src.providers.passive import decode_bacnet_bvll + + obj_id_bytes = ((8 << 22) | 200011).to_bytes(4, byteorder="big") + # 1. Forwarded-NPDU (0x04) from BBMD 10.0.0.1 with real originating IP 192.168.50.12:47808 + # and routed MS/TP SNET=6100, SLEN=1, SADR=10 (control=0x28: DNET=0xFFFF, DLEN=0 + SNET/SADR + HopCount) + forwarded_routed_payload = ( + b"\x81\x04\x00\x1d" + + bytes([192, 168, 50, 12]) + + (47808).to_bytes(2, "big") + + b"\x01\x28\xff\xff\x00" + + (6100).to_bytes(2, "big") + + b"\x01\x0a\xff" + + b"\x10\x00\xc4" + + obj_id_bytes + ) + decoded = decode_bacnet_bvll( + forwarded_routed_payload, outer_ip="10.0.0.1", outer_port=47808 + ) + self.assertIsNotNone(decoded) + self.assertEqual(decoded.device_id, 200011) + self.assertEqual(decoded.orig_ip, "192.168.50.12") + self.assertEqual(decoded.orig_port, 47808) + self.assertEqual(decoded.snet, 6100) + self.assertEqual(decoded.sadr, "10") + + # 2. I-Am-Router-To-Network (NPDU control=0x80, msg_type=0x01) + router_payload = ( + b"\x81\x0b\x00\x0b\x01\x80\x01" + + (6100).to_bytes(2, "big") + + (6200).to_bytes(2, "big") + ) + decoded_router = decode_bacnet_bvll( + router_payload, outer_ip="192.168.1.1", outer_port=47808 + ) + self.assertIsNotNone(decoded_router) + self.assertIsNone(decoded_router.device_id) + self.assertEqual(decoded_router.iam_router_networks, (6100, 6200)) + def test_build_bpf_filter_default(self): """Verifies that default BPF filter matches private IP subnets.""" provider = PassiveFamilyProvider() @@ -357,11 +772,11 @@ def test_build_bpf_filter_with_subnet(self): self.assertIn("and not src host 192.168.1.1", bpf) self.assertIn("and not src host 192.168.1.50", bpf) - def test_build_bpf_filter_invalid(self): - """Verifies graceful fallback on invalid subnet string.""" + def test_build_bpf_filter_invalid_fails_fast(self): + """Verifies ValueError raised on invalid subnet string.""" provider = PassiveFamilyProvider(subnet_filter="invalid_subnet") - bpf = provider.build_bpf_filter(provider.subnet_filter) - self.assertIn("src net invalid_subnet", bpf) + with self.assertRaises(ValueError): + provider.build_bpf_filter(provider.subnet_filter) @patch("edge.spotter.src.providers.passive.scapy") def test_passive_scan_markers_and_lifecycle(self, mock_scapy): @@ -371,35 +786,87 @@ def test_passive_scan_markers_and_lifecycle(self, mock_scapy): provider = PassiveFamilyProvider(interface="eth0") config = FamilyDiscoveryConfig( - generation="2026-09-11T09:00:00Z", scan_duration_sec=1 + generation="2026-11-10T09:00:00Z", scan_duration_sec=1 ) published = [] def mock_publish(addr, event): published.append((addr, event)) - # Stop immediately on start event to test finish marker if event.event_no == 0: provider.stop_scan() provider.start_scan(config, mock_publish) self.assertGreaterEqual(len(published), 2) - # Start marker self.assertEqual(published[0][0], "self") self.assertEqual(published[0][1].event_no, 0) self.assertEqual(published[0][1].family, "ipv4") - # Finish marker self.assertEqual(published[-1][0], "self") self.assertEqual(published[-1][1].event_no, -1) self.assertEqual(published[-1][1].family, "ipv4") + @patch("edge.spotter.src.providers.passive.scapy") + def test_passive_re_emission_after_holdoff(self, mock_scapy): + """Verifies passive_sec holdoff suppression and re-emission after expiry.""" + provider = PassiveFamilyProvider(interface="eth0") + provider._get_host = MagicMock(return_value=None) + + class FakePacket: + + def __contains__(self, layer): + return layer is mock_scapy.layers.inet.IP + + def __getitem__(self, layer): + ip_mock = MagicMock() + ip_mock.src = "10.0.0.77" + return ip_mock + + pkt = FakePacket() + published = [] + + provider._queue.put(pkt) + provider._queue.put(pkt) + + def stop_after_queue(): + while not provider._queue.empty(): + time.sleep(0.01) + time.sleep(0.05) + provider._cancelled.set() + + stopper = threading.Thread(target=stop_after_queue) + stopper.start() + provider._queue_worker(passive_sec=1) + stopper.join() + provider._flush_pending_records( + "2026-11-10T09:00:00Z", lambda addr, evt: published.append(evt) + ) + + self.assertEqual(len(published), 1) + self.assertEqual(published[0].addr, "10.0.0.77") + self.assertEqual(provider.passive_holdoff_count, 1) + + provider._cancelled.clear() + provider._last_published_at["10.0.0.77"] = time.monotonic() - 2.0 + provider._queue.put(pkt) + stopper2 = threading.Thread(target=stop_after_queue) + stopper2.start() + provider._queue_worker(passive_sec=1) + stopper2.join() + provider._flush_pending_records( + "2026-11-10T09:00:00Z", lambda addr, evt: published.append(evt) + ) + + self.assertEqual(len(published), 2) + self.assertEqual(published[1].addr, "10.0.0.77") + self.assertEqual(published[1].event_no, 2) + @patch("edge.spotter.src.providers.passive.scapy", None) def test_passive_scan_fails_fast_when_scapy_missing(self): """Verifies start_scan raises RuntimeError if scapy is not installed.""" provider = PassiveFamilyProvider(interface="eth0") - config = FamilyDiscoveryConfig(generation="2026-09-11T09:00:00Z") + config = FamilyDiscoveryConfig(generation="2026-11-10T09:00:00Z") with self.assertRaises(RuntimeError) as ctx: provider.start_scan(config, MagicMock()) self.assertIn("Scapy library is not installed", str(ctx.exception)) @@ -407,4 +874,3 @@ def test_passive_scan_fails_fast_when_scapy_missing(self): if __name__ == "__main__": unittest.main() - diff --git a/edge/spotter/tests/test_resource_contention.py b/edge/spotter/tests/test_resource_contention.py index 8ff9b53872..c6607ef6da 100644 --- a/edge/spotter/tests/test_resource_contention.py +++ b/edge/spotter/tests/test_resource_contention.py @@ -75,8 +75,14 @@ def test_no_file_descriptor_leaks_under_repeated_operations(self): max_duration_sec=1, max_bytes=1024, ) - # Drain generator chunks - _ = list(gen) + try: + # Drain generator chunks + _ = list(gen) + except RuntimeError as err: + # On unprivileged hosts without CAP_NET_RAW, tcpdump exits non-zero; + # verify the fail-fast error message and confirm pipe FDs are still + # closed cleanly in capture_packets' finally block. + self.assertIn("tcpdump failed", str(err)) fd_after = get_current_fd_count() fd_diff = fd_after - fd_before From ca5c018d725cf4733ee7e5949e84eb73dd0e350b Mon Sep 17 00:00:00 2001 From: Khyati Mahendru Date: Fri, 13 Nov 2026 07:22:53 +0000 Subject: [PATCH 5/8] Address independent review findings across Butler, Spotter, and SiteModel - Lazily initialize Google Cloud Storage client in PcapUploadHandler._upload_to_gcs when BUTLER_PCAP_GCS_BUCKET is set and require sha256 on terminal EOF markers. - Guard SpotterDiscoveryManager against superseded scan generation races when active scans are cancelled or replaced. - Preserve BACnet I-Am enrichment and routed MS/TP re-emission across passive_sec holdoff intervals and bound I-Am-Router-To-Network parsing by bvlc_len. - Issue per-range BACnet Who-Is discovery calls instead of collapsing disjoint addrs ranges and validate Nmap target specifications. - Collect sorted device IDs into LinkedHashSet in SiteModel.getDeviceIds() and require connection spec in ButlerProvider.trigger_bacnet_trace. --- butler/README.md | 12 ++ butler/src/handlers/pcap_upload.py | 25 +++- butler/tests/test_handlers.py | 27 ++++ .../java/com/google/udmi/util/SiteModel.java | 3 +- edge/spotter/README.md | 2 +- edge/spotter/bin/reassemble_pcap | 5 + edge/spotter/src/manager/discovery.py | 117 +++++++++++------- edge/spotter/src/pcap.py | 4 + edge/spotter/src/providers/bacnet.py | 15 ++- edge/spotter/src/providers/ether.py | 36 +++++- edge/spotter/src/providers/passive.py | 51 +++++--- mcp/butler/provider.py | 27 ++-- tests/test_mcp_butler.py | 5 + 13 files changed, 243 insertions(+), 86 deletions(-) diff --git a/butler/README.md b/butler/README.md index 52096fd717..61523c9435 100644 --- a/butler/README.md +++ b/butler/README.md @@ -103,6 +103,18 @@ Execute mapping reconciliation against database discovery events: bin/mapper sites/udmi_site_model //mqtt/localhost:46432 GAT-1 map ``` +### 3. PCAP Upload Reassembly & MCP Trace Tools + +Butler's `PcapUploadHandler` (`butler/src/handlers/pcap_upload.py`) subscribes to `upload/discovery` (`DiscoveryUpload`), reassembles gzip-compressed chunks `1..N` in order, verifies the mandatory `sha256` digest on the terminal `-(N+1)` EOF marker, and archives the `.pcap` and `scan_manifest.json` without writing raw chunk blobs to `udmi_messages`. + +- **Environment Variables**: + - `BUTLER_PCAP_DIR`: Local directory for reassembled `.pcap` and `scan_manifest.json` files (default: `out/pcap`). + - `BUTLER_PCAP_GCS_BUCKET`: Optional Google Cloud Storage bucket name (`gs:////.pcap`). + - `BUTLER_CONN_SPEC`: Default UDMI connection specification (e.g. `//mqtt/localhost:46432`) used by the Butler MCP server when triggering remote traces. +- **MCP Tools (`mcp/butler/`)**: + - `trigger_bacnet_trace`: Publishes a `depth: "trace"` `config/discovery` trigger for `families.bacnet`, records a `PENDING` capture entry in `udmi_pcap_captures`, and returns the target `.pcap` and `scan_manifest.json` URIs. + - `get_pcap_capture`: Queries `udmi_pcap_captures` for chunk reassembly progress (`PENDING`, `RECEIVING`, `COMPLETED`, `FAILED`), verified `sha256`, `scan_manifest`, and resolved URIs. + --- ## Testing diff --git a/butler/src/handlers/pcap_upload.py b/butler/src/handlers/pcap_upload.py index d0b4b9e611..f39f101a63 100644 --- a/butler/src/handlers/pcap_upload.py +++ b/butler/src/handlers/pcap_upload.py @@ -176,9 +176,18 @@ def _upsert_capture_metadata( def _upload_to_gcs( self, blob_path: str, content: bytes, content_type: str ) -> None: - """Uploads a reassembled artifact to GCS when gcs_client is configured.""" - if not self.gcs_bucket or self.gcs_client is None: + """Uploads a reassembled artifact to GCS when gcs_bucket is configured.""" + if not self.gcs_bucket: return + if self.gcs_client is None: + try: + from google.cloud import storage # pylint: disable=import-outside-toplevel + + self.gcs_client = storage.Client() + except Exception as err: + raise RuntimeError( + f"Failed to initialize GCS client for bucket '{self.gcs_bucket}': {err}" + ) from err bucket = self.gcs_client.bucket(self.gcs_bucket) blob = bucket.blob(blob_path) blob.upload_from_string(content, content_type=content_type) @@ -219,7 +228,17 @@ def _finalize_session( session.actual_sha256 = actual_sha256 session.total_bytes = len(pcap_bytes) - if session.expected_sha256 and actual_sha256 != session.expected_sha256: + if not session.expected_sha256: + err_msg = ( + f"Missing required 'sha256' digest in terminal upload/discovery EOF for " + f"{session.site}/{session.device_id}/{session.generation}" + ) + self._upsert_capture_metadata( + postgres_manager, session, status="FAILED", error_message=err_msg + ) + raise ValueError(err_msg) + + if actual_sha256 != session.expected_sha256: err_msg = ( f"PCAP SHA-256 digest mismatch for {session.site}/{session.device_id}/" f"{session.generation}: expected {session.expected_sha256}, got {actual_sha256}" diff --git a/butler/tests/test_handlers.py b/butler/tests/test_handlers.py index 52b8be016b..efead9db61 100644 --- a/butler/tests/test_handlers.py +++ b/butler/tests/test_handlers.py @@ -316,6 +316,33 @@ def test_pcap_upload_handler_reassembly_and_sha256_verification(self): ) self.assertEqual(len(handler._sessions), 0) + # Verify missing sha256 on terminal EOF raises ValueError and evicts session + with self.assertRaises(ValueError): + handler.process_message( + env, + { + "generation": "2026-11-05T15:00:00Z", + "family": "bacnet", + "event_no": 1, + "data": base64.b64encode(gzip.compress(c1)).decode( + "ascii" + ), + }, + self.mock_pg, + self.mock_influx, + ) + handler.process_message( + env, + { + "generation": "2026-11-05T15:00:00Z", + "family": "bacnet", + "event_no": -2, + }, + self.mock_pg, + self.mock_influx, + ) + self.assertEqual(len(handler._sessions), 0) + if __name__ == "__main__": unittest.main() diff --git a/common/src/main/java/com/google/udmi/util/SiteModel.java b/common/src/main/java/com/google/udmi/util/SiteModel.java index b6b169b3b6..89c25e67c1 100644 --- a/common/src/main/java/com/google/udmi/util/SiteModel.java +++ b/common/src/main/java/com/google/udmi/util/SiteModel.java @@ -389,7 +389,8 @@ public Set getDeviceIds() { File[] files = Objects.requireNonNull(devicesFile.listFiles(), "no files in " + devicesFile.getAbsolutePath()); return Arrays.stream(files).map(File::getName).sorted() - .filter(device -> validDeviceDirectory(devicesFile, device)).collect(Collectors.toSet()); + .filter(device -> validDeviceDirectory(devicesFile, device)) + .collect(Collectors.toCollection(java.util.LinkedHashSet::new)); } public Set getTemplateIds() { diff --git a/edge/spotter/README.md b/edge/spotter/README.md index 4176b2b7e5..699732fcc0 100644 --- a/edge/spotter/README.md +++ b/edge/spotter/README.md @@ -194,6 +194,6 @@ To prove byte-for-byte discovery parity on an actual field testbed machine witho The following capabilities are tracked as future milestones: -1. **Ephemeral Secret Delivery**: Architectural mechanism for delivering transient, authenticated operational credentials (e.g., vendor device credentials, BACnet network encryption keys, or REST API bearer tokens) strictly in volatile RAM without disk persistence. A dedicated architectural discussion will finalize the delivery transport (such as non-persisted command channels e.g. `commands/secret` vs encrypted `config.blobset`), memory scrubbing lifecycles, and cryptographic envelope validation before implementation. +1. **Ephemeral Secret Delivery**: Architectural mechanism for delivering transient, authenticated operational credentials (e.g., vendor device credentials, BACnet network encryption keys, or REST API bearer tokens) strictly in volatile RAM without disk persistence via the `download/blobset` channel framed by `config.blobset` and `state.blobset`. 2. **Key Rotation & Lifecycle**: End-to-end device private/public key rotation with automated cloud IoT registry coordination, backup verification, and zero-downtime reconnection. 3. **Expanded Host Observability Metrics**: Network adapter error/drop counters, hardware temperature, storage/inode thresholds, and edge-to-cloud roundtrip latency. diff --git a/edge/spotter/bin/reassemble_pcap b/edge/spotter/bin/reassemble_pcap index 7afaafb2e2..1cd7b6e264 100755 --- a/edge/spotter/bin/reassemble_pcap +++ b/edge/spotter/bin/reassemble_pcap @@ -128,6 +128,11 @@ def reassemble_pcap( if eof_events: terminal = eof_events[-1] expected_sha256 = terminal.get("sha256") + if not expected_sha256: + sys.exit( + "Error: Terminal EOF message (event_no < 0) is missing required" + " 'sha256' digest." + ) expected_chunks = (-int(terminal["event_no"])) - 1 if isinstance(terminal.get("scan_manifest"), dict): scan_manifest = terminal["scan_manifest"] diff --git a/edge/spotter/src/manager/discovery.py b/edge/spotter/src/manager/discovery.py index 744ae7b8af..19a95e8db7 100644 --- a/edge/spotter/src/manager/discovery.py +++ b/edge/spotter/src/manager/discovery.py @@ -683,14 +683,21 @@ def _run_scan(self, family: str, provider: Any) -> None: depth_val = getattr(fam_config, "depth", None) if fam_config else None if depth_val in (Depth.trace, Depth.trace.value): + f_state = self._discovery_state.families.get(family) + run_generation = getattr(f_state, "generation", None) or ( + getattr(fam_config, "generation", None) if fam_config else None + ) try: self._run_trace_capture(family, fam_config) finally: if provider in self._active_providers: self._active_providers.remove(provider) - self._family_providers.pop(family, None) - self._update_family_state(family, False) - self.trigger_state_update(immediate=True) + if self._family_providers.get(family) is provider: + self._family_providers.pop(family, None) + cur_state = self._discovery_state.families.get(family) + if cur_state is not None and cur_state.generation == run_generation: + self._update_family_state(family, False) + self.trigger_state_update(immediate=True) return # Standard Protocol Scan @@ -705,6 +712,7 @@ def _run_scan(self, family: str, provider: Any) -> None: and getattr(fam_config, "generation", None) ): f_state.generation = fam_config.generation + run_generation = f_state.generation f_state.phase = DiscoveryPhase.active f_state.active_count = 0 @@ -729,25 +737,29 @@ def _run_scan(self, family: str, provider: Any) -> None: try: provider.start_scan(effective_config, self._handle_scan_result) LOGGER.info("Scan finished for '%s'.", family) - f_state.status = None - passive_holdoff = getattr(provider, "passive_holdoff_count", 0) - if passive_holdoff: - f_state.passive_count = passive_holdoff + if f_state.generation == run_generation: + f_state.status = None + passive_holdoff = getattr(provider, "passive_holdoff_count", 0) + if passive_holdoff: + f_state.passive_count = passive_holdoff except Exception as e: # pylint: disable=broad-exception-caught LOGGER.error("Scan failed for '%s': %s", family, e, exc_info=True) - err_msg = str(e).strip() or type(e).__name__ - f_state.status = Entry( - category="discovery.family.scan", - level=500, - message=err_msg, - timestamp=_format_generation(datetime.now(timezone.utc)), - ) + if f_state.generation == run_generation: + err_msg = str(e).strip() or type(e).__name__ + f_state.status = Entry( + category="discovery.family.scan", + level=500, + message=err_msg, + timestamp=_format_generation(datetime.now(timezone.utc)), + ) finally: if provider in self._active_providers: self._active_providers.remove(provider) - self._family_providers.pop(family, None) - self._update_family_state(family, False) - self.trigger_state_update(immediate=True) + if self._family_providers.get(family) is provider: + self._family_providers.pop(family, None) + if f_state.generation == run_generation: + self._update_family_state(family, False) + self.trigger_state_update(immediate=True) def _run_trace_capture(self, family: str, fam_config: Any) -> None: """Executes PCAP capture, runs raw-socket BACnet Who-Is rounds, and streams chunks over upload/discovery.""" @@ -946,10 +958,14 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: _emit_compressed_chunk(bytes(pending_buf)) pending_buf.clear() + cancelled_externally = whois_stop_event.is_set() whois_stop_event.set() if whois_thread and whois_thread.is_alive(): whois_thread.join(timeout=2.0) + if f_state.generation != generation: + return + if circuit_breaker_tripped and chunk_count == 0: f_state.phase = DiscoveryPhase.stopped f_state.active_count = 0 @@ -961,6 +977,10 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: ) return + if cancelled_externally and total_bytes == 0: + f_state.phase = DiscoveryPhase.stopped + return + if total_bytes == 0: raise RuntimeError( f"Packet capture on '{interface}' (filter: '{filter_str}') produced" @@ -993,28 +1013,29 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: digest, ) - f_state.phase = DiscoveryPhase.stopped - f_state.active_count = chunk_count - if circuit_breaker_tripped: - f_state.status = Entry( - category="discovery.family.scan", - level=400, - message=( - "Trace capture throttled by safety circuit breaker after" - f" {chunk_count} upload/discovery chunks." - ), - timestamp=_format_generation(datetime.now(timezone.utc)), - ) - else: - f_state.status = Entry( - category="discovery.family.scan", - level=200, - message=( - f"Trace capture complete. {chunk_count} upload/discovery chunks" - " emitted." - ), - timestamp=_format_generation(datetime.now(timezone.utc)), - ) + if f_state.generation == generation: + f_state.phase = DiscoveryPhase.stopped + f_state.active_count = chunk_count + if circuit_breaker_tripped: + f_state.status = Entry( + category="discovery.family.scan", + level=400, + message=( + "Trace capture throttled by safety circuit breaker after" + f" {chunk_count} upload/discovery chunks." + ), + timestamp=_format_generation(datetime.now(timezone.utc)), + ) + else: + f_state.status = Entry( + category="discovery.family.scan", + level=200, + message=( + f"Trace capture complete. {chunk_count} upload/discovery" + " chunks emitted." + ), + timestamp=_format_generation(datetime.now(timezone.utc)), + ) except Exception as e: # pylint: disable=broad-exception-caught whois_stop_event.set() @@ -1023,13 +1044,15 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: LOGGER.error( "Trace capture failed for family '%s': %s", family, e, exc_info=True ) - f_state.phase = DiscoveryPhase.stopped - f_state.status = Entry( - category="discovery.family.scan", - level=500, - message=str(e), - timestamp=_format_generation(datetime.now(timezone.utc)), - ) + if f_state.generation == generation: + f_state.phase = DiscoveryPhase.stopped + f_state.status = Entry( + category="discovery.family.scan", + level=500, + message=str(e), + timestamp=_format_generation(datetime.now(timezone.utc)), + ) finally: - self._trace_stop_events.pop(family, None) + if self._trace_stop_events.get(family) is whois_stop_event: + self._trace_stop_events.pop(family, None) self.trigger_state_update() diff --git a/edge/spotter/src/pcap.py b/edge/spotter/src/pcap.py index 2b7440096c..8493bcdb0e 100644 --- a/edge/spotter/src/pcap.py +++ b/edge/spotter/src/pcap.py @@ -209,6 +209,10 @@ def run_bacnet_trace_whois_rounds( dnet_pace_sec = 1.0 * scale global_wait_sec = 15.0 * scale + # Brief initial startup sync so tcpdump opens its capture socket before Round 1 + if stop_event.wait(timeout=min(0.1, 0.02 * scale)): + return + for _ in range(rounds): if stop_event.is_set(): break diff --git a/edge/spotter/src/providers/bacnet.py b/edge/spotter/src/providers/bacnet.py index dc00d109f9..3f245f2b08 100644 --- a/edge/spotter/src/providers/bacnet.py +++ b/edge/spotter/src/providers/bacnet.py @@ -432,14 +432,13 @@ def start_scan( target_nets: Any = ( self._active_networks if self._active_networks else "known" ) - min_low = min(low for low, _ in self._active_instance_ranges) - max_high = max(high for _, high in self._active_instance_ranges) - client.discover( - networks=target_nets, - limits=(min_low, max_high), - global_broadcast=True, - reset=True, - ) + for idx, (low, high) in enumerate(self._active_instance_ranges): + client.discover( + networks=target_nets, + limits=(low, high), + global_broadcast=True, + reset=(idx == 0), + ) self._scan_thread = threading.Thread( target=self._devices_consumer, diff --git a/edge/spotter/src/providers/ether.py b/edge/spotter/src/providers/ether.py index 72439fa850..2ff2a74bcb 100644 --- a/edge/spotter/src/providers/ether.py +++ b/edge/spotter/src/providers/ether.py @@ -249,6 +249,34 @@ def expand_ip_targets( yield str(ipaddress.ip_address(target_str)) +def _resolve_nmap_targets( + targets: List[str], fallback_subnet: Optional[str] = None +) -> List[str]: + """Validates and resolves IP addresses, CIDRs, or VLAN IDs into Nmap target specs.""" + resolved: List[str] = [] + for target in targets: + target_str = str(target).strip() + if not target_str: + continue + if target_str.isdigit(): + vlan_id = int(target_str) + if MIN_VLAN_ID <= vlan_id <= MAX_VLAN_ID: + if fallback_subnet: + resolved.append( + str(ipaddress.ip_interface(fallback_subnet).network) + ) + continue + raise ValueError( + f"Ether VLAN network ID {target_str!r} must be between" + f" {MIN_VLAN_ID} and {MAX_VLAN_ID}" + ) + if "/" in target_str: + resolved.append(str(ipaddress.ip_network(target_str, strict=False))) + else: + resolved.append(str(ipaddress.ip_address(target_str))) + return resolved + + class EtherFamilyProvider(FamilyProvider): """Pluggable Ethernet protocol discovery provider (Ping & Nmap).""" @@ -643,11 +671,17 @@ def _run_nmap_scan( if not os.path.exists("/usr/bin/nmap"): raise RuntimeError("nmap binary not found at /usr/bin/nmap") + nmap_targets = _resolve_nmap_targets( + targets, fallback_subnet=self.subnet_filter + ) + if not nmap_targets: + return + cmd = ["/usr/bin/nmap"] if depth in ("system", "details", "parts", "refs"): cmd.extend(["--script", "banner", "-sV"]) cmd.extend(["-p-", "-T4", "--max-hostgroup", "32", "-oX", "-"]) - cmd.extend(targets) + cmd.extend(nmap_targets) try: with self._lock: diff --git a/edge/spotter/src/providers/passive.py b/edge/spotter/src/providers/passive.py index 6ec45eaa3e..c1870d7b86 100644 --- a/edge/spotter/src/providers/passive.py +++ b/edge/spotter/src/providers/passive.py @@ -77,6 +77,7 @@ def decode_bacnet_bvll( return None bvlc_func = payload[1] + bvlc_len = int.from_bytes(payload[2:4], byteorder="big") orig_ip = outer_ip orig_port = outer_port npdu_offset = 4 @@ -130,7 +131,12 @@ def decode_bacnet_bvll( # Network Layer Message: 0x01 is I-Am-Router-To-Network if pos < len(payload) and payload[pos] == 0x01: dnets = [] - rem = payload[pos + 1 :] + end_pos = ( + min(len(payload), bvlc_len) + if bvlc_len >= pos + 1 + else len(payload) + ) + rem = payload[pos + 1 : end_pos] for i in range(0, len(rem) - 1, 2): dnet = int.from_bytes(rem[i : i + 2], byteorder="big") if 1 <= dnet <= 65534 and dnet not in dnets: @@ -501,28 +507,45 @@ def _queue_worker(self, passive_sec: Optional[int] = None) -> None: now = time.monotonic() record_key = ( - f"{effective_ip}:{snet}:{sadr}:{bacnet_id}" - if snet is not None + f"{effective_ip}:{snet or ''}:{sadr or ''}:{bacnet_id}" + if (snet is not None or bacnet_id is not None) else effective_ip ) with self._records_lock: if passive_sec and int(passive_sec) > 0: last_pub = self._last_published_at.get(record_key) + if ( + last_pub is None + and snet is None + and bacnet_id is None + ): + last_pub = self._last_published_at.get(effective_ip) if last_pub is not None and (now - last_pub) < float(passive_sec): self.passive_holdoff_count += 1 continue self._last_published_at[record_key] = now - if snet is None: - self._records_published = { - r - for r in self._records_published - if not (r.addr == effective_ip and r.snet is None) - } - self._device_records = { - r - for r in self._device_records - if not (r.addr == effective_ip and r.snet is None) - } + if snet is None and bacnet_id is None: + self._last_published_at[effective_ip] = now + self._records_published = { + r + for r in self._records_published + if not ( + r.addr == effective_ip + and r.snet == snet + and r.sadr == sadr + and (r.bacnet_id == bacnet_id or bacnet_id is None) + ) + } + self._device_records = { + r + for r in self._device_records + if not ( + r.addr == effective_ip + and r.snet == snet + and r.sadr == sadr + and (r.bacnet_id == bacnet_id or bacnet_id is None) + ) + } elif effective_ip in self._addresses_seen and bacnet_id is None: continue diff --git a/mcp/butler/provider.py b/mcp/butler/provider.py index 16f37febec..fa8ac173ed 100644 --- a/mcp/butler/provider.py +++ b/mcp/butler/provider.py @@ -956,17 +956,10 @@ def trigger_bacnet_trace( effective_spec = ( conn_spec or self.project_spec or os.environ.get("BUTLER_CONN_SPEC") ) - if effective_spec: - from butler.src.discovery import trigger_bacnet_trace as publish_trace - - publish_trace( - conn_spec=effective_spec, - registry_id=site, - device_id=gateway_id, - scan_duration_sec=int(scan_duration_sec), - max_bytes=int(max_bytes), - site_model=site_model or os.environ.get("BUTLER_SITE_MODEL"), - generation=generation, + if not effective_spec: + raise ValueError( + "Missing connection specification (conn_spec or BUTLER_CONN_SPEC) " + "required to trigger BACnet trace" ) if self.pg_manager and hasattr(self.pg_manager, "insert_row"): @@ -985,6 +978,18 @@ def trigger_bacnet_trace( }, ) + from butler.src.discovery import trigger_bacnet_trace as publish_trace + + publish_trace( + conn_spec=effective_spec, + registry_id=site, + device_id=gateway_id, + scan_duration_sec=int(scan_duration_sec), + max_bytes=int(max_bytes), + site_model=site_model or os.environ.get("BUTLER_SITE_MODEL"), + generation=generation, + ) + return { "status": "PENDING", "site": site, diff --git a/tests/test_mcp_butler.py b/tests/test_mcp_butler.py index 1179e592e5..3d28f5dde6 100644 --- a/tests/test_mcp_butler.py +++ b/tests/test_mcp_butler.py @@ -812,8 +812,13 @@ def test_stdio_initialize_and_tools_list(self): self.assertIn("list_rollouts", tool_names) self.assertIn("get_rollout", tool_names) self.assertIn("update_rollout", tool_names) + self.assertIn("trigger_bacnet_trace", tool_names) + self.assertIn("get_pcap_capture", tool_names) finally: + for stream in (proc.stdin, proc.stdout, proc.stderr): + if stream is not None: + stream.close() proc.terminate() proc.wait(timeout=2) From aa8dafd9e04d2163f9b179261120937c676bdf69 Mon Sep 17 00:00:00 2001 From: Khyati Mahendru Date: Fri, 13 Nov 2026 08:41:39 +0000 Subject: [PATCH 6/8] Fix Checkstyle line length in MqttToPubSubBridge and docs spellcheck - Wrap 101-character gracefulShutdown call in MqttToPubSubBridge.java to satisfy Checkstyle LineLength (<= 100 chars). - Code-quote protocol and compression terms (BVLL, BBMD, NPDU, MS/TP, DNET, gzip) in docs/specs/discovery.md, docs/specs/discovery_bacnet.md, and docs/tools/spotter.md for Docs Spelling Checks. --- docs/specs/discovery.md | 4 ++-- docs/specs/discovery_bacnet.md | 2 +- docs/tools/spotter.md | 6 +++--- .../google/bos/udmi/service/bridge/MqttToPubSubBridge.java | 6 +++++- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/specs/discovery.md b/docs/specs/discovery.md index ba619c275e..013d2667d9 100644 --- a/docs/specs/discovery.md +++ b/docs/specs/discovery.md @@ -55,7 +55,7 @@ Discovery `depth` controls the level of detail collected during a scan. Each dep * **`entries`**: Individual discovered devices and cross-family address associations. * **`system`**: Device identity and hardware information. * **`details`**: Enumerated device points, objects, or services. -* **`trace`**: Diagnostic raw packet capture (PCAP) streamed in gzip-compressed chunks over the `upload/discovery` channel ([schema](../../schema/upload_discovery.json)). +* **`trace`**: Diagnostic raw packet capture (PCAP) streamed in `gzip`-compressed chunks over the `upload/discovery` channel ([schema](../../schema/upload_discovery.json)). | `depth` | Description | `bacnet` ([Spec](discovery_bacnet.md)) | `iot` | `ipv4` | | :--- | :--- | :--- | :--- | :--- | @@ -63,7 +63,7 @@ Discovery `depth` controls the level of detail collected during a scan. Each dep | **`entries`** | Device addresses and bindings | Device instances and IP/MAC bindings | IoT device IDs and gateway bindings | Host IP, MAC, and hostname bindings | | **`system`** | Device identity and hardware | Device object identity and vendor info | Reported system hardware and software | Host OS and hardware fingerprint | | **`details`** | Exposed points or services | BACnet objects and properties | Configured or self-enumerated points | Open ports and network services | -| **`trace`** | Diagnostic packet capture | Raw BACnet/IP & MS/TP PCAP chunks (`upload/discovery`) | Raw message trace | Filtered interface PCAP chunks (`upload/discovery`) | +| **`trace`** | Diagnostic packet capture | Raw BACnet/IP & `MS/TP` PCAP chunks (`upload/discovery`) | Raw message trace | Filtered interface PCAP chunks (`upload/discovery`) | ## Enumeration diff --git a/docs/specs/discovery_bacnet.md b/docs/specs/discovery_bacnet.md index 9a33805847..3a79b917d9 100644 --- a/docs/specs/discovery_bacnet.md +++ b/docs/specs/discovery_bacnet.md @@ -20,7 +20,7 @@ A BACnet active discovery scan is controlled by `config.discovery.families.bacne | **2** | **`entries`** | Discovered BACnet devices & MAC/IP bindings | `Who-Is` / `I-Am` (global, network-filtered, or unicast `addrs`) | `events/discovery`: `buckets` + `addr` (Device Instance) + per-device `families` (`ipv4` `addr`/`port`, `ethmac`, `mstp`) | | **3** | **`system`** | Device Object (`DO/0`) identity properties | `ReadPropertyMultiple` on `device,` (`object-name`, `vendor-name`, `model-name`, `serial-number`, etc.) | `events/discovery`: `entries` + `system` (`name`, `description`, `serial_no`, `hardware`, `ancillary`) | | **4** | **`details`** | BACnet object references & properties | `ReadProperty` / `ReadPropertyMultiple` on `device,` `object-list` + per-object `(object-type, instance)` properties | `events/discovery`: `system` + `refs` map (`"/"` $\rightarrow$ populated `RefDiscovery` fields: `name`, `description`, `type`, `units`, `possible_values`, `writable`, `ancillary`) | -| **5** | **`trace`** | Raw BACnet packet capture (PCAP) | `tcpdump` capture (`udp port 47808`) + paced raw-socket `Who-Is-Router-To-Network` and `Who-Is` rounds | `upload/discovery`: [`DiscoveryUpload`](../../schema/upload_discovery.json) chunks (`event_no = 0`, `1..N` gzipped base64 `data`, `-(N+1)` with `sha256` + `scan_manifest`) | +| **5** | **`trace`** | Raw BACnet packet capture (PCAP) | `tcpdump` capture (`udp port 47808`) + paced raw-socket `Who-Is-Router-To-Network` and `Who-Is` rounds | `upload/discovery`: [`DiscoveryUpload`](../../schema/upload_discovery.json) chunks (`event_no = 0`, `1..N` `gzip`-compressed base64 `data`, `-(N+1)` with `sha256` + `scan_manifest`) | Each level is strictly additive: requesting a deeper level produces all fields required by the preceding level plus the additional fields defined for that depth. diff --git a/docs/tools/spotter.md b/docs/tools/spotter.md index a5756c77aa..ba7579dba8 100644 --- a/docs/tools/spotter.md +++ b/docs/tools/spotter.md @@ -13,7 +13,7 @@ Spotter runs as a single unified process using the UDMI Python Client Library (` 1. **`LocalnetManager` & Pluggable Family Providers**: - **`BacnetFamilyProvider`**: Performs active BACnet Who-Is / I-Am discovery, object enumeration, and UDP port extraction. - **`EtherFamilyProvider`**: Performs Layer-2 Ethernet / ARP, nmap XML host parsing, and ICMP ping sweeps. - - **`PassiveFamilyProvider`**: Listens for passive broadcast network traffic, decodes BACnet/IP BVLL (`Forwarded-NPDU` real controller IP/port behind BBMDs) and NPDU (`SNET`/`SADR` routed MS/TP frames and `I-Am-Router-To-Network` DNET lists), and extracts discovered device metadata. + - **`PassiveFamilyProvider`**: Listens for passive broadcast network traffic, decodes BACnet/IP `BVLL` (`Forwarded-NPDU` real controller IP/port behind `BBMD` routers) and `NPDU` (`SNET`/`SADR` routed `MS/TP` frames and `I-Am-Router-To-Network` `DNET` lists), and extracts discovered device metadata. 2. **`SpotterDiscoveryManager`**: - Manages scheduled and on-demand discovery sweeps. - Streams live remote packet capture traces (`upload/discovery`) buffered in volatile memory with circuit-breaker protection (zero-disk streaming). @@ -62,10 +62,10 @@ Spotter processes diagnostic packet capture triggers sent declaratively over the - Spawns `tcpdump` with configurable interface filters (defaulting to `"udp port 47808"` for `bacnet`), enforcing strict execution bounds (maximum duration and byte quotas). - For `families.bacnet` with `depth: "trace"`, skips `BAC0.lite()` socket binding so UDP port `47808` remains unbound and executes paced raw-socket (`SOCK_RAW, IPPROTO_UDP`) `Who-Is` and `Who-Is-Router-To-Network` rounds during the capture window. 2. **Streaming MQTT Egress Transport (`upload/discovery`)**: - - **Zero-Disk Streaming**: Packets are buffered dynamically in volatile memory (RAM), gzip-compressed per chunk, and sequentially published as `DiscoveryUpload` chunks over the `upload/discovery` MQTT topic (`event_no = 0` start marker, `1..N` gzipped base64 chunks, and `-(N+1)` terminal marker with uncompressed `sha256` and `scan_manifest`). + - **Zero-Disk Streaming**: Packets are buffered dynamically in volatile memory (RAM), `gzip`-compressed per chunk, and sequentially published as `DiscoveryUpload` chunks over the `upload/discovery` MQTT topic (`event_no = 0` start marker, `1..N` `gzip`-compressed base64 chunks, and `-(N+1)` terminal marker with uncompressed `sha256` and `scan_manifest`). - **Zero Secret Distribution**: Leverages the existing mTLS hardware key/certificate connection directly, avoiding external network credentials or outbound HTTP rules at the edge. 3. **Cloud & Local PCAP Reassembly**: - - **Butler Service (`PcapUploadHandler`)**: Subscribes to `upload/discovery` (or `uufi_upload`), gunzips and reassembles chunks in order, validates the terminal `sha256` digest, and writes the `.pcap` and `scan_manifest.json` to GCS (`gs:////.pcap`) or local disk without persisting raw chunks to PostgreSQL. + - **Butler Service (`PcapUploadHandler`)**: Subscribes to `upload/discovery` (or `uufi_upload`), decompresses and reassembles chunks in order, validates the terminal `sha256` digest, and writes the `.pcap` and `scan_manifest.json` to GCS (`gs:////.pcap`) or local disk without persisting raw chunks to PostgreSQL. - **Ad-hoc CLI Reassembly ([bin/reassemble_pcap](../../edge/spotter/bin/reassemble_pcap))**: Reassembles chunked `upload/discovery` messages (from JSON, JSONL, or `mosquitto_sub`) back into a valid `.pcap` binary capture file and `scan_manifest.json`: ```bash diff --git a/udmis/src/main/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridge.java b/udmis/src/main/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridge.java index 97cea3e8d2..9fd125b1ad 100644 --- a/udmis/src/main/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridge.java +++ b/udmis/src/main/java/com/google/bos/udmi/service/bridge/MqttToPubSubBridge.java @@ -460,7 +460,11 @@ public static void main(String[] args) { Runnable shutdownTask = () -> { if (isShuttingDown.compareAndSet(false, true)) { gracefulShutdown( - finalBridge, finalMqttClient, finalPublisher, finalEtcdProvider, finalUploadPublisher); + finalBridge, + finalMqttClient, + finalPublisher, + finalEtcdProvider, + finalUploadPublisher); } }; From 4b60c3d88c27848eb343015d4075ecf9421f0790 Mon Sep 17 00:00:00 2001 From: Khyati Mahendru Date: Thu, 26 Nov 2026 08:39:46 +0000 Subject: [PATCH 7/8] Align Spotter PCAP trace with spec: pacing, capture_only mode, explicit interface, exclude_capture_host, and I-Am manifest counts --- .gencode_hash.txt | 12 +- butler/src/discovery.py | 16 +- docs/tools/spotter.md | 15 +- edge/spotter/spotter_config.json | 5 + edge/spotter/src/agent.py | 14 +- edge/spotter/src/manager/discovery.py | 230 +++++++++--- edge/spotter/src/pcap.py | 355 ++++++++++++------ edge/spotter/src/providers/bacnet.py | 3 +- edge/spotter/src/providers/passive.py | 9 - edge/spotter/tests/test_agent.py | 203 +++++++++- edge/spotter/tests/test_pcap.py | 134 +++++-- gencode/docs/config.html | 62 +++ gencode/docs/upload_discovery.html | 158 ++++++++ gencode/java/udmi/schema/ScanManifest.java | 30 +- .../udmi/schema/TraceDiscoveryConfig.java | 12 +- .../udmi/schema/config_discovery_trace.py | 1 + .../python/udmi/schema/upload_discovery.py | 3 + mcp/butler/provider.py | 4 + mcp/butler/server.py | 4 + schema/config_discovery_trace.json | 5 + schema/upload_discovery.json | 17 + 21 files changed, 1049 insertions(+), 243 deletions(-) diff --git a/.gencode_hash.txt b/.gencode_hash.txt index b485759864..45455d131c 100644 --- a/.gencode_hash.txt +++ b/.gencode_hash.txt @@ -1,6 +1,6 @@ fe8e504acbdc788893e3441cf38b6c7b9bbbe4d28995ee89914aa332c3864779 gencode/docs/building_config_entity.html c21266e8de23b6e8acfac16a177db782375bf71df470c343c3f8eb8b822ef56a gencode/docs/commands_discovery.html -dcedf223d5a2676bc0be39513b513d98c87a97309edfa3016c5b465b14c0d854 gencode/docs/config.html +cbe78244fa34297dbffe2383c4339c775b59ed5d36f02cf07f6cbf8531cf7438 gencode/docs/config.html 0dcc1e8245bf0b2791a4bf9be15d8647acd89124ade475345ce4a9c56d62a824 gencode/docs/configuration_endpoint.html 40f078753386e07bfc200eaf3c35cb4362eb413101f4f00d87c88cde3ee53080 gencode/docs/configuration_execution.html 0e2f9b56fd0d3762ff7ce14e0f9fc119cba17a3c2eeb2dcdbf1ff2fad5c6c9d1 gencode/docs/configuration_pod.html @@ -27,7 +27,7 @@ a0003efed16bbbfd2fe8c8a6c6bf9c16c5f8fbc74559c583bc04752fe2ecfd10 gencode/docs/r 7a1bbe014c739078d354ec484147325e1d0bd19468f275a53da38add43ebe089 gencode/docs/site_metadata.html 0993d21a1a0ae485bdb2f1794f279d13f782e841d07832f795624cc9f158ea93 gencode/docs/state.html 275171b2329d64d497fa54f8877656920be7c4f79bc90f67a0ff1bae6700399b gencode/docs/state_validation.html -4643457f1580e601c14d5382aa7ed5070ef56c2c100d8b5d2bbe33a191d67517 gencode/docs/upload_discovery.html +022df91c65e3311d5db5871f290bb34cbaf4995e7f02206f948f042885bf6bba gencode/docs/upload_discovery.html 46347b31bc2a56bc74af9bb702ad40c7823887d5e9b1427903a4892cde3cd169 gencode/java/udmi/schema/AlarmAlarmsetConfig.java 520b12eb8cec4f043f81f898c4be12def09b7de138533922e17c038415fb8902 gencode/java/udmi/schema/AlarmAlarmsetEvents.java 0740aeb4462739e9be7e9c846ebc3f3e6f45f3bb752327c681aa013fbd5c2711 gencode/java/udmi/schema/AlarmAlarmsetModel.java @@ -126,7 +126,7 @@ fbe287eb5b915a7df6ccffade4e3d6afc82eaf4c0195501f36d2facacbb6590f gencode/java/u a374c601a5d729e31a140ddbf019f346077db7615ffda2d34d638c2ba0ebbbd9 gencode/java/udmi/schema/PubberOptions.java 54e0593235c1f19cf3b5b2708f831e734b0acf049b2576e3b29707c93f1241d9 gencode/java/udmi/schema/RefDiscovery.java 2bf34a526fcf3ee4e4440deeb215c6c8e18de15b07d521e8ef327e51b7fe1db5 gencode/java/udmi/schema/Role.java -f40a56d2080bfbbd48ae441fc41d66b8767fab8188e57dcfab1fa56183591acb gencode/java/udmi/schema/ScanManifest.java +e26867c3e6c37d41d1269d5346ceff0f3eaf79ef41807245bc50c7e3913d354a gencode/java/udmi/schema/ScanManifest.java f5eda4fdb24fcc3ccbc82fe39fe8ed87cf8b4d4d0699faef31f83de4a1fa1306 gencode/java/udmi/schema/SchemaValidationState.java 4b26a101e8edc299274e5b221db616b83d8e569000e0b59b940d0a0d5387852b gencode/java/udmi/schema/Scoring.java 280e35e8dee942bfa3e205c0c00dd01d14c2cd804e3d55be580c91408dd62137 gencode/java/udmi/schema/SequenceValidationState.java @@ -149,7 +149,7 @@ c7ad7b69216e002d54b73e266f79a8802643c9c008d0f7a8a5ead168f658c442 gencode/java/u fad0fa75b621c45aa203c58cd799bf7c2c34f795c2a2f5a6cf3893b3b8571cac gencode/java/udmi/schema/TargetTestingModel.java 769f019881e51db5ae00234afb391286af191c5a753a70b215da2ec199fd85af gencode/java/udmi/schema/TestingModel.java 7912195d86bbf6267e7add4178ec329efa5bfa64dfe021c9e5db4de2f57d5583 gencode/java/udmi/schema/TestingSystemConfig.java -099c6145cefc8190b70ab018e148c9dfad041b6b5a81cb48fa68b10e94e49a97 gencode/java/udmi/schema/TraceDiscoveryConfig.java +407af3a874ba80f1c2050c38a3cb01289d223f183c5aa0f53a445cb8c52f4ebd gencode/java/udmi/schema/TraceDiscoveryConfig.java 3083099ecc7eac132aed098b752a2dcbd33492ba71a38f0b64436c913df1f6e7 gencode/java/udmi/schema/UdmiConfig.java d9e72c3a35e482c136a7c69793467655a09926ff2cc38bcc2f6544e611da5f61 gencode/java/udmi/schema/UdmiEvents.java b717117775118a92f0756325029943f93eafbd6413a8f465a9f4ffddd74fb3a5 gencode/java/udmi/schema/UdmiState.java @@ -178,7 +178,7 @@ f3d91b7386c6f9685991b370b8667853baa2526a881d8fda472536ed5b8aa5a7 gencode/python 234b237a299d31b92dd873af6713c56e388345faeb79cbf2b46090c7d10ef00a gencode/python/udmi/schema/config_blobset_blob.py 246f6878e5a4b7f5e1a27d1c51aadd42bef07ee2113b9cd568bb623b24bc85de gencode/python/udmi/schema/config_discovery.py 5815f7f1ec7e5a2d5b7e3065060872d109ebb64f595c004a4b5b490c918684c2 gencode/python/udmi/schema/config_discovery_family.py -326edbdbb90e376375294ba645fd789d1ae1809e8a98f3b32c3d04c2bc316ac1 gencode/python/udmi/schema/config_discovery_trace.py +fd69cffe33900b760a7b4caad6d55454f2f1dfcb7c62bf06729fa8335d748e33 gencode/python/udmi/schema/config_discovery_trace.py 0d100d1fec28c4e59cba704e5a512549972f427ea4da268c7472208fdccd96a6 gencode/python/udmi/schema/config_gateway.py 8119455e323f686da48ccf65d494d0dc2a26ad2a2a02d0f0167dc9a020740225 gencode/python/udmi/schema/config_localnet.py c7efa5243aa5fb6bba49529c1c8dddaa8314f42e024d2bc60bf284d324947744 gencode/python/udmi/schema/config_localnet_family.py @@ -264,4 +264,4 @@ e23b1b67fc5066ee0c9a948fbc0b31bc425d73740a8d2104b30004173f049f4a gencode/python 6c62d12f392525e4c08d3ee6105f475b941c21e0a8b7a23eaf1650d01a5b5aae gencode/python/udmi/schema/state_validation_feature.py 8a92d352337c118831e3a3b64b350a5ab248fc29150e7cdb968d5e5cf0aae30c gencode/python/udmi/schema/state_validation_schema.py 8862c955ea0aee91db532cb076112305ce6e18d9ac5b323f758fd7fcf75db7cd gencode/python/udmi/schema/state_validation_sequence.py -caa4263df095dcf90c96284442db6aceaa73c72a66808bdf7a07fd4b5aa00a05 gencode/python/udmi/schema/upload_discovery.py +fdc398005411894bbc4b0dd6b893fe24391797b9dfc000a7cbe1c7f2f4c128ed gencode/python/udmi/schema/upload_discovery.py diff --git a/butler/src/discovery.py b/butler/src/discovery.py index c8813af39a..15bbdcff8a 100644 --- a/butler/src/discovery.py +++ b/butler/src/discovery.py @@ -62,14 +62,26 @@ def trigger_bacnet_trace( max_bytes=268435456, site_model=None, generation=None, + interface="eth0", + exclude_capture_host=False, ): """Publishes config/discovery (families.bacnet with depth: 'trace') to trigger a Spotter PCAP capture.""" + if not interface or str(interface).strip().lower() == "any": + raise ValueError( + "Explicit host network interface is required for BACnet trace (cannot be empty or 'any')" + ) connection = ButlerConnection(conn_spec, registry_id, site_model, device_id) actual_registry = connection.actual_registry now = generation or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") tx_id = f"TXN-{uuid.uuid4().hex[:8]}" source_id = "butler" + trace_payload = { + "interface": str(interface).strip(), + "max_bytes": int(max_bytes), + } + if exclude_capture_host: + trace_payload["exclude_capture_host"] = True payload = { "version": "1.5.7", "timestamp": now, @@ -78,9 +90,7 @@ def trigger_bacnet_trace( "generation": now, "scan_duration_sec": int(scan_duration_sec), "depth": "trace", - "trace": { - "max_bytes": int(max_bytes), - }, + "trace": trace_payload, } }, } diff --git a/docs/tools/spotter.md b/docs/tools/spotter.md index ba7579dba8..83903666a8 100644 --- a/docs/tools/spotter.md +++ b/docs/tools/spotter.md @@ -59,12 +59,17 @@ graph TD Spotter processes diagnostic packet capture triggers sent declaratively over the UDMI discovery configuration channel (`config.discovery.families.` with `depth: "trace"`): 1. **Capture Worker & Active BACnet Trace Rounds ([pcap.py](../../edge/spotter/src/pcap.py))**: - - Spawns `tcpdump` with configurable interface filters (defaulting to `"udp port 47808"` for `bacnet`), enforcing strict execution bounds (maximum duration and byte quotas). - - For `families.bacnet` with `depth: "trace"`, skips `BAC0.lite()` socket binding so UDP port `47808` remains unbound and executes paced raw-socket (`SOCK_RAW, IPPROTO_UDP`) `Who-Is` and `Who-Is-Router-To-Network` rounds during the capture window. -2. **Streaming MQTT Egress Transport (`upload/discovery`)**: - - **Zero-Disk Streaming**: Packets are buffered dynamically in volatile memory (RAM), `gzip`-compressed per chunk, and sequentially published as `DiscoveryUpload` chunks over the `upload/discovery` MQTT topic (`event_no = 0` start marker, `1..N` `gzip`-compressed base64 chunks, and `-(N+1)` terminal marker with uncompressed `sha256` and `scan_manifest`). + - Requires an explicit host network interface in `trace.interface` (never `"any"`), plus explicit positive `scan_duration_sec` and `trace.max_bytes` bounds (fail-fast with status `500` on missing or invalid values). + - Spawns `tcpdump` with a kernel BPF filter (defaulting to `"udp port 47808"` for `bacnet`), and waits for `tcpdump` to start listening before launching active probes. When `trace.exclude_capture_host` is `true`, appends `and not host ` to the BPF filter and records the effective filter in `scan_manifest.filter`. + - For `families.bacnet` with `depth: "trace"`, releases any cached `BAC0` socket so UDP port `47808` remains unbound, runs a `CAP_NET_RAW` pre-flight check (failing fast with status `500` if unavailable), and executes 3 broadcast-only raw-socket (`SOCK_RAW, IPPROTO_UDP`) `Who-Is-Router-To-Network` and `Who-Is` rounds spaced across the capture window (`t = 0, T/3, 2T/3`). + - Decodes `I-Am` and `I-Am-Router-To-Network` frames inline during capture to populate `scan_manifest` (`bacnet_ip_devices`, `routed_mstp_devices`, `duplicate_device_ids`, `discovered_routed_networks`) and reports the unique discovered BACnet `I-Am` device count in `state.discovery.families.bacnet.active_count`. +2. **Discovery Modes & Coexistence (`udmi.discovery.mode`)**: + - `"full"` (default): Enables standard active BACnet, Ether, and passive IPv4 discovery alongside `depth: "trace"` captures. Active `BAC0` clients are closed immediately at the end of every standard scan so UDP `47808` is never held open when idle. + - `"capture_only"`: Designed for coexistence on hosts running an external BACnet gateway (such as Mango). Skips registering `BacnetFamilyProvider` so UDP `47808` is never bound, rejects non-`trace` BACnet discovery configs with status `500`, and permits `depth: "trace"` captures. +3. **Streaming MQTT Egress Transport (`upload/discovery`)**: + - **Zero-Disk Streaming**: Packets are buffered dynamically in volatile memory (RAM), flushed on size (128 KB) or time interval thresholds, `gzip`-compressed per chunk, and sequentially published as `DiscoveryUpload` chunks over the `upload/discovery` MQTT topic (`event_no = 0` start marker, `1..N` `gzip`-compressed base64 chunks, and `-(N+1)` terminal marker with uncompressed `sha256` and `scan_manifest`). - **Zero Secret Distribution**: Leverages the existing mTLS hardware key/certificate connection directly, avoiding external network credentials or outbound HTTP rules at the edge. -3. **Cloud & Local PCAP Reassembly**: +4. **Cloud & Local PCAP Reassembly**: - **Butler Service (`PcapUploadHandler`)**: Subscribes to `upload/discovery` (or `uufi_upload`), decompresses and reassembles chunks in order, validates the terminal `sha256` digest, and writes the `.pcap` and `scan_manifest.json` to GCS (`gs:////.pcap`) or local disk without persisting raw chunks to PostgreSQL. - **Ad-hoc CLI Reassembly ([bin/reassemble_pcap](../../edge/spotter/bin/reassemble_pcap))**: Reassembles chunked `upload/discovery` messages (from JSON, JSONL, or `mosquitto_sub`) back into a valid `.pcap` binary capture file and `scan_manifest.json`: diff --git a/edge/spotter/spotter_config.json b/edge/spotter/spotter_config.json index b88675def6..02fa42cb5e 100644 --- a/edge/spotter/spotter_config.json +++ b/edge/spotter/spotter_config.json @@ -16,6 +16,11 @@ "ca_file": "../../sites/udmi_site_model/reflector/ca.crt", "algorithm": "RS256" }, + "udmi": { + "discovery": { + "mode": "full" + } + }, "bacnet": { "ip": "127.0.0.1" } diff --git a/edge/spotter/src/agent.py b/edge/spotter/src/agent.py index e3697ef46f..5ff7227812 100644 --- a/edge/spotter/src/agent.py +++ b/edge/spotter/src/agent.py @@ -471,7 +471,16 @@ def is_truthy(val: Any) -> bool: return bool(val) discovery_cfg = config.get("udmi", {}).get("discovery", {}) - bacnet_enabled = is_truthy(discovery_cfg.get("bacnet", True)) + discovery_mode = str(discovery_cfg.get("mode", "full")).strip().lower() + if discovery_mode not in ("full", "capture_only"): + raise ValueError( + f"Invalid udmi.discovery.mode {discovery_mode!r}: expected 'full' or" + " 'capture_only'" + ) + bacnet_enabled = ( + is_truthy(discovery_cfg.get("bacnet", True)) + and discovery_mode != "capture_only" + ) ether_enabled = is_truthy(discovery_cfg.get("ether", True)) ipv4_enabled = is_truthy(discovery_cfg.get("ipv4", True)) @@ -518,7 +527,8 @@ def is_truthy(val: Any) -> bool: ) discovery_manager = SpotterDiscoveryManager( - max_mem_pct=circuit_breaker_mem_pct + max_mem_pct=circuit_breaker_mem_pct, + discovery_mode=discovery_mode, ) # Create Unified Device diff --git a/edge/spotter/src/manager/discovery.py b/edge/spotter/src/manager/discovery.py index 19a95e8db7..8f5929caa9 100644 --- a/edge/spotter/src/manager/discovery.py +++ b/edge/spotter/src/manager/discovery.py @@ -39,24 +39,32 @@ try: from host_telemetry import check_safety_circuit_breaker from pcap import ( + build_trace_bpf_filter, capture_packets, - extract_routed_networks_from_pcap_chunk, + check_raw_socket_permission, + extract_bacnet_trace_observations, resolve_gateway_ip, run_bacnet_trace_whois_rounds, + validate_trace_interface, ) except ImportError: from edge.spotter.src.host_telemetry import check_safety_circuit_breaker from edge.spotter.src.pcap import ( + build_trace_bpf_filter, capture_packets, - extract_routed_networks_from_pcap_chunk, + check_raw_socket_permission, + extract_bacnet_trace_observations, resolve_gateway_ip, run_bacnet_trace_whois_rounds, + validate_trace_interface, ) LOGGER = logging.getLogger("spotter_agent") # Clock skew tolerance (in seconds) for newly issued 'now' scan generations GENERATION_PAST_TOLERANCE_SEC = 15.0 +VALID_DISCOVERY_MODES = frozenset(("full", "capture_only")) +DEFAULT_TRACE_CHUNK_FLUSH_SEC = 30.0 def strip_none_fields(obj: Any) -> Any: @@ -123,9 +131,22 @@ class SpotterDiscoveryManager(DiscoveryManager): and strict UDMI discovery phase lifecycle tracking (pending/active/stopped). """ - def __init__(self, max_mem_pct: float = 85.0) -> None: + def __init__( + self, + max_mem_pct: float = 85.0, + discovery_mode: str = "full", + trace_flush_interval_sec: float = DEFAULT_TRACE_CHUNK_FLUSH_SEC, + ) -> None: super().__init__() + mode_norm = str(discovery_mode or "full").strip().lower() + if mode_norm not in VALID_DISCOVERY_MODES: + raise ValueError( + f"Invalid udmi.discovery.mode {discovery_mode!r}: expected one of" + f" {sorted(VALID_DISCOVERY_MODES)}" + ) self.max_mem_pct = max_mem_pct + self.discovery_mode = mode_norm + self.trace_flush_interval_sec = float(trace_flush_interval_sec) self._start_time = datetime.now(timezone.utc) self._active_event_counts: Dict[str, int] = {} self._applied_family_configs: Dict[str, Any] = {} @@ -320,19 +341,41 @@ def handle_config(self, config: Config) -> None: self._applied_family_configs[family] = copy.deepcopy(fam_config) - # Validate provider availability if device LocalnetManager is wired - if not self._has_registered_provider(family): + raw_depth = getattr(fam_config, "depth", None) + depth_val = str(getattr(raw_depth, "value", raw_depth) or "").lower() + is_trace = depth_val == "trace" + + # Enforce capture_only mode for BACnet coexistence (e.g. alongside Mango) + if self.discovery_mode == "capture_only" and family == "bacnet" and not is_trace: f_state.phase = DiscoveryPhase.stopped f_state.generation = getattr(fam_config, "generation", None) f_state.status = Entry( category="discovery.family.scan", level=500, - message=f"No provider registered for family '{family}'", + message=( + "Active BACnet discovery is disabled in capture_only mode;" + " only depth='trace' is permitted" + ), timestamp=_format_generation(now_dt), ) state_updated = True continue + # Validate provider availability if device LocalnetManager is wired + # Trace captures do not require an active BAC0 provider when in capture_only mode + if not (is_trace and family == "bacnet" and self.discovery_mode == "capture_only"): + if not self._has_registered_provider(family): + f_state.phase = DiscoveryPhase.stopped + f_state.generation = getattr(fam_config, "generation", None) + f_state.status = Entry( + category="discovery.family.scan", + level=500, + message=f"No provider registered for family '{family}'", + timestamp=_format_generation(now_dt), + ) + state_updated = True + continue + interval_sec = getattr(fam_config, "scan_interval_sec", None) duration_sec = getattr(fam_config, "scan_duration_sec", None) if ( @@ -808,6 +851,7 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: whois_stop_event = threading.Event() self._trace_stop_events[family] = whois_stop_event whois_thread: Optional[threading.Thread] = None + whois_errors: List[BaseException] = [] try: trace_cfg = getattr(fam_config, "trace", None) @@ -815,38 +859,71 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: trace_cfg = fam_config.get("trace") if isinstance(trace_cfg, dict): - interface = trace_cfg.get("interface") or "any" + raw_interface = trace_cfg.get("interface") filter_str = trace_cfg.get("filter") or "" - max_bytes = int(trace_cfg.get("max_bytes") or (10 * 1024 * 1024)) + raw_max_bytes = trace_cfg.get("max_bytes") + exclude_capture_host = bool(trace_cfg.get("exclude_capture_host", False)) elif trace_cfg: - interface = getattr(trace_cfg, "interface", None) or "any" + raw_interface = getattr(trace_cfg, "interface", None) filter_str = getattr(trace_cfg, "filter", None) or "" - max_bytes = int( - getattr(trace_cfg, "max_bytes", None) or (10 * 1024 * 1024) + raw_max_bytes = getattr(trace_cfg, "max_bytes", None) + exclude_capture_host = bool( + getattr(trace_cfg, "exclude_capture_host", False) ) else: - interface = "any" + raw_interface = None filter_str = "" - max_bytes = 10 * 1024 * 1024 + raw_max_bytes = None + exclude_capture_host = False - if not filter_str and family == "bacnet": - filter_str = "udp port 47808" + # Fail fast on missing/invalid explicit interface, scan_duration_sec, or max_bytes + interface = validate_trace_interface(raw_interface) + + raw_duration = getattr(fam_config, "scan_duration_sec", None) + if isinstance(fam_config, dict): + raw_duration = fam_config.get("scan_duration_sec") + if raw_duration is None or int(raw_duration) <= 0: + raise ValueError( + "scan_duration_sec must be explicitly set and > 0 for trace capture" + ) + max_duration_sec = int(raw_duration) + + if raw_max_bytes is None or int(raw_max_bytes) <= 0: + raise ValueError( + "trace.max_bytes must be explicitly set and > 0 for trace capture" + ) + max_bytes = int(raw_max_bytes) - max_duration_sec = int( - getattr(fam_config, "scan_duration_sec", None) - or ( - fam_config.get("scan_duration_sec") - if isinstance(fam_config, dict) - else None + # Release any cached BAC0 client before BACnet trace so UDP 47808 stays unbound + if family == "bacnet": + localnet = getattr(self._device, "get_manager", lambda *_: None)( + "localnet" + ) + if localnet is not None: + bacnet_prov = getattr(localnet, "get_provider", lambda *_: None)( + "bacnet" ) - or 60 + if bacnet_prov is not None and callable( + getattr(bacnet_prov, "close", None) + ): + bacnet_prov.close() + # CAP_NET_RAW pre-flight check before starting capture + check_raw_socket_permission() + + gateway_ip = resolve_gateway_ip(interface) + if not filter_str and family == "bacnet": + filter_str = "udp port 47808" + effective_filter = build_trace_bpf_filter( + filter_str, + exclude_capture_host=exclude_capture_host, + gateway_ip=gateway_ip, ) LOGGER.info( "Spawning TRACE capture worker on '%s' (filter: '%s', max_duration:" " %ds, max_bytes: %d)", interface, - filter_str, + effective_filter, max_duration_sec, max_bytes, ) @@ -862,12 +939,17 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: self.publish_upload(start_msg, "discovery") discovered_routed_networks: Set[int] = set() - discovered_routers: Set[str] = set() scan_round_timestamps: List[str] = [] - gateway_ip = resolve_gateway_ip(interface) - - # 2. For BACnet trace, launch paced raw-socket Who-Is discovery rounds - if family == "bacnet": + bacnet_ip_devices: Set[int] = set() + routed_mstp_devices: Set[int] = set() + device_addrs: Dict[int, Set[str]] = {} + bvll_tail = b"" + + # 2. Launch Who-Is rounds ONLY once tcpdump signals ready (G1) + def _start_whois_rounds() -> None: + nonlocal whois_thread + if family != "bacnet" or whois_stop_event.is_set(): + return whois_thread = threading.Thread( target=run_bacnet_trace_whois_rounds, kwargs={ @@ -877,7 +959,7 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: "max_duration_sec": max_duration_sec, "interface": interface, "src_ip": gateway_ip, - "discovered_routers": discovered_routers, + "error_out": whois_errors, }, name="BACnet-Trace-WhoIs", daemon=True, @@ -891,9 +973,10 @@ def _run_trace_capture(self, family: str, fam_config: Any) -> None: chunk_count = 0 total_bytes = 0 circuit_breaker_tripped = False + last_flush_mono = time.monotonic() def _emit_compressed_chunk(raw_bytes: bytes) -> None: - nonlocal chunk_count + nonlocal chunk_count, last_flush_mono sha256_hasher.update(raw_bytes) compressed = gzip.compress(raw_bytes) b64_data = base64.b64encode(compressed).decode("ascii") @@ -907,7 +990,7 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: data=b64_data, ) self.publish_upload(chunk_msg, "discovery") - f_state.active_count = chunk_count + last_flush_mono = time.monotonic() self.trigger_state_update() LOGGER.info( "Published upload/discovery chunk %d (event_no: %d, %d raw bytes ->" @@ -918,12 +1001,19 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: len(compressed), ) + heartbeat = ( + min(1.0, self.trace_flush_interval_sec) + if self.trace_flush_interval_sec > 0 + else None + ) data_generator = capture_packets( interface=interface, - filter_str=filter_str, + filter_str=effective_filter, max_duration_sec=max_duration_sec, max_bytes=max_bytes, stop_event=whois_stop_event, + on_ready=_start_whois_rounds if family == "bacnet" else None, + heartbeat_sec=heartbeat, ) try: @@ -935,34 +1025,54 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: ) circuit_breaker_tripped = True break - if not chunk: - continue - total_bytes += len(chunk) - if family == "bacnet": - routed = extract_routed_networks_from_pcap_chunk( - chunk, discovered_routers=discovered_routers - ) - if routed: - discovered_routed_networks.update(routed) - pending_buf.extend(chunk) - while len(pending_buf) >= chunk_size: - slice_bytes = bytes(pending_buf[:chunk_size]) - del pending_buf[:chunk_size] - _emit_compressed_chunk(slice_bytes) + if chunk: + total_bytes += len(chunk) + if family == "bacnet": + routed, iam_obs, bvll_tail = extract_bacnet_trace_observations( + chunk, tail=bvll_tail + ) + if routed: + discovered_routed_networks.update(routed) + if iam_obs: + for dev_id, addr_key, is_routed in iam_obs: + if is_routed: + routed_mstp_devices.add(dev_id) + else: + bacnet_ip_devices.add(dev_id) + device_addrs.setdefault(dev_id, set()).add(addr_key) + f_state.active_count = len( + bacnet_ip_devices | routed_mstp_devices + ) + pending_buf.extend(chunk) + while len(pending_buf) >= chunk_size: + slice_bytes = bytes(pending_buf[:chunk_size]) + del pending_buf[:chunk_size] + _emit_compressed_chunk(slice_bytes) + if ( + pending_buf + and self.trace_flush_interval_sec > 0 + and (time.monotonic() - last_flush_mono) + >= self.trace_flush_interval_sec + ): + _emit_compressed_chunk(bytes(pending_buf)) + pending_buf.clear() finally: close_fn = getattr(data_generator, "close", None) if callable(close_fn): close_fn() - if pending_buf: - _emit_compressed_chunk(bytes(pending_buf)) - pending_buf.clear() - - cancelled_externally = whois_stop_event.is_set() + cancelled_externally = whois_stop_event.is_set() and not whois_errors whois_stop_event.set() if whois_thread and whois_thread.is_alive(): whois_thread.join(timeout=2.0) + if whois_errors: + raise whois_errors[0] + + if pending_buf: + _emit_compressed_chunk(bytes(pending_buf)) + pending_buf.clear() + if f_state.generation != generation: return @@ -983,18 +1093,24 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: if total_bytes == 0: raise RuntimeError( - f"Packet capture on '{interface}' (filter: '{filter_str}') produced" - " 0 bytes" + f"Packet capture on '{interface}' (filter: '{effective_filter}')" + " produced 0 bytes" ) # 4. Emit mandatory EOF marker (event_no: -(N + 1)) with sha256 and scan_manifest digest = sha256_hasher.hexdigest() + duplicate_device_ids = sorted( + dev_id for dev_id, addrs in device_addrs.items() if len(addrs) > 1 + ) manifest = ScanManifest( gateway_ip=gateway_ip, interface=interface, - filter=filter_str, + filter=effective_filter, scan_round_timestamps=scan_round_timestamps, discovered_routed_networks=sorted(discovered_routed_networks), + bacnet_ip_devices=len(bacnet_ip_devices), + routed_mstp_devices=len(routed_mstp_devices), + duplicate_device_ids=duplicate_device_ids, ) eof_msg = DiscoveryUpload( timestamp=_format_generation(datetime.now(timezone.utc)), @@ -1015,7 +1131,11 @@ def _emit_compressed_chunk(raw_bytes: bytes) -> None: if f_state.generation == generation: f_state.phase = DiscoveryPhase.stopped - f_state.active_count = chunk_count + f_state.active_count = ( + len(bacnet_ip_devices | routed_mstp_devices) + if family == "bacnet" + else 0 + ) if circuit_breaker_tripped: f_state.status = Entry( category="discovery.family.scan", diff --git a/edge/spotter/src/pcap.py b/edge/spotter/src/pcap.py index 8493bcdb0e..586c3a54fc 100644 --- a/edge/spotter/src/pcap.py +++ b/edge/spotter/src/pcap.py @@ -10,7 +10,7 @@ import subprocess import threading import time -from typing import Iterator, List, Optional, Set +from typing import Callable, Iterator, List, Optional, Set, Tuple try: from host_telemetry import check_safety_circuit_breaker @@ -32,12 +32,52 @@ BACNET_UDP_PORT = 47808 GLOBAL_BACNET_DNET = 0xFFFF +_MAX_BVLL_LEN = 1500 +_MAX_TAIL_BYTES = _MAX_BVLL_LEN + 28 + + +def validate_trace_interface(interface: Optional[str]) -> str: + """Validates that a trace capture interface is an explicit host interface.""" + if not interface or not str(interface).strip(): + raise ValueError( + "Explicit host network interface is required for trace capture" + ) + iface = str(interface).strip() + if iface.lower() == "any": + raise ValueError( + "Interface 'any' is not permitted for trace capture; specify an" + " explicit host interface" + ) + return iface + + +def build_trace_bpf_filter( + base_filter: str, + exclude_capture_host: bool = False, + gateway_ip: Optional[str] = None, +) -> str: + """Constructs the effective tcpdump BPF filter, optionally excluding the capture host.""" + base = (base_filter or "").strip() + if not exclude_capture_host: + return base + if not gateway_ip: + raise ValueError( + "exclude_capture_host requires a resolved capture host IPv4 address" + ) + try: + socket.inet_aton(gateway_ip) + except OSError as err: + raise ValueError( + f"Invalid capture host IPv4 address for exclude_capture_host: {gateway_ip!r}" + ) from err + exclude_clause = f"not host {gateway_ip}" + if base: + return f"({base}) and {exclude_clause}" + return exclude_clause def build_whois_router_to_network_bvll(unicast: bool = False) -> bytes: """Builds an unconfirmed BACnet/IP BVLL Who-Is-Router-To-Network frame.""" - # BVLL Type 0x81, Function 0x0a (Unicast) or 0x0b (Broadcast), Length 7 - # NPDU Version 0x01, Control 0x80 (Network Layer Message), MsgType 0x00 (Who-Is-Router-To-Network) bvlc_func = 0x0A if unicast else 0x0B return bytes([0x81, bvlc_func, 0x00, 0x07, 0x01, 0x80, 0x00]) @@ -91,11 +131,12 @@ def _compute_udp_checksum( def resolve_gateway_ip(interface: Optional[str] = None) -> str: - """Resolves the local IPv4 address for the gateway or target capture interface.""" - if interface and interface != "any": + """Resolves the local IPv4 address for the explicit target capture interface.""" + if interface: + iface = validate_trace_interface(interface) try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: - ifreq = struct.pack("256s", interface[:15].encode("utf-8")) + ifreq = struct.pack("256s", iface[:15].encode("utf-8")) res = fcntl.ioctl(s.fileno(), 0x8915, ifreq) # SIOCGIFADDR ip = socket.inet_ntoa(res[20:24]) if ip and ip != "0.0.0.0": @@ -110,6 +151,12 @@ def resolve_gateway_ip(interface: Optional[str] = None) -> str: return "127.0.0.1" +def check_raw_socket_permission() -> None: + """Verifies CAP_NET_RAW availability by opening and closing a raw UDP socket.""" + with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP): + pass + + def send_raw_bvll( pdu: bytes, dst_ip: str = "255.255.255.255", @@ -118,7 +165,12 @@ def send_raw_bvll( dst_port: int = BACNET_UDP_PORT, interface: Optional[str] = None, ) -> bool: - """Transmits a BACnet BVLL frame with source port 47808 via raw socket without binding UDP 47808.""" + """Transmits a BACnet BVLL frame with source port 47808 via raw socket without binding UDP 47808. + + Raises: + OSError: If CAP_NET_RAW is unavailable or socket transmission fails. + """ + iface = validate_trace_interface(interface) if interface is not None else None udp_len = 8 + len(pdu) header_zero_csum = struct.pack("!HHHH", src_port, dst_port, udp_len, 0) checksum = _compute_udp_checksum(src_ip, dst_ip, header_zero_csum + pdu) @@ -126,70 +178,106 @@ def send_raw_bvll( struct.pack("!HHHH", src_port, dst_port, udp_len, checksum) + pdu ) - try: - with socket.socket( - socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP - ) as raw_sock: - raw_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - if interface and interface != "any" and hasattr(socket, "SO_BINDTODEVICE"): - raw_sock.setsockopt( - socket.SOL_SOCKET, - socket.SO_BINDTODEVICE, - interface.encode("utf-8") + b"\x00", - ) - raw_sock.sendto(udp_frame, (dst_ip, dst_port)) - return True - except OSError as err: - LOGGER.debug("Raw UDP transmit skipped/failed: %s", err) - return False + with socket.socket( + socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP + ) as raw_sock: + raw_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) + if iface and hasattr(socket, "SO_BINDTODEVICE"): + raw_sock.setsockopt( + socket.SOL_SOCKET, + socket.SO_BINDTODEVICE, + iface.encode("utf-8") + b"\x00", + ) + raw_sock.sendto(udp_frame, (dst_ip, dst_port)) + return True -def extract_routed_networks_from_pcap_chunk( +def extract_bacnet_trace_observations( chunk: bytes, - discovered_routers: Optional[Set[str]] = None, -) -> Set[int]: - """Extracts BACnet DNETs and router IPs from I-Am-Router-To-Network and NPDU SNET frames.""" - discovered: Set[int] = set() - if not chunk or decode_bacnet_bvll is None: - return discovered + tail: bytes = b"", +) -> Tuple[Set[int], List[Tuple[int, str, bool]], bytes]: + """Extracts I-Am-Router-To-Network DNETs and I-Am device observations from a PCAP stream chunk. + + Carries incomplete trailing BVLL frames in ``tail`` across chunk boundaries. + + Returns: + Tuple of (routed_dnets, iam_observations, next_tail) where each entry in + ``iam_observations`` is ``(device_id, address_key, is_routed_mstp)``. + """ + discovered_dnets: Set[int] = set() + iam_observations: List[Tuple[int, str, bool]] = [] + if decode_bacnet_bvll is None: + return discovered_dnets, iam_observations, b"" + + buf = (tail or b"") + (chunk or b"") + if not buf: + return discovered_dnets, iam_observations, b"" + next_tail = b"" idx = 0 - while True: - pos = chunk.find(b"\x81", idx) - if pos < 0 or pos + 7 > len(chunk): + buf_len = len(buf) + while idx < buf_len: + pos = buf.find(b"\x81", idx) + if pos < 0: + break + if pos + 4 > buf_len: + # Incomplete BVLL header at end of chunk; preserve with preceding IPv4/UDP header if any. + keep_from = max(0, pos - 28) + next_tail = buf[keep_from:] break - bvlc_func = chunk[pos + 1] + + bvlc_func = buf[pos + 1] if bvlc_func in (0x04, 0x0A, 0x0B): - bvlc_len = int.from_bytes(chunk[pos + 2 : pos + 4], "big") - if 7 <= bvlc_len <= 1500 and pos + bvlc_len <= len(chunk): + bvlc_len = int.from_bytes(buf[pos + 2 : pos + 4], "big") + if 7 <= bvlc_len <= _MAX_BVLL_LEN: + if pos + bvlc_len > buf_len: + keep_from = max(0, pos - 28) + next_tail = buf[keep_from:] + break + outer_ip: Optional[str] = None outer_port: int = BACNET_UDP_PORT if ( pos >= 28 - and (chunk[pos - 28] >> 4) == 4 - and chunk[pos - 19] == socket.IPPROTO_UDP + and (buf[pos - 28] >> 4) == 4 + and buf[pos - 19] == socket.IPPROTO_UDP ): try: - outer_ip = socket.inet_ntoa(chunk[pos - 16 : pos - 12]) - outer_port = int.from_bytes(chunk[pos - 8 : pos - 6], "big") + outer_ip = socket.inet_ntoa(buf[pos - 16 : pos - 12]) + outer_port = int.from_bytes(buf[pos - 8 : pos - 6], "big") except OSError: outer_ip = None + decoded = decode_bacnet_bvll( - chunk[pos : pos + bvlc_len], + buf[pos : pos + bvlc_len], outer_ip=outer_ip, outer_port=outer_port, ) if decoded: if decoded.iam_router_networks: - discovered.update(decoded.iam_router_networks) - if discovered_routers is not None and decoded.orig_ip: - discovered_routers.add(decoded.orig_ip) - if decoded.snet is not None: - discovered.add(decoded.snet) - if discovered_routers is not None and decoded.orig_ip: - discovered_routers.add(decoded.orig_ip) + discovered_dnets.update(decoded.iam_router_networks) + if decoded.device_id is not None: + is_routed = decoded.snet is not None + if is_routed: + addr_key = f"{decoded.snet}:{decoded.sadr or ''}" + else: + ip_str = decoded.orig_ip or outer_ip or "unknown" + port_num = decoded.orig_port or outer_port or BACNET_UDP_PORT + addr_key = f"{ip_str}:{port_num}" + iam_observations.append((decoded.device_id, addr_key, is_routed)) + idx = pos + bvlc_len + continue idx = pos + 1 - return discovered + + if len(next_tail) > _MAX_TAIL_BYTES: + next_tail = next_tail[-_MAX_TAIL_BYTES:] + return discovered_dnets, iam_observations, next_tail + + +def extract_routed_networks_from_pcap_chunk(chunk: bytes) -> Set[int]: + """Extracts BACnet DNETs from I-Am-Router-To-Network frames in a PCAP chunk.""" + dnets, _, _ = extract_bacnet_trace_observations(chunk) + return dnets def run_bacnet_trace_whois_rounds( @@ -201,102 +289,87 @@ def run_bacnet_trace_whois_rounds( dst_ip: str = "255.255.255.255", src_ip: str = "0.0.0.0", rounds: int = 3, - discovered_routers: Optional[Set[str]] = None, + router_wait_sec: float = 2.0, + dnet_pace_sec: float = 1.0, + global_wait_sec: float = 15.0, + monotonic_fn: Callable[[], float] = time.monotonic, + error_out: Optional[List[BaseException]] = None, ) -> None: - """Executes paced rounds of raw-socket broadcast and unicast Who-Is-Router-To-Network and Who-Is.""" - scale = min(1.0, max(0.02, float(max_duration_sec) / 60.0)) - router_wait_sec = 2.0 * scale - dnet_pace_sec = 1.0 * scale - global_wait_sec = 15.0 * scale - - # Brief initial startup sync so tcpdump opens its capture socket before Round 1 - if stop_event.wait(timeout=min(0.1, 0.02 * scale)): + """Executes broadcast-only Who-Is rounds spaced at t = 0, T/3, 2T/3 across the capture window.""" + if rounds <= 0: return - for _ in range(rounds): - if stop_event.is_set(): - break - round_ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - scan_round_timestamps.append(round_ts) - - # 1. Local broadcast + unicast Who-Is-Router-To-Network - send_raw_bvll( - pdu=build_whois_router_to_network_bvll(unicast=False), - dst_ip=dst_ip, - src_ip=src_ip, - src_port=BACNET_UDP_PORT, - interface=interface, - ) - for router_ip in sorted(list(discovered_routers or ())): - send_raw_bvll( - pdu=build_whois_router_to_network_bvll(unicast=True), - dst_ip=router_ip, - src_ip=src_ip, - src_port=BACNET_UDP_PORT, - interface=interface, - ) - if stop_event.wait(timeout=router_wait_sec): - break + window_start = monotonic_fn() + round_spacing_sec = float(max_duration_sec) / float(rounds) - # 2. Local Who-Is + paced per-DNET Who-Is (broadcast and unicast to routers) - send_raw_bvll( - pdu=build_whois_bvll(dnet=None, unicast=False), - dst_ip=dst_ip, - src_ip=src_ip, - src_port=BACNET_UDP_PORT, - interface=interface, - ) - for router_ip in sorted(list(discovered_routers or ())): + try: + for round_idx in range(rounds): + if stop_event.is_set(): + break + + if round_idx > 0: + target_time = window_start + round_idx * round_spacing_sec + wait_sec = target_time - monotonic_fn() + if wait_sec > 0 and stop_event.wait(timeout=wait_sec): + break + if stop_event.is_set(): + break + + # 1. Broadcast Who-Is-Router-To-Network (record round timestamp only after send succeeds) send_raw_bvll( - pdu=build_whois_bvll(dnet=None, unicast=True), - dst_ip=router_ip, + pdu=build_whois_router_to_network_bvll(unicast=False), + dst_ip=dst_ip, src_ip=src_ip, src_port=BACNET_UDP_PORT, interface=interface, ) + round_ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + scan_round_timestamps.append(round_ts) - for dnet in sorted(list(discovered_routed_networks)): - if stop_event.is_set(): + if router_wait_sec > 0 and stop_event.wait(timeout=router_wait_sec): break + + # 2. Local broadcast Who-Is + paced per-DNET broadcast Who-Is send_raw_bvll( - pdu=build_whois_bvll(dnet=dnet, unicast=False), + pdu=build_whois_bvll(dnet=None, unicast=False), dst_ip=dst_ip, src_ip=src_ip, src_port=BACNET_UDP_PORT, interface=interface, ) - for router_ip in sorted(list(discovered_routers or ())): + + for dnet in sorted(list(discovered_routed_networks)): + if stop_event.is_set(): + break send_raw_bvll( - pdu=build_whois_bvll(dnet=dnet, unicast=True), - dst_ip=router_ip, + pdu=build_whois_bvll(dnet=dnet, unicast=False), + dst_ip=dst_ip, src_ip=src_ip, src_port=BACNET_UDP_PORT, interface=interface, ) - if stop_event.wait(timeout=dnet_pace_sec): - break + if dnet_pace_sec > 0 and stop_event.wait(timeout=dnet_pace_sec): + break - if stop_event.is_set(): - break + if stop_event.is_set(): + break - # 3. Global Who-Is (broadcast and unicast to routers) - send_raw_bvll( - pdu=build_whois_bvll(dnet=GLOBAL_BACNET_DNET, unicast=False), - dst_ip=dst_ip, - src_ip=src_ip, - src_port=BACNET_UDP_PORT, - interface=interface, - ) - for router_ip in sorted(list(discovered_routers or ())): + # 3. Global broadcast Who-Is send_raw_bvll( - pdu=build_whois_bvll(dnet=GLOBAL_BACNET_DNET, unicast=True), - dst_ip=router_ip, + pdu=build_whois_bvll(dnet=GLOBAL_BACNET_DNET, unicast=False), + dst_ip=dst_ip, src_ip=src_ip, src_port=BACNET_UDP_PORT, interface=interface, ) - if stop_event.wait(timeout=global_wait_sec): - break + if global_wait_sec > 0 and stop_event.wait(timeout=global_wait_sec): + break + except BaseException as err: # pylint: disable=broad-exception-caught + if error_out is not None: + error_out.append(err) + stop_event.set() + else: + raise def capture_packets( @@ -305,15 +378,22 @@ def capture_packets( max_duration_sec: int, max_bytes: int, stop_event: Optional[threading.Event] = None, + on_ready: Optional[Callable[[], None]] = None, + heartbeat_sec: Optional[float] = None, ) -> Iterator[bytes]: """Spawns tcpdump to capture packets, yielding chunks of bytes. Guarantees resource safety by: + - Requiring an explicit host network interface (never 'any'). + - Invoking ``on_ready`` only after tcpdump starts listening so active probes + never race ahead of capture initialization. - Bounded polling with non-blocking I/O so idle networks do not block. - Concurrent stderr draining to eliminate pipe buffer deadlocks. - Safety circuit breaker evaluation to prevent kernel OOM termination. - Strict caps on duration and byte volume. """ + iface = validate_trace_interface(interface) + if check_safety_circuit_breaker and check_safety_circuit_breaker(): LOGGER.warning( "Safety circuit breaker active: Throttling packet capture before" @@ -324,13 +404,13 @@ def capture_packets( LOGGER.info( "Starting packet capture. Interface: %s, Filter: '%s', Duration Limit:" " %ss, Size Limit: %s bytes", - interface, + iface, filter_str, max_duration_sec, max_bytes, ) - cmd = ["tcpdump", "-i", interface, "-w", "-", "-U"] + cmd = ["tcpdump", "-i", iface, "-w", "-", "-U"] if filter_str: cmd.append(filter_str) @@ -343,9 +423,18 @@ def capture_packets( ) start_time = time.time() + last_yield_time = start_time total_bytes = 0 - stderr_chunks = [] + stderr_chunks: List[bytes] = [] stopped_by_limit = False + ready_notified = False + + def _notify_ready() -> None: + nonlocal ready_notified + if not ready_notified: + ready_notified = True + if on_ready is not None: + on_ready() # Configure non-blocking I/O if running with real OS file descriptors is_real_fd = False @@ -371,11 +460,15 @@ def capture_packets( if proc.stderr and not proc.stderr.closed: rlist.append(proc.stderr) + # Wait briefly for tcpdump's "listening on" banner on stderr before signaling ready + ready_deadline = start_time + min(2.0, float(max_duration_sec)) + while rlist: if stop_event is not None and stop_event.is_set(): stopped_by_limit = True break - elapsed = time.time() - start_time + now = time.time() + elapsed = now - start_time if elapsed >= max_duration_sec: LOGGER.info( "Capture duration limit reached (%ss). Stopping tcpdump...", @@ -384,6 +477,9 @@ def capture_packets( stopped_by_limit = True break + if not ready_notified and now >= ready_deadline: + _notify_ready() + remaining_time = max(0.0, max_duration_sec - elapsed) poll_timeout = min(0.2, remaining_time) @@ -398,13 +494,15 @@ def capture_packets( stopped_by_limit = True break - # 1. Drain stderr to prevent pipe buffer deadlock (>64KB) + # 1. Drain stderr to prevent pipe buffer deadlock (>64KB) and detect readiness if proc.stderr in readable: try: err_chunk = proc.stderr.read(65536) if err_chunk: if len(stderr_chunks) < 16: stderr_chunks.append(err_chunk) + if not ready_notified and b"listening on" in err_chunk.lower(): + _notify_ready() elif err_chunk == b"": rlist.remove(proc.stderr) except (BlockingIOError, IOError): @@ -418,7 +516,10 @@ def capture_packets( chunk = None if chunk: + if not ready_notified: + _notify_ready() total_bytes += len(chunk) + last_yield_time = time.time() yield chunk if total_bytes >= max_bytes: LOGGER.warning( @@ -430,11 +531,20 @@ def capture_packets( elif chunk == b"": rlist.remove(proc.stdout) + if ( + heartbeat_sec is not None + and heartbeat_sec > 0 + and (time.time() - last_yield_time) >= heartbeat_sec + ): + last_yield_time = time.time() + yield b"" + if proc.poll() is not None and not readable: break else: - # Fallback path for mocked execution environments + # Fallback path for mocked execution environments: Popen has already been invoked + _notify_ready() while True: if stop_event is not None and stop_event.is_set(): stopped_by_limit = True @@ -532,4 +642,3 @@ def capture_packets( "Packet capture worker stopped. Total bytes captured: %s", total_bytes, ) - diff --git a/edge/spotter/src/providers/bacnet.py b/edge/spotter/src/providers/bacnet.py index 3f245f2b08..eb29a8c562 100644 --- a/edge/spotter/src/providers/bacnet.py +++ b/edge/spotter/src/providers/bacnet.py @@ -518,11 +518,12 @@ def _discover_buckets( publish_func(f"network-{net_num}", event) def stop_scan(self) -> None: - """Stops any active BACnet scan immediately.""" + """Stops any active BACnet scan immediately and releases UDP 47808.""" LOGGER.info("Stopping BACnet discovery scan...") self._cancelled.set() if self._scan_thread and self._scan_thread.is_alive(): self._scan_thread.join(timeout=1.0) + self.close() def _matches_active_filters(self, address: Any, device_id: Any) -> bool: """Checks if a discovered BACnet device matches configured scope filters.""" diff --git a/edge/spotter/src/providers/passive.py b/edge/spotter/src/providers/passive.py index c1870d7b86..e2dc8f9008 100644 --- a/edge/spotter/src/providers/passive.py +++ b/edge/spotter/src/providers/passive.py @@ -233,8 +233,6 @@ def __init__( self.bacnet_packets_seen = 0 self.passive_holdoff_count = 0 self.discovered_routed_networks: Set[int] = set() - self.bacnet_ip_devices_seen: Set[int] = set() - self.routed_mstp_devices_seen: Set[int] = set() self._packet_count_start: Optional[int] = None def _get_packet_counter_total(self) -> Optional[int]: @@ -323,8 +321,6 @@ def start_scan( self._records_published.clear() self.passive_holdoff_count = 0 self.discovered_routed_networks.clear() - self.bacnet_ip_devices_seen.clear() - self.routed_mstp_devices_seen.clear() with self._event_lock: self._event_count = 0 @@ -490,11 +486,6 @@ def _queue_worker(self, passive_sec: Optional[int] = None) -> None: bacnet_port = int(decoded.orig_port or sport or 47808) snet = decoded.snet sadr = decoded.sadr - with self._records_lock: - if snet is not None: - self.routed_mstp_devices_seen.add(bacnet_id) - else: - self.bacnet_ip_devices_seen.add(bacnet_id) LOGGER.debug( "Passively observed BACnet I-Am device %d at %s:%d" " (snet=%s, sadr=%s)", diff --git a/edge/spotter/tests/test_agent.py b/edge/spotter/tests/test_agent.py index b5bb7ab073..74fcb39d66 100644 --- a/edge/spotter/tests/test_agent.py +++ b/edge/spotter/tests/test_agent.py @@ -436,15 +436,40 @@ def setUp(self): self.manager._device = self.mock_device self.manager._dispatcher = self.mock_dispatcher + @patch("edge.spotter.src.manager.discovery.check_raw_socket_permission") @patch("edge.spotter.src.manager.discovery.run_bacnet_trace_whois_rounds") @patch("edge.spotter.src.manager.discovery.capture_packets") - def test_run_trace_worker_streaming(self, mock_capture, mock_whois): + def test_run_trace_worker_streaming( + self, mock_capture, mock_whois, mock_perm + ): """Verifies gzip-compressed upload/discovery streaming, start/EOF markers, sha256, and scan_manifest.""" + del mock_perm import base64 import gzip - raw_chunks = [b"MOCK_PACKET_HEADER", b"MOCK_PACKET_BODY"] - mock_capture.return_value = raw_chunks + # Build two I-Am frames: BACnet/IP device 1001 and routed MS/TP device 2002 (plus dup of 1001) + def _iam_bvll(dev_id: int, ip_bytes: bytes, snet: int = None, sadr: int = None) -> bytes: + obj_id = (8 << 22) | dev_id + apdu = b"\x10\x00\xc4" + obj_id.to_bytes(4, "big") + b"\x22\x01\xe0\x91\x00\x21\x0f" + if snet is not None: + npdu = b"\x01\x08" + snet.to_bytes(2, "big") + b"\x01" + bytes([sadr]) + else: + npdu = b"\x01\x00" + total = 10 + len(npdu) + len(apdu) + return b"\x81\x04" + total.to_bytes(2, "big") + ip_bytes + (47808).to_bytes(2, "big") + npdu + apdu + + iam_ip_1 = _iam_bvll(1001, bytes([10, 0, 0, 11])) + iam_ip_dup = _iam_bvll(1001, bytes([10, 0, 0, 12])) + iam_mstp = _iam_bvll(2002, bytes([10, 0, 0, 20]), snet=6100, sadr=5) + + def fake_capture(**kwargs): + on_ready = kwargs.get("on_ready") + if callable(on_ready): + on_ready() + yield b"MOCK_PACKET_HEADER" + iam_ip_1 + yield iam_ip_dup + iam_mstp + b"MOCK_PACKET_BODY" + + mock_capture.side_effect = fake_capture def fake_whois(**kwargs): kwargs["scan_round_timestamps"].append("2026-11-10T14:35:01Z") @@ -456,10 +481,19 @@ def fake_whois(**kwargs): generation="2026-11-10T14:35:00Z", depth=Depth.trace, scan_duration_sec=2, + trace=TraceDiscoveryConfig( + interface="eth0", + max_bytes=1048576, + exclude_capture_host=True, + ), ) - self.manager._discovery_state.families["bacnet"] = FamilyDiscoveryState() - self.manager._run_trace_capture("bacnet", fam_config) + with patch( + "edge.spotter.src.manager.discovery.resolve_gateway_ip", + return_value="10.0.0.5", + ): + self.manager._discovery_state.families["bacnet"] = FamilyDiscoveryState() + self.manager._run_trace_capture("bacnet", fam_config) # Expect 3 publishes on upload/discovery: start (0), data chunk (1), EOF (-2) self.assertEqual(self.mock_dispatcher.publish_event.call_count, 3) @@ -472,29 +506,36 @@ def fake_whois(**kwargs): self.assertEqual(start_msg.family, "bacnet") self.assertIsNone(start_msg.data) + expected_raw = ( + b"MOCK_PACKET_HEADER" + iam_ip_1 + iam_ip_dup + iam_mstp + b"MOCK_PACKET_BODY" + ) data_ch, data_msg, _ = calls[1][0] self.assertEqual(data_ch, "upload/discovery") self.assertEqual(data_msg.event_no, 1) decompressed = gzip.decompress(base64.b64decode(data_msg.data)) - self.assertEqual(decompressed, b"MOCK_PACKET_HEADERMOCK_PACKET_BODY") + self.assertEqual(decompressed, expected_raw) eof_ch, eof_msg, _ = calls[2][0] self.assertEqual(eof_ch, "upload/discovery") self.assertEqual(eof_msg.event_no, -2) - expected_sha = hashlib.sha256( - b"MOCK_PACKET_HEADERMOCK_PACKET_BODY" - ).hexdigest() + expected_sha = hashlib.sha256(expected_raw).hexdigest() self.assertEqual(eof_msg.sha256, expected_sha) self.assertIsNotNone(eof_msg.scan_manifest) - self.assertEqual(eof_msg.scan_manifest.filter, "udp port 47808") + self.assertEqual( + eof_msg.scan_manifest.filter, "(udp port 47808) and not host 10.0.0.5" + ) self.assertEqual( eof_msg.scan_manifest.scan_round_timestamps, ["2026-11-10T14:35:01Z"] ) self.assertEqual(eof_msg.scan_manifest.discovered_routed_networks, [6100]) + self.assertEqual(eof_msg.scan_manifest.bacnet_ip_devices, 1) + self.assertEqual(eof_msg.scan_manifest.routed_mstp_devices, 1) + self.assertEqual(eof_msg.scan_manifest.duplicate_device_ids, [1001]) f_state = self.manager._discovery_state.families["bacnet"] self.assertEqual(f_state.phase, DiscoveryPhase.stopped) - self.assertEqual(f_state.active_count, 1) + # Q-P5: active_count tracks unique BACnet I-Am devices (1001 + 2002 = 2) + self.assertEqual(f_state.active_count, 2) self.assertEqual(f_state.status.level, 200) self.assertEqual(f_state.status.category, "discovery.family.scan") self.assertIsNotNone(f_state.status.timestamp) @@ -510,6 +551,7 @@ def test_run_trace_worker_failure(self, mock_capture): trace=TraceDiscoveryConfig( interface="eth0", filter="udp port 47808", + max_bytes=1048576, ), scan_duration_sec=2, ) @@ -538,7 +580,7 @@ def test_run_scan_trace_cleans_up_active_providers(self, mock_capture): fam_config = FamilyDiscoveryConfig( generation="2026-11-10T15:00:00Z", depth=Depth.trace, - trace=TraceDiscoveryConfig(interface="any", filter=""), + trace=TraceDiscoveryConfig(interface="eth0", filter="", max_bytes=1024), scan_duration_sec=1, ) self.manager._config = DiscoveryConfig(families={"ether": fam_config}) @@ -553,6 +595,143 @@ def test_run_scan_trace_cleans_up_active_providers(self, mock_capture): self.assertEqual(f_state.generation, "2026-11-10T15:00:00Z") self.assertEqual(f_state.phase, DiscoveryPhase.stopped) + def test_trace_fail_fast_validation_and_cap_net_raw(self): + """Verifies G5/G8/Q-P4 fail-fast on missing interface/any/duration/max_bytes and CAP_NET_RAW.""" + # Missing / 'any' interface + for bad_iface in (None, "", "any"): + fam_cfg = FamilyDiscoveryConfig( + generation="2026-11-10T15:00:00Z", + depth=Depth.trace, + trace=TraceDiscoveryConfig(interface=bad_iface, max_bytes=1024), + scan_duration_sec=10, + ) + self.manager._discovery_state.families["bacnet"] = FamilyDiscoveryState() + self.manager._run_trace_capture("bacnet", fam_cfg) + f_state = self.manager._discovery_state.families["bacnet"] + self.assertEqual(f_state.phase, DiscoveryPhase.stopped) + self.assertEqual(f_state.status.level, 500) + + # Missing/zero max_bytes or scan_duration_sec + for dur, mb in ((0, 1024), (None, 1024), (10, 0), (10, None)): + fam_cfg = FamilyDiscoveryConfig( + generation="2026-11-10T15:00:00Z", + depth=Depth.trace, + trace=TraceDiscoveryConfig(interface="eth0", max_bytes=mb), + scan_duration_sec=dur, + ) + self.manager._discovery_state.families["bacnet"] = FamilyDiscoveryState() + self.manager._run_trace_capture("bacnet", fam_cfg) + f_state = self.manager._discovery_state.families["bacnet"] + self.assertEqual(f_state.phase, DiscoveryPhase.stopped) + self.assertEqual(f_state.status.level, 500) + + # CAP_NET_RAW PermissionError fails fast with status 500 and zero uploads + self.mock_dispatcher.publish_event.reset_mock() + with patch( + "edge.spotter.src.manager.discovery.check_raw_socket_permission", + side_effect=PermissionError("CAP_NET_RAW required"), + ): + fam_cfg = FamilyDiscoveryConfig( + generation="2026-11-10T15:00:00Z", + depth=Depth.trace, + trace=TraceDiscoveryConfig(interface="eth0", max_bytes=1024), + scan_duration_sec=10, + ) + self.manager._discovery_state.families["bacnet"] = FamilyDiscoveryState() + self.manager._run_trace_capture("bacnet", fam_cfg) + f_state = self.manager._discovery_state.families["bacnet"] + self.assertEqual(f_state.phase, DiscoveryPhase.stopped) + self.assertEqual(f_state.status.level, 500) + self.assertIn("CAP_NET_RAW", f_state.status.message) + self.mock_dispatcher.publish_event.assert_not_called() + + def test_capture_only_mode_rejects_active_bacnet_and_allows_trace(self): + """Verifies G3: capture_only rejects non-trace bacnet and allows depth='trace' without provider.""" + from udmi.core.managers import LocalnetManager + + mgr = SpotterDiscoveryManager(discovery_mode="capture_only") + mock_device = MagicMock() + localnet = LocalnetManager() # No bacnet provider registered! + mock_device.get_manager.side_effect = ( + lambda name: localnet if name == "localnet" else None + ) + mgr._device = mock_device + mgr._dispatcher = MagicMock() + + now_gen = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + # 1. Non-trace BACnet config is rejected with status 500 + cfg_active = Config( + discovery=DiscoveryConfig( + families={ + "bacnet": FamilyDiscoveryConfig( + generation=now_gen, depth=Depth.entries + ) + } + ) + ) + mgr.handle_config(cfg_active) + f_state = mgr._discovery_state.families["bacnet"] + self.assertEqual(f_state.phase, DiscoveryPhase.stopped) + self.assertEqual(f_state.status.level, 500) + self.assertIn("capture_only", f_state.status.message) + + # 2. Trace BACnet config is accepted into pending/active even without BacnetFamilyProvider + future_gen = ( + datetime.now(timezone.utc) + timedelta(minutes=5) + ).strftime("%Y-%m-%dT%H:%M:%SZ") + cfg_trace = Config( + discovery=DiscoveryConfig( + families={ + "bacnet": FamilyDiscoveryConfig( + generation=future_gen, + depth=Depth.trace, + scan_duration_sec=30, + trace=TraceDiscoveryConfig( + interface="eth0", max_bytes=1048576 + ), + ) + } + ) + ) + mgr.handle_config(cfg_trace) + f_state = mgr._discovery_state.families["bacnet"] + self.assertEqual(f_state.phase, DiscoveryPhase.pending) + + @patch("edge.spotter.src.manager.discovery.check_raw_socket_permission") + @patch("edge.spotter.src.manager.discovery.capture_packets") + def test_bacnet_provider_closed_before_trace_starts( + self, mock_capture, mock_perm + ): + """Verifies G4: cached BAC0 client is closed before tcpdump starts.""" + del mock_perm + events = [] + mock_bacnet_prov = MagicMock() + mock_bacnet_prov.close.side_effect = lambda: events.append("bac0_close") + + def fake_capture(**kwargs): + del kwargs + events.append("tcpdump") + yield b"PCAP_BYTES" + + mock_capture.side_effect = fake_capture + mock_localnet = MagicMock() + mock_localnet.get_provider.side_effect = ( + lambda fam: mock_bacnet_prov if fam == "bacnet" else None + ) + self.mock_device.get_manager.side_effect = ( + lambda name: mock_localnet if name == "localnet" else None + ) + + fam_cfg = FamilyDiscoveryConfig( + generation="2026-11-10T15:00:00Z", + depth=Depth.trace, + trace=TraceDiscoveryConfig(interface="eth0", max_bytes=1024), + scan_duration_sec=2, + ) + self.manager._discovery_state.families["bacnet"] = FamilyDiscoveryState() + self.manager._run_trace_capture("bacnet", fam_cfg) + self.assertEqual(events, ["bac0_close", "tcpdump"]) + @patch("edge.spotter.src.manager.discovery.check_safety_circuit_breaker") def test_run_scan_circuit_breaker_throttles_execution(self, mock_cb): """Verifies scan throttling when memory safety circuit breaker trips.""" diff --git a/edge/spotter/tests/test_pcap.py b/edge/spotter/tests/test_pcap.py index 5da97dd569..e2d60a9a65 100644 --- a/edge/spotter/tests/test_pcap.py +++ b/edge/spotter/tests/test_pcap.py @@ -57,7 +57,7 @@ def test_capture_packets_duration_limit(self, mock_popen, mock_time): mock_time.side_effect = [0.0, 5.0, 65.0] generator = capture_packets( - interface="any", filter_str="", max_duration_sec=60, max_bytes=1000000 + interface="eth0", filter_str="", max_duration_sec=60, max_bytes=1000000 ) chunks = list(generator) @@ -107,7 +107,7 @@ def test_capture_packets_kill_on_timeout_expired(self, mock_popen): mock_proc.stderr.read.return_value = b"" generator = capture_packets( - interface="any", filter_str="", max_duration_sec=1, max_bytes=100 + interface="eth0", filter_str="", max_duration_sec=1, max_bytes=100 ) with patch("time.time", side_effect=[0.0, 2.0, 3.0]): @@ -131,7 +131,7 @@ def test_capture_packets_idle_timeout_nonblocking(self): ): t0 = time.time() gen = capture_packets( - interface="any", filter_str="", max_duration_sec=1, max_bytes=1000 + interface="eth0", filter_str="", max_duration_sec=1, max_bytes=1000 ) chunks = list(gen) elapsed = time.time() - t0 @@ -158,7 +158,7 @@ def test_capture_packets_drains_large_stderr_no_deadlock(self): ), ): gen = capture_packets( - interface="any", filter_str="", max_duration_sec=5, max_bytes=1000 + interface="eth0", filter_str="", max_duration_sec=5, max_bytes=1000 ) chunks = list(gen) self.assertEqual(chunks, [b"PACKET_DATA"]) @@ -171,7 +171,7 @@ def test_capture_packets_circuit_breaker_throttles( """Verifies circuit breaker blocks capture launch before spawning.""" mock_cb.return_value = True gen = capture_packets( - interface="any", filter_str="", max_duration_sec=5, max_bytes=1000 + interface="eth0", filter_str="", max_duration_sec=5, max_bytes=1000 ) chunks = list(gen) self.assertEqual(chunks, []) @@ -243,9 +243,10 @@ def test_send_raw_bvll_uses_raw_socket_without_binding_47808( @patch("edge.spotter.src.pcap.send_raw_bvll", return_value=True) def test_run_bacnet_trace_whois_rounds_and_routed_extraction(self, mock_send): - """Verifies 3 paced rounds of raw-socket broadcast/unicast Who-Is and I-Am-Router / SNET extraction.""" + """Verifies 3 broadcast-only rounds spaced across T and I-Am-Router-only DNET extraction.""" import threading from edge.spotter.src.pcap import ( + extract_bacnet_trace_observations, extract_routed_networks_from_pcap_chunk, run_bacnet_trace_whois_rounds, ) @@ -257,6 +258,7 @@ def test_run_bacnet_trace_whois_rounds_and_routed_extraction(self, mock_send): + (9288).to_bytes(2, "big") ) # 2. BVLL Forwarded-NPDU (0x04) from router 192.168.50.12 with NPDU SNET=7700, SLEN=1, SADR=5 + # SNET must NOT be promoted to DNET (G7: I-Am-Router-To-Network only). routed_snet_frame = ( b"\x81\x04\x00\x16" + bytes([192, 168, 50, 12]) @@ -266,34 +268,122 @@ def test_run_bacnet_trace_whois_rounds_and_routed_extraction(self, mock_send): + b"\x01\x05" + b"\x00\x05\x01\x0c\x0c" ) - routers = set() routed = extract_routed_networks_from_pcap_chunk( - b"PCAP_HDR" + iam_router_frame + routed_snet_frame + b"TRAILING", - discovered_routers=routers, + b"PCAP_HDR" + iam_router_frame + routed_snet_frame + b"TRAILING" ) - self.assertEqual(routed, {6100, 9288, 7700}) - self.assertEqual(routers, {"192.168.50.12"}) + self.assertEqual(routed, {6100, 9288}) + # Verify tail-buffer carry-over across split chunk boundaries (G9) + split_idx = 4 + dnets1, obs1, tail1 = extract_bacnet_trace_observations( + b"PCAP_HDR" + iam_router_frame[:split_idx] + ) + self.assertEqual(dnets1, set()) + self.assertEqual(obs1, []) + self.assertTrue(len(tail1) >= split_idx) + dnets2, _, tail2 = extract_bacnet_trace_observations( + iam_router_frame[split_idx:], tail=tail1 + ) + self.assertEqual(dnets2, {6100, 9288}) + self.assertEqual(tail2, b"") + + # Verify 3 rounds spaced at t = 0, T/3, 2T/3 with fake clock (G2) and broadcast-only (G7) + fake_now = [0.0] + round_start_times = [] + + class FakeEvent(threading.Event): + def wait(self, timeout=None): + if timeout and timeout > 0: + fake_now[0] += timeout + return self.is_set() + + def record_send(**kwargs): + if kwargs["pdu"] == b"\x81\x0b\x00\x07\x01\x80\x00": + round_start_times.append(fake_now[0]) + return True + + mock_send.side_effect = record_send timestamps = [] - stop_evt = threading.Event() run_bacnet_trace_whois_rounds( discovered_routed_networks={6100, 9288}, scan_round_timestamps=timestamps, - stop_event=stop_evt, - max_duration_sec=1, + stop_event=FakeEvent(), + max_duration_sec=900, interface="eth0", src_ip="192.168.1.50", rounds=3, - discovered_routers=routers, + monotonic_fn=lambda: fake_now[0], ) self.assertEqual(len(timestamps), 3) - # Per round (with 1 router and 2 DNETs): - # - Who-Is-Router: 1 bcast + 1 unicast = 2 - # - Local Who-Is: 1 bcast + 1 unicast = 2 - # - 2 DNETs: 2 * (1 bcast + 1 unicast) = 4 - # - Global Who-Is: 1 bcast + 1 unicast = 2 - # Total per round = 10 * 3 rounds = 30 - self.assertEqual(mock_send.call_count, 30) + self.assertEqual(round_start_times, [0.0, 300.0, 600.0]) + # Per round (broadcast-only, 2 DNETs): WIRTN (1) + local (1) + 2 DNETs (2) + global (1) = 5 * 3 = 15 + self.assertEqual(mock_send.call_count, 15) + + def test_capture_packets_rejects_any_interface(self): + """Verifies capture_packets fails fast when interface is 'any' or empty.""" + for bad_iface in ("any", "ANY", "", " "): + with self.assertRaises(ValueError): + list( + capture_packets( + interface=bad_iface, + filter_str="udp port 47808", + max_duration_sec=10, + max_bytes=1024, + ) + ) + + def test_build_trace_bpf_filter_exclude_capture_host(self): + """Verifies exclude_capture_host appends 'not host ' to BPF filter.""" + from edge.spotter.src.pcap import build_trace_bpf_filter + + self.assertEqual( + build_trace_bpf_filter("udp port 47808", False, "10.0.0.5"), + "udp port 47808", + ) + self.assertEqual( + build_trace_bpf_filter("udp port 47808", True, "10.0.0.5"), + "(udp port 47808) and not host 10.0.0.5", + ) + self.assertEqual( + build_trace_bpf_filter("", True, "10.0.0.5"), + "not host 10.0.0.5", + ) + + @patch("socket.socket") + def test_send_raw_bvll_raises_on_permission_error(self, mock_socket_cls): + """Verifies send_raw_bvll raises PermissionError instead of swallowing (G5).""" + from edge.spotter.src.pcap import build_whois_bvll, send_raw_bvll + + mock_socket_cls.side_effect = PermissionError("Operation not permitted") + with self.assertRaises(PermissionError): + send_raw_bvll(pdu=build_whois_bvll(), interface="eth0") + + @patch("subprocess.Popen") + def test_capture_packets_invokes_on_ready_after_popen(self, mock_popen): + """Verifies Popen is invoked before on_ready callback fires (G1).""" + events = [] + mock_proc = MagicMock() + mock_proc.poll.return_value = 0 + mock_proc.stdout.read.side_effect = [b"PCAP", b""] + mock_proc.stderr.read.return_value = b"" + + def fake_popen(*args, **kwargs): + del args, kwargs + events.append("popen") + return mock_proc + + mock_popen.side_effect = fake_popen + chunks = list( + capture_packets( + interface="eth0", + filter_str="udp port 47808", + max_duration_sec=5, + max_bytes=1000, + on_ready=lambda: events.append("ready"), + ) + ) + self.assertEqual(chunks, [b"PCAP"]) + self.assertEqual(events, ["popen", "ready"]) @patch("subprocess.Popen") def test_capture_packets_raises_on_tcpdump_nonzero_exit(self, mock_popen): diff --git a/gencode/docs/config.html b/gencode/docs/config.html index 71c6a8b053..f0e55f0ac8 100644 --- a/gencode/docs/config.html +++ b/gencode/docs/config.html @@ -2435,6 +2435,68 @@

Value must be greater or equal to 0

+

+
+
+ +
+
+
+

+ +

+
+ +
+
+ + Type: boolean Default: false
+

Exclude packets to or from the capture host IP address from the capture filter

+
+ + + + + +
diff --git a/gencode/docs/upload_discovery.html b/gencode/docs/upload_discovery.html index 02fa7fc595..b3b90194f9 100644 --- a/gencode/docs/upload_discovery.html +++ b/gencode/docs/upload_discovery.html @@ -566,6 +566,164 @@

+

+ + + + + +
+
+
+

+ +

+
+ +
+
+ + Type: integer
+

Count of unique BACnet/IP devices observed via I-Am during trace

+
+ + + +

Value must be greater or equal to 0

+ + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: integer
+

Count of unique routed MS/TP devices observed via I-Am during trace

+
+ + + +

Value must be greater or equal to 0

+ + +
+
+
+
+
+
+
+

+ +

+
+ +
+
+ + Type: array of integer
+

BACnet device instance IDs observed from multiple distinct addresses during trace

+
+ + + + + + No Additional Items

Each item of this array must be:

+
+
+ + + Type: integer
+ + + + + + +
diff --git a/gencode/java/udmi/schema/ScanManifest.java b/gencode/java/udmi/schema/ScanManifest.java index 0e715bebcb..80f1b1b0b1 100644 --- a/gencode/java/udmi/schema/ScanManifest.java +++ b/gencode/java/udmi/schema/ScanManifest.java @@ -52,15 +52,39 @@ public class ScanManifest { @JsonProperty("discovered_routed_networks") @JsonPropertyDescription("Routed BACnet DNET numbers discovered via I-Am-Router-To-Network during trace") public List discovered_routed_networks; + /** + * Count of unique BACnet/IP devices observed via I-Am during trace + * + */ + @JsonProperty("bacnet_ip_devices") + @JsonPropertyDescription("Count of unique BACnet/IP devices observed via I-Am during trace") + public Integer bacnet_ip_devices; + /** + * Count of unique routed MS/TP devices observed via I-Am during trace + * + */ + @JsonProperty("routed_mstp_devices") + @JsonPropertyDescription("Count of unique routed MS/TP devices observed via I-Am during trace") + public Integer routed_mstp_devices; + /** + * BACnet device instance IDs observed from multiple distinct addresses during trace + * + */ + @JsonProperty("duplicate_device_ids") + @JsonPropertyDescription("BACnet device instance IDs observed from multiple distinct addresses during trace") + public List duplicate_device_ids; @Override public int hashCode() { int result = 1; result = ((result* 31)+((this.filter == null)? 0 :this.filter.hashCode())); - result = ((result* 31)+((this.gateway_ip == null)? 0 :this.gateway_ip.hashCode())); + result = ((result* 31)+((this.duplicate_device_ids == null)? 0 :this.duplicate_device_ids.hashCode())); result = ((result* 31)+((this.discovered_routed_networks == null)? 0 :this.discovered_routed_networks.hashCode())); - result = ((result* 31)+((this._interface == null)? 0 :this._interface.hashCode())); + result = ((result* 31)+((this.bacnet_ip_devices == null)? 0 :this.bacnet_ip_devices.hashCode())); result = ((result* 31)+((this.scan_round_timestamps == null)? 0 :this.scan_round_timestamps.hashCode())); + result = ((result* 31)+((this.gateway_ip == null)? 0 :this.gateway_ip.hashCode())); + result = ((result* 31)+((this.routed_mstp_devices == null)? 0 :this.routed_mstp_devices.hashCode())); + result = ((result* 31)+((this._interface == null)? 0 :this._interface.hashCode())); return result; } @@ -73,7 +97,7 @@ public boolean equals(Object other) { return false; } ScanManifest rhs = ((ScanManifest) other); - return ((((((this.filter == rhs.filter)||((this.filter!= null)&&this.filter.equals(rhs.filter)))&&((this.gateway_ip == rhs.gateway_ip)||((this.gateway_ip!= null)&&this.gateway_ip.equals(rhs.gateway_ip))))&&((this.discovered_routed_networks == rhs.discovered_routed_networks)||((this.discovered_routed_networks!= null)&&this.discovered_routed_networks.equals(rhs.discovered_routed_networks))))&&((this._interface == rhs._interface)||((this._interface!= null)&&this._interface.equals(rhs._interface))))&&((this.scan_round_timestamps == rhs.scan_round_timestamps)||((this.scan_round_timestamps!= null)&&this.scan_round_timestamps.equals(rhs.scan_round_timestamps)))); + return (((((((((this.filter == rhs.filter)||((this.filter!= null)&&this.filter.equals(rhs.filter)))&&((this.duplicate_device_ids == rhs.duplicate_device_ids)||((this.duplicate_device_ids!= null)&&this.duplicate_device_ids.equals(rhs.duplicate_device_ids))))&&((this.discovered_routed_networks == rhs.discovered_routed_networks)||((this.discovered_routed_networks!= null)&&this.discovered_routed_networks.equals(rhs.discovered_routed_networks))))&&((this.bacnet_ip_devices == rhs.bacnet_ip_devices)||((this.bacnet_ip_devices!= null)&&this.bacnet_ip_devices.equals(rhs.bacnet_ip_devices))))&&((this.scan_round_timestamps == rhs.scan_round_timestamps)||((this.scan_round_timestamps!= null)&&this.scan_round_timestamps.equals(rhs.scan_round_timestamps))))&&((this.gateway_ip == rhs.gateway_ip)||((this.gateway_ip!= null)&&this.gateway_ip.equals(rhs.gateway_ip))))&&((this.routed_mstp_devices == rhs.routed_mstp_devices)||((this.routed_mstp_devices!= null)&&this.routed_mstp_devices.equals(rhs.routed_mstp_devices))))&&((this._interface == rhs._interface)||((this._interface!= null)&&this._interface.equals(rhs._interface)))); } } diff --git a/gencode/java/udmi/schema/TraceDiscoveryConfig.java b/gencode/java/udmi/schema/TraceDiscoveryConfig.java index ba3c850942..de3ef517ad 100644 --- a/gencode/java/udmi/schema/TraceDiscoveryConfig.java +++ b/gencode/java/udmi/schema/TraceDiscoveryConfig.java @@ -37,13 +37,21 @@ public class TraceDiscoveryConfig { @JsonProperty("max_bytes") @JsonPropertyDescription("Maximum byte volume cap for trace collection to prevent exhaustion") public Integer max_bytes; + /** + * Exclude packets to or from the capture host IP address from the capture filter + * + */ + @JsonProperty("exclude_capture_host") + @JsonPropertyDescription("Exclude packets to or from the capture host IP address from the capture filter") + public Boolean exclude_capture_host = false; @Override public int hashCode() { int result = 1; - result = ((result* 31)+((this._interface == null)? 0 :this._interface.hashCode())); result = ((result* 31)+((this.filter == null)? 0 :this.filter.hashCode())); + result = ((result* 31)+((this.exclude_capture_host == null)? 0 :this.exclude_capture_host.hashCode())); result = ((result* 31)+((this.max_bytes == null)? 0 :this.max_bytes.hashCode())); + result = ((result* 31)+((this._interface == null)? 0 :this._interface.hashCode())); return result; } @@ -56,7 +64,7 @@ public boolean equals(Object other) { return false; } TraceDiscoveryConfig rhs = ((TraceDiscoveryConfig) other); - return ((((this._interface == rhs._interface)||((this._interface!= null)&&this._interface.equals(rhs._interface)))&&((this.filter == rhs.filter)||((this.filter!= null)&&this.filter.equals(rhs.filter))))&&((this.max_bytes == rhs.max_bytes)||((this.max_bytes!= null)&&this.max_bytes.equals(rhs.max_bytes)))); + return (((((this.filter == rhs.filter)||((this.filter!= null)&&this.filter.equals(rhs.filter)))&&((this.exclude_capture_host == rhs.exclude_capture_host)||((this.exclude_capture_host!= null)&&this.exclude_capture_host.equals(rhs.exclude_capture_host))))&&((this.max_bytes == rhs.max_bytes)||((this.max_bytes!= null)&&this.max_bytes.equals(rhs.max_bytes))))&&((this._interface == rhs._interface)||((this._interface!= null)&&this._interface.equals(rhs._interface)))); } } diff --git a/gencode/python/udmi/schema/config_discovery_trace.py b/gencode/python/udmi/schema/config_discovery_trace.py index de87747ec9..e97fe13123 100644 --- a/gencode/python/udmi/schema/config_discovery_trace.py +++ b/gencode/python/udmi/schema/config_discovery_trace.py @@ -18,3 +18,4 @@ class TraceDiscoveryConfig(DataModel): interface: Optional[str] = None filter: Optional[str] = None max_bytes: Optional[int] = None + exclude_capture_host: Optional[bool] = False diff --git a/gencode/python/udmi/schema/upload_discovery.py b/gencode/python/udmi/schema/upload_discovery.py index 12b28e257d..c584bb3837 100644 --- a/gencode/python/udmi/schema/upload_discovery.py +++ b/gencode/python/udmi/schema/upload_discovery.py @@ -20,6 +20,9 @@ class ScanManifest(DataModel): filter: Optional[str] = None scan_round_timestamps: Optional[List[str]] = None discovered_routed_networks: Optional[List[int]] = None + bacnet_ip_devices: Optional[int] = None + routed_mstp_devices: Optional[int] = None + duplicate_device_ids: Optional[List[int]] = None @dataclass diff --git a/mcp/butler/provider.py b/mcp/butler/provider.py index fa8ac173ed..ea389ba9ad 100644 --- a/mcp/butler/provider.py +++ b/mcp/butler/provider.py @@ -931,6 +931,8 @@ def trigger_bacnet_trace( bug_id: Optional[str] = None, conn_spec: Optional[str] = None, site_model: Optional[str] = None, + interface: str = "eth0", + exclude_capture_host: bool = False, ) -> Dict[str, Any]: """Triggers a depth: 'trace' BACnet packet capture on the target gateway and tracks reassembly.""" generation = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") @@ -988,6 +990,8 @@ def trigger_bacnet_trace( max_bytes=int(max_bytes), site_model=site_model or os.environ.get("BUTLER_SITE_MODEL"), generation=generation, + interface=interface, + exclude_capture_host=bool(exclude_capture_host), ) return { diff --git a/mcp/butler/server.py b/mcp/butler/server.py index a08597fe0e..6c07265e02 100644 --- a/mcp/butler/server.py +++ b/mcp/butler/server.py @@ -326,6 +326,8 @@ "bug_id": {"type": "string", "description": "Optional issue or ticket identifier"}, "conn_spec": {"type": "string", "description": "Optional UDMI connection specification (e.g. //mqtt/localhost)"}, "site_model": {"type": "string", "description": "Optional path to the UDMI site model directory"}, + "interface": {"type": "string", "default": "eth0", "description": "Explicit host network interface for capture (never 'any')"}, + "exclude_capture_host": {"type": "boolean", "default": False, "description": "Exclude capture host IP packets from BPF filter"}, }, "required": ["site", "gateway_id"], }, @@ -557,6 +559,8 @@ def _dispatch_tool(self, name: str, args: Dict[str, Any]) -> Any: bug_id=args.get("bug_id"), conn_spec=args.get("conn_spec"), site_model=args.get("site_model"), + interface=args.get("interface", "eth0"), + exclude_capture_host=bool(args.get("exclude_capture_host", False)), ) if name == "get_pcap_capture": return self.provider.get_pcap_capture( diff --git a/schema/config_discovery_trace.json b/schema/config_discovery_trace.json index b771e07ba0..57dbf70fc7 100644 --- a/schema/config_discovery_trace.json +++ b/schema/config_discovery_trace.json @@ -18,6 +18,11 @@ "description": "Maximum byte volume cap for trace collection to prevent exhaustion", "type": "integer", "minimum": 0 + }, + "exclude_capture_host": { + "description": "Exclude packets to or from the capture host IP address from the capture filter", + "type": "boolean", + "default": false } } } diff --git a/schema/upload_discovery.json b/schema/upload_discovery.json index ddbcd1b3cf..70696fcd15 100644 --- a/schema/upload_discovery.json +++ b/schema/upload_discovery.json @@ -69,6 +69,23 @@ "items": { "type": "integer" } + }, + "bacnet_ip_devices": { + "description": "Count of unique BACnet/IP devices observed via I-Am during trace", + "type": "integer", + "minimum": 0 + }, + "routed_mstp_devices": { + "description": "Count of unique routed MS/TP devices observed via I-Am during trace", + "type": "integer", + "minimum": 0 + }, + "duplicate_device_ids": { + "description": "BACnet device instance IDs observed from multiple distinct addresses during trace", + "type": "array", + "items": { + "type": "integer" + } } } } From d7bd40d279df70e0d952c4aa1f494af13eabf221 Mon Sep 17 00:00:00 2001 From: Khyati Mahendru Date: Fri, 27 Nov 2026 17:14:56 +0000 Subject: [PATCH 8/8] Fix Spotter docs spelling and pass explicit eth0 interface in test_pcap --- docs/tools/spotter.md | 4 ++-- edge/spotter/bin/test_pcap | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/tools/spotter.md b/docs/tools/spotter.md index 83903666a8..ee65506b60 100644 --- a/docs/tools/spotter.md +++ b/docs/tools/spotter.md @@ -60,8 +60,8 @@ Spotter processes diagnostic packet capture triggers sent declaratively over the 1. **Capture Worker & Active BACnet Trace Rounds ([pcap.py](../../edge/spotter/src/pcap.py))**: - Requires an explicit host network interface in `trace.interface` (never `"any"`), plus explicit positive `scan_duration_sec` and `trace.max_bytes` bounds (fail-fast with status `500` on missing or invalid values). - - Spawns `tcpdump` with a kernel BPF filter (defaulting to `"udp port 47808"` for `bacnet`), and waits for `tcpdump` to start listening before launching active probes. When `trace.exclude_capture_host` is `true`, appends `and not host ` to the BPF filter and records the effective filter in `scan_manifest.filter`. - - For `families.bacnet` with `depth: "trace"`, releases any cached `BAC0` socket so UDP port `47808` remains unbound, runs a `CAP_NET_RAW` pre-flight check (failing fast with status `500` if unavailable), and executes 3 broadcast-only raw-socket (`SOCK_RAW, IPPROTO_UDP`) `Who-Is-Router-To-Network` and `Who-Is` rounds spaced across the capture window (`t = 0, T/3, 2T/3`). + - Spawns `tcpdump` with a kernel `BPF` filter (defaulting to `"udp port 47808"` for `bacnet`), and waits for `tcpdump` to start listening before launching active probes. When `trace.exclude_capture_host` is `true`, appends `and not host ` to the `BPF` filter and records the effective filter in `scan_manifest.filter`. + - For `families.bacnet` with `depth: "trace"`, releases any cached `BAC0` socket so UDP port `47808` remains unbound, runs a `CAP_NET_RAW` startup check (failing fast with status `500` if unavailable), and executes 3 broadcast-only raw-socket (`SOCK_RAW, IPPROTO_UDP`) `Who-Is-Router-To-Network` and `Who-Is` rounds spaced across the capture window (`t = 0, T/3, 2T/3`). - Decodes `I-Am` and `I-Am-Router-To-Network` frames inline during capture to populate `scan_manifest` (`bacnet_ip_devices`, `routed_mstp_devices`, `duplicate_device_ids`, `discovered_routed_networks`) and reports the unique discovered BACnet `I-Am` device count in `state.discovery.families.bacnet.active_count`. 2. **Discovery Modes & Coexistence (`udmi.discovery.mode`)**: - `"full"` (default): Enables standard active BACnet, Ether, and passive IPv4 discovery alongside `depth: "trace"` captures. Active `BAC0` clients are closed immediately at the end of every standard scan so UDP `47808` is never held open when idle. diff --git a/edge/spotter/bin/test_pcap b/edge/spotter/bin/test_pcap index 4187e50bda..84dbd13798 100755 --- a/edge/spotter/bin/test_pcap +++ b/edge/spotter/bin/test_pcap @@ -209,6 +209,7 @@ cat < "$TEST_DIR/config_payload.json" "depth": "trace", "scan_duration_sec": 4, "trace": { + "interface": "eth0", "max_bytes": 100000 } }