Commit graph

419 commits

Author SHA1 Message Date
8d4333b237
fix superadmin page 2026-02-07 11:58:56 -06:00
3931a9c14a
more tests and fixes 2026-02-07 11:50:18 -06:00
141c775230
fix: discovery retry, disabled assignment cascade, and silent spawn crashes
- Move last_discovery_at update to after successful processing so failed
  discoveries are retried on the next poll cycle instead of being blocked
  for 24 hours
- Add disabled assignment check to agent polling target query so devices
  with enabled=false assignments don't leak through site/org cascade
- Wrap spawned polling data processing in try/rescue so crashes are logged
  instead of silently disappearing
2026-02-07 09:17:28 -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
070241d15a
feat: add queue depth display to health metrics
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:37:21 -06:00
1eaf6d9ac5
feat: build recent activity timeline with color-coded events
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:35:55 -06:00
8bceb6dce2
feat: build comprehensive health metrics panel with success rates
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:34:43 -06:00
1e45b1609b
feat: build detailed problems section UI for stuck and failed jobs
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:33:21 -06:00
daa223c49d
feat: enhance active operations display with device context
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:32:06 -06:00
2fb0101bab
feat: add job monitoring link to admin dashboard
Add Job Monitoring card to admin dashboard with:
- Hero icon for visual identification
- Brief description of monitoring capabilities
- Link to /admin/monitoring dashboard

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:28:41 -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
e3e47fb82f
fix: include SNMPv3 fields in API device responses
The API was not returning SNMPv3 fields (security_level, username,
auth_protocol, auth_password, priv_protocol, priv_password) in device
responses, causing Terraform provider to see inconsistent state between
plan and apply.

Updated both format_device/1 and format_device_details/1 to include
all SNMPv3 fields in JSON responses.
2026-02-06 14:05:15 -06:00
7f7b722965
feat: add SNMPv3 credential logging for debugging
Log SNMPv3 credentials being sent to agents (with passwords redacted) to help diagnose authentication issues. Shows security level, username, auth/priv protocols, and whether passwords are present.
2026-02-06 13:48:35 -06:00
6a29ee1671
fix: Split agent polling queries to isolate SNMP failures
Changed from one large WALK query with all OIDs to separate WALK queries
per table type. This prevents a failure in one unsupported table (like ARP
on a device that doesn't support it) from killing the entire polling
operation.

Before: Single WALK with neighbor + ARP + MAC + IP + HOST-RESOURCES OIDs
After: Separate WALKs for each table type

This makes polling more resilient - if a device doesn't support ARP tables
or HOST-RESOURCES-MIB, those WALKs will fail individually while neighbors,
MAC tables, and IP addresses can still succeed.

Fixes agent errors where a single SNMP receive error was killing the
entire poller thread and failing all subsequent operations with
'Poller thread died'.
2026-02-06 12:30:52 -06:00
184c2bc999
fix: Use snmp_device.id for sync_processors and sync_storage
Fixes KeyError when processing processors/storage during agent polling.
The sync_processors and sync_storage functions expect device.id to be
the snmp_device id, not the main device id.

Changed from:
  %{device_id: device.id}

To:
  %{id: device.snmp_device.id}

This matches the expected structure for these sync functions which
query where snmp_device_id == device.id.
2026-02-06 12:06:30 -06:00
26e5d20510
fix: Add device_id to interfaces for neighbor discovery in agent polling
Fixes KeyError when processing neighbor discovery during agent polling.
NeighborDiscovery.discover_neighbors/2 requires interfaces to have a
:device_id field for building neighbor records, but interfaces from the
database only have :snmp_device_id.

Solution matches the approach in DevicePollerWorker which adds device_id
to interfaces before calling discover_neighbors.
2026-02-06 11:26:00 -06:00
f17ee2183c
fix: Use server-side timestamps for agent polling metrics
Replaces agent-supplied timestamps with server-side DateTime.utc_now()
to prevent clock drift issues between agents from causing weird graphs.

All metrics now use consistent server time regardless of polling method:
- Agent polling (via WebSocket): server time on receipt
- Phoenix polling (direct SNMP): server time on poll (already correct)

This ensures time-series data aligns correctly when graphing metrics
from devices polled by different agents with potentially different
system clocks.
2026-02-06 11:23:26 -06:00
bf4fee4846
feat: Add comprehensive agent polling for all discoverable data
Extended agent polling to collect all available SNMP data during regular
polls, not just sensors and interfaces. This ensures data stays current
and reduces reliance on periodic discovery runs.

Changes:
- Added polling queries for: neighbors (LLDP/CDP), ARP tables, MAC tables,
  IP addresses, HOST-RESOURCES processors and storage
- Process additional data using Replay adapter pattern to reuse existing
  parsing logic from discovery modules
- Made discovery helper functions public for reuse in polling context:
  save_neighbors/2, save_arp_entries/3, sync_ip_addresses/2,
  sync_processors/2, sync_storage/2
- Optimized by fetching interfaces once and reusing across operations
- Fixed compilation warnings by using proper guard syntax (list != [])

Technical details:
- Detection threshold: polls with more OIDs than sensors+interfaces
  are processed for additional data
- Background processing: spawns async process to avoid blocking metric
  recording
- Replay adapter: allows reusing discovery parsing logic without
  re-querying SNMP device
2026-02-06 11:18:36 -06:00
5f0549908e
Add IP address table walks to agent discovery queries
Fixes missing IP addresses tab on device page after agent-based discovery.

Issue:
Discovery was not collecting IP address data because the agent's
discovery job didn't include IP address table OID walks.

Root cause:
build_discovery_queries() walked interface tables, sensors, vendor MIBs,
and neighbors, but was missing the IP-MIB address tables.

Changes:
- Add new SnmpQuery to walk IP address tables during discovery:
  - 1.3.6.1.2.1.4.20 (ipAddrTable - IPv4, deprecated but widely supported)
  - 1.3.6.1.2.1.4.34 (ipAddressTable - RFC 4293, unified IPv4/IPv6)

This matches the OIDs used by Phoenix's direct discovery in
lib/towerops/snmp/profiles/base.ex discover_all_ip_addresses/1.

Result:
Agent now collects IP address data during discovery, which is then
synced to the database and displayed in the IP Addresses tab.

Tests: 5578 tests passing (1 pre-existing failure in unrelated Dahua test)
2026-02-06 11:05:59 -06:00
a4dd7210d8
Improve error logging for SNMP result validation failures
Add detailed error logging to show specific validation error type and
message when SNMP results fail validation. Also handle base64 decode
failures separately.

This will help diagnose validation issues introduced by recent strict
protobuf validation changes (commit 8044a6d1).
2026-02-06 10:36:37 -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
0a0ec23fc9
Fix all compilation warnings for --warnings-as-errors
Resolves all warnings in agent_channel.ex and validator.ex to enable strict
compilation mode.

agent_channel.ex changes:
- Removed unused aliases: AgentError, AgentHeartbeat, CredentialTestResult, SnmpResult
- Removed unused typep declarations: device_id, job_id, agent_token_id
- Prefixed unused variable with underscore: binary -> _binary
- Grouped handle_in/3 clauses together (moved credential_test_result handler)
- Removed @doc from private functions (safe_base64_decode)
- Removed unused private function safe_base64_encode/1

validator.ex changes:
- Removed unused alias: MikrotikSentence
- Prefixed unused parameter with underscore in validate_counter: field -> _field
- Commented out unused module attributes: @max_oid_length, @max_port, @max_interval_seconds
- Removed redundant validate_response_time(0.0) clause (covered by general case)
- Updated validate_response_time guard to use >= 0.0 instead of pattern matching on 0.0

All tests passing (3434 tests). Compilation now succeeds with --warnings-as-errors.
2026-02-06 09:57:04 -06:00
3fff0db784
Add comprehensive typespecs to agent-related modules
Adds @spec annotations to all public functions in agent-related modules for
better static analysis and documentation.

Changes:
- Added 17 typespecs to Towerops.Agents context module
  - All CRUD operations (create, read, update, delete, revoke)
  - Assignment management functions
  - Agent token resolution and lookup functions
  - PubSub broadcast function
- Added 9 typespecs to Towerops.Agents.Stats module
  - Agent health and metrics statistics
  - Device assignment breakdowns
  - Latency analysis and reassignment candidate detection
- Added typespec to Towerops.Workers.StaleAgentWorker
  - find_stale_agents/0 function
- Preserved existing typespecs in AgentChannel (socket types)

Benefits:
- Improved code documentation with clear function signatures
- Better static analysis via dialyzer
- Clearer API contracts for all agent management functions
- Type-safe UUID handling throughout agent system
2026-02-06 09:33:44 -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
156d9a47bf
UI improvements 2026-02-05 14:57:11 -06:00
cb0cc66768
fix mistaken poller ids 2026-02-05 13:57:15 -06:00
472482c4f5
fix nil firmware comparison 2026-02-05 13:47:56 -06:00
38eeb1c7b8
fix: improve agent polling and SNMP testing
Changes:
- Fix traffic graph to handle nil interface octets gracefully
- Add comprehensive tests for nil octets scenarios
- Fix agent polling query to support devices assigned directly to org (left join on sites)
- Fix test SNMP connection to inherit credentials from site/org
- Refactor agent_channel process_polling_result to reduce nesting (Credo)
- Add alias for JobCleanupTask in application.ex (Credo)

This fixes crashes when interface stats have nil octets and ensures
devices without a site assignment can be polled by agents.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 12:34:28 -06:00
987eae0408
fix: improve agent-based live polling with better logging and validation
- Added Logger.require for debug logging
- Refactored fetch_latest_agent_data to reduce nesting depth
- Added debug logging to trace agent assignment detection
- Check for nil/stale sensor readings and log appropriately
- Use actual reading timestamp instead of current time for data points

This will help diagnose why live polling shows 0 values and why
Phoenix SNMP disabled messages appear for agent-assigned devices.
2026-02-05 09:25:29 -06:00
e0592dbf3d
fix: use agent-collected data for live polling when agent assigned
Modified GraphLive live polling to check for agent assignments and use
agent-collected sensor data from the database instead of doing direct
SNMP polling. This respects the agent assignment and prevents Phoenix
from bypassing the agent for live graph updates.

Also refactored handle_params to reduce nesting depth.
2026-02-05 09:21:43 -06:00
dd8c97a45f
fix: handle devices without sites in GraphLive live polling
Devices can belong directly to organizations without sites. Fixed
perform_live_poll to check device.organization_id instead of
device.site.organization_id which caused BadMapError when site is nil.
Also removed unused Repo alias.
2026-02-05 09:16:11 -06:00
912cb8d280
fix: add missing handle_info for state_sensors_updated in GraphLive.Show
Adds handler to reload graph data when state sensors are updated via PubSub,
preventing GenServer crash when viewing graph page during sensor updates.
2026-02-05 09:14:21 -06:00
0d6caa897f
refactor: remove debug logging from SNMPv3 credential handling
Discovery is now working successfully with SNMPv3 after increasing
agent timeout to 60s. Removing the temporary debug logging that was
added to verify credentials were being properly decrypted and sent
to the agent.
2026-02-05 09:00:42 -06:00
b36da6f327
debug: log SNMPv3 credential lengths sent to agent
Added logging to show what SNMPv3 parameters are being sent from Phoenix
to the agent, including password lengths to verify they're decrypted
properly.
2026-02-05 08:35:09 -06:00
129bc9a8f4
fix: handle nil site in graph_live access check
Similar to previous fix - use device.organization_id directly instead of
device.site.organization_id to avoid BadMapError when device has no site.
2026-02-04 18:25:48 -06:00
c70b385db1
refactor: consolidate reorder handlers in device_live
Extract common pattern from perform_site_reorder/4 and perform_device_reorder/4
into a single perform_reorder/4 helper function.

Both reorder handlers now delegate to the shared helper, reducing duplication
and making the reload/regroup/flash pattern consistent.

- Reduces code from 40 lines to 28 lines
- Maintains identical behavior (all tests pass)
- Uses static gettext strings to satisfy compile-time requirements
2026-02-04 18:02:13 -06:00
aa0e7f3d05
help update 2026-02-04 17:56:48 -06:00
6f6627a54d
refactor: consolidate device count calculations in agent_live
Remove duplicate device counting logic by consolidating three identical
implementations into a single reusable function.

**Changes:**
- Refactor agent_live/index.ex mount/3 to use calculate_device_counts/1
- Delete duplicate calculate_cloud_poller_counts/1 function
- Replace all usages with calculate_device_counts/1

**Before:**
- Lines 31-47: Inline counting for agent_tokens and cloud_pollers
- Lines 312-318: calculate_device_counts/1
- Lines 320-326: calculate_cloud_poller_counts/1 (identical logic)

**After:**
- Single calculate_device_counts/1 function used everywhere
- ~20 lines removed

**Benefits:**
- Eliminates triple duplication of counting logic
- Single source of truth for device counting
- Easier to maintain and test

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 17:53:18 -06:00
6aab59dcf5
refactor: centralize LiveView access control checks
Extract duplicate access control logic from multiple LiveView files into
a reusable AccessControl helper module.

**Changes:**
- NEW: lib/towerops_web/live/helpers/access_control.ex
- NEW: test/towerops_web/live/helpers/access_control_test.exs
- Refactor device_live/index.ex to use AccessControl.verify_site_access/2
  and verify_device_access/2
- Refactor device_live/form.ex to use AccessControl.verify_device_access/2
- Refactor alert_live/index.ex to use AccessControl.verify_alert_access/2
- Refactor device_live/show.ex to use AccessControl.verify_device_access/2
- Remove unused Repo aliases from refactored files

**Benefits:**
- Reduces code duplication across 7+ locations
- Centralizes security-critical access checks
- Improves testability (helper module has >90% coverage)
- Consistent error handling across all LiveViews

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 17:51:05 -06:00
d16f09666f
snmp v3 ui fixes 2026-02-04 17:41:15 -06:00
dbb2412e89
tcp snmp test 2026-02-04 17:28:14 -06:00
89911bae9c
Device list bug fix 2026-02-04 16:49:17 -06:00
4f936d5549
device edit fix 2026-02-04 16:28:15 -06:00
6689eb27b4
prevent poller fallback when assigned poller is selected 2026-02-04 16:24:19 -06:00
031880c954
fix device page 2026-02-04 16:17:07 -06:00
fc66109f19
Add default organization feature
Features:
- Users can set a default organization in org settings
- First organization created is automatically set as default
- Default org selector only shown if user has 2+ organizations
- Migration auto-sets first org as default for existing users

Database changes:
- Added is_default boolean field to organization_memberships
- Added partial index for efficient default org lookups
- Migration sets oldest org as default for each existing user

UI changes:
- Organization settings page shows default org toggle
- Green badge displayed when org is already default
- Button to set org as default if it's not current default

Backend:
- Organizations.set_default_organization/2 manages defaults
- Organizations.get_default_membership/1 retrieves default
- Auto-set first org as default in create_organization/3
2026-02-04 16:09:43 -06:00
7a1317d0d0
API: Default organization_id to authenticated org when empty
When creating devices via API, organization_id is now properly defaulted
to the authenticated organization's ID even when an empty string is sent.

This fixes Terraform provider compatibility where organization_id may be
sent as "" instead of omitted entirely.

Before: Only checked if key was missing (Map.has_key?)
After: Also handles nil and empty string values
2026-02-04 16:03:20 -06:00
8382b5df6a
make devices site optional and many test fix 2026-02-04 15:05:42 -06:00