Commit graph

301 commits

Author SHA1 Message Date
9f8b925ecd
test: expand coverage for devices, workers, and LiveView modules
Add tests for untested Devices context functions (get_device_by_ip,
get_mikrotik_config, get_snmpv3_config, credential propagation,
resolve_snmp_community, list_mikrotik_devices_with_api), activity
log action descriptions, firmware version extraction edge cases,
and discovery worker enqueue/retryable_error paths.
2026-02-12 09:06:41 -06:00
1c0cccdf25
feat: add UniFi channel-to-frequency dynamic conversion
Add TIER 3 MEDIUM priority dynamic frequency sensor discovery for Ubiquiti UniFi APs.
Implements channel-to-frequency conversion matching LibreNMS behavior exactly.

Implementation:
- discover_frequency_sensors/1: Orchestrates discovery with `with` for flat control flow
- fetch_channels/1: Walks channel OID (.1.3.6.1.4.1.41112.1.6.1.2.1.4)
- fetch_radio_names/1: Walks radio name OID (.1.3.6.1.4.1.41112.1.6.1.2.1.1)
- build_frequency_sensors/2: Converts channels to frequency sensors
- channel_to_frequency/1: Module attribute map lookup (29 Wi-Fi channels)
  - 2.4GHz: Channels 1-14 → 2412-2484 MHz
  - 5GHz: Channels 34-165 → 5170-5825 MHz
  - Unknown channels filtered out (return 0 → rejected)
- Frequency sensors added alongside static sensors
- Per-radio sensors with descriptive names (e.g., "Frequency (ng)")

Code Quality:
- Refactored to reduce cyclomatic complexity (map lookup vs case statements)
- Extracted helper functions to reduce nesting depth
- Pattern matching in tests instead of length/1 checks
- All Credo checks passing without disabling rules

Testing:
- Added comprehensive test coverage (16 tests, all passing)
- Tests 2.4GHz channel conversion (1, 6, 11)
- Tests 5GHz channel conversion (36, 149, 165)
- Tests unknown channel filtering (999 → filtered out)
- Tests integration with static sensors (10 static + 2 frequency = 12 total)
- Tests graceful handling of channel walk failures
- Mox-based SNMP adapter mocking

Impact:
- Dynamic frequency monitoring enables accurate channel tracking
- Handles AP channel changes (auto-DFS, manual config changes)
- Static OID approach was inaccurate (channel changes not reflected)

Source:
- LibreNMS LibreNMS/OS/Unifi.php discoverWirelessFrequency/pollWirelessFrequency
- LibreNMS LibreNMS/Modules/Wireless.php channelToFrequency lookup table

Priority: TIER 3 MEDIUM (3-5 hour effort, vendor module enhancement)
Gap Status: UniFi parity 80% → 90%
Result: TIER 3 COMPLETE - All Ubiquiti platform gaps resolved

Files:
- lib/towerops/snmp/profiles/vendors/unifi.ex
- test/towerops/snmp/profiles/vendors/unifi_test.exs
- CHANGELOG.txt
2026-02-12 09:05:00 -06:00
9094f42098
feat: add Dell PowerVault storage array text-based sensor parsing
Implement vendor module for Dell PowerVault storage arrays that parse
text-based sensor messages from FCMGMT-MIB instead of structured tables.

Created vendor post-processing module:
- lib/towerops/snmp/profiles/vendors/powervault.ex
  * Walks FCMGMT-MIB::connUnitSensorMessage (OID 1.3.6.1.3.94.1.8.1.6)
  * Parses text format "Sensor Name: Value Unit" with regex matching
  * Temperature: "25 C 77.0F" → 25°C (extracts Celsius)
  * Voltage: "12.1V" → 12.1V
  * Current: "0.5A" → 0.5A
  * Battery Charge: "95%" → 95% (with threshold limits)

Integrated into discovery pipeline:
- lib/towerops/snmp/profiles/dynamic.ex
  * Added "dell-powervault" case to apply_vendor_post_processing/3
  * Follows Arista vendor module pattern

Comprehensive test coverage:
- test/towerops/snmp/profiles/vendors/powervault_test.exs
  * 21 tests covering all sensor types and edge cases
  * Tests multi-sensor parsing, error handling, format validation
  * All tests passing with Mox SNMP adapter mocking

Technical notes:
- Client.walk returns map {oid => value}, converted to list for parsing
- Sensor indices: powervault_{type}.{oid_index} for uniqueness
- post_process_sensors/2 combines with existing sensors from base discovery

