# fleetlayer-capacity

How much room each machine has, so nothing runs out of memory, swaps itself solid, pegs its CPU until everything
freezes or fills a disk, and so idle machines can take more work.

It's a node plugin that ships with Fleetlayer as `fleetlayer-capacity`. Every 15 seconds it looks at the machine it
runs on:

- **CPU:** how busy it was since the last look, iowait and the load average, and the CPU limit when the node runs in a
  container.
- **Memory and swap:** total and available (inside a container, its own limit, not the host's), swap used.
- **Pressure:** on Linux, pressure stall information (PSI): the share of the last 10 and 60 seconds in which tasks
  waited for a CPU, for memory or for the disk. It's the figure that matters: memory 90% used with no pressure is page
  cache doing its job; 70% used while tasks wait on memory is a machine about to freeze. On macOS, the system's memory
  pressure level (normal, warn or critical), the one Activity Monitor graphs.
- **Disks:** each local file system, the fullest first, without the ones in memory, inside containers or read-only
  (a mounted disk image, an ISO, a snap: always full, never filling). ZFS datasets that share their pool's room count
  once, and a Proxmox host skips its containers' disks (each container's own node reports them).
- **Power:** on a laptop, whether it runs on battery.
- **What runs inside it (Linux):** each Proxmox VM and LXC container, Docker container, the Kubernetes or k3s pods,
  each Unix user's slice and the system's services, from the cgroup tree: their CPU share, memory in use against their
  own limit (without the file cache the kernel can drop, which otherwise keeps any container that reads files near its
  limit), swap and memory pressure. Docker containers (systemd driver) also count in the system services' total.

Inside a container (an LXC, Docker), the container is the machine: its own memory limit, CPU time and pressure, not
the host's.

It decides one **state** for the machine and for each thing inside it, with the reasons in words:

| State | When (defaults) |
|---|---|
| `critical` | everything stalled on memory 10% of the last 10 s, memory available under 5%, on Linux swap over 80% used while memory is under pressure, a disk under 3% free (or under 2 GB and 10%), or macOS memory pressure critical |
| `strained` | tasks waited on memory 10% of the last 10 s, memory available under 12%, a disk under 8% free (or under 10 GB and 15%), tasks waited for a CPU 60% of the last 10 s, or on macOS swap over 1× RAM |
| `busy` | CPU over 80% busy, tasks waited for a CPU 25% of the last 10 s (or, without PSI, a load over 1.5 per CPU), tasks waited on the disk 30% of the last 10 s, on macOS memory pressure warn (everyday use on a Mac), or on macOS swap over half of RAM |
| `ok` | none of these |

Swap is judged differently on a Mac. macOS creates swap files as it needs them and deletes them when it's done, so its
swap total grows and shrinks with what's in use and swap stays nearly 100% used whenever there's any. Against physical
memory it means something: over half of RAM in swap makes a Mac `busy`, more than all of it `strained` (`swap is 1.2×
RAM`). How short memory really is comes from the kernel's own pressure level, the one Activity Monitor graphs: warn
makes it `strained`, critical `critical`. The thresholds are `mac_swap_ram_busy` and `mac_swap_ram_strained`, in
percent of RAM.

It also keeps an hourly history in its state directory (30 days, a few hundred KB) and forecasts from the last week:
the days until each disk fills at that rate (within 60 days), and the week's peak memory use. The fit starts again
after a big jump in free space (a clean-up), so last week's full build directory doesn't count once it's gone. A
disk that will fill within three days makes the machine `strained`, within a day `critical`, but only from two days
of history that a straight line fits well: one big build on a fresh install never stops a machine taking work.

Something inside the machine is `critical` at 95% of its memory limit and `strained` at 88%, or when its own tasks
wait on memory.

It publishes all of it as one `capacity.host` reading keyed by the machine's name (the node's machine name; on a Mac
whose node.yaml doesn't name its machine, its LocalHostName from Sharing settings, since the hostname DHCP hands it can
change from one network to the next; `machine:` in the plugin's config sets it outright): at once when the state changes,
otherwise once a minute. The dashboard's **Capacity** tab shows them beside the Claude accounts' use and the lease
queues. Nothing in it stops or kills anything: it only measures.

## Setup

On **one node per machine** (the machine's main Unix user: other nodes on the same machine would publish the same
figures), in `node.yaml`:

```yaml
plugins:
  - name: capacity
    command: fleetlayer-capacity
    grants: [reading.publish]
    config:                     # all optional
      interval: 15              # seconds between looks (at least 5)
      publish_every: 60         # seconds between readings when the state doesn't change
      boundaries: true          # the VMs, containers and slices inside the machine
      state_dir: ~/.local/state/fleetlayer/capacity   # the hourly history forecasts come from
      thresholds:               # any of these, in percent
        memory_available_critical: 5
        memory_available_strained: 12
        memory_full_critical: 10
        memory_some_strained: 10
        swap_critical: 80             # Linux: % of the swap total, while memory is under pressure
        mac_swap_ram_busy: 50         # macOS: swap used as % of RAM
        mac_swap_ram_strained: 100
        cpu_some_strained: 60
        cpu_some_busy: 25
        cpu_busy: 80
        io_some_busy: 30
        disk_free_critical: 3
        disk_free_strained: 8
```

It needs no privileges and no privacy permission. On Linux it reads `/proc` and `/sys/fs/cgroup`, which any user may
read, and names Proxmox VMs and containers from `/etc/pve` when it's readable (otherwise they show by number). On
macOS it runs `sysctl`, `vm_stat`, `iostat`, `pmset` and `df`.

To look at a machine by hand, without a node:

```
$ fleetlayer-capacity sample
state: strained
  tasks waited on memory 14% of the last 10 s
cpu: 16 CPUs, 72% busy, load 13.20
memory: 5.0 GB of 64.0 GB free (host), swap 3.0 GB of 8.0 GB used
...
```

`--json` prints the reading's data.

## What a reading holds

`capacity.host`, keyed by the machine's name. Bytes are integers, percentages are numbers from 0 to 100:

```json
{
  "os": "linux", "cpus": 4, "cpuQuota": null, "cpuPct": 37.5, "iowaitPct": 1.2, "load1": 1.9,
  "memTotal": 8589934592, "memAvailable": 2147483648, "memLimitedBy": "host",
  "swapTotal": 2147483648, "swapUsed": 104857600,
  "pressure": {"cpu": {"some10": 4.1, "some60": 3.2},
               "memory": {"some10": 0.0, "some60": 0.1, "full10": 0.0, "full60": 0.0},
               "io": {"some10": 0.5, "some60": 0.4, "full10": 0.2, "full60": 0.1}},
  "macPressure": null,
  "disks": [{"mount": "/", "device": "/dev/sda1", "total": 107374182400, "avail": 32212254720}],
  "power": {"onBattery": false, "batteryPct": null},
  "state": "ok", "reasons": [],
  "boundaries": [{"kind": "lxc", "id": "117", "name": "search", "cpuPct": 2.1, "memBytes": 2147483648,
                  "memMaxBytes": 8589934592, "memoryPressure": 0.0, "state": "ok"}],
  "sampledEvery": 15, "publishEvery": 60,
  "forecast": {"disks": [{"mount": "/", "daysToFull": 6.4, "spanHours": 168, "fit": 0.93}], "weekPeakMemPct": 81.0,
               "weekPeakMemPressure": 3.0, "samples": 168}
}
```

A boundary's `memBytes` is memory in use, without inactive file cache. `memLimitedBy` is `cgroup` when the node runs in a container whose memory limit is below the host's. A boundary's
`kind` is `vm`, `lxc`, `container`, `pods`, `user`, `slice`, or `other` (past the 40 largest, the rest summed).
`cpuPct` of a boundary is its share of the whole machine. Read the newest with `fleetlayer readings capacity.host`.

`forecast` needs at least six hours of history before it names a disk, and lists only disks losing space; each
entry carries `spanHours` (the history it's fitted to) and `fit` (R², how well a line fits it).

## Moving it

Its state is the history in `state_dir`; `fleetlayer move` carries it. Without it, forecasts start again from
nothing, which costs a few hours of figures and nothing else.

## Monitoring

It reports its own status at least once a minute (`_fleetlayer.dev/plugin/status`). When six looks in a row fail, it
says it can't measure the machine and why; so it does when no look has finished for three intervals (a look stuck on
a file system, such as Proxmox's `/etc/pve`). Its status comes from a task of its own, so a stuck look can't silence
it. That shows on the node's status, the dashboard and wherever node problems alert. The Capacity tab marks a
machine's figures stale after three minutes without a reading (or twice `publish_every` and half a minute, when
that's longer), which catches a node that stopped publishing.

## Who sees it

A reading is visible where its node is: other nodes get it only if the access policy lets them read the machine's
node. Everyone signed in to the dashboard sees the Capacity tab, as they see the Machines tab. Besides numbers, a
reading names what runs on the machine (VM and container names, Unix user names) and its disks (mount points and
device names, which can hold a person's name, such as `/Volumes/Alex Backup`), nothing more.
