# Monitoring and alerts

Source: https://argoctl-docs.pages.dev/docs/guides/monitoring

> Metrics with Prometheus and kubectl top, alerts through Alertmanager to your own receivers, your own alert rules, silences, the Watchdog heartbeat and Grafana dashboards.

Every cluster `argoctl create cluster` builds has a monitoring stack in the namespace **`monitoring`**:

| Component | What it does |
|---|---|
| **metrics-server** | `kubectl top nodes` and `kubectl top pods`, and the resource metrics that pod autoscaling uses. |
| **Prometheus** | Collects CPU, memory, network, disk, restarts and OOM kills for the cluster, every node, namespace, pod and container, and node health (disk fill, filesystem errors) from node-exporter on every node, every 30 seconds. Keeps **15 days or 8 GiB**, whichever comes first, on a 10 GiB volume. |
| **Alertmanager** | Receives the alerts and sends them to your receivers. Silences and its notification log are kept on a 1 GiB volume. |
| **Grafana** | Dashboards for the cluster, nodes, namespaces, pods and workloads, and a Logs dashboard. Its database is on a 1 GiB volume. |
| **Prometheus Operator** | Manages Prometheus and Alertmanager, and picks up your `PrometheusRule`, `AlertmanagerConfig`, `ServiceMonitor` and `PodMonitor` objects. |

Prometheus, Alertmanager, Grafana and the operator run on the **control plane**, so a worker going down is always reported, and the workers stay free for your workloads. Their volumes use the default `local-path` StorageClass, so they live on the control plane's disk. Nothing is reachable from outside the cluster except Grafana's LoadBalancer address, when the site file has an `lb_pool`.

## Quick look: kubectl top

```bash
kubectl top nodes
kubectl top pods -A --sort-by=memory
```

## Prometheus and PromQL

Prometheus' own UI and API are reached with `kubectl port-forward` (from mgmt with the admin kubeconfig, or on the control plane):

```bash
kubectl -n monitoring port-forward svc/kube-prometheus-stack-prometheus 9090:9090
# then http://localhost:9090, or the API:
curl -s localhost:9090/api/v1/query --data-urlencode 'query=up' | jq '.data.result | length'
```

To open it on your laptop, tunnel to mgmt as well: `ssh -L 9090:localhost:9090 <you>@<mgmt>`.

Useful queries:

```text
# CPU per pod, in cores (5-minute average)
sum by (namespace, pod) (rate(container_cpu_usage_seconds_total{container!="", image!=""}[5m]))

# memory per pod (working set: what the OOM killer looks at)
sum by (namespace, pod) (container_memory_working_set_bytes{container!="", image!=""})

# one namespace, by container
sum by (pod, container) (container_memory_working_set_bytes{namespace="my-app", container!=""})

# CPU and memory in use per node
1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes

# restarts in the last hour, and containers last killed for memory
increase(kube_pod_container_status_restarts_total[1h]) > 0
kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1

# disk free on each node, and whether it runs out within a day at the current rate
node_filesystem_avail_bytes{mountpoint="/"}
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 24*3600) < 0

# what's firing now
ALERTS{alertstate="firing"}
```

## Alerts

A standard set of alert rules is on from the start. The ones for the most common problems:

| Situation | Alert | Fires after |
|---|---|---|
| Node down (powered off, crashed, off the network) | `NodeDown` | 1 minute |
| Node up but NotReady (kubelet unhealthy) | `KubeNodeNotReady`, `KubeNodeUnreachable` | 15 minutes |
| Node memory or CPU running out | `NodeMemoryHighUtilization`, `NodeCPUHighUsage` | 15 minutes |
| Disk running out | `NodeFilesystemAlmostOutOfSpace`, `NodeFilesystemAlmostOutOfFiles` | 30 minutes, 1 hour |
| Disk filling, with a time-to-full prediction | `NodeFilesystemSpaceFillingUp` (full within 24 hours, or 4 hours) | 1 hour |
| Pod crash-looping | `KubePodCrashLooping` | 15 minutes |
| Container killed for running out of memory | `ContainerOOMKilled` | at once |
| Pod stuck Pending or not Ready | `KubePodNotReady` | 15 minutes |
| Deployment not at its desired replicas | `KubeDeploymentReplicasMismatch`, `KubeDeploymentRolloutStuck` | 15 minutes |
| Certificates expiring | `KubeClientCertificateExpiration`, `KubeletClientCertificateExpiration`, `KubeletServerCertificateExpiration` | 5 minutes |
| Control plane unhealthy | `KubeAPIDown`, `KubeAPIErrorBudgetBurn`, `ControlPlaneComponentDown` (etcd, API server, controller manager or scheduler not ready) | 15 minutes, 2 to 15 minutes, 5 minutes |
| A metrics endpoint not answering | `TargetDown` | 10 minutes |
| Heartbeat | `Watchdog` | always firing (see below) |

**How long until you hear about it.** Prometheus checks every 30 seconds, and Alertmanager waits for your route's `groupWait` (30 seconds by default) before the first notification of a new group. A node that goes down reaches your receiver as `NodeDown` within about **3 minutes**. When the problem clears, the "resolved" notification follows at the group's next `groupInterval` (5 minutes by default; set a shorter one on your route if you want it sooner).

To see what's firing: `ALERTS{alertstate="firing"}` in Prometheus, the Alertmanager UI (below), or the report of `argoctl verify cluster`, which lists the alerts firing at the time.

## Send alerts to your receivers

Alerts go nowhere until you add a receiver. Add one with an **`AlertmanagerConfig` in your own namespace**: email, Slack, Microsoft Teams, PagerDuty, Opsgenie, a webhook and more. You don't edit Alertmanager's own configuration. Every `AlertmanagerConfig` in the cluster is picked up, and its route sees **every alert**, node and cluster alerts included, and the [log alerts](https://argoctl-docs.pages.dev/docs/guides/search-logs#log-alerts) Loki sends: use matchers to choose which.

```yaml
apiVersion: monitoring.coreos.com/v1alpha1
kind: AlertmanagerConfig
metadata:
  name: ops
  namespace: acme
spec:
  route:
    receiver: ops-slack
    matchers:
      - { name: severity, value: "critical|warning", matchType: "=~" }
    groupBy: [alertname, namespace]
    groupWait: 30s
    groupInterval: 1m
    repeatInterval: 4h
  receivers:
    - name: ops-slack
      slackConfigs:
        - apiURL: { name: slack-webhook, key: url }   # a Secret in the same namespace
          channel: "#ops"
          sendResolved: true
```

```bash
kubectl -n acme create secret generic slack-webhook --from-literal=url=https://hooks.slack.com/services/...
kubectl apply -f ops-alerts.yaml
```

Credentials always come from Secrets in the same namespace; receivers can't read files from Alertmanager's container. Several `AlertmanagerConfig` objects (yours and other teams') work side by side: each one's route sees every alert.

### The Watchdog heartbeat

`Watchdog` fires all the time, on purpose. Route it to a **dead man's switch**, a service that alerts you when the heartbeat *stops* (for example Healthchecks.io, or the heartbeat feature of PagerDuty or Opsgenie). Then a dead monitoring stack, a control plane that's down, or a cut network gets noticed too.

```yaml
apiVersion: monitoring.coreos.com/v1alpha1
kind: AlertmanagerConfig
metadata:
  name: heartbeat
  namespace: acme
spec:
  route:
    receiver: deadmans-switch
    matchers: [{ name: alertname, value: Watchdog }]
    groupInterval: 1m      # together with repeatInterval, sets how often the heartbeat is sent
    repeatInterval: 1m
  receivers:
    - name: deadmans-switch
      webhookConfigs:
        - url: https://hc-ping.com/<your-check-uuid>
```

## Add your own alert rules

A `PrometheusRule` in any namespace is loaded, whatever its labels. One that doesn't parse is rejected when you apply it. Give your alerts `severity: warning` or `critical`: alerts with `severity: info` are held back unless a warning or critical alert fires in the same namespace.

```yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: my-app
  namespace: acme
spec:
  groups:
    - name: my-app
      rules:
        - alert: MyAppTooManyRestarts
          expr: increase(kube_pod_container_status_restarts_total{namespace="acme"}[15m]) > 3
          for: 5m
          labels: { severity: warning }
          annotations:
            summary: "{{ $labels.pod }} restarted more than 3 times in 15 minutes"
```

To collect your own apps' metrics, add a `ServiceMonitor` or `PodMonitor` in your namespace the same way.

**What you can change.** Add your own `AlertmanagerConfig`, `PrometheusRule`, `ServiceMonitor` and `PodMonitor` objects and Grafana dashboards in your namespaces. The monitoring stack's own resources in `monitoring` (its rules, Alertmanager's main configuration, its dashboards) belong to argoCTL: `create cluster` puts them back, so changes to them don't last.

## Silence alerts during maintenance

A silence mutes matching alerts until it ends: they still fire, but no notification goes out. Silences are kept across Alertmanager restarts.

```bash
kubectl -n monitoring port-forward svc/kube-prometheus-stack-alertmanager 9093:9093
# open http://localhost:9093, then "New Silence"
```

Or with `amtool`, which is in the Alertmanager container:

```bash
AM="kubectl -n monitoring exec alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- amtool --alertmanager.url=http://localhost:9093"
$AM silence add node=gpu2 --duration=2h --comment="gpu2 maintenance" --author="$USER"
$AM silence query
$AM silence expire <id>
```

Don't silence `Watchdog`: your dead man's switch would alert.

## Grafana

Grafana comes with dashboards for the cluster, nodes, namespaces, pods and workloads, node-exporter, Prometheus and Alertmanager, and a **Logs** dashboard: log lines by namespace, pod and container, with a search box. Its data sources (Prometheus, Alertmanager and Loki) are set up for you and read-only. The dashboards are restored by every `create cluster` and can't be saved over in Grafana; use **Save as** to make your own copy, or add a dashboard as a ConfigMap labelled `grafana_dashboard: "1"` in any namespace.

**Open it** with a port-forward:

```bash
kubectl -n monitoring port-forward svc/kube-prometheus-stack-grafana 3000:80
# then http://localhost:3000
```

or, when the site file has an `lb_pool`, at its LoadBalancer address, `http://<address>`; the `create cluster` and `verify cluster` reports print it, as does `kubectl -n monitoring get service kube-prometheus-stack-grafana`. It's plain HTTP: reach it from a trusted network, or through an SSH tunnel (`ssh -L 3000:<address>:80 <you>@<mgmt>`).

**Log in** as `admin`. argoCTL generates the password when it first installs Grafana and keeps it in a Secret; later runs never change it, and it never appears in argoCTL's logs or reports:

```bash
kubectl -n monitoring get secret grafana-admin -o jsonpath='{.data.admin-password}' | base64 -d; echo
```

Anonymous access and self sign-up are off. Add users for your team under **Administration → Users**. If you change the admin password in Grafana, the Secret no longer matches it.

## Limits

- **One of each.** Prometheus, Alertmanager and Grafana run once, on the control plane's disk. If the control plane is down, monitoring is down with it (the Watchdog heartbeat stops, which is how you'll know). If its disk is lost, so is the metrics history.
- **No "PVC almost full" for `local-path` volumes.** Kubernetes reports no usage for them, as they are directories on the node's disk. The node disk alerts cover the space they share.
- **The controller manager, scheduler, etcd and kube-proxy** serve metrics only on the node itself, so they aren't collected. Their health is watched through their pods (`ControlPlaneComponentDown`); the API server's metrics are collected.