Result: Dell PowerVault arrays now supported with text message parsing.
Gap: CRITICAL (no sensors) → RESOLVED. Parity: 0% → 85%.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 08:38:30 -06:00
95e3870fec
feat: add Force10 FTOS and optical transceiver monitoring (ProCurve, Comware)
Completed Tier 1 (critical network switches) and Tier 2 (optical transceiver monitoring)
from Phase 3 implementation plan. All major network switches now have comprehensive sensor
coverage including temperature and fiber optic link diagnostics.

Files Changed:
- priv/profiles/os_discovery/ftos.yaml (enhanced)
  Added Dell Force10 FTOS temperature monitoring for all 3 series:
  - S-Series: Stack unit temperature (chStackUnitTemp)
    OID: .1.3.6.1.4.1.6027.3.10.1.2.2.1.14
    MIB: F10-S-SERIES-CHASSIS-MIB
  - C-Series: Card temperature (chSysCardTemp)
    OID: .1.3.6.1.4.1.6027.3.8.1.2.1.1.5
    MIB: F10-C-SERIES-CHASSIS-MIB
  - E-Series: Card upper + lower temperature (chSysCardUpperTemp, chSysCardLowerTemp)
    OIDs: .1.3.6.1.4.1.6027.3.1.1.2.3.1.8-9
    MIB: F10-CHASSIS-MIB
  Gap: CRITICAL (no sensors) → RESOLVED
  Parity: 0% → 90%

- priv/profiles/os_discovery/procurve.yaml (enhanced)
  Added HP ProCurve transceiver optical monitoring (5 sensor types):
  MIB: HP-ICF-TRANSCEIVER-MIB::hpicfXcvrInfoTable
  Sensors:
    - Temperature: hpicfXcvrTemp (OID .1.3.6.1.4.1.11.2.14.11.5.1.82.1.1.1.1.11, divisor 1000)
    - Bias Current: hpicfXcvrBias (OID .1.3.6.1.4.1.11.2.14.11.5.1.82.1.1.1.1.13, divisor 1000)
    - Supply Voltage: hpicfXcvrVoltage (OID .1.3.6.1.4.1.11.2.14.11.5.1.82.1.1.1.1.12, divisor 1000)
    - RX Power (dBm): hpicfXcvrRxPower (OID .1.3.6.1.4.1.11.2.14.11.5.1.82.1.1.1.1.14, divisor 10)
    - TX Power (dBm): hpicfXcvrTxPower (OID .1.3.6.1.4.1.11.2.14.11.5.1.82.1.1.1.1.15, divisor 10)
  Gap: HIGH (missing transceivers) → RESOLVED
  Parity: 60% → 100%

- priv/profiles/os_discovery/comware.yaml (enhanced)
  Added HP Comware transceiver optical monitoring (5 sensor types):
  MIB: HH3C-TRANSCEIVER-INFO-MIB::hh3cTransceiverInfoTable
  Sensors:
    - Temperature: hh3cTransceiverTemperature (OID .1.3.6.1.4.1.25506.2.70.1.1.1.15)
    - Bias Current: hh3cTransceiverBiasCurrent (OID .1.3.6.1.4.1.25506.2.70.1.1.1.17)
    - Supply Voltage: hh3cTransceiverVoltage (OID .1.3.6.1.4.1.25506.2.70.1.1.1.16)
    - RX Power (dBm): hh3cTransceiverCurRXPower (OID .1.3.6.1.4.1.25506.2.70.1.1.1.9, divisor 100)
    - TX Power (dBm): hh3cTransceiverCurTXPower (OID .1.3.6.1.4.1.25506.2.70.1.1.1.12, divisor 100)
  Gap: HIGH (missing transceivers) → RESOLVED
  Parity: 60% → 95%

- test/towerops_web/controllers/api/mobile_controller_test.exs (fixed)
  Fixed Credo warning: replaced length/1 with empty list comparison

- CHANGELOG.txt (updated)
  Documented Tier 1 + Tier 2 completion

Impact:
- Force10 FTOS: Complete temperature monitoring for S/C/E-Series data center switches
- ProCurve: Full optical transceiver diagnostics (SFP/SFP+ monitoring)
- Comware: Full optical transceiver diagnostics (completes sensor coverage)

Business Value:
- All major network switch platforms now have fundamental temperature monitoring
- Fiber optic link health monitoring enabled for ProCurve and Comware
- Data center switches (Force10 FTOS) fully supported
- Enables proactive maintenance (detect failing transceivers before link failure)

