# Anomalens — Real-Time System Intelligence Dashboard

A production-quality, polyglot system monitoring dashboard that streams live metrics to a beautiful dark-themed web UI.

## Features

| Feature | Detail |
| --- | --- |
| **Real-time streaming** | WebSocket push at 1 Hz — no polling |
| **System metrics** | CPU (per-core), Memory, Disk I/O, Network I/O, Processes |
| **Anomaly detection** | Z-score statistical analysis, threshold alerting |
| **Live charts** | Scrolling Chart.js area charts with gradient fills |
| **SVG ring gauges** | Animated circular progress for CPU / Memory / Disk |
| **Process table** | Top 15 processes, sortable by CPU or Memory |
| **Toast notifications** | Critical alerts appear as overlay toasts |
| **Auto-reconnect** | WebSocket client reconnects automatically |
| **Single binary** | Web assets embedded via `go:embed` |
| **Graceful shutdown** | SIGINT / SIGTERM handled cleanly |

## Languages Used

- **Go** — core engine (HTTP server, WebSocket hub, metrics collection, ring-buffer storage, statistical analyzer)
- **JavaScript / HTML / CSS** — cyberpunk dark-theme dashboard with Chart.js
- **Python** — offline anomaly analysis tool with optional NumPy acceleration
- **Bash** — stress-test script and setup automation
- **Makefile** — build orchestration

## Quick Start

```bash
# One-step setup (fetches deps + builds)
bash scripts/setup.sh

# Run the dashboard
./anomalens

# Open your browser
open http://localhost:8080
```

## Usage

```bash
Usage of ./anomalens:
  -db string          Path to local database file (default "anomalens.db")
  -interval duration   Metrics collection interval (default 1s)
  -history int         Number of data points to retain in memory (default 120)
  -port int            HTTP server port (default 8080)
```

Anomalens now persists recorded snapshots and known anomaly registry data to a local BoltDB file. In the dashboard header, use the VIEW selector to switch between live streaming data and historical data loaded from the local DB.

## Makefile Targets

```bash
make build    — compile binary
make run      — build and start on :8080
make test     — run unit tests with race detector
make stress   — 30s stress test (generates CPU/memory/network load)
make analyze  — run Python anomaly detector against live instance
make analyze-up — auto-start Anomalens on a free port, run detector, auto-stop
make clean    — remove binary
make help     — show all targets
```

## REST API

| Endpoint | Description |
| --- | --- |
| `GET /api/metrics` | Latest `SystemSnapshot` as JSON |
| `GET /api/history?n=60` | Last *n* snapshots (max 300) |
| `GET /api/alerts` | Active alerts from latest snapshot |
| `GET /api/anomalies?limit=100` | Known anomaly registry |
| `GET /api/status` | Server health, WS client count |
| `WS  /ws` | WebSocket — receives a `SystemSnapshot` every second |

For persisted local DB reads, pass `source=db` to supported endpoints (`/api/metrics`, `/api/history`, `/api/alerts`, `/api/anomalies`).

## Python Anomaly Detector

Requires a running Anomalens instance. The project now auto-builds a local virtual environment (`.venv`) and installs dependencies from `requirements.txt` before running analysis.

```bash
# Recommended (auto-venv + dependency install + run)
make analyze

# Fully automated (build + start server on free port + analyze + stop)
make analyze-up

# Or directly
bash scripts/run_anomaly.sh --host localhost --port 8080 --points 120

# Optional custom args forwarded to detector
make analyze-up ANALYZE_ARGS="--points 180"
```

If Anomalens is not reachable on the specified host/port, the runner now exits quickly with a clear message instead of waiting on a Python request timeout.

## Architecture

```bash
main.go
 ├── metrics.Collector   — gopsutil, ticks every 1s
 │    └── pushes JSON to broadcast channel
 ├── storage.RingBuffer  — thread-safe circular buffer (120 points)
 ├── analyzer.Analyzer   — z-score + threshold alerts
 ├── server.Hub          — WebSocket broadcast to all connected clients
 └── server.Server       — HTTP + REST API + embedded web assets
          └── web/        — HTML/CSS/JS (served from embedded FS)
```

## Project Structure

```bash
anomalens/
├── main.go
├── go.mod
├── Makefile
├── internal/
│   ├── metrics/
│   │   ├── types.go        — SystemSnapshot, CPUStats, …
│   │   └── collector.go    — gopsutil metric collection
│   ├── storage/
│   │   └── ring_buffer.go  — thread-safe ring buffer
│   ├── analyzer/
│   │   └── analyzer.go     — z-score anomaly detection
│   └── server/
│       ├── hub.go          — gorilla/websocket broadcast hub
│       ├── server.go       — HTTP server, routing
│       └── handlers.go     — REST API handlers
├── web/
│   ├── index.html          — dashboard layout
│   ├── style.css           — cyberpunk dark theme
│   └── app.js              — WebSocket client, Chart.js
└── scripts/
    ├── anomaly_detector.py — Python offline analysis
    ├── stress_test.sh      — Bash load generator
    └── setup.sh            — Bash setup script
```

## License

MIT
