# Monitoring with Prometheus

> Scrape your Legion agent's metrics with your own Prometheus, and use the example alert rules and Grafana dashboard.

Source: https://legion.ambient.xyz/docs/providing/monitoring

The agent serves Prometheus metrics about your host: its health, whether it is listed, rentals, GPUs, benchmarks and its link to Legion. Point your own Prometheus at it to chart them and to get alerts when something needs you.

You don't have to do this. Legion monitors your hosts itself, over the Legion network. You don't open anything for that. This page is for providers who want their own alerts and dashboards.

The metrics need agent 0.8.0 or later. An older agent has no `legion_agent_*` series. The agent [updates itself](https://legion.ambient.xyz/docs/providing/agent-updates).

## What you get

- Every metric starts with `legion_agent_`. Their names are stable: a new series may be added, but none is renamed or removed in a major version of the agent.
- Labels are few and bounded: `check`, `state`, `version`, the GPU number `gpu`, and the GPU `model` on one metric. There is no rental ID, host ID or address in them.
- The older `agent_*` metrics on the same endpoint are the agent's own internals. Build on the `legion_agent_*` ones.

## Turn it on

The agent serves `GET /metrics` on `127.0.0.1:9123`, so only the machine itself can read it. To scrape from another machine, set `metrics_addr` in `/etc/legion-agent/config.yaml`:

```yaml
metrics_addr: 10.0.0.5:9123   # a private interface; 0.0.0.0:9123 listens on every interface
```

You can set `METRICS_ADDR` in the unit's environment drop-in instead. Then restart the agent:

```sh
sudo systemctl restart legion-agent
```

Restarting the agent drops renters' SSH sessions, so pick a quiet moment on a host that is rented.

> `/metrics` has no password. It shows your GPU model, rental counts and health, never a renter's data. Bind it to a private interface or a VPN address, and firewall the port so only your Prometheus can reach it. The agent logs a warning at startup when the address is not loopback. Never expose it to the internet.

## Scrape it

Add the agent to your `prometheus.yml`, one target for each host:

```yaml
scrape_configs:
  - job_name: legion-agent
    scrape_interval: 30s
    static_configs:
      - targets: ["10.0.0.5:9123", "10.0.0.6:9123"]
```

Check that it works with `curl http://10.0.0.5:9123/metrics` from the Prometheus machine. You should see lines that start with `legion_agent_`.

## Health checks

`legion_agent_health_status` is 1 when all seven checks pass, and 0 when any fails. `legion_agent_health_check{check="..."}` is 1 or 0 for each check, so you can see which one failed.

| `check` | Passes when |
| --- | --- |
| `controller_sync` | The last sync with Legion succeeded, and the last success is less than three poll intervals old (at least 2 minutes). |
| `mesh` | The agent's connection to the Legion network is up. |
| `docker` | Docker answered the agent's last poll. |
| `gpu_driver` | `nvidia-smi` answers. A host without GPUs always passes. |
| `disk_space` | The disk that holds the agent's state has at least 10 GiB free. |
| `certificate` | The agent's certificate is valid and has not been revoked. |
| `clock` | The host's clock is within 60 seconds of Legion's. |

## Metrics

### Health and listing

| Metric | Labels | Meaning |
| --- | --- | --- |
| `legion_agent_health_status` |  | 1 healthy, 0 an issue (any failing check). |
| `legion_agent_health_check` | `check` | 1 pass, 0 fail, for each check above. |
| `legion_agent_host_listing_status` |  | 1 when the host is listed in the market and can be rented, 0 when it is not. Absent while Legion doesn't say. |
| `legion_agent_host_listing_state` | `state` | One state is 1 and the rest are 0: `listed`, `unlisted`, `awaiting_first_benchmark`, `first_benchmark_failed`, `held` (agent too old), `under_review` (not approved yet), `quarantined`, `suspended` (your organization), `removed`, `unknown` (Legion didn't say). |

### Rentals and GPUs

| Metric | Labels | Meaning |
| --- | --- | --- |
| `legion_agent_active_rentals` |  | Rentals running now. |
| `legion_agent_rentals` | `state` | Rentals by state: `running`, `stopped`, `deleted`, `failed`. |
| `legion_agent_gpus_total` |  | GPUs in the host. |
| `legion_agent_gpus_rented` |  | GPUs held by running rentals. |
| `legion_agent_workspace_disk_free_bytes` |  | Free space on the disk that holds rentals. |
| `legion_agent_workspace_disk_total_bytes` |  | Size of that disk. |

### Per GPU

| Metric | Labels | Meaning |
| --- | --- | --- |
| `legion_agent_gpu_info` | `gpu`, `model` | 1 for each GPU. |
| `legion_agent_gpu_utilization_percent` | `gpu` | Utilization, 0 to 100. |
| `legion_agent_gpu_memory_used_bytes` | `gpu` | Device memory in use. |
| `legion_agent_gpu_memory_total_bytes` | `gpu` | Device memory in total. |
| `legion_agent_gpu_power_watts` | `gpu` | Power draw. |
| `legion_agent_gpu_power_limit_watts` | `gpu` | Enforced power limit. |
| `legion_agent_gpu_temperature_celsius` | `gpu` | Temperature. Absent where the driver doesn't report it. |

### Benchmarks

These are the figures of the agent's last completed run. They stay available across restarts. See [Benchmarks and your score](https://legion.ambient.xyz/docs/providing/benchmarks-and-score).

| Metric | Labels | Meaning |
| --- | --- | --- |
| `legion_agent_bench_upload_bits_per_second` |  | Upload line speed of the last run. |
| `legion_agent_bench_download_bits_per_second` |  | Download line speed of the last run. |
| `legion_agent_bench_disk_read_bytes_per_second` |  | Sequential disk read speed. |
| `legion_agent_bench_disk_write_bytes_per_second` |  | Sequential disk write speed. |
| `legion_agent_bench_disk_random_read_iops` |  | Random 4 KiB reads a second. |
| `legion_agent_bench_disk_random_write_iops` |  | Random 4 KiB writes a second. |
| `legion_agent_bench_last_run_timestamp_seconds` |  | When the last network and disk run finished (Unix time). |
| `legion_agent_bench_gpu_fp16_tflops` | `gpu` | FP16 dense matrix multiply speed. |
| `legion_agent_bench_gpu_bf16_tflops` | `gpu` | BF16 dense matrix multiply speed. |
| `legion_agent_bench_gpu_fp32_tflops` | `gpu` | FP32 dense matrix multiply speed. |
| `legion_agent_bench_gpu_memory_bandwidth_bytes_per_second` | `gpu` | Device memory bandwidth. |
| `legion_agent_bench_gpu_last_run_timestamp_seconds` |  | When the last GPU run finished (Unix time). |

Whether Legion flagged a run is not a metric. Look at the benchmark in the app.

### Agent and connection

| Metric | Labels | Meaning |
| --- | --- | --- |
| `legion_agent_controller_reachable` |  | 1 when the last sync with Legion succeeded. |
| `legion_agent_last_sync_timestamp_seconds` |  | When the last sync succeeded (Unix time). |
| `legion_agent_mesh_connected` |  | 1 when the agent's connection to the Legion network is up. |
| `legion_agent_clock_skew_seconds` |  | Legion's clock minus the host's. |
| `legion_agent_certificate_expiry_timestamp_seconds` |  | When the agent's certificate expires (Unix time). |
| `legion_agent_build_info` | `version` | Always 1. The label is the agent's version. |
| `legion_agent_start_time_seconds` |  | When the agent process started (Unix time). |
| `legion_agent_uptime_seconds` |  | Seconds since it started. |
| `legion_agent_upgrade_deferred` |  | 1 while an update is held back for a renter's open SSH session. |

The agent's certificate lasts about a day. The agent renews it by itself when about 8 hours are left. So alert on under 4 hours, not on days.

## Example alert rules

These rules cover the agent being down or unhealthy and which check failed, the host not being listed, no contact with Legion, a stale sync, a certificate about to expire, low disk, a hot GPU, and an update held back for a day. Copy what you want into your Prometheus rule files, or download the file: [legion-agent-alerts.yml](https://legion.ambient.xyz/docs/providing/legion-agent-alerts.yml).

The `for:` times ride out an agent restart and a busy moment at Legion. Change them and the thresholds to suit your hosts.

```yaml
groups:
  - name: legion-agent
    rules:
      - alert: LegionAgentDown
        expr: up{job="legion-agent"} == 0
        for: 5m
        labels: { severity: critical }
        annotations:
          summary: "Cannot scrape the Legion agent on {{ $labels.instance }}"
          description: "The agent is down, or its metrics port is not reachable from Prometheus."

      - alert: LegionAgentUnhealthy
        expr: legion_agent_health_status == 0
        for: 10m
        labels: { severity: warning }
        annotations:
          summary: "Legion agent on {{ $labels.instance }} reports an issue"
          description: "See legion_agent_health_check for the failing check: {{ range query (printf \"legion_agent_health_check{instance='%s'} == 0\" .Labels.instance) }}{{ .Labels.check }} {{ end }}"

      - alert: LegionAgentHealthCheckFailing
        expr: legion_agent_health_check == 0
        for: 10m
        labels: { severity: warning }
        annotations:
          summary: "Legion agent {{ $labels.instance }}: check {{ $labels.check }} fails"

      - alert: LegionHostNotListed
        expr: legion_agent_host_listing_status == 0
        for: 15m
        labels: { severity: info }
        annotations:
          summary: "{{ $labels.instance }} is not offered for rent"
          description: "legion_agent_host_listing_state says why: unlisted, awaiting_first_benchmark, held, under_review, suspended and so on."

      - alert: LegionAgentControllerUnreachable
        expr: legion_agent_controller_reachable == 0
        for: 10m
        labels: { severity: warning }
        annotations:
          summary: "Legion agent on {{ $labels.instance }} cannot reach the controller"
          description: "Running rentals are left as they are, but the host takes no new work until it syncs again."

      - alert: LegionAgentSyncStale
        expr: time() - legion_agent_last_sync_timestamp_seconds > 600
        labels: { severity: warning }
        annotations:
          summary: "Legion agent on {{ $labels.instance }} last synced over 10 minutes ago"

      - alert: LegionAgentCertificateExpiring
        # The certificate lasts about a day and the agent renews it once a third
        # of that is left (about 8 hours), so under 4 hours means renewal failed.
        expr: legion_agent_certificate_expiry_timestamp_seconds - time() < 4 * 3600
        for: 30m
        labels: { severity: warning }
        annotations:
          summary: "The agent certificate on {{ $labels.instance }} expires in under 4 hours"
          description: "The agent renews it by itself when about 8 hours are left; if this fires it has not been able to. Check the agent's log and that it can reach the controller."

      - alert: LegionWorkspaceDiskLow
        expr: legion_agent_workspace_disk_free_bytes < 20 * 1024^3
        for: 15m
        labels: { severity: warning }
        annotations:
          summary: "{{ $labels.instance }} has under 20 GiB free for rentals"

      - alert: LegionGPUHot
        expr: legion_agent_gpu_temperature_celsius > 88
        for: 10m
        labels: { severity: warning }
        annotations:
          summary: "GPU {{ $labels.gpu }} on {{ $labels.instance }} is at {{ $value }} C"

      - alert: LegionAgentOutdated
        expr: legion_agent_upgrade_deferred == 1
        for: 24h
        labels: { severity: info }
        annotations:
          summary: "An agent upgrade has been held back on {{ $labels.instance }} for a day (a renter's SSH session is open)"
```

## Grafana dashboard

[Download the dashboard](https://legion.ambient.xyz/docs/providing/legion-agent-dashboard.json) (`legion-agent-dashboard.json`). In Grafana open **Dashboards**, **New**, **Import**, upload the file, and pick your Prometheus or VictoriaMetrics data source. It shows health, listing, rentals, GPUs, benchmarks and the certificate for each host.

## Troubleshooting

- **No `legion_agent_health_*` series.** The agent exposes them after its first poll. A host that has just started shows nothing until then, which is not the same as unhealthy.
- **A series is missing, not 0.** A figure that can't be measured is left out, never reported as 0. A GPU that doesn't report temperature has no temperature series. Write alerts so that a missing series is not an error.
- **No benchmark series.** They appear after the agent's first completed run. The network and disk run about once a day, and only while the host is idle. A host that is always rented can wait a long time. You can [ask for a re-run](https://legion.ambient.xyz/docs/providing/benchmarks-and-score).
- **`up` is 0 for your target.** Prometheus can't reach the port. Check `metrics_addr`, that the agent was restarted, and your firewall.
- **`legion_agent_host_listing_status` is 0.** Read `legion_agent_host_listing_state` for the reason. See [Review and approval](https://legion.ambient.xyz/docs/providing/review-and-approval) and [Listing and pricing](https://legion.ambient.xyz/docs/providing/listing-and-pricing).