Parity Achievement:
- Tier 1 Complete: HP Comware (60→95%), Dell PowerConnect (0→80%), Dell SONiC (0→95%),
  Dell Force10 FTOS (0→90%)
- Tier 2 Complete: HP ProCurve (60→100%), HP Comware (95% - transceivers added)

Next Steps: Tier 3 (storage/compute platforms: PowerVault, Dell Servers, hpblmos)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 08:19:12 -06:00
aa9ed52bff
feat: add critical network switch sensor support (HP Comware, Dell PowerConnect, Dell SONiC)
Implemented top 3 critical network switch sensor gaps identified in Phase 3 analysis.
Restores fundamental temperature monitoring for common enterprise switch platforms.

Files Changed:
- priv/profiles/os_discovery/comware.yaml (enhanced)
  Added HP Comware chassis temperature monitoring via HH3C-ENTITY-EXT-MIB
  OID: 1.3.6.1.4.1.25506.2.6.1.1.1.1.12 (hh3cEntityExtTemperature)
  Uses entPhysicalName for sensor descriptions
  Gap: CRITICAL (broke fundamental monitoring) → RESOLVED
  Parity: 40% → 60%

- priv/profiles/os_discovery/powerconnect.yaml (enhanced)
  Added Dell PowerConnect/DNOS CPU temperature monitoring
  OID: 1.3.6.1.4.1.674.10895.5000.2.6132.1.1.43.1.8.1.5
  MIB: FASTPATH-BOXSERVICES-PRIVATE-MIB
  Gap: CRITICAL (no sensors) → RESOLVED
  Parity: 0% → 80%

- priv/profiles/os_discovery/dell-sonic.yaml (new)
  Created comprehensive Dell SONiC sensor profile
  MIB: NETGEAR-BOXSERVICES-PRIVATE-MIB (Quanta-based)
  Sensors:
    - Temperature: boxServicesTempSensorState (OID .1.3.6.1.4.1.4413.1.1.43.1.8.1.4)
    - Fan Speed: boxServicesFanSpeed (OID .1.3.6.1.4.1.4413.1.1.43.1.6.1.4)
    - PSU State: boxServicesPowSupplyItemState (OID .1.3.6.1.4.1.4413.1.1.43.1.7.1.3)
      States: other, notpresent, operational, failed, powering, nopower,
              notpowering, incompatible
  Gap: CRITICAL (OS detected, no sensors) → RESOLVED
  Parity: 0% → 95%

- test/towerops_web/plugs/brute_force_protection_test.exs (fixed)
  Fixed Credo warning: replaced length/1 with empty list comparison

- CHANGELOG.txt (updated)
  Documented Phase 3 analysis completion and critical fix implementation

Impact:
- HP Comware: Enables overheating alerts (fundamental monitoring restored)
- Dell PowerConnect: First sensor support for common access switches
- Dell SONiC: Complete hardware monitoring for modern data center platform

Business Value:
- Resolves production blockers for customers with HP Comware switches
- Adds support for very common Dell enterprise access switches
- Enables monitoring for Dell's modern SONiC-based data center switches

Next Steps: Remaining Tier 1 switches (Dell Force10 FTOS), then Tier 2
(optical transceiver monitoring for ProCurve/Comware).

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 17:36:45 -06:00
b3fae05693
feat: implement Arista EOS sensor enhancements (DOM power, thresholds, grouping)
Implemented all critical and nice-to-have Arista sensor improvements identified
in LibreNMS parity audit. Upgrades Arista EOS support from 85% to 100% parity.

Files Changed:
- lib/towerops/snmp/profiles/vendors/arista.ex (enhanced)
  Added 4 major enhancements:
  1. DOM power conversion (watts→dBm): Detects optical power sensors via regex,
     converts using formula dBm = 10*log10(watts*1000), preserves original value
     in metadata
  2. Arista threshold discovery: Walks ARISTA-ENTITY-SENSOR-MIB threshold table
     (OID 1.3.6.1.4.1.30065.3.3.1.1.1), applies 4 threshold types (low_critical,
     low_warn, high_warn, high_critical), converts thresholds to dBm for optical
     sensors
  3. Smart grouping: Organizes sensors by SFPs, PSUs, Platform (chipsets), Power
     Connectors, System for better UX
  4. Description cleanup: Removes redundant "sensor" text, simplifies PSU naming,
     cleans whitespace

- lib/towerops/snmp/profiles/dynamic.ex (integration)
  Added apply_vendor_post_processing/3 to call Arista enhancements after sensor
  discovery. Applies to both arista_eos and arista-mos profiles.

