|
| 1 | +"""Continuous monitoring — repeat scans, diff findings, notify on changes.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import logging |
| 7 | +import uuid |
| 8 | +from datetime import datetime, timezone |
| 9 | +from pathlib import Path |
| 10 | +from typing import Callable |
| 11 | + |
| 12 | +from argus_lite.core.config import AppConfig |
| 13 | +from argus_lite.core.incremental import diff_findings |
| 14 | +from argus_lite.models.finding import Finding |
| 15 | +from argus_lite.models.monitor import MonitorConfig, MonitorRun, MonitorState |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class MonitorSession: |
| 21 | + """Runs repeated scans, diffs findings, notifies on changes.""" |
| 22 | + |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + monitor_config: MonitorConfig, |
| 26 | + app_config: AppConfig, |
| 27 | + on_run_complete: Callable[[MonitorRun], None] | None = None, |
| 28 | + ) -> None: |
| 29 | + self._mc = monitor_config |
| 30 | + self._app_config = app_config |
| 31 | + self._on_run_complete = on_run_complete |
| 32 | + self._shutdown = asyncio.Event() |
| 33 | + self._run_count = 0 |
| 34 | + self._state = MonitorState( |
| 35 | + monitor_id=str(uuid.uuid4())[:8], |
| 36 | + config=monitor_config, |
| 37 | + started_at=datetime.now(tz=timezone.utc), |
| 38 | + ) |
| 39 | + |
| 40 | + async def start(self) -> None: |
| 41 | + """Main monitoring loop. Blocks until stop() or max_runs reached.""" |
| 42 | + self._state.is_running = True |
| 43 | + |
| 44 | + while not self._shutdown.is_set(): |
| 45 | + await self._execute_run() |
| 46 | + self._run_count += 1 |
| 47 | + |
| 48 | + if self._mc.max_runs and self._run_count >= self._mc.max_runs: |
| 49 | + break |
| 50 | + |
| 51 | + # Wait for interval or shutdown |
| 52 | + try: |
| 53 | + await asyncio.wait_for( |
| 54 | + self._shutdown.wait(), |
| 55 | + timeout=self._mc.interval_seconds, |
| 56 | + ) |
| 57 | + break # shutdown requested |
| 58 | + except asyncio.TimeoutError: |
| 59 | + continue # interval elapsed |
| 60 | + |
| 61 | + self._state.is_running = False |
| 62 | + |
| 63 | + async def stop(self) -> None: |
| 64 | + """Signal graceful shutdown.""" |
| 65 | + self._shutdown.set() |
| 66 | + |
| 67 | + async def _execute_run(self) -> None: |
| 68 | + """Single scan cycle: scan → diff → notify → record.""" |
| 69 | + from argus_lite.core.orchestrator import ScanOrchestrator |
| 70 | + from argus_lite.core.risk_scorer import score_scan |
| 71 | + |
| 72 | + logger.info("Monitor run %d for %s", self._run_count + 1, self._mc.target) |
| 73 | + |
| 74 | + orch = ScanOrchestrator( |
| 75 | + target=self._mc.target, |
| 76 | + config=self._app_config, |
| 77 | + preset=self._mc.preset, |
| 78 | + skip_cve=True, # Skip CVE in monitor for speed |
| 79 | + ) |
| 80 | + |
| 81 | + try: |
| 82 | + result = await orch.run() |
| 83 | + result.risk_summary = score_scan(result) |
| 84 | + except Exception as exc: |
| 85 | + logger.warning("Monitor scan failed: %s", exc) |
| 86 | + run = MonitorRun( |
| 87 | + run_number=self._run_count + 1, |
| 88 | + timestamp=datetime.now(tz=timezone.utc), |
| 89 | + risk_level="NONE", |
| 90 | + ) |
| 91 | + self._state.runs.append(run) |
| 92 | + return |
| 93 | + |
| 94 | + # Diff with previous findings |
| 95 | + current_findings = result.findings |
| 96 | + prev_findings = self._state.last_findings |
| 97 | + |
| 98 | + diff = diff_findings(prev_findings, current_findings) |
| 99 | + |
| 100 | + run = MonitorRun( |
| 101 | + run_number=self._run_count + 1, |
| 102 | + timestamp=datetime.now(tz=timezone.utc), |
| 103 | + scan_id=result.scan_id, |
| 104 | + findings_count=len(current_findings), |
| 105 | + new_count=len(diff.new), |
| 106 | + resolved_count=len(diff.resolved), |
| 107 | + unchanged_count=len(diff.unchanged), |
| 108 | + risk_level=result.risk_summary.risk_level if result.risk_summary else "NONE", |
| 109 | + ) |
| 110 | + |
| 111 | + self._state.runs.append(run) |
| 112 | + self._state.last_findings = current_findings |
| 113 | + |
| 114 | + # Notify if new findings appeared |
| 115 | + if diff.new and self._mc.notify_on_new: |
| 116 | + await self._send_notification(result, diff.new) |
| 117 | + |
| 118 | + # Callback |
| 119 | + if self._on_run_complete: |
| 120 | + try: |
| 121 | + self._on_run_complete(run) |
| 122 | + except Exception: |
| 123 | + pass |
| 124 | + |
| 125 | + # Save state |
| 126 | + self._save_state() |
| 127 | + |
| 128 | + async def _send_notification(self, result, new_findings: list[Finding]) -> None: |
| 129 | + """Send notification about new findings.""" |
| 130 | + try: |
| 131 | + from argus_lite.core.notifier import NotificationDispatcher |
| 132 | + |
| 133 | + if not self._app_config.notifications.enabled: |
| 134 | + return |
| 135 | + |
| 136 | + dispatcher = NotificationDispatcher(self._app_config.notifications) |
| 137 | + if dispatcher.get_active_notifiers(): |
| 138 | + await dispatcher.notify_all(result) |
| 139 | + except Exception as exc: |
| 140 | + logger.warning("Monitor notification failed: %s", exc) |
| 141 | + |
| 142 | + def _save_state(self) -> None: |
| 143 | + """Persist monitor state to disk.""" |
| 144 | + try: |
| 145 | + state_dir = ( |
| 146 | + Path.home() / ".argus-lite" / "monitors" / self._state.monitor_id |
| 147 | + ) |
| 148 | + state_dir.mkdir(parents=True, exist_ok=True) |
| 149 | + (state_dir / "state.json").write_text( |
| 150 | + self._state.model_dump_json(indent=2) |
| 151 | + ) |
| 152 | + except Exception as exc: |
| 153 | + logger.debug("Failed to save monitor state: %s", exc) |
0 commit comments