Extracted SNMP configuration extraction and connection testing
into separate helper functions, reducing cyclomatic complexity
from 11 to ~5.
- extract_snmp_config/1: Consolidates form data and params
- normalize_port/1: Handles port type conversion
- test_snmp_connection/1: Performs test and formats result
This makes the handle_event callback simpler and each concern
easier to test independently.
Refactored three highly complex functions to improve code maintainability:
1. PollerWorker.detect_sensor_changes (complexity 33 -> ~9):
- Extracted threshold checking logic into separate functions
- Split event creation into focused helper functions
- Reduced nesting by using pipe operator pattern
2. PollerWorker.detect_and_log_changes (complexity 16 -> ~5):
- Created separate functions for each interface change type
- Extracted event building logic into dedicated functions
- Improved readability with clear function names
3. EquipmentLive.Show.format_duration (complexity 13 -> ~5):
- Extracted time unit conversion into separate functions
- Simplified pluralization logic with pattern matching
- Reduced nested conditionals
These changes make the code easier to test, maintain, and understand
while preserving all existing functionality.
The poller was re-logging SNMP errors from Client.get as warnings,
even though the client now logs them at debug level. Updated the
poller to also use debug level for expected errors like :no_such_object.
This completes the fix to reduce SNMP logging noise for devices
that don't support certain MIB objects.
The admin layout was incorrectly defined as a separate .html.heex file
using @inner_content. Phoenix components should use render_slot(@inner_block).
Moved admin layout definition into layouts.ex as a proper function
component, matching the pattern used by app/1 and authenticated/1 layouts.
Changed SNMP Client to use debug level for expected errors
(:no_such_object, :no_such_instance, :end_of_mib_view) and
only use warning level for actual communication errors.
This prevents log spam when polling interfaces that don't
support certain MIB objects, which is normal behavior.
Replace raw HTML form with Phoenix .link helper using method="delete" to properly handle CSRF token in LiveView context. This fixes the UndefinedFunctionError when accessing /admin route.
Replace expensive length/1 comparisons with direct list comparisons or Enum.empty?/1 checks (13 instances in source code and tests). Add module aliases for Phoenix.HTML.Form and Towerops.Accounts.Scope to reduce nested module references.
Changes:
- Replace length(list) > 0 with list != [] or refute Enum.empty?(list)
- Add Phoenix.HTML.Form alias in CoreComponents
- Add Towerops.Accounts.Scope alias in ConnCase test helper
This eliminates all credo warnings and software design suggestions.
Implement comprehensive admin interface allowing designated superusers to view all users and organizations, impersonate users for debugging, and perform administrative operations. All superuser actions are tracked in audit logs for compliance.
Features:
- Superuser authentication with dedicated admin routes at /admin
- User impersonation with session state preservation
- Admin dashboard with system statistics
- User and organization management interfaces
- Comprehensive audit logging with IP tracking
- Visual impersonation banner with exit capability
- Security controls preventing self-impersonation and superuser-to-superuser impersonation
Database:
- Add is_superuser boolean field to users table
- Create audit_logs table for tracking sensitive operations
- Set graham@mcintire.me as initial superuser
- Prefix unused alert variables with underscore
- Remove unused test_env?/0 function
All warnings resolved, compilation clean with --warnings-as-errors
- Display storage sensors as a list similar to temperature/voltage
- Show individual disk/partition usage with current values
- Link to graph view from sensor names
- More consistent with other sensor displays
Based on MikroTik MIB analysis, added discovery for:
Device Information:
- Board name, display name, build time
Health Sensors - Voltages:
- Core voltage, 3.3V/5V/12V supplies, input voltage
Health Sensors - Temperatures:
- Sensor chip, CPU, board, system, processor temperatures
Health Sensors - Power & Cooling:
- Power consumption (W), current draw (mA)
- Processor frequency (MHz)
- Active fan status, fan speeds (RPM)
- Power supply state, backup PSU state
POE Monitoring (per port):
- Voltage, current, power consumption
- Automatically discovers all POE-enabled ports
Optical/SFP Monitoring (per interface):
- Temperature, voltage
- TX/RX optical power levels (dBm)
- Supports fiber transceivers and SFP modules
All sensors include proper units, divisors, and descriptive names.
- Add new event types: sensor_threshold_warning, sensor_threshold_critical, sensor_threshold_normal, sensor_value_spike, sensor_value_drop
- Implement sensor change detection in PollerWorker
- Track threshold violations (warning/critical high/low)
- Detect value spikes/drops for percentage sensors (30% change)
- Track return to normal from threshold violations
- Store threshold config in sensor metadata
- Update sensor last_value and last_checked_at on each poll
- Broadcast sensor events via PubSub for real-time logging
- Detect when interface speed changes from null to a value
- Detect when MAC address changes from null to a value
- Log initial discoveries with "info" severity
- Differentiate between initial discovery and actual changes
- Show "detected" message for initial values
- Show "changed from X to Y" message for actual changes
- Replace grid of sensor cards with table format matching device info
- Display sensor name on left, value on right
- Make sensor names clickable links to graph detail page
- Remove generic "Sensors" section from overview
- Cleaner, more scannable layout for temperature and voltage sensors
- Create GraphLive.Show for detailed sensor graph visualization
- Add route for /equipment/:id/graph/:sensor_type endpoint
- Make all chart headers clickable with navigation to detail view
- Implement date range selector (1h, 6h, 12h, 24h, 7d, 30d)
- Fix chart rendering by destroying and recreating on data updates
- Fix duplicate data loading in LiveView event handlers
- Fix MikroTik profile typing warning for entity sensor discovery
- Add Chart.js integration for interactive sensor graphs
- Add processor, memory, storage, temperature, and voltage charts showing 24 hours of data
- Fix device information box to use natural height instead of stretching
- Update MikroTik profile to discover ENTITY-SENSOR-MIB sensors
- Support multiple sensor types per chart (celsius/temperature, volts/voltage)
- Use 24-hour time format in chart tooltips and x-axis labels
- Support auto-scaling y-axis for non-percentage metrics
- Add equipment_events table and Event schema for tracking device changes
- Implement automatic change detection for interface attributes during SNMP polling
- Detects operational status changes (up/down)
- Detects admin status changes
- Detects speed changes with warning severity for speed drops
- Detects MAC address changes
- Add Logs tab to equipment detail page with event display
- Fix temperature sensor display bug (was showing 4.3C instead of 43C due to double division)
- Remove response time tracking from monitoring checks and UI
- Move Rediscover Device button to equipment edit page
This fixes critical issues where SNMP sensor readings, interface stats, and
monitoring checks were not being saved to the database due to schema mismatches.
Database schema fixes:
- Recreate snmp_sensor_readings table with binary_id primary key
- Recreate snmp_interface_stats table with binary_id primary key
- Recreate monitoring_checks table with binary_id primary key
The original migrations used default integer primary keys, but the schemas
expected binary_id (UUID). This caused Ecto to generate UUID strings that
Postgrex tried to encode as binaries, resulting in silent insert failures.
SNMP interface stats fixes:
- Fix field name mismatch in get_interface_stats (if_in_octets vs in_octets)
- Remove unnecessary tuple handling code (Client already unwraps SNMPKit tuples)
- Clean up decode_snmp_value function and improve error messages
Monitoring check fixes:
- Fix response_time type from float to integer in Poller.check_device
- Add error logging to catch and report check creation failures
These changes enable:
- SNMP sensor readings to be collected and stored (disk usage, memory, CPU, etc.)
- Interface statistics to be collected (Counter64 octets, errors, discards)
- Equipment availability metrics to update on the dashboard
Shows the full UTC timestamp when hovering over the relative 'time ago'
text on the equipment detail page.
Changes:
- Wrapped time_ago display in a span with title attribute
- Title shows full datetime in UTC format
- Added cursor-help class for visual hint that tooltip is available
Users can now see both the easy-to-read relative time ('5m ago') and
the precise UTC timestamp (2026-01-04 19:30:15Z) by hovering.
Added back navigation links at the top of all edit/new pages to
improve UX and make it easier to navigate back to previous pages.
Changes:
- Added back link to equipment edit/new pages
- Edit: goes back to equipment detail page
- New: goes back to equipment list
- Added back link to site edit/new pages
- Edit: goes back to site detail page
- New: goes back to sites list
- Links styled with arrow icon and subtle hover effect
- Added error handling to Counter64 decoder with try/rescue
The back links appear above the page header and provide clear
navigation context for users.
Added a new 'danger' button variant to the button component for
destructive actions like deleting equipment or sites.
Changes:
- Added 'danger' variant to button component (red background/hover)
- Updated equipment delete button to use variant="danger"
- Updated site delete button to use variant="danger"
- Removed custom red color classes in favor of standardized variant
This provides consistent styling for all delete/destructive actions
across the application while maintaining proper button base styles
(padding, rounded corners, shadow, focus ring, etc).
Removed the manual 'Check Now' functionality since polling happens
automatically on a schedule with distributed coordination. Manual
triggers would interfere with the coordinated polling system.
Changes:
- Removed 'Check Now' button from equipment detail page
- Removed trigger_check event handler
- Simplified Discover and Edit buttons to use standard button styling
- Removed custom classes in favor of default button component styling
The equipment is now polled automatically based on its configured
check_interval_seconds, coordinated across all pods.
Some SNMP implementations return 16-byte binaries for Counter64 values
instead of the standard 8 bytes. Updated decoder to:
- Handle 8-byte standard Counter64
- Handle 16-byte values by reading last 8 bytes
- Handle any size > 8 bytes by reading last 8 bytes
- Add debug/warning logging for non-standard sizes
This fixes DBConnection.EncodeError when polling interface statistics
from devices that return non-standard Counter64 encodings.
Prevents duplicate polling when multiple pods are running by using
database-based coordination.
Changes:
- Added last_snmp_poll_at timestamp to equipment table
- Added Equipment.update_snmp_poll_time/1 function
- Updated PollerWorker to check last_snmp_poll_at before polling
- Polls are skipped if equipment was polled within (interval - 5s)
- Updates timestamp before polling (optimistic locking)
This ensures that when K8s scales up/down or pods restart, only one
pod polls each piece of equipment at a time, preventing wasteful
duplicate SNMP queries and database writes.
The 5-second grace period accounts for clock drift and processing delays
between pods.
Improved startup reliability and debugging for SNMP pollers:
- Added try/rescue blocks around monitor and poller startup
- Added logging for successful startup and errors
- Added error logging to PollerWorker's perform_poll
- Added debug logging for successful sensor/interface polls
This will help identify issues when pollers fail to start or
encounter errors during polling, which was causing silent failures
where sensors weren't being collected.
Storage sensors (disk/memory usage) need to fetch two OIDs to calculate
percentages: the 'used' value and the 'size' value. Previously, only the
'used' OID was stored and polled, resulting in meaningless raw values.
Changes:
- Added metadata JSONB field to snmp_sensors table
- Updated Sensor schema to include metadata field
- Updated MikroTik profile to store size_oid in metadata for storage sensors
- Updated PollerWorker to handle percentage calculation sensors:
- poll_simple_sensor: Standard OID fetch with divisor
- poll_percentage_sensor: Fetches both used and size OIDs, calculates percentage
Storage sensors now properly calculate and store percentage values during polling.
NOTE: Existing MikroTik devices need to re-run SNMP discovery to populate
the metadata field for storage sensors.
SNMP Counter64 values (used for interface byte counters) are returned
as 8-byte binary data by SNMPKit and need to be decoded to integers
before database insertion.
Added decode_snmp_value/1 helper that:
- Passes through numeric values unchanged
- Decodes 8-byte binaries as 64-bit unsigned big-endian integers
- Returns nil for unknown formats
Updated both sensor and interface polling to use this decoder,
preventing DBConnection.EncodeError when trying to insert binary
values into integer columns.
Add background workers to regularly poll SNMP sensors and interfaces:
- Create PollerWorker GenServer to poll SNMP devices
- Poll all sensors for temperature, voltage, CPU, memory, etc.
- Poll all interfaces for bandwidth, errors, and discards
- Save time-series data to snmp_sensor_readings and snmp_interface_stats
- Integrate with monitoring supervisor to auto-start pollers
- Use same interval as connectivity checks (minimum 30 seconds)
- Add list_snmp_enabled_equipment function to Equipment context
Pollers start automatically on app boot for all SNMP-enabled equipment
and run independently of connectivity monitoring.
- Remove delete buttons from show pages
- Add 'Danger Zone' section to edit pages with delete functionality
- Improves UX by keeping destructive actions on edit pages
- Add clear warnings about deletion consequences
- After creating a site, redirect to site detail page instead of list
- Show helpful empty state on site page with instructions to add equipment
- Flash message guides user to add their first device
- Dashboard shows welcome wizard when no sites exist
- Equipment page redirects to site creation when no sites exist
- Equipment form redirects users to create a site if none exist
- Equipment list hides "New Equipment" button when no sites exist
- Update layouts to accept nil current_organization for org-less pages