# Tailcove agent

The agent is one small program for a server. It follows your log files, the
systemd journal and, when you ask it to, Docker container logs and Kubernetes
pods, and reports CPU, memory, disk and network to your source. It is a single
static binary (Linux, and macOS for host metrics) with no dependencies, so there
is nothing to install around it.

## Install

On a Linux server with systemd, use your source's token:

```sh
curl -fsSL https://github.com/tailcove/agent/releases/latest/download/install.sh | \
  TAILCOVE_TOKEN=your-source-token TAILCOVE_LOG_PATHS=/var/log/nginx/*.log sh
```

The script checks the download against the release's SHA-256 sums, installs
`/usr/local/bin/tailcove-agent`, writes `/etc/tailcove-agent.json` and starts
a systemd service called `tailcove-agent`. Follow its output with
`journalctl -u tailcove-agent -f`.

Or install the package for your distribution from the
[release page](https://github.com/tailcove/agent/releases) (amd64 and arm64):

```sh
# Debian, Ubuntu
sudo apt install ./tailcove-agent_<version>_amd64.deb
# Fedora, RHEL and compatibles, openSUSE
sudo dnf install ./tailcove-agent-<version>-1.x86_64.rpm
```

Put your source token in `/etc/tailcove-agent.json` (the package wrote it from an
example, readable by root and the service only), then
`sudo systemctl enable --now tailcove-agent`. The package does not start a service
that has no token. It creates a `tailcove-agent` user in the `adm` and
`systemd-journal` groups (never `docker`). Upgrading keeps your configuration;
removing keeps it, and `apt purge` deletes it along with the saved positions.
The release lists the packages' checksums in `SHA256SUMS`.

With Docker:

```sh
docker run -d --name tailcove-agent --restart always \
  -e TAILCOVE_TOKEN=your-source-token \
  -e TAILCOVE_LOG_PATHS=/var/log/app/*.log \
  -v /var/log/app:/var/log/app:ro \
  ghcr.io/tailcove/agent
```

On a Mac, see [macOS](#macos) below for the launchd service.

> [!NOTE]
> There's no Windows build of the agent. On a Windows server, ship files with [Vector](https://tailcove.dev/docs/sending-logs/vector) or
> [Fluent Bit](https://tailcove.dev/docs/sending-logs/fluentbit), both of which run as Windows services, or send from your app with a
> [client library](https://tailcove.dev/docs/sending-logs/node). On a Windows machine with Docker Desktop, the Docker command above works
> for Linux containers.

## Configure

The agent reads a JSON file (`-config`, or `/etc/tailcove-agent.json`) and then
the environment:

```json
{
    "token": "YOUR_SOURCE_TOKEN",
    "logs": [
        { "path": "/var/log/nginx/*.log" },
        { "path": "/var/log/myapp/app.log", "from_beginning": false }
    ],
    "metrics": { "enabled": true, "interval_seconds": 30 },
    "heartbeat": { "enabled": true, "interval_seconds": 30 }
}
```

| Setting                      | Environment                                 | Default                       |
| ---------------------------- | ------------------------------------------- | ----------------------------- |
| `token`                      | `TAILCOVE_TOKEN`                            | required                      |
| `endpoint`                   | `TAILCOVE_ENDPOINT`                         | `https://ingest.tailcove.dev` |
| `host`                       | `TAILCOVE_HOST`                             | the machine's hostname        |
| `logs[].path`                | `TAILCOVE_LOG_PATHS` (comma separated)      | none                          |
| `metrics.enabled`            | `TAILCOVE_METRICS` (`true` or `false`)      | `true`                        |
| `metrics.interval_seconds`   | `TAILCOVE_METRICS_INTERVAL`                 | 30 (at least 10)              |
| `heartbeat.enabled`          | `TAILCOVE_HEARTBEAT` (`true` or `false`)    | `true`                        |
| `heartbeat.interval_seconds` | `TAILCOVE_HEARTBEAT_INTERVAL`               | 30 (at least 10)              |
| `journald.enabled`           | `TAILCOVE_JOURNALD` (`true` or `false`)     | `false`                       |
| `docker.enabled`             | `TAILCOVE_DOCKER` (`true` or `false`)       | `false`                       |
| `mask_secrets`               | `TAILCOVE_MASK_SECRETS` (`true` or `false`) | `true`                        |
| `secret_keys`                | `TAILCOVE_SECRET_KEYS` (comma separated)    | none                          |

Only `true`, `false`, `1` and `0` are accepted for a switch. A plain `http`
endpoint is refused unless it is on the same machine or you set
`"insecure": true`, because the token would travel in the clear.

`tailcove-agent check` validates the configuration and asks Tailcove whether the
token is accepted.

## Secret masking

Since v0.3.2 masking is on by default. Before a line leaves the machine, the agent replaces the value after a key that names a secret with `[redacted]` (`password=hunter2`, `"api_key": "..."`, `Authorization: Bearer ...`, `?token=...`), and credentials it knows by their shape with `[key]`: JWTs, AWS access key ids, Stripe secret and webhook keys, GitHub, Slack and Google API tokens, and whole private key blocks.

In a line that's a JSON object, a field whose name is a secret (`password`, `db_password`, `x-api-key`, `client_secret`, `cookies`) loses its whole value, even a nested object. `true`, `false` and `null` stay, so `"has_password": true` still reads right. Names like `max_tokens` or `password_changed_at` aren't touched.

Only the line itself is masked: the host, file name, journald unit and container details the agent adds are sent as they are. The rules are the ones Tailcove uses for [recommended masking](https://tailcove.dev/docs/transform-rules) on the server, so a line looks the same whichever side masked it.

```json
{
    "token": "YOUR_SOURCE_TOKEN",
    "logs": [{ "path": "/var/log/myapp/app.log" }],
    "secret_keys": ["customer_ssn", "iban"]
}
```

`secret_keys` adds your own field names, matched whole and ignoring case, `-`, `_`, `.` and spaces. `"mask_secrets": false` sends lines exactly as they're read, and the agent says so in its log when it starts. A line that can't be masked for any reason is sent as `[redacted: masking failed]`, never as it was.

## Logs

Every line appended to a followed file becomes a log line, with the host and
the file name in its context. A line that is already a JSON object is sent as it
is, so structured logs keep their fields (see the [HTTP API](https://tailcove.dev/docs/sending-logs/http-api)
for the names Tailcove reads).

- Files are followed through rotation and truncation, and a glob picks up files
  created later.
- Where each file got to is saved, so a restart neither repeats nor skips lines.
- A file that was already there when the agent first saw it is followed from
  its end; set `"from_beginning": true` to send what it already holds.
- Lines over 64 KB are cut and marked.
- `"multiline"` on an entry joins stack traces into one entry, as for
  [Kubernetes](#kubernetes); it is off for files unless set.

## Metrics

On Linux, every interval the agent reports the host's CPU usage, load, memory,
swap and uptime, and for each mount and network interface its disk and network
figures, all named `system.*`. They appear in the source's
[Metrics](https://tailcove.dev/docs/metrics/overview) tab.

Disk and network figures are the kernel's counters and gauges: chart a counter
with the `max` or `last` aggregate. Virtual interfaces (`lo`, `veth*`,
`docker*`, `br-*`, `cali*`, `flannel*`, `cni*`, `virbr*`) are left out by
default (`exclude_interfaces` replaces that list), and `exclude_mounts` leaves
mounts out. Every distinct mount and interface is a series that counts toward your
plan's [series limit](https://tailcove.dev/docs/metrics/overview#limits).

## Heartbeat

Every interval the agent also sends one point, `system.agent.up` with the value 1
and the host name, and the first one the moment it starts. It is sent whether or
not host metrics are on and whether or not a log line arrives, so a host or agent
that stopped can be told from one that is only quiet. Switch it off with
`"heartbeat": {"enabled": false}` or `TAILCOVE_HEARTBEAT=false`.

The source's **Overview** lists each host with **Beating** or **Quiet** (a host
that has missed three minutes) and when it last beat. Beside each is **Alert if it
goes quiet**, which opens a new alert filled in as a [no-data metric alert](https://tailcove.dev/docs/alerts#no-data-alerts)
on `system.agent.up` for that host with a three-minute window, so you choose the
channels and save it. A host that has not beaten for a day is no longer listed.

The heartbeat is one series per host and counts toward your plan's
[series limit](https://tailcove.dev/docs/metrics/overview#limits).

## Delivery

Batches go out as soon as 500 lines are waiting or a second has passed.
Failures are retried with growing, jittered waits, and a `429` or `503` waits at
least as long as `Retry-After` says. A batch Tailcove refuses for what it holds
is dropped with a log line. While Tailcove is unreachable the agent stops reading
further instead of losing lines: the files stay where they are.

## Journald

On a machine with systemd, `"journald": {"enabled": true}` (or
`TAILCOVE_JOURNALD=true`) follows the journal, which is where most services that do
not write a file log to. The agent runs `journalctl`, which is read-only and
already on the machine, so there is no library to install.

```json
{
    "journald": {
        "enabled": true,
        "units": ["nginx.service", "sshd*"],
        "min_priority": "info"
    }
}
```

Each entry is a log line with its time and host, a `level` from the syslog priority
(`emergency` to `debug`), and a `journald` context (`unit`, `identifier`, `pid`,
`command`, `transport`). `units` limits it to those systemd units (globs allowed),
`min_priority` leaves out what is less important (`warning` sends warnings and
worse), `directory` reads another directory's journal files, and `from_beginning`
reads the whole journal the first time (otherwise only what is written from then
on). A message over 64 KB is cut. The journal's cursor is saved, so a restart
continues after the last delivered entry and a line is never lost, only (after a
crash) possibly sent twice. The service user must be allowed to read the journal:
the packages add it to `systemd-journal`, and `install.sh` leaves that to you.

## Docker

`"docker": {"enabled": true}` (or `TAILCOVE_DOCKER=true`) follows the logs of every
running container through the engine's socket, `/var/run/docker.sock`
(`TAILCOVE_DOCKER_SOCKET` for another).

**Access to that socket is root-equivalent for whoever can write to it**: anyone who
can talk to the Docker engine can start a container that mounts the whole host. That
is why this is off unless you turn it on, and why the packages never add the agent's
user to the `docker` group. The agent itself only lists the containers, inspects
one, and reads its logs; it never starts, stops, creates or executes anything, and
refuses a container id that is not a hexadecimal id. To allow it, add the service
user to the `docker` group on purpose (`usermod -aG docker tailcove-agent`), or run
the agent as a container with the socket mounted read-only (`-v
/var/run/docker.sock:/var/run/docker.sock:ro`; a read-only mount of a socket does not
restrict what is asked of it, so this is not a safeguard in itself).

```json
{
    "docker": {
        "enabled": true,
        "host": "service",
        "exclude": ["tailcove-agent"],
        "labels": ["team"]
    }
}
```

An entry has the container's name, image and Compose project and service in a
`docker` context, and `stream` (`stdout` or `stderr`). Its `host` is the container
by default; `"host": "host"` makes it the machine, and `"service"` the Compose
service. `include` and `exclude` are globs on container names, `labels` names
container labels to keep, `max_containers` bounds how many are followed (200), and
`from_beginning` reads a container's whole log the first time it is seen. A line that
is already a JSON object is sent as it is, with the host, a time and the context
added. Stack traces are joined into one entry (`multiline`, as for
[Kubernetes](#kubernetes)). Each container's position is saved, so a restart
continues after the last delivered line, and a container that is gone for good
loses its saved position.

## macOS

Release binaries for macOS (Intel and Apple silicon) follow files and report host
metrics with the same names as on Linux, read by running macOS's own `top`,
`sysctl`, `vm_stat`, `netstat` and `mount`. journald and Docker are Linux features.
To run it as a service, put the binary, a config with your token and a launchd definition in place, then load it:

```sh
sudo install -m 0755 tailcove-agent /usr/local/bin/tailcove-agent
sudo install -m 0600 tailcove-agent.json /usr/local/etc/tailcove-agent.json   # your token goes in it
sudo mkdir -p /usr/local/var/lib/tailcove-agent /usr/local/var/log
sudo tee /Library/LaunchDaemons/com.tailcove.agent.plist >/dev/null <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key><string>com.tailcove.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/tailcove-agent</string>
        <string>-config</string><string>/usr/local/etc/tailcove-agent.json</string>
        <string>run</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict><key>TAILCOVE_STATE_FILE</key><string>/usr/local/var/lib/tailcove-agent/state.json</string></dict>
    <key>RunAtLoad</key><true/>
    <key>KeepAlive</key><true/>
    <key>ThrottleInterval</key><integer>5</integer>
    <key>StandardErrorPath</key><string>/usr/local/var/log/tailcove-agent.log</string>
    <key>StandardOutPath</key><string>/usr/local/var/log/tailcove-agent.log</string>
</dict>
</plist>
PLIST
sudo launchctl bootstrap system /Library/LaunchDaemons/com.tailcove.agent.plist
```

Its own messages go to `/usr/local/var/log/tailcove-agent.log`. Stop it with
`sudo launchctl bootout system/com.tailcove.agent`.

## Kubernetes

Run the agent as a DaemonSet and it follows every pod on its node: the logs the
kubelet writes under `/var/log/pods`, and the CPU and memory of every container
and pod from the node's cgroups. Install it with three commands:

```sh
kubectl create namespace tailcove
kubectl -n tailcove create secret generic tailcove-agent --from-literal=token=YOUR_SOURCE_TOKEN
kubectl apply -f https://tailcove.dev/agent/tailcove-agent.yaml
```

The manifest makes a ServiceAccount that may only read pods (to name each log line's pod and namespace), and a
DaemonSet that runs one unprivileged agent per node with the host paths mounted read-only. To change its resources
or tolerations, download it first and edit it before applying.

Every line carries where it came from, in its context:
`context.kubernetes` holds the `namespace`, `pod`, `container`, `node`, the
workload that owns the pod (a Deployment, StatefulSet, DaemonSet or Job) and the
pod labels you keep. A line's `host` is the pod by default; `host` can instead be
`node`, `workload` or `label:<key>`. A line that is already a JSON object is sent
as it is, with the host, a time and the context added.

```json
{
    "kubernetes": {
        "enabled": true,
        "host": "workload",
        "labels": ["app", "team"],
        "exclude_namespaces": ["kube-system"],
        "routes": [
            { "namespace": "billing", "token": "SOURCE_TOKEN_OF_BILLING" }
        ],
        "multiline": { "mode": "auto" },
        "metrics": { "enabled": true, "max_series": 500 }
    }
}
```

| Setting                                                | Environment                                                 | Default                                                   |
| ------------------------------------------------------ | ----------------------------------------------------------- | --------------------------------------------------------- |
| `kubernetes.enabled`                                   | `TAILCOVE_KUBERNETES` (`true` or `false`)                   | `false`                                                   |
| `kubernetes.node_name`                                 | `NODE_NAME`, `TAILCOVE_NODE_NAME`                           | the downward API                                          |
| `kubernetes.host`                                      | `TAILCOVE_K8S_HOST`                                         | `pod`                                                     |
| `kubernetes.labels`                                    | `TAILCOVE_K8S_LABELS` (comma separated)                     | `app`, `app.kubernetes.io/name`, `/component`, `/version` |
| `kubernetes.include_namespaces` / `exclude_namespaces` | `TAILCOVE_K8S_INCLUDE_NAMESPACES`, `..._EXCLUDE_NAMESPACES` | all                                                       |
| `kubernetes.exclude_pods` / `exclude_containers`       | `TAILCOVE_K8S_EXCLUDE_PODS`, `..._EXCLUDE_CONTAINERS`       | none                                                      |
| `kubernetes.from_beginning`                            | `TAILCOVE_K8S_FROM_BEGINNING`                               | `false`                                                   |
| `kubernetes.api`                                       |                                                             | `true`                                                    |
| `kubernetes.metrics.max_series`                        |                                                             | 500                                                       |

**Routes** send the pods they match (a namespace glob, labels, or both) to another
source, with that source's own token, so one team's logs can land in its own source.
Each routed source has its own queue: if its token is refused, its lines are dropped
with one log line and read again after a restart, and every other source keeps going.

**Labels and owners** come from the Kubernetes API, read-only: the agent's
ServiceAccount may get, list and watch pods and nothing else (never secrets). Without
it (`api: false`, or no ServiceAccount) lines carry what the file's path says: the
namespace, pod and container.

**Stack traces** are joined into one entry. `auto` glues indented lines and the
usual trace lines (`Caused by:`, `... 12 more`, PHP `#3` frames, a Python
`Traceback`) to the event before them, and a line that starts with `{` always begins
a new event; `pattern` takes a regular expression that begins an event; `off` sends
every line. An event is cut at 200 lines or 64 KiB, or sent after a second without a
further line. The runtime splits a very long line into pieces; the agent joins them
back.

**Container and pod metrics** are `container.cpu.usage_cores`,
`container.cpu.usage_seconds_total`, `container.cpu.throttled_seconds_total`,
`container.cpu.limit_cores`, `container.memory.working_set_bytes`,
`container.memory.usage_bytes`, `container.memory.limit_bytes`,
`container.memory.oom_kills_total`, and per pod `pod.cpu.usage_cores` and
`pod.memory.working_set_bytes`, labelled with the namespace, pod and container. They
read cgroup v2 and v1. Every distinct container is a series that counts toward your
plan's [series limit](https://tailcove.dev/docs/metrics/overview#limits): `max_series` keeps one reading
to that many points, pods first.

A pod that restarts starts a new log file, which is followed from its beginning; a
rotated file is finished and the new one picked up; a deleted pod's saved position is
forgotten. Delivery is at least once: after the agent restarts, a line may be sent
twice, never lost. The agent runs as root on the node because the kubelet writes the
logs as root, with every capability dropped, a read-only root filesystem and read-only
mounts of the log, cgroup and `/proc` directories (the state file is the one writable
path).

## What the agent does not do

It does not collect process or application metrics, and it does not read the logs of Podman or containerd directly
(Podman's Docker-compatible socket works with `TAILCOVE_DOCKER_SOCKET`; Kubernetes nodes use the pod logs). It does not instrument your code either: for application traces
and metrics without changing code, see
[OpenTelemetry auto-instrumentation](https://tailcove.dev/docs/opentelemetry/auto-instrumentation). For the rest use [Vector](https://tailcove.dev/docs/sending-logs/vector) or
[Fluent Bit](https://tailcove.dev/docs/sending-logs/fluentbit), or an OpenTelemetry SDK for
[traces and application telemetry](https://tailcove.dev/docs/opentelemetry/overview).

## Probe mode

The same program can act as a **probe**: a host in one region that runs your monitors' HTTP and TCP checks from there, so a
monitor can be checked from several places (see [Monitors](https://tailcove.dev/docs/monitors)). A probe needs a probe token, which starts with
`tcp_`, and which whoever runs your Tailcove creates; a source token does not work.

```sh
TAILCOVE_TOKEN=tcp_your-probe-token tailcove-agent probe
```

It pulls the checks due for its region every few seconds, runs them, and posts the results. It follows no log files and sends no
host metrics. It refuses to connect to private, loopback, link-local and other non-public addresses at the moment of connecting,
and sends a monitor's headers and body only to the host the monitor names. To keep it running on a Linux server, create a user for it and a systemd unit:

```sh
sudo useradd --system --no-create-home --shell /usr/sbin/nologin tailcove-probe
sudo tee /etc/systemd/system/tailcove-probe.service >/dev/null <<'UNIT'
[Unit]
Description=Tailcove probe
After=network-online.target
Wants=network-online.target

[Service]
Environment=TAILCOVE_TOKEN=tcp_your-probe-token
ExecStart=/usr/local/bin/tailcove-agent probe
Restart=always
RestartSec=5
User=tailcove-probe
Group=tailcove-probe
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
PrivateTmp=true

[Install]
WantedBy=multi-user.target
UNIT
sudo systemctl daemon-reload
sudo systemctl enable --now tailcove-probe
```

`journalctl -u tailcove-probe -f` shows what it is doing.
