Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@ The comprehensive Value vs. Effort Prioritization Matrix, phased milestone deliv
| | `devops sandbox stop [OPTIONS] <instance_id>` | Gracefully stop and tear down a sandbox container. |
| | `devops sandbox exec [OPTIONS] <instance_id> <command>` | Execute a command inside an active sandbox container. |
| | `devops sandbox probe [OPTIONS] <identifier>` | Probe endpoint readiness and service health across network protocols. |
| | `devops sandbox metrics [OPTIONS] <identifier>` | Capture real-time cgroup v2 metrics and scrape Prometheus application metrics. |
| **dashboard** | `devops dashboard [OPTIONS]` | Interactive terminal UI dashboard for workstation situational awareness. |
| **tui** | `devops tui [OPTIONS]` | Interactive terminal UI dashboard for workstation situational awareness. |
| **format** | `devops format [OPTIONS]` | Format codebase with ruff format (or verify in check-only mode with --check). |
Expand Down
25 changes: 25 additions & 0 deletions docs/CLI_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5803,6 +5803,31 @@ devops sandbox probe [OPTIONS] <identifier>
| `--json` | `boolean` | - | Output details in structured JSON format. |
| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. |

### `devops sandbox metrics`

**Capture real-time cgroup v2 metrics and scrape Prometheus application metrics.**

```bash
devops sandbox metrics [OPTIONS] <identifier>
```

**Arguments:**

| Argument | Type | Required | Description |
|---|---|---|---|
| `<identifier>` | `string` | Yes | Unique instance ID or name of the sandbox. |

**Options:**

| Option / Flag | Type | Default | Description |
|---|---|---|---|
| `--prom-endpoint`, `-p`, `--path` | `string` | `/metrics` | Prometheus metrics scrape path (default /metrics). |
| `--timeout`, `-t` | `float` | `5.0` | Graceful stop timeout in seconds before SIGKILL. |
| `--warn-memory-pct` | `float` | `80.0` | Warning threshold percentage for container memory consumption. |
| `--warn-cpu-pct` | `float` | `85.0` | Warning threshold percentage for container CPU utilization. |
| `--json` | `boolean` | - | Output details in structured JSON format. |
| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. |

---

## devops dashboard
Expand Down
68 changes: 68 additions & 0 deletions docs/agent/tasks/task-108-sandbox-metrics-cgroup-prom.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Task 108: Cgroup v2 Metrics Collection & Prometheus Application Scraping

**Issue**: [#108](https://github.com/dan-petty/devops-cli/issues/108)
**PR**: TBD
**Status**: In Progress
Comment on lines +3 to +5
**Milestone**: `v0.2.17`
**Priority**: `priority/p1-high`
**Scope**: `scope/telemetry`

---

## 1. Description & Architectural Objectives

Implement real-time container resource telemetry capturing cgroup v2 metrics and Prometheus application scraping on `/metrics` endpoints to detect memory leaks, resource starvation, and performance degradation under load for sandboxed workloads.

### Key Architectural Capabilities
1. **Cgroup v2 Resource Telemetry**:
- Extraction of CPU utilization percentage, RSS/current memory, peak memory, configured memory limit, usage percentage, page faults, active tasks/pids, I/O read/write bytes, and network throughput.
- Dual-path collection: Direct cgroup v2 filesystem reading (`/sys/fs/cgroup`) with automated fallback to container engine inspection (`docker inspect`/`docker stats`).
2. **Prometheus Exposition Format Scraper**:
- HTTP `/metrics` scraper using `httpx2` with URL scheme validation.
- Resilient parser for Prometheus text exposition format (counters, gauges, histograms) supporting multi-label dimensional queries.
3. **Automated Threshold Warnings & Leak Detection**:
- Evaluator asserting resource limits (e.g. RSS > 80% limit, high CPU > 85%).
- Warning generation on memory leak trajectory and Prometheus error rate spikes.
4. **Visual & Machine-Readable Reporting (`devops sandbox metrics`)**:
- Rich terminal display with formatted memory/CPU tables, threshold warning callouts, and latency/request summaries.
- Structured JSON export (`--json`) and `--dry-run` validation.
5. **Architectural Invariants**:
- Cyclomatic complexity $\le 10$, nesting depth $\le 5$.
- Bounded string truncation $\le 256$ chars, test coverage $\ge 90\%$.

---

## 2. Planned Changes

1. **Models (`src/devops_cli/sandbox/models.py`)**:
- Define `CgroupV2Metrics`, `PrometheusMetric`, `SandboxMetricsSnapshot`, `ThresholdWarning`.
2. **Telemetry Submodule (`src/devops_cli/sandbox/metrics.py`)**:
- Implement `read_cgroup_v2_metrics()`.
- Implement `scrape_prometheus_metrics()`.
- Implement `evaluate_threshold_warnings()`.
- Implement `collect_sandbox_metrics()`.
3. **Engine Integration (`src/devops_cli/sandbox/engine.py` & `__init__.py`)**:
- Expose `WorkloadSandboxEngine.metrics()`.
4. **CLI Command (`src/devops_cli/commands/sandbox.py`)**:
- Implement `devops sandbox metrics [identifier]` with table/json rendering and dry-run support.
5. **Localization (`src/devops_cli/lang/en/help.py`, `messages.py`)**:
- Add help docstrings and messages.
6. **Submodule Tests (`tests/test_sandbox_metrics.py`)**:
- Comprehensive test suite covering cgroup parsing, mock Prometheus endpoints, threshold alerts, CLI command, and dry-run.

---

## 3. Progress Tracking

- [x] Ground issue in GitHub tracking (#108) and set label to `status/in-progress`.
- [x] Author task tracking file `docs/agent/tasks/task-108-sandbox-metrics-cgroup-prom.md`.
- [x] Create dedicated topic branch `feat/108-sandbox-metrics-cgroup-prom`.
- [x] Author test suite in `tests/test_sandbox_metrics.py`.
- [x] Implement metrics models in `src/devops_cli/sandbox/models.py`.
- [x] Implement cgroup & prometheus collector in `src/devops_cli/sandbox/metrics.py`.
- [x] Integrate metrics method in `WorkloadSandboxEngine`.
- [x] Implement CLI command in `src/devops_cli/commands/sandbox.py`.
- [x] Update language help strings in `src/devops_cli/lang/en/help.py`.
- [x] Verify test suite, complexity, Bandit, and full CI gate (`devops ci`).
- [x] Synchronize documentation (`devops docs generate --sync-readme`).
- [ ] Author Pull Request targeting `release/v0.2.17` and verify CI checks pass.
27 changes: 27 additions & 0 deletions docs/commands/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,30 @@ devops sandbox probe [OPTIONS] <identifier>
| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. |

---

## `devops sandbox metrics`

**Capture real-time cgroup v2 metrics and scrape Prometheus application metrics.**

```bash
devops sandbox metrics [OPTIONS] <identifier>
```

**Arguments:**

| Argument | Type | Required | Description |
|---|---|---|---|
| `<identifier>` | `string` | Yes | Unique instance ID or name of the sandbox. |

**Options:**

| Option / Flag | Type | Default | Description |
|---|---|---|---|
| `--prom-endpoint`, `-p`, `--path` | `string` | `/metrics` | Prometheus metrics scrape path (default /metrics). |
| `--timeout`, `-t` | `float` | `5.0` | Graceful stop timeout in seconds before SIGKILL. |
| `--warn-memory-pct` | `float` | `80.0` | Warning threshold percentage for container memory consumption. |
| `--warn-cpu-pct` | `float` | `85.0` | Warning threshold percentage for container CPU utilization. |
| `--json` | `boolean` | - | Output details in structured JSON format. |
| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. |

---
153 changes: 153 additions & 0 deletions src/devops_cli/commands/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,18 @@
print_error,
print_success,
print_table,
print_warning,
render_dry_run_result,
)
from devops_cli.sandbox.engine import WorkloadSandboxEngine
from devops_cli.sandbox.models import (
CgroupV2Metrics,
ProbeProtocol,
ProbeStatus,
PrometheusMetric,
SandboxDeployConfig,
SandboxInstance,
SandboxMetricsSnapshot,
SandboxProbeReport,
SandboxStatus,
)
Expand Down Expand Up @@ -417,4 +421,153 @@ def probe(
return None


def _render_cgroup_table(target: str, cgroup: CgroupV2Metrics) -> None:
"""Render Cgroup v2 resource telemetry table."""
columns = [
("Resource / Metric", "cyan"),
("Value", "white"),
("Limit / Baseline", "yellow"),
("Status", "bold"),
]
cpu_badge = "[red]HIGH[/red]" if cgroup.cpu_percent > 85.0 else "[green]HEALTHY[/green]"
mem_lim_str = f"{cgroup.memory_limit_mb:.1f} MB" if cgroup.memory_limit_mb else "unbounded"
mem_pct = (
f"{cgroup.memory_usage_percent:.1f}%" if cgroup.memory_usage_percent is not None else "-"
)
Comment on lines +432 to +436
mem_badge = (
"[red]HIGH[/red]"
if (cgroup.memory_usage_percent or 0.0) > 80.0
else "[green]HEALTHY[/green]"
)

rows = [
["CPU Utilization", f"{cgroup.cpu_percent:.1f}%", "< 85.0%", cpu_badge],
["Memory (RSS)", f"{cgroup.memory_current_mb:.1f} MB", mem_lim_str, mem_badge],
["Memory Usage %", mem_pct, "< 80.0%", mem_badge],
["Active Tasks (PIDs)", str(cgroup.pids_current), "-", "[dim]ACTIVE[/dim]"],
["Page Faults Total", str(cgroup.page_faults_total), "-", "[dim]NORMAL[/dim]"],
[
"Block I/O (R/W)",
f"{cgroup.io_read_bytes / (1024 * 1024):.1f} MB / {cgroup.io_write_bytes / (1024 * 1024):.1f} MB",
"-",
"[dim]I/O[/dim]",
],
]
print_table(f"Cgroup v2 Resource Telemetry: {target}", columns, rows)


def _render_prom_table(target: str, metrics: list[PrometheusMetric]) -> None:
"""Render Prometheus application metrics table."""
columns = [
("Metric Name", "cyan"),
("Type", "magenta"),
("Labels", "dim"),
("Value", "green"),
]
rows = []
for m in metrics[:15]:
lbl_str = ", ".join(f"{k}={v}" for k, v in m.labels.items()) if m.labels else "-"
lbl_truncated = lbl_str if len(lbl_str) <= 40 else lbl_str[:37] + "..."
rows.append([m.name, m.metric_type.upper(), lbl_truncated, f"{m.value:.2f}"])
print_table(f"Prometheus Application Metrics: {target}", columns, rows)


def _render_metrics_snapshot(snapshot: SandboxMetricsSnapshot) -> None:
"""Render structured container telemetry and Prometheus metrics in Rich tables."""
if snapshot.cgroup:
_render_cgroup_table(snapshot.target, snapshot.cgroup)

if snapshot.prometheus_metrics:
_render_prom_table(snapshot.target, snapshot.prometheus_metrics)

for warning in snapshot.warnings:
print_warning(f"THRESHOLD ALERT: {warning}")

if snapshot.is_healthy:
print_success(f"Workload '{snapshot.target}' operating within normal performance bounds.")
else:
print_error(
f"Workload '{snapshot.target}' exceeded {len(snapshot.warnings)} operating threshold(s)."
)


@app.command("metrics")
def metrics(
identifier: Annotated[str, typer.Argument(help=HELP.sandbox.instance_id)],
prom_endpoint: Annotated[
str,
typer.Option(
"--prom-endpoint",
"-p",
"--path",
help=HELP.sandbox.metrics_endpoint,
),
] = "/metrics",
timeout: Annotated[float, typer.Option("--timeout", "-t", help=HELP.sandbox.timeout)] = 5.0,
warn_memory_pct: Annotated[
float,
typer.Option(
"--warn-memory-pct",
help=HELP.sandbox.warn_memory_pct,
),
] = 80.0,
warn_cpu_pct: Annotated[
float,
typer.Option(
"--warn-cpu-pct",
help=HELP.sandbox.warn_cpu_pct,
),
] = 85.0,
json_output: Annotated[bool, typer.Option("--json", help=HELP.sandbox.json_output)] = False,
dry_run: Annotated[bool, typer.Option("--dry-run", help=HELP.options.dry_run)] = False,
) -> None:
"""Capture real-time cgroup v2 metrics and scrape Prometheus application metrics."""
set_dry_run(dry_run)

if is_dry_run():
render_dry_run_result(
command="devops sandbox metrics",
action="collect_sandbox_metrics",
details={
"identifier": identifier,
"prom_endpoint": prom_endpoint,
"timeout": timeout,
"warn_memory_pct": warn_memory_pct,
"warn_cpu_pct": warn_cpu_pct,
},
)
return None

engine = WorkloadSandboxEngine()
try:
snapshot = engine.metrics(
identifier=identifier,
prom_endpoint=prom_endpoint,
timeout=timeout,
memory_threshold_pct=warn_memory_pct,
cpu_threshold_pct=warn_cpu_pct,
)
except SandboxNotFoundError:
if "://" in identifier or ":" in identifier:
from devops_cli.sandbox.metrics import collect_sandbox_metrics

snapshot = collect_sandbox_metrics(
instance_or_target=identifier,
prom_endpoint=prom_endpoint,
timeout=timeout,
memory_threshold_pct=warn_memory_pct,
cpu_threshold_pct=warn_cpu_pct,
)
else:
print_error(f"Sandbox instance '{identifier}' not found.")
raise typer.Exit(1)

if json_output:
typer.echo(json.dumps(snapshot.model_dump(), indent=2))
return None

_render_metrics_snapshot(snapshot)
return None


__all__ = ["app"]
4 changes: 4 additions & 0 deletions src/devops_cli/lang/en/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,10 @@ class SandboxCommandHelp:
probe_expected_status: str = "Expected HTTP response status code(s)."
probe_regex: str = "Regex pattern to assert against HTTP response body."
probe_latency_sla: str = "Maximum acceptable response latency budget in milliseconds."
metrics: str = "Capture real-time cgroup v2 metrics and scrape Prometheus application metrics."
metrics_endpoint: str = "Prometheus metrics scrape path (default /metrics)."
warn_memory_pct: str = "Warning threshold percentage for container memory consumption."
warn_cpu_pct: str = "Warning threshold percentage for container CPU utilization."


@dataclass(frozen=True)
Expand Down
20 changes: 20 additions & 0 deletions src/devops_cli/sandbox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,25 @@
from __future__ import annotations

from devops_cli.sandbox.engine import WorkloadSandboxEngine
from devops_cli.sandbox.metrics import (
collect_sandbox_metrics,
evaluate_threshold_warnings,
parse_cgroup_v2_directory,
parse_prometheus_exposition,
read_cgroup_v2_metrics,
scrape_prometheus_metrics,
)
from devops_cli.sandbox.models import (
CgroupV2Metrics,
EndpointProbeResult,
PortBinding,
ProbeProtocol,
ProbeStatus,
PrometheusMetric,
SandboxDeployConfig,
SandboxExecResult,
SandboxInstance,
SandboxMetricsSnapshot,
SandboxProbeReport,
SandboxStatus,
)
Expand All @@ -25,24 +36,33 @@
from devops_cli.sandbox.registry import SandboxRegistry, get_default_sandbox_registry_path

__all__ = [
"CgroupV2Metrics",
"EndpointProbeResult",
"PortBinding",
"ProbeProtocol",
"ProbeStatus",
"PrometheusMetric",
"SandboxDeployConfig",
"SandboxExecResult",
"SandboxInstance",
"SandboxMetricsSnapshot",
"SandboxProbeReport",
"SandboxRegistry",
"SandboxStatus",
"WorkloadSandboxEngine",
"allocate_ports",
"collect_sandbox_metrics",
"evaluate_threshold_warnings",
"find_available_port",
"get_default_sandbox_registry_path",
"is_port_available",
"parse_cgroup_v2_directory",
"parse_prometheus_exposition",
"probe_grpc",
"probe_http",
"probe_openapi",
"probe_tcp",
"read_cgroup_v2_metrics",
"run_sandbox_probes",
"scrape_prometheus_metrics",
]
Loading
Loading