- test/towerops/snmp/profiles/vendors/arista_test.exs (comprehensive tests)
  Added 23 new tests covering:
  - DOM conversion (6 tests): Rx/Tx power, Xcvr power, non-DOM sensors, edge cases
  - Threshold discovery (4 tests): Basic thresholds, dBm conversion, no thresholds,
    SNMP failures
  - Smart grouping (6 tests): SFPs, Xcvr, PSUs, power connectors, platform, system
  - Description cleanup (5 tests): Trailing sensor, duplicate Sensor strings, PSU
    naming, hotspot, whitespace
  - End-to-end post-processing (1 test): All enhancements in correct order

All tests passing (30/30 in arista_test.exs, 6367/6367 total).

Result: Arista EOS support upgraded from 85% to 100% LibreNMS parity. All critical
gaps closed: optical power now displayed correctly in dBm, alerting enabled via
thresholds, sensors organized for better UX, descriptions cleaned up.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 17:23:33 -06:00
f00dc3ff12
test: expand agent channel coverage from 8% to 66%
add 54 tests covering join/terminate lifecycle, heartbeat, error,
credential_test_result, monitoring_check, mikrotik_result, catch-all
handle_in events, handle_info lifecycle messages, PubSub messages,
SNMP result edge cases, poll result sensor/interface data storage,
SNMPv3 credential paths, and monitoring-enabled device job building.

fix bug where error.error_message was used instead of error.message
matching the AgentError protobuf struct field name.
2026-02-11 16:52:12 -06:00
030ed43708
test: add coverage for ExpiredBanCleanupWorker
7 tests exercising perform/1: expired/active/permanent ban handling,
mixed scenarios, empty database, and PubSub broadcast behavior.
2026-02-11 16:25:33 -06:00
1f07b3b640
fix: deduplicate sensors with leading-dot OID differences
normalize OIDs by stripping leading dots when grouping for deduplication.
gosnmp returns OIDs with leading dots but YAML profiles and vendor modules
define them without, causing the same sensor to appear twice (e.g. MikroTik
DHCP lease count). also removed redundant DHCP Leases entry from routeros
wireless_oid_defs since the YAML profile already covers it.
2026-02-11 16:12:15 -06:00
47fcbeb483
fix: agent discovery and polling accuracy improvements
- use 64-bit HC counters (ifHCInOctets/ifHCOutOctets) instead of 32-bit
  counters that wrap every ~34s on gigabit links
- fix negative integer parsing in replay adapter so sensor scale values
  like -3 produce correct divisors (1000) instead of falling through to 1
- replace walking entire Cisco enterprise tree with targeted subtrees to
  avoid timeouts; add Juniper, HP/H3C, Fortinet, Cambium vendor OIDs
- add missing discovery OIDs: ENTITY-STATE-MIB, HOST-RESOURCES-MIB
  tables, and UCD-SNMP-MIB Linux CPU stats fallback
2026-02-11 15:58:31 -06:00
863f92a94a
fix: handle RouterOS version returned as list of integers
Some MikroTik devices return the version OID as a list of integers
[7, 20, 6] instead of a binary string "7.20.6". Added pattern match
to detect_version/1 to handle this case and convert to dotted string.

Fixes warning: "Failed to detect version: {:ok, [7, 20, 6]}"

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 15:49:57 -06:00
edb330e4de
normalize OIDs to fix agent-polled sensor matching
strip leading dots from OID keys returned by agent so they match
sensor OIDs stored without leading dots. fixes ubiquiti airos
wireless sensors (clients, ccq, frequency, etc) not being polled.
also fix flaky sensor_change_detector tests using global pubsub topic.
2026-02-11 15:33:08 -06:00
abbe117f5e
add sensor value change events for all sensor types
extract sensor change detection from DevicePollerWorker into shared
SensorChangeDetector module. add sensor_value_changed event for non-%
sensors when value differs from last_value. agent channel now detects
changes and updates last_value, matching phoenix poller behavior.
2026-02-11 15:06:55 -06:00
4e290b1938
fix String.replace crash when YAML index is numeric
YAML parses bare numbers like `index: 0` as integers. coerce
index_template to string before calling String.replace in both
build_table_sensor and build_state_sensor.
2026-02-11 13:27:46 -06:00
9e36d5030a
poll device immediately after discovery completes
newly discovered devices sat idle with no metric data until the
next scheduling cycle. now the channel sends a poll job (and ping
job if monitoring enabled) right after discovery succeeds, using
send(self(), ...) so discovery DB writes commit first.

also reduces k8s replicas from 3 to 2.
2026-02-11 13:24:55 -06:00
10d1157ec3
fix agent discovery system OIDs returning no_such_name
gosnmp returns OIDs with leading dots (e.g., ".1.3.6.1.2.1.1.1.0")
but the Replay adapter did exact-match lookups without the dot.
Walks already normalized both sides, so interfaces worked. GETs
did not, breaking all system OID resolution (sysDescr, sysName, etc).
2026-02-11 12:46:44 -06:00
c9f154f8cd
fix 5 failing tests
- increase timing threshold in session activity test (flaky at 50ms)
- show org name instead of agent ID in admin agents list
- fix agent live tests wiping auth session with init_test_session
- add resilient error handling in FourOhFourTracker for missing redis
2026-02-11 12:21:06 -06:00
f2cd3488ee
fix heartbeat validation rejecting git-describe version strings
the version regex only allowed [a-zA-Z0-9.] in semver suffixes,
which rejected hyphens from git-describe output (e.g. 0.1.0-5-gabcdef0).
this caused every heartbeat to fail validation, preventing last_seen_at
from updating, which led to agent status showing "warning" and eventual
channel disconnect after 360s.

also accept bare git SHAs and short identifiers like "dev".
2026-02-11 11:31:19 -06:00
c5d8d73a0c
add row_link to table component for proper anchor tags
Replace phx-click JS.navigate with real <.link navigate> elements
on table rows so users can Ctrl+Click to open in new tabs, use
right-click context menus, and navigate via keyboard. Adds row_link
attr to <.table> core component and applies it to all agent tables.
Converts device list custom table from phx-click to inner links.
2026-02-11 08:46:03 -06:00
77cf289058
Add real-time device list with PubSub and LiveView streams
Broadcast org-scoped PubSub events from Devices context mutations
(create, update, delete, status change). Convert DeviceLive.Index
from assigns to streams with flat row items. Subscribe on mount so
the device list updates automatically across browser tabs.
2026-02-10 17:38:58 -06:00
4d73e77f3a
Add 404-based brute force protection system
Implements automated detection and blocking of IPs exhibiting scanning behavior (5+ unique 404s within 1 minute).

Key features:
- Progressive ban escalation (5 min → 1 hour → permanent)
- CIDR range and exact IP whitelisting
- Redis-backed 404 path tracking with 60s TTL
- Cloudflare WAF integration for permanent bans
- Admin UI for whitelist and blocked IP management
- Oban cron jobs for cleanup (expired bans, stale violations)
- ETS caching for whitelist performance

Components:
- Plug: ToweropsWeb.Plugs.BruteForceProtection
- Context: Towerops.Security.BruteForce
- Schemas: IpBlock, IpWhitelist
- Workers: CloudflareBanWorker, ExpiredBanCleanupWorker, StaleViolationCleanupWorker
- Admin UI: /admin/security (superuser only)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 16:31:48 -06:00
c7df6a8569
Add CI-triggered mass agent update webhook
POST /api/v1/webhooks/agent-release triggers all connected agents
to self-update via their existing WebSocket channels. Authenticated
with a shared secret (AGENT_WEBHOOK_SECRET env var).

- Add ReleaseChecker.invalidate_cache/0 for fresh GitHub fetch
- Add Agents.list_updatable_agents/0 (enabled + seen < 10min)
- Add Agents.broadcast_mass_update/0 orchestration function
- Add WebhookAuth plug with timing-safe secret comparison
- Add AgentReleaseWebhookController with :webhook pipeline
- Configure AGENT_WEBHOOK_SECRET in dev/test/runtime configs
2026-02-10 13:40:32 -06:00
fbce65070a
Add agent restart and self-update commands
Add server-initiated restart and self-update capabilities for remote
agents. Restart broadcasts on the lifecycle PubSub topic causing the
agent to exit cleanly for Docker to restart. Self-update fetches the
latest release from GitHub, finds the matching binary for the agent's
architecture, and sends the download URL with SHA256 checksum.

- Add restart_agent/1 and update_agent/3 to Agents context
- Handle :restart_requested and :update_requested in AgentChannel
- Add superuser-only Restart and Update buttons on agent show page
- Add ReleaseChecker module for GitHub Releases API with 5-min cache
- Add arch field to AgentHeartbeat protobuf for architecture detection
- Store arch in agent metadata from heartbeat
2026-02-10 13:06:10 -06:00
c066399e18
Allow superadmins to view and edit any agent regardless of org
The admin agents page links to /agents/:id but the show and edit
pages were scoped to the current user's organization, causing 404s
for agents belonging to other orgs.
2026-02-10 12:19:20 -06:00
c1fca6276a
Add real-time updates to admin agents page via PubSub
Broadcast agent lifecycle events (created/deleted) on a separate
"admin:agents" topic so the admin page updates dynamically when
agents are added or removed from any organization.
2026-02-10 11:20:51 -06:00
183f2a89ac
Add admin agents page at /admin/agents
Superuser-only page showing all agents across all organizations
and cloud pollers in a single table with live-ticking timestamps
and real-time status updates via PubSub.
2026-02-10 10:56:10 -06:00
95eafd0c47
routeros fixes and latency rounding 2026-02-09 17:30:06 -06:00
4cfab3b1ee
Reliability improvements: agent channel, polling, discovery, batch ops
- Add Task.Supervisor for supervised background tasks in agent channel
- Discovery worker retries transient failures (max 3 attempts)
- Log silent polling timeouts with named task identification
- Track errors in batch ARP/MAC upserts instead of silently ignoring
- Discovery gracefully degrades on interface/sensor timeout (partial results)
- Synchronous job dispatch on agent join to prevent race condition
- Surface SNMP result, monitoring check, and backup processing errors
- Atomic delete-stale + upsert for neighbors/ARP/MAC (transaction)
- Discovery transaction timeout (60s) with duration logging
- Heartbeat timeout detection (5min) closes stale agent channels
- Live poll timeout (60s) notifies waiting LiveView on expiry
- Disconnect agent channel when token is disabled or deleted
- Debounce rapid assignment changes to prevent redundant job dispatches
- Sensor index deduplication via YAML index template substitution
2026-02-09 16:28:12 -06:00
3b8e1ea639
Reliability improvements: Task.Supervisor, discovery retries, polling visibility
- Add Towerops.TaskSupervisor to supervision tree, replace bare spawn/1
  in agent channel with supervised tasks for polling data processing
- Change DiscoveryWorker from max_attempts: 1 to 3 with retryable error
  classification (transient errors retry, permanent errors discard)
- Name all 9 parallel polling tasks and log timeouts/crashes instead of
  silently dropping results via Stream.run()
- Add tests for TaskSupervisor presence and error classification
2026-02-09 16:05:30 -06:00
2911a3c17d
test fixes 2026-02-09 15:30:52 -06:00
a50c8e6314
Use datestamp as agent version 2026-02-09 13:51:32 -06:00
623fe07081
wip 2026-02-09 12:44:37 -06:00
cedbc5abd1
fix: resolve critical data loss and protobuf schema bugs (Phase 1)
This commit addresses Phase 1 (CRITICAL - Data Loss Prevention) issues
from the comprehensive bugs and inconsistencies analysis.

CRITICAL FIXES:

1. Protobuf Schema Inconsistencies
   - Added missing job_id field (field 5) to SnmpResult message
   - Fixed AgentError message structure (job_id, message, timestamp)
   - Removed obsolete transport field from SnmpDevice struct
   - Regenerated protobuf code with protoc-gen-elixir
   - Prevents crashes when agent sends SNMP results or errors

2. Interface/Sensor Discovery Timeout Data Loss
   - Changed timeout behavior to return error instead of empty list
   - Prevents deletion of ALL existing interfaces/sensors on slow networks
   - Discovery fails gracefully instead of destroying historical data
   - Addresses commit 7a57f7c sensor discovery pipeline data loss issue

3. Polling Offset Schedule Mismatch
   - Fixed schedule_next_poll() to use offset only (not interval + offset)
   - Maintains consistent polling intervals across all executions
   - Prevents load bunching that offset was designed to prevent
   - Example: 300s interval with offset=94s now consistently polls every 5m

4. Always Reschedule Race Condition
   - Added should_continue_polling?() and should_continue_monitoring?()
   - Only reschedule if device is still enabled and should be polled by Phoenix
   - Prevents zombie jobs from continuing to poll disabled/deleted/reassigned devices
   - Stops race condition where stop_polling() is bypassed by in-flight jobs

Files Changed:
- priv/proto/agent.proto
- lib/towerops/proto/agent.pb.ex (regenerated)
- lib/towerops_web/channels/agent_channel.ex
- lib/towerops/snmp/discovery.ex
- lib/towerops/workers/device_poller_worker.ex
- lib/towerops/workers/device_monitor_worker.ex
- test/towerops/workers/device_poller_worker_test.exs

Test Results: All passing
- device_poller_worker_test.exs: 8 tests, 0 failures
- device_monitor_worker_test.exs: 3 tests, 0 failures
- discovery_test.exs: 13 tests, 0 failures

Remaining Phases:
- Phase 2 (HIGH): 8 data integrity issues
- Phase 3 (MEDIUM): 10 reliability issues
- Phase 4 (LOW): 3 cleanup issues

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 09:16:03 -06:00
3931a9c14a
more tests and fixes 2026-02-07 11:50:18 -06:00
3eb3d4890e
Merge branch 'feature/job-monitoring-dashboard'
# Conflicts:
#	lib/towerops/workers/device_poller_worker.ex
#	lib/towerops/workers/discovery_worker.ex
2026-02-06 19:01:08 -06:00
137d7c83ec
test: add comprehensive integration tests for monitoring dashboard
Added integration tests for real-time updates and metrics display.
Also fixed dialyzer warnings in worker event broadcasting by removing
unreachable error handling branches.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:41:08 -06:00
bb9e6f0b0c
feat: create MonitoringLive base structure with PubSub subscription
Add LiveView for real-time job monitoring dashboard:
- Subscribe to job:lifecycle PubSub topic for live updates
- Display health metrics (completed, failed, avg duration, active jobs)
- Show active operations with real-time updates
- Display problems section (stuck/failed job counts)
- Add router entry under /admin/monitoring

Tests verify PubSub subscription and basic rendering.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:27:40 -06:00
9f30d366b1 feat: add PubSub event broadcasting for job lifecycle
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:36:34 -06:00
9b0b000263
feat: add health metrics calculation module
Create JobMonitoring.Metrics module with calculate_all/0 to provide
comprehensive metrics including execution counts, success rates,
queue depths, and average execution times.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:31:27 -06:00
adbaeef83d
feat: add failed jobs and recent completions queries
Add list_failed_jobs/0 to return retryable and cancelled jobs
and list_recent_completions/1 to return completed, cancelled,
or discarded jobs with configurable limit.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:29:19 -06:00
a3cbf7f412
test: add edge case tests for stuck job detection 2026-02-06 16:27:12 -06:00
d845f372d0
feat: add stuck job detection with per-worker thresholds
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:21:23 -06:00
b2cc622036
test: add missing assertions for ordering and worker filtering 2026-02-06 16:17:26 -06:00
35c7328831
feat: add JobMonitoring context with list_active_jobs query
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:15:18 -06:00
d03ad72aec
Increase max OID values limit from 1,000 to 50,000
Fixes discovery failures on enterprise network devices with many
interfaces and routing table entries.

Issue:
Discovery was failing with "too_many_oids - OID values map exceeds
1000 entries" on SNMPv3 devices. Enterprise routers/switches during
discovery can easily return 10k-50k OIDs from:
- 100+ interfaces with 20-30 OIDs each
- System info, routing tables, ARP tables, neighbor tables
- Various MIB objects

The original limit of 1,000 was too restrictive for real-world devices
while still being intended as DoS protection.

Changes:
- Increase @max_oid_values from 1,000 to 50,000
- Update test to generate 50,100 OIDs (exceeds new limit)
- Add comment explaining why limit is set to 50k

This maintains DoS protection (prevents multi-million OID attacks)
while accommodating realistic device discovery scenarios.

All tests passing (5578 tests, 0 failures).
2026-02-06 10:41:30 -06:00
0a978746e1
Fix all Credo issues
Resolves 26 Credo warnings/issues:

Code Readability (2 issues):
- Break long line in mac_address.ex (line 316 > 120 chars)
- Break long @spec in agents.ex (line 332 > 120 chars)

Refactoring Opportunities (2 issues):
- Reduce cyclomatic complexity in device_live/form.ex
  - Extract helper functions to simplify SNMPv3 credential resolution
  - Split logic into smaller, focused functions
- Reduce nesting depth in snmp_oid.ex
  - Extract nested logic into separate helper functions

Warnings (22 issues):
- Fix comparison warning in validator.ex
  - Split validate_sensor_value/1 into separate clauses for int/float
  - Add credo directive for valid NaN check (value != value)
- Replace 21 expensive length/1 checks with Enum.empty?/1
  - Change assertions from `assert length(list) >= 1` to `refute Enum.empty?(list)`
  - Change assertions from `assert length(list) > 0` to `refute Enum.empty?(list)`
  - Affected files: device_poller_worker_test.exs, mib_test.exs,
    snmp_tokenizer_test.exs, parser_test.exs, error_test.exs, compiler_test.exs

All tests passing (5578 tests, 0 failures).
Credo now reports: "found no issues"
2026-02-06 10:31:09 -06:00
ed50257d8a
fix snmp v3 test 2026-02-06 10:21:54 -06:00
e363fbc691
Implement MacAddress and SnmpOid custom Ecto types
Continues the pattern of using custom Ecto types to create rich domain objects
and avoid primitive obsession. Adds two new custom types following the
established pattern from IPAddress.

## MacAddress Custom Type

Provides structured MAC address handling with:
- Multiple input format support (colon, hyphen, dot-separated, compact)
- Normalization to colon-separated lowercase (canonical format)
- SNMP binary format conversion (6-byte binary)
- Format conversion helpers (:colon, :hyphen, :dot, :compact)
- Comprehensive validation and error handling

### Supported Formats
- Colon: `00:11:22:33:44:55`
- Hyphen: `00-11-22-33-44-55`
- Dot (Cisco): `0011.2233.4455`
- Compact: `001122334455`
- SNMP binary: `<<0, 17, 34, 51, 68, 85>>`

All formats normalize to lowercase colon-separated format for consistency.

## SnmpOid Custom Type

Provides structured SNMP OID handling with:
- OID format validation (numeric and named)
- Normalization to dotted-decimal with leading dot
- OID resolution via SnmpKit (named → numeric)
- Helper functions (parent, child_of?, append)
- Integer list representation support

### Supported Formats
- Dotted-decimal: `.1.3.6.1.2.1.1.1.0`
- Numeric (no leading dot): `1.3.6.1.2.1.1.1.0`
- Named OID: `sysDescr.0` (with automatic resolution)
- Integer list: `[1, 3, 6, 1, 2, 1, 1, 1, 0]`

## Benefits

- **Type Safety**: Structured data with validation at cast time
- **Normalization**: Consistent storage format regardless of input
- **Rich API**: Helper functions for common operations
- **Zero Migration Cost**: No database changes needed
- **Better Errors**: Clear validation errors instead of DB constraint violations
- **Domain Modeling**: Code works with %MacAddress{} and %SnmpOid{} instead of strings

## Database Storage

Both types store as VARCHAR in the database:
- MacAddress: VARCHAR(17) - colon-separated format
- SnmpOid: VARCHAR(255) - dotted-decimal format with leading dot

## Test Coverage

Added comprehensive test suites:
- MacAddress: 47 tests covering all formats, roundtrips, edge cases
- SnmpOid: 49 tests covering OID operations, validation, helpers
- All 96 tests passing 

## Usage Example

```elixir
# Before (primitive obsession)
field :mac_address, :string
field :sensor_oid, :string

# After (rich domain types)
field :mac_address, Towerops.EctoTypes.MacAddress
field :sensor_oid, Towerops.EctoTypes.SnmpOid

# Usage
changeset
|> cast(attrs, [:mac_address, :sensor_oid])
# Validation happens automatically in cast/1
```

Files:
- lib/towerops/ecto_types/mac_address.ex (330 lines)
- lib/towerops/ecto_types/snmp_oid.ex (340 lines)
- test/towerops/ecto_types/mac_address_test.exs (380 lines)
- test/towerops/ecto_types/snmp_oid_test.exs (390 lines)
2026-02-06 09:41:54 -06:00
20952a781f
add device count to superadmin 2026-02-06 09:32:13 -06:00
8044a6d140
Add strict protobuf validation for agent messages
Implements comprehensive validation layer on top of protobuf schema to
prevent malformed data, DoS attacks, and business logic violations.

Changes:
- Created Towerops.Agent.Validator module with strict validation for all
  agent message types (AgentHeartbeat, MetricBatch, SnmpResult, AgentError,
  CredentialTestResult, MikrotikResult)
- Added validation limits to prevent memory exhaustion and DoS attacks
  (max string lengths, collection sizes, numeric ranges)
- Added format validation for UUIDs, IP addresses, versions, hostnames
- Added enum validation for status and protocol fields
- Modified AgentChannel handlers to validate all incoming messages before
  processing
- Added comprehensive typespecs to AgentChannel for better static analysis
- Created safe_base64_decode/1 helper with error handling
- Added 32 comprehensive tests covering valid cases, invalid inputs, and
  edge cases

Security improvements:
- Prevents memory exhaustion via oversized strings and collections
- Validates all numeric fields are within expected ranges
- Checks UUID format for all ID fields
- Validates IP addresses and hostnames against RFC standards
- Rejects future timestamps and excessive values

Backward compatibility:
- Empty version and hostname strings allowed for older agents
2026-02-06 09:26:04 -06:00