# Node agent reference

The node agent, `kite-agent`, runs on each node in place of kubelet,
kube-proxy, the network add-on and CoreDNS. For procedures, see
[Manage nodes](/docs/manage-nodes/).

## WireGuard settings

Pass these to `kite-agent join`, which records them in `/etc/kite/node.env`.

| Join option                 | Environment                    | Sets                                                                              | Default                                                                                 |
| --------------------------- | ------------------------------ | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `--network-endpoint`        | `KITE_NETWORK_ENDPOINT`        | The address and port that other nodes connect to, as `IPv4:port` or `[IPv6]:port` | The default route's source address, with the port                                       |
| `--network-public-endpoint` | `KITE_NETWORK_PUBLIC_ENDPOINT` | The public address, or address and port, that nodes in other networks connect to  | None. A node pool machine reads its public address from the provider's metadata server. |
| `--network-port`            | `KITE_NETWORK_PORT`            | The UDP port `kitewg0` listens on                                                 | `51820`                                                                                 |
| `--network-mtu`             | `KITE_NETWORK_MTU`             | The MTU of `kitewg0` and of pod interfaces                                        | Default-route link MTU minus 80 bytes                                                   |
| `--network-key-file`        | `KITE_NETWORK_KEY_FILE`        | Absolute path of the private key                                                  | See [Private key file](#private-key-file)                                               |

### MTU

Lower the MTU when the network between your nodes adds its own encapsulation on
top of WireGuard's 80 bytes. The minimum is 576 for an IPv4 pod network and
1280 for IPv6.

### Kernels without WireGuard

On a kernel built without WireGuard, such as the kernel of a Kata Containers
VM, the agent runs `kitewg0` itself, as a userspace WireGuard device.
`wg show kitewg0` works on this device as it does on a kernel device.
To use a userspace device on any kernel, set
`KITE_NETWORK_WIREGUARD=userspace` in `/etc/kite/node.env`.

A userspace `kitewg0` stops when the agent stops, so pods on this node cannot
connect to pods on other nodes while the agent restarts.

When the agent creates a userspace device, it logs `wireguard in userspace`
with the reason. Each node also has a `NodeNetworkStatus` object, which the
control plane writes with the node's network state. Its `status.wireguard`
field shows which kind of device the node uses:

```bash
kubectl get nodenetworkstatus <node> -o jsonpath='{.status.wireguard}'
```

### Private key file

The default key path is
`/var/lib/kite/wireguard/<cluster-hash>/<node-hash>.key`. A `.scope` file next
to the key records the cluster and the node that the key belongs to. The agent
rejects a key whose scope file names another cluster or node.

:::caution
A key file you supply, and its scope file, must be regular files owned by root
with no group or other access. Their directory must be owned by root and not
writable by group or others.
:::

## Identity document source

A GCE or EC2 machine that a node pool creates passes these variables to
`kite-agent join`. When the first two are set, the agent reads an identity
document from the provider's metadata server for each join, and joins with it.
It does not use `KITE_BOOTSTRAP_TOKEN`.

| Environment                        | Sets                                                          |
| ---------------------------------- | ------------------------------------------------------------- |
| `KITE_BOOTSTRAP_DOCUMENT_URL`      | The metadata server's identity endpoint                       |
| `KITE_BOOTSTRAP_DOCUMENT_AUDIENCE` | The audience in the document: the cluster's address           |
| `KITE_BOOTSTRAP_DOCUMENT_STS`      | On EC2, the STS endpoint the cluster sends the signed join to |

When you run `kite-agent join` again with the same cluster address, it keeps
the saved values. With a new cluster address, it drops them. `kite-agent join`
refuses `KITE_BOOTSTRAP_DOCUMENT_URL` without `KITE_BOOTSTRAP_DOCUMENT_AUDIENCE`,
and it refuses `KITE_BOOTSTRAP_DOCUMENT_STS` without both.

## Cluster certificate

The agent trusts Mozilla's root certificates when it dials the cluster. For a
cluster whose certificate another authority signed, pass one of these to
`kite-agent join`, which records it in `/etc/kite/node.env`. A join with a new
cluster address drops it unless you pass it again.

| Environment                      | Sets                                                                                                                    |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `NODE_EXTRA_CA_CERTS`            | A PEM file of certificates that the agent trusts beside Mozilla's roots. The agent logs and skips a file it cannot read |
| `NODE_TLS_REJECT_UNAUTHORIZED=0` | Turns off the check of the cluster's certificate, for a development cluster that signs its own                          |

## Registry mirror

The agent runs a registry mirror on the node's loopback address, and containerd
reads image blobs through it. containerd uses the mirror only when its CRI
plugin pulls images itself: `use_local_image_pull = true` in
`/etc/containerd/config.toml` turns that on. Node pool machines have it set.
The agent logs `registry mirror on` when containerd will use the mirror, and
`registry mirror off: containerd would not read it` when it will not.

| Environment               | Sets                                                        | Default           |
| ------------------------- | ----------------------------------------------------------- | ----------------- |
| `KITE_REGISTRY_MIRROR`    | The loopback address the mirror listens on, or `off`        | `127.0.0.1:10265` |
| `KITE_REGISTRY_UPSTREAMS` | For each registry, a copy of it that the mirror reads first | None              |

Set them in `/etc/kite/node.env` and restart the agent.

- The mirror fetches each blob from its registry over several connections. It
  replaces a connection that delivers less than 1 MiB/s for five seconds, so one
  slow path does not stall a pull.
- The agent writes the mirror's address to
  `/etc/containerd/certs.d/_default/hosts.toml`. containerd reads that file for
  every registry that has no `certs.d` directory of its own.
- containerd still resolves tags at the registry. When the mirror refuses a
  read, containerd pulls from the registry directly.
- With `off`, the agent removes the `hosts.toml` it wrote. It never changes a
  `_default/hosts.toml` it did not write.

### Pull from a copy of a registry

To pull a registry's images from a copy of it, such as Docker Hub's from
Google's `mirror.gcr.io`, name the copy in `KITE_REGISTRY_UPSTREAMS`. Each
entry is `<registry>=<origin>`, and a comma separates entries:

```sh
KITE_REGISTRY_UPSTREAMS=docker.io=https://mirror.gcr.io
```

The mirror reads each blob and manifest from the copy first, without the pod's
credential. It reads from the registry, with the credential, when the copy
answers with anything but success or sends no response within 15 seconds. The
agent logs the copies it uses in its `registry mirror on` line.

:::caution
Do not also give that registry a `certs.d` directory of its own: containerd
then reads that directory, and the registry's pulls skip the mirror.
:::

## Machine shutdown

When the host shuts down or reboots, the agent stops the node's pods before it
lets the shutdown continue.
[When a node disconnects](/docs/nodes/#when-a-node-disconnects) says what
happens to each pod.

| Join option                             | Environment                                | Sets                                                                                                     | Default                                     |
| --------------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| `--shutdown-grace-period`               | `KITE_SHUTDOWN_GRACE_PERIOD`               | How long the agent stops pods for, in whole seconds such as `30s`. `0s` leaves the pods to the shutdown. | `30s`                                       |
| `--shutdown-grace-period-critical-pods` | `KITE_SHUTDOWN_GRACE_PERIOD_CRITICAL_PODS` | The last part of that time, for pods at `system-cluster-critical` priority or above                      | `10s`, or the whole period if it is shorter |

systemd-logind waits 5 seconds for the agent by default. At start, the agent
writes `/etc/systemd/logind.conf.d/zz-kite-agent.conf`, which raises logind's
`InhibitDelayMaxSec` to the grace period plus 2 seconds for telling the
control plane, and has logind read it. If logind keeps a shorter delay, the
agent shortens the grace period to fit, and logs
`logind holds a shutdown for less than the grace period`.

## Files and devices on the host

| Path or device                                  | What it is                                                                                      |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `kite-agent.service`                            | The systemd unit that runs the agent                                                            |
| `/opt/kite`                                     | The agent's files                                                                               |
| `/etc/kite/node.env`                            | The settings that `kite-agent join` records                                                     |
| `/etc/systemd/logind.conf.d/zz-kite-agent.conf` | Makes logind wait for the agent at a shutdown. See [Machine shutdown](#machine-shutdown)        |
| `/etc/cni/net.d/10-kite.conflist`               | The CNI configuration                                                                           |
| `/etc/containerd/certs.d/_default/hosts.toml`   | Points containerd at the registry mirror                                                        |
| `/var/lib/kite/nodes`                           | The node's credential for each cluster it joined                                                |
| `/var/lib/kite/wireguard`                       | The node's WireGuard keys                                                                       |
| `/var/lib/kite/volumes`                         | Local volumes that the control plane provisions                                                 |
| `/var/lib/kite/pods`                            | Pod and volume directories                                                                      |
| `/var/lib/kite/telemetry`                       | How far the agent has sent each log                                                             |
| `/var/log/kite/pods`                            | Container logs                                                                                  |
| `cni0`                                          | The pod bridge                                                                                  |
| `kitewg0`                                       | The WireGuard device                                                                            |
| `/var/lib/kite/services.nft`                    | The last nftables change the agent loaded                                                       |
| The `kite` nftables table                       | Service and NetworkPolicy rules. `nft list table ip kite` shows them, or `ip6` on an IPv6 node. |

## Update annotations

Each Node has these annotations. Two of them appear as columns in
`kubectl get nodes -o wide`, and each column shows the first 12 characters of
the digest. The `UPDATE` column shows the reason from the Node's `AgentUpdate`
condition.

| Annotation                                | Value                                           | Column    |
| ----------------------------------------- | ----------------------------------------------- | --------- |
| `kiteplane.dev/agent-digest`              | Digest of the running agent                     | `AGENT`   |
| `kiteplane.dev/desired-agent-digest`      | Digest of the agent the control plane serves    | `DESIRED` |
| `kiteplane.dev/settings-revision`         | Settings revision that the running agent loaded | —         |
| `kiteplane.dev/desired-settings-revision` | Settings revision that the control plane serves | —         |

Kite sets these four, and ignores a value that you write for one of them. It
keeps the other annotations that you write on a Node.

## Agent telemetry

When the control plane sets `KITE_TELEMETRY_URL`, each agent posts OTLP/JSON
logs, traces and metrics to `<url>/logs`, `<url>/traces` and `<url>/metrics`.
[Send node telemetry](/docs/configure/#send-node-telemetry) shows how to set the URL.

| Variable                        | Sets                                                                                                                                                                                                                                                                                                   | Default  |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- |
| `KITE_TELEMETRY_UTILIZATION_MS` | How often the agent samples usage                                                                                                                                                                                                                                                                      | 60000 ms |
| `KITE_TELEMETRY_INTERVAL_MS`    | How often the agent reads logs and checks the queues                                                                                                                                                                                                                                                   | 10000 ms |
| `KITE_TELEMETRY_MAX_WAIT_MS`    | How long a row waits before the agent posts its stream. The agent keeps a queue of rows, such as log lines, for each stream, and posts it when it holds a full 1 MiB batch or its oldest row has waited this long. So a busy node sends fewer, larger batches, and a row arrives within about a minute | 40000 ms |

The fields below describe the agent itself. Each metric has the resource
attribute `k8s.node.name`. To get a metric's name from a field, replace `_`
with `.`, drop a trailing `_total`, and add `kite.agent.`:
`cpu_user_seconds_total` becomes `kite.agent.cpu.user.seconds`. Fields ending
in `_total` are counters, and the rest are gauges.

### Process fields

Counters reset when the agent restarts, so group them by node and by
`process_start_time_seconds`.

| Fields                                                                | Measurement                                                |
| --------------------------------------------------------------------- | ---------------------------------------------------------- |
| `memory_rss_bytes`                                                    | Resident process memory                                    |
| `cpu_user_seconds_total`, `cpu_system_seconds_total`                  | Process CPU time since startup                             |
| `event_loop_utilization`                                              | Fraction of wall time worker threads were busy             |
| `event_loop_delay_{p50,p99,max}_ms`                                   | How late a task that wakes every 100 ms woke               |
| `process_start_time_seconds`, `process_uptime_seconds`, `process_pid` | When the process started, how long it has run, and its PID |

### Exporter fields

Each `telemetry_<stream>_*` field describes one of the `logs`, `traces` and
`metrics` streams:

| Field suffix          | Measurement                                    |
| --------------------- | ---------------------------------------------- |
| `queue_rows`          | Rows waiting to be posted                      |
| `queue_bytes`         | Bytes waiting to be posted                     |
| `oldest_age_seconds`  | Age of the oldest waiting row                  |
| `dropped_rows_total`  | Rows dropped because the queue was full        |
| `refused_rows_total`  | Rows in batches the receiver refused           |
| `requests_total`      | HTTP requests attempted                        |
| `failures_total`      | HTTP requests that did not return a 2xx status |
| `payload_bytes_total` | Request-body bytes attempted                   |

These fields count all three streams together:

| Field                         | Measurement                            |
| ----------------------------- | -------------------------------------- |
| `telemetry_queue_bytes`       | Bytes waiting across all three streams |
| `telemetry_log_tails`         | Log files the exporter reads           |
| `telemetry_log_partial_bytes` | Bytes of log lines not yet finished    |
| `telemetry_assigned_pods`     | Pods whose logs the exporter follows   |
| `telemetry_leaving_pods`      | Pods whose logs it is finishing        |

### Control connection fields

Each `control_*` field describes the agent's connection to the control plane.
While the agent is disconnected, the gauges read 0, except
`control_pending_request_handlers`, which keeps counting requests in progress.

| Field                                                                                   | Measurement                                          |
| --------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| `control_connected`                                                                     | 1 while the connection is open, 0 otherwise          |
| `control_connection_attempts_total`                                                     | Connection attempts                                  |
| `control_reconnections_total`                                                           | Attempts after the first                             |
| `control_buffered_bytes`                                                                | Bytes queued on the socket and not yet sent          |
| `control_pending_request_handlers`                                                      | Requests from the control plane still being handled  |
| `control_active_follows`                                                                | Log streams the agent is following                   |
| `control_active_exec_streams`                                                           | Open exec streams                                    |
| `control_active_forward_streams`                                                        | Open port-forward streams                            |
| `control_assigned_pods`                                                                 | Pods assigned to the node                            |
| `control_assigned_service_routes`                                                       | Service route entries, one per port                  |
| `control_assigned_service_backends`                                                     | Backend references across those routes               |
| `control_assigned_peers`                                                                | WireGuard peers in the node's peer map               |
| `control_sent_messages_<type>_total`, `control_sent_payload_bytes_<type>_total`         | Messages and payload bytes sent, by message type     |
| `control_received_messages_<type>_total`, `control_received_payload_bytes_<type>_total` | Messages and payload bytes received, by message type |

### Node, pod and container metrics

Each agent also posts usage for its node, its pods and their containers, with
the metric names from OpenTelemetry's semantic conventions.

#### Node

- **CPU and memory:** `k8s.node.cpu.usage`, `k8s.node.cpu.count`,
  `k8s.node.memory.usage`, `k8s.node.memory.capacity`,
  `k8s.node.memory.utilization`, `system.cpu.load_average.1m`.
- **Disk:** `k8s.node.ephemeral_storage.capacity`,
  `k8s.node.filesystem.capacity`, `k8s.node.filesystem.usage`,
  `k8s.node.filesystem.utilization`.
- **Network:** `k8s.node.network.io`, `k8s.node.network.errors`,
  `k8s.node.network.dropped`.
- **Pods:** `k8s.node.pod.count`.
- **Pressure**, from Linux pressure stall information:
  `kite.pressure.cpu.some`, `kite.pressure.memory.some`,
  `kite.pressure.memory.full`, `kite.pressure.io.some`, `kite.pressure.io.full`.
- **Traffic by path:** `kite.node.network.bytes`, `kite.node.network.untracked`,
  `kite.node.network.map.bytes`. See [Pod traffic by path](#pod-traffic-by-path).
- **The agent itself:** `kite.agent.memory.usage`, the memory of the agent's
  own cgroup.

#### Pod

- **CPU and memory:** `k8s.pod.cpu.usage`, `k8s.pod.memory.usage`,
  `k8s.pod.process.count`.
- **Memory limit:** `k8s.pod.memory_limit_utilization`. Memory usage over the memory limit, as a ratio, so a rule can alert at 90% of a limit. Sent only for a pod with a memory limit: its `spec.resources`, or the sum of its containers' limits when each sets one, without the RuntimeClass's overhead. A SandboxPool's reservation Pod counts the memory of the sandboxes under it, against its pool's `spec.reservation`.
- **Disk:** `k8s.pod.filesystem.usage`.
- **Network:** `k8s.pod.network.io`, `k8s.pod.network.errors`,
  `k8s.pod.network.dropped`, and `kite.pod.network.bytes` by path. See
  [Pod traffic by path](#pod-traffic-by-path).

#### Container

- **CPU and memory:** `k8s.container.cpu.usage`, `k8s.container.memory.usage`.
- **Memory limit:** `k8s.container.memory_limit_utilization`. Memory usage over
  the memory limit, as a ratio. Sent only for a container that has a memory
  limit.
- **Requests and limits:** `k8s.container.cpu.request.current`,
  `k8s.container.cpu.limit.current`, `k8s.container.memory.request.current`,
  `k8s.container.memory.limit.current`.
- **State:** `k8s.container.restarts`, `k8s.container.ready`.
- **Disk:** `k8s.container.filesystem.usage`.

#### Timing

Each is a histogram in seconds.

| Metric                           | Measures                                                                                                                  | Buckets                             | Each point covers               |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | ------------------------------- |
| `kite.cri.call.duration`         | Calls, by `rpc.method`                                                                                                    | 0.1 ms to 10 s                      | A minute of calls               |
| `kite.socket.heartbeat.duration` | From a heartbeat to the control plane's acknowledgement                                                                   | 0.1 ms to 10 s                      | A minute of calls               |
| `kite.pod.start.duration`        | From when the node first receives a pod to when all its containers have started                                           | The kubelet's, from 0.5 s to 1 hour | The starts since the last point |
| `kite.pod.start.sli.duration`    | The same time less the image pulls the pod waited on and its init containers' runtime, for a pod with no PersistentVolume | The kubelet's, from 0.5 s to 1 hour | The starts since the last point |

#### Attributes on every metric

| Attribute                                                                           | On                                                                    | From                                                                              |
| ----------------------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `k8s.node.name`                                                                     | Every metric                                                          | The node                                                                          |
| `k8s.namespace.name`, `k8s.pod.name`, `k8s.pod.uid`                                 | Pod and container metrics                                             | The pod                                                                           |
| `k8s.container.name`                                                                | Container metrics                                                     | The container                                                                     |
| `k8s.pod.label.<key>`, such as `k8s.pod.label.app`                                  | Pod and container metrics, a pod's log lines and OTLP telemetry       | Each of the pod's labels                                                          |
| `k8s.replicaset.name`, `k8s.job.name`, `k8s.statefulset.name`, `k8s.daemonset.name` | A pod's metrics, log lines and OTLP telemetry                         | The owner reference that sets `controller`. A controller of another kind has none |
| `cloud.provider`                                                                    | Node, pod and container metrics, a pod's log lines and OTLP telemetry | The node label `kiteplane.dev/provider`                                           |
| `cloud.region`                                                                      | The same                                                              | The node label `topology.kubernetes.io/region`                                    |
| `cloud.availability_zone`                                                           | The same                                                              | The node label `topology.kubernetes.io/zone`                                      |
| `kite.node.pool`                                                                    | The same                                                              | The node label `kiteplane.dev/nodepool`                                           |

A node without one of the labels leaves its attribute out. The pod's OTLP
telemetry is what the pod sends to the node's OTLP endpoint. On it, the agent
sets the pod's labels from the Pod object, and the location attributes, and
drops any value for them that the pod set itself.

### Pod traffic by path

:::note
The node counts pod traffic with a BPF program on Linux 6.4 or later. On an
older kernel it logs `pod traffic is not counted` and sends none of these
metrics.
:::

`kite.pod.network.bytes` counts the bytes a pod sends to and receives from
anything off its node, by the path they take. A cloud bills a byte by that
path, so you can see which pods send the bytes that cost money. Each point has
these attributes:

| Attribute              | Values                                                                                                                                                                                                                              |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `network.io.direction` | `transmit` or `receive`                                                                                                                                                                                                             |
| `network.path`         | See the next table                                                                                                                                                                                                                  |
| `network.peer.node`    | For a pod on another node: that node, for the pod's 10 peer nodes with the most bytes, and `other` for the rest                                                                                                                     |
| `network.peer.name`    | For an address outside the cluster: the name that the pod asked the node's DNS forwarder for, for the pod's 10 names with the most bytes, `other` for the rest, and `unnamed` for an address that the pod reached without asking it |

| `network.path`  | When                                                                                                                                                                       |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `zone`          | A pod on another node in the same zone                                                                                                                                     |
| `cross-zone`    | A pod on another node in another zone                                                                                                                                      |
| `cross-region`  | A pod on another node in another region, or an address in the node's cloud's ranges for another region                                                                     |
| `cross-cloud`   | A pod on another node in another cloud                                                                                                                                     |
| `cluster`       | A pod on another node, when either node lacks a `kiteplane.dev/provider`, `topology.kubernetes.io/region` or `topology.kubernetes.io/zone` label that the comparison needs |
| `cloud-service` | An address in the ranges that the node's cloud publishes for its region, or for a service with no region                                                                   |
| `internet`      | Any other address                                                                                                                                                          |

The node loads its cloud's published ranges when it starts and each day after:

| Cloud        | Files                        |
| ------------ | ---------------------------- |
| AWS          | `ip-ranges.json`             |
| Google Cloud | `goog.json` and `cloud.json` |

A node has no `cloud-service` traffic, and counts those addresses as
`internet`, when it:

- runs on another provider
- lacks the `kiteplane.dev/provider` and `topology.kubernetes.io/region` labels
- has no route to the files, or cannot load them. It logs
  `cloud ranges not loaded` with the reason.

How the node counts:

- A name is the one the pod asked for, before any CNAME. When two names answer
  with one address, as behind a CDN, the pod's latest question wins.
- A name stays with a connection for as long as the node counts it, past the
  record's TTL.
- The node names a connection when it first reads it, every telemetry
  interval. So bytes that a pod sent to an address just before asking for its
  name can count under the name.
- A Service's traffic counts under the path to the backend that served it.
- A pod with no traffic for an hour starts its totals again.
- A `hostNetwork` pod's traffic counts as the node's own, because it has the
  node's address.

#### Node totals

| Metric                        | What it counts                                                                                                                 |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `kite.node.network.bytes`     | The node's bytes on the wire, by `network.io.direction`, `network.path` and `network.peer.node`                                |
| `kite.network.share`          | The node's bytes, split into `pods` and `node`. The two add up to what the cloud sees                                          |
| `kite.node.network.untracked` | The bytes the node counted but could not keep by pod and peer, because more than 65,536 pod and peer pairs were active at once |
| `kite.node.network.map.bytes` | The kernel memory that the BPF program takes. `kite.agent.memory.usage` includes it                                            |

How `kite.network.share` splits the bytes:

- Pods' traffic to another node goes through WireGuard, so the node's bytes
  with that node are WireGuard's packets, with their encryption. The pods'
  share of those bytes is the pods' part of what entered the tunnel.
- Off the cluster, the pods' share is their bytes, and the node's share is its
  own traffic, such as the control plane's connection, telemetry and image
  pulls.
- A packet that the kernel handles as one large segment counts its headers
  once.
