Merge branch 'nix'
All checks were successful
nixos / nixos (push) Successful in 1m38s

asxpio-services runs NixOS since 2026-11-17 and is deployed from here by
.forgejo/workflows/nixos.yaml from now on. asxpio-ops still runs Debian:
Ansible keeps deploying it, and the NixOS workflow skips it until its
conversion (MIGRATION.md).

Assisted-by: Claude:opus-5-5
This commit is contained in:
Sergei Poljanski 2026-11-17 07:29:19 +04:00
commit 347c6542f9
Signed by: asxpi
GPG key ID: 4F8851660FA4121B
71 changed files with 34397 additions and 386 deletions

View file

@ -0,0 +1,90 @@
name: nixos
# Every push: evaluate every host, so a broken config never reaches main.
# main: build and switch each production host that already runs NixOS.
# A host still on Debian is skipped (it is checked for /etc/NIXOS first),
# so this job cannot touch a server before its conversion.
#
# Secret: SSH_DEPLOY_KEY (user deploy). Service secrets are decrypted on
# the hosts by sops-nix; CI holds none of them.
#
# Switching asxpio-services can restart the runner that runs this job:
# the change lands, the job shows as cancelled, the next run confirms.
run-name: "${{ github.ref == 'refs/heads/main' && 'deploy' || 'evaluate' }}: ${{ github.ref_name }}"
on:
push:
paths:
- 'nixos/**'
- '.forgejo/workflows/nixos.yaml'
workflow_dispatch:
jobs:
nixos:
runs-on: nix-latest
env:
NIX_CONFIG: |
experimental-features = nix-command flakes
build-users-group =
sandbox = false
steps:
- name: Prepare container for actions
run: nix-env -iA nixpkgs.nodejs_22
- name: Checkout
uses: actions/checkout@v7.0.1
# Job containers are unprivileged, so Nix cannot sandbox builds in
# them. Evaluating catches config errors; the build itself happens
# on each server during the deploy.
- name: Evaluate
working-directory: nixos
run: |
for host in asxpio-ops asxpio-services rehearsal-ops rehearsal-services; do
nix eval --raw ".#nixosConfigurations.$host.config.system.build.toplevel.drvPath"
echo
done
- name: Set up SSH
if: github.ref == 'refs/heads/main'
env:
SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
run: |
umask 077
mkdir -p ~/.ssh
printf '%s\n' "$SSH_DEPLOY_KEY" > ~/.ssh/id_ed25519
cp known_hosts ~/.ssh/known_hosts
# The runner's own host is reached through asxpio-ops: a job
# container connecting to its host arrives from a bridge address
# that sshd refuses.
cat > ~/.ssh/config <<'EOF'
Host asxpio-ops
HostName 10.10.0.10
User deploy
Host asxpio-services
HostName 10.10.0.20
User deploy
ProxyJump asxpio-ops
EOF
- name: Deploy
if: github.ref == 'refs/heads/main'
working-directory: nixos
# Ops first: services reaches it for WireGuard, logs and Forgejo
run: |
# Tools from the flake's dev shell: the same pinned nixpkgs
for host in asxpio-ops asxpio-services; do
os=$(nix develop -c ssh "$host" 'test -e /etc/NIXOS && echo nixos || echo other')
if [ "$os" != nixos ]; then
echo "$host: not NixOS yet, skipped"
continue
fi
echo "== $host"
nix develop -c nixos-rebuild switch --flake ".#$host" \
--target-host "$host" --build-host "$host" --sudo
done
- name: Remove credentials
if: always()
run: rm -f ~/.ssh/id_ed25519

326
MIGRATION.md Normal file
View file

@ -0,0 +1,326 @@
# Moving production from Ansible and Terraform to NixOS and OpenTofu
The plan and the runbook. Delete this file when the last step is done.
**End state:** both servers run NixOS built from `nixos/`, deployed by
`.forgejo/workflows/nixos.yaml`; services are native NixOS services
where nixpkgs has a module and Podman containers otherwise; no Docker
daemon, no Ansible; infrastructure in `terraform/` is applied with
OpenTofu. The servers themselves stay: they are billed below today's
list price, so each one is converted **in place** and never recreated.
**Nothing in production changes without the owner's go-ahead for that
step.** Every step below that touches a server says so.
## Where things stand (2026-11-17)
Production is untouched: both servers run Debian, deployed by Ansible
from `main`. Branch `nix` holds the new system, and every part of it ran
on the rehearsal pair (two cx23 in the personal project), most of it on
a restored copy of last night's production data:
| Area | Rehearsed | Notes |
|---|---|---|
| First boot (cloud-init + nixos-infect) | yes | 3–4 min to a bare NixOS |
| In-place conversion with Docker data | yes | data kept under `/old-root` |
| Base, SSH, firewall, WireGuard, sops | yes | same host keys, same peers |
| Postgres 18.7, Garage 2.5, Forgejo 17 | yes, prod data | roles, buckets, keys from sops |
| Traefik, label routing via Podman | yes | certificates: staging CA only |
| asxpio, datacenterbingo on Podman | yes, prod data | mail and IndexNow disabled |
| Minecraft, SillyTavern, Xray, ACME forward | yes, prod data | Discord plugin kept off |
| XMPP (ejabberd, apushd, tackygram) | dummy data only | never started on prod data on purpose |
| CI runner + jobs | yes | against the rehearsal Forgejo |
| Backup, restore, bucket replica | yes | replica: config only, no run |
| Monitoring, logs, alerts, security baseline | yes | 28 targets up, 0 unknown items |
| CI deploy job | evaluate only | deploys nothing until a host is NixOS |
What each service became, and why:
| Was (Ansible role, container) | Now |
|---|---|
| `base`, `ssh_hardening`, `swap` | `modules/base.nix`, `hetzner.nix` |
| `wireguard` | `modules/wireguard.nix`, keys in sops |
| `traefik` | native `services.traefik`; native services' routes in Nix, apps keep labels |
| `forgejo` | native `services.forgejo` as user `git`; no SSH passthrough needed |
| storage repo: Postgres, Garage | native `services.postgresql`, `services.garage` (2.x pinned) |
| `monitoring`, `monitoring_agent` | native Prometheus, Loki, Grafana, Alloy, exporters, cAdvisor (Podman) |
| `restic_backup`, `s3_replicate`, `crawler_alert`, `xmpp_cert_sync` | systemd units from Nix, same scripts and schedules |
| `forgejo_runner`, `forgejo_runner_interop` | native runner module; interop as its own unit |
| `sillytavern`, `minecraft`, `xray`, `acme_forward` | native modules |
| `xmpp` | Podman containers (a custom build, not nixpkgs' ejabberd) |
| App stacks (asxpio, datacenterbingo, blog, czsk, vhpbot) | unchanged compose stacks on Podman, deployed by their own CI |
## Phase 0: preparation (no downtime)
Everything here can be done while Ansible still runs production.
1. **Push `nix`** and let CI evaluate it. It does not deploy: the job
skips any host without `/etc/NIXOS`, and branches never deploy.
2. **OpenTofu.** Once, from a workstation:
```sh
cd terraform
tofu init -reconfigure
tofu plan # expected: only the new user_data output
tofu apply # writes the output; changes no resource
```
The state is the one Terraform wrote; the servers ignore
`user_data`, `image` and `ssh_keys`, so nothing can be replaced.
3. **App repositories: healthcheck in the compose file.** Podman ignores
the `HEALTHCHECK` of OCI-format images, which is what the app CI
builds, so the deploy's wait for "healthy" would time out on NixOS.
Copy each image's healthcheck into its compose file (asxpio,
datacenterbingo, blog; czsk has none). Under Docker the result is the
same, so this ships now, through the normal deploy. The exact block
for asxpio:
```yaml
healthcheck:
test: ["CMD-SHELL","ruby -rnet/http -e 'port = ENV.fetch(\"PUMA_PORT\", \"3000\"); exit(Net::HTTP.get_response(URI(\"http://127.0.0.1:#{port}/healthz\")).code == \"200\" ? 0 : 1)'"]
interval: 30s
timeout: 5s
start_period: 20s
retries: 3
```
Read the others with `skopeo inspect --raw --config docker://<image>`.
4. **Storage repo: stop its deploys.** Its CI starts Postgres and Garage
containers in `/opt/storage`; after the ops conversion those would
fight the native services for their ports. Disable the deploy
workflow (or archive the repo) before Phase 2. Its secrets
(`ASXPIO_*`, `BINGO_*`, `PUBLIC_*`) stay: the app repos use the same
values.
5. **Secrets.** `nixos/secrets/asxpio-*.yaml` were filled on 2026-11-16
and 17 from the Ansible vault, `/opt/storage/.env` and the Garage RPC
secret. If any of those changed since, update the sops file
(`sops nixos/secrets/asxpio-ops.yaml`). Keys: WireGuard, Xray config,
restic password, S3, alert SMTP, Forgejo (secret key, internal token,
JWT secrets, SMTP, metrics token), Postgres roles, Garage keys and RPC
secret, Traefik ACME email, runner tokens, Grafana admin password,
Hetzner read-only token. The vault and sops must agree until Ansible
is gone.
6. **Freeze.** On conversion day: no pushes to the app repos, to `iac`,
or Renovate merges, from the start of a phase until its checks pass.
7. **Rehearse once more against the latest backups** (both hosts), on a
fresh rehearsal pair, following `nixos/README.md` → Rehearsal and the
rules at the end of this file. It costs about €0.02 an hour and is the
only way to know that the night's data still fits the config.
**Go/no-go for Phase 1:** steps 1–7 done, last night's restic backup of
both hosts green, a Hetzner snapshot of the host just taken.
## Phase 1: asxpio-services (owner's go-ahead required)
Downtime about 15–20 minutes for Minecraft, SillyTavern, XMPP, Xray and
CI. asxpio-ops and everything on it stays up. Services first: it has
less data and nothing on ops depends on it.
From a workstation on WireGuard, in the repo:
1. **Snapshot** (the rollback):
```sh
hcloud server create-image --type snapshot --description pre-nixos asxpio-services
```
2. **Stop what writes, then Docker:**
```sh
ssh root@10.20.0.20 'docker stop -t 120 minecraft; cd /opt/xmpp && docker compose stop; \
docker stop forgejo-runner forgejo-runner-interop sillytavern xray acme-forward; \
systemctl stop docker.socket docker containerd'
```
3. **Convert** (the same lines cloud-init runs; `tofu output -json
user_data | jq -r '."asxpio-services"'` shows them filled in). Write
`/etc/nixos/bootstrap.nix` with the content from there, then:
```sh
ssh root@10.20.0.20 'umount -l /tmp; curl -fsSL -o /root/nixos-infect \
https://raw.githubusercontent.com/elitak/nixos-infect/40f62a680bb0e8f2f607d79abfaaecd99d59401c/nixos-infect \
&& echo "4354bd68773b41da65c0e815202c43c8549713b3ed3ff6381c71fbc0b0a840ab /root/nixos-infect" | sha256sum -c \
&& PROVIDER=hetznercloud NIX_CHANNEL=nixos-26.05 NIXOS_IMPORT=./bootstrap.nix \
setsid bash /root/nixos-infect > /var/log/nixos-infect.log 2>&1 < /dev/null &'
```
It reboots into a bare NixOS after about four minutes. WireGuard is
down until step 4; reach it through ops over the private network:
`ssh -J root@10.20.0.10 root@10.10.0.20`.
4. **Switch to the flake** (through ops, as above):
```sh
cd nixos
NIX_SSHOPTS="-J root@10.20.0.10" nixos-rebuild switch --flake .#asxpio-services \
--target-host root@10.10.0.20 --build-host root@10.10.0.20
```
Services that own data stay stopped: the marker file is missing.
5. **Move the data and start everything:**
```sh
ssh root@10.20.0.20 'bash -s /old-root' < migration/services-data.sh
ssh root@10.20.0.20 reboot
```
6. **Check:**
- `wg show` on ops: the services peer has a fresh handshake.
- `systemctl --failed` empty; Grafana's security panel shows nothing
unknown for asxpio-services.
- Minecraft log reaches `Done`; join once (Java and Bedrock).
- SillyTavern on `http://10.20.0.20:8000`.
- An XMPP client logs in; a message to a contact goes through.
- Forgejo → Site administration → Runners: the new runner idle (it
registered itself again); delete the old, offline entry. Push an
empty commit to an app repo and watch a full CI run.
- `systemctl start restic-backup` succeeds (it continues the same
repositories).
**Rollback:** until step 3, start Docker and the containers again.
After it: `hcloud server disable-protection asxpio-services rebuild`,
rebuild from the snapshot, `tofu apply`. Debian comes back as it was at
the snapshot.
After a week without surprises: `rm -rf /old-root`, delete the snapshot.
## Phase 2: asxpio-ops (owner's go-ahead required)
Downtime about 30–45 minutes for every site, Forgejo, the registry and
monitoring: the conversion itself, the first build of the system, then
pulling each app image again (Docker's image store does not carry over).
Announce it.
ops is the WireGuard hub, so during the window the admin network is
down. Until step 4, ops is reachable as root on its public address
(nixos-infect's bootstrap system has no address restriction); from step
4 on, over WireGuard again, or from services over the private network.
1. **Snapshot**, as in Phase 1.
2. **Dumps and stop**, the staged copies the data script loads:
```sh
ssh root@10.20.0.10 'set -e; d=/var/backups/restic-stage; install -d -m 700 $d; \
docker exec storage-postgres pg_dumpall -U postgres > $d/pg_dumpall.sql; \
sqlite3 /opt/forgejo/data/gitea/gitea.db ".backup $d/forgejo-gitea.db"; \
docker exec storage-garage /garage meta snapshot --all; \
docker ps -q | xargs -r docker stop -t 60; systemctl stop docker.socket docker containerd'
```
3. **Convert**, as in Phase 1 step 3, on 135.181.27.77.
4. **Switch to the flake** on its public address:
```sh
nixos-rebuild switch --flake .#asxpio-ops --target-host root@135.181.27.77 \
--build-host root@135.181.27.77
```
From here on root logs in from WireGuard and the private network only;
WireGuard is up again with the same keys, so clients reconnect.
5. **Move the data, start everything, pull the app images:**
```sh
ssh root@10.20.0.10 'bash -s /old-root' < migration/ops-data.sh
ssh root@10.20.0.10 reboot
```
The script moves Forgejo, Garage, Traefik's certificates, the
monitoring history and `/opt/<app>`; loads the Postgres dump (roles
then get their passwords from sops); regenerates Forgejo's hooks and
SSH keys file; and runs `docker compose pull && up -d` for each app
as `deploy` (vhpbot-prod builds locally).
6. **Check:**
- Every site answers (Grafana → Probes). Certificates are the old ones
from `acme.json`; Traefik renews as before.
- `git clone` over SSH and HTTPS; a push; the package registry serves
a pull.
- asxpio: log in to the admin, render an invoice (the boot test that
catches what a database check does not).
- datacenterbingo shows photos (Garage through the app) and
`/data.json`.
- `garage status`; `curl -I https://s3.asxp.io/public/<a known key>`.
- Grafana: targets up, logs from both hosts, security panel clean.
- CI: push an empty commit to an app repo; the deploy reaches
"healthy" (Phase 0 step 3).
- `systemctl start restic-backup xmpp-cert-sync` succeed.
**Rollback:** as in Phase 1. If services has already moved, it keeps
working against a Debian ops: nothing on services depends on how ops is
built.
## Phase 3: clean-up
1. Merge `nix` into `main`: `deploy.yaml` (Ansible) then finds no change
to apply, `nixos.yaml` deploys both hosts from now on.
2. Delete `ansible/`, `.forgejo/workflows/deploy.yaml`, the
`ANSIBLE_VAULT_PASSWORD` secret, `ansible/known_hosts` (the root copy
`known_hosts` stays), the Ansible parts of `renovate.json`.
3. Retire the storage repo (archive). Optional, later: drop the
`storage` network from the app compose files and point their
`DATABASE_URL`/`S3_ENDPOINT` at the host, then remove `apps.nix`'s
compatibility entries.
4. On both hosts after a week: `rm -rf /old-root`; delete the snapshots;
on ops remove the old Postgres 17 volume data, which went with
`/old-root`.
5. Delete the rehearsal servers, network and firewall (`managed-by=claude`
in the personal project).
6. Rotate what sat in the old history and the vault for a year
(`INTERNAL_TOKEN`, the JWT secrets, runner tokens), now in sops; and
give Grafana its own `secret_key` (production keeps the default for
now because its database was written with it; Grafana documents the
rotation).
7. Update the workspace `CLAUDE.md` (servers, deploys, gotchas).
8. Branches, last, because until then `main` is what deploys:
```sh
git push origin main:retired/ansible # keep the Ansible line
# Forgejo → Settings → Branches: default branch nix; unprotect main
git push origin --delete main
git push origin nix:main
# Forgejo: default branch main again; then
git push origin --delete nix
git branch -m main retired/ansible && git branch -m nix main
```
## Rules for the rehearsal pair
Restored data carries production credentials inside it. Anything that
would use them outward is kept from starting in `hosts/rehearsal/`, and
the following must hold every time:
- **Before a runner meets restored Forgejo data,** run
`migration/rehearsal-sanitize-forgejo.sh` on the rehearsal ops. A
restored database still has production's queued jobs, schedules and
Actions secrets; on 2026-11-16 the test runner picked up a queued
production job and was stopped only by the different secret key.
- XMPP and the Telegram gateway, Forgejo's mail, mirrors and webhooks,
Grafana mail, the crawler mail, the bucket replica and the interop
runner do not start there. The Minecraft plugins that talk outward
(DiscordSRV, ServerBackup, AutoUpdateGeyser) are set aside before
every start: on 2026-11-16 DiscordSRV was missed on the first start
and logged the production bot in from the test server for 15 seconds.
- Apps run with mail pointed at nothing and `INDEXNOW_KEY` empty; the
asxpio monitor worker (external probes) stays off.
- SSH is limited by a Hetzner firewall to the admin; backup credentials
are on the servers only in `/run`, only during a restore.
- Delete the servers when testing ends: they hold production data.
## Risks
| Risk | Mitigation |
|---|---|
| Lock-out after the switch | Phase steps say how each host is reached at each point; services through ops and the other way round; Hetzner console last |
| nixos-infect breaks with a later NixOS | pinned by commit and checksum; `nix_channel` pinned to 26.05; nixos-anywhere as the fallback (`nixos/README.md`) |
| ops disk (38 GB) | 18 GB free today; the Nix store adds 3–5 GB, `/old-root` holds the old images until deleted; delete `/old-root/var/lib/docker` once the apps run |
| Data of newer versions than 26.05 ships | Prometheus, Grafana, Xray, SillyTavern from nixos-unstable; Garage 2.x pinned; checked on the rehearsal pair with prod data |
| Something only production does | XMPP on real data and Let's Encrypt issuance were not rehearsed; both have a snapshot rollback and are checked first in their phase |
| A deploy during the window | freeze (Phase 0 step 6); the storage repo's deploy is off (step 4) |

View file

@ -1,8 +1,11 @@
# asxp.io infrastructure
Two Hetzner Cloud servers, described by Terraform and configured by
Ansible. Pushing to `main` deploys: a Forgejo Actions workflow applies
`ansible/site.yaml` to both servers.
Two Hetzner Cloud servers, described by OpenTofu. They are moving from
Debian configured by Ansible to NixOS (`MIGRATION.md`); until a host has
moved, pushing to `main` still applies `ansible/site.yaml` to it.
- Build the servers from nothing: `nixos/README.md`
- Restore data from backups: `RESTORE.md`
## Servers

127
RESTORE.md Normal file
View file

@ -0,0 +1,127 @@
# Restoring from backups
Each host backs itself up nightly with restic (ops 03:30, services 04:15
UTC) into two independent repositories:
| Name | Repository |
|------|------------|
| `hel1` | `s3:https://hel1.your-objectstorage.com/asxpio-backups-main/restic/<host>` |
| `fsn1` | `s3:https://fsn1.your-objectstorage.com/asxpio-backups-repl/restic/<host>` |
A snapshot holds `/etc`, `/opt`, the listed container volumes and
`/var/backups/restic-stage`, where hooks put consistent copies of the
databases just before the run:
| Host | In `/var/backups/restic-stage` | Volumes |
|------|--------------------------------|---------|
| asxpio-ops | `pg_dumpall.sql`, `asxpio.dump` (`pg_dump -Fc`), `forgejo-gitea.db` | `storage_garage_meta`, `storage_garage_data` (with a fresh Garage metadata snapshot) |
| asxpio-services | `ejabberd.sqlite`; ejabberd's Mnesia as `nightly.backup` inside `xmpp_database` | `xmpp_database`, `xmpp_tackygram` |
Not in the backup: Postgres' data directory (restore from the dump),
`/opt/containerd`, and what Minecraft downloads again (`cache`,
`libraries`, `versions`). The exact lists are `restic_paths`,
`restic_excludes` and `restic_pre_hooks` in
`ansible/inventory/host_vars/`.
Three secrets are needed, and none of them may exist only on the
servers: the Object Storage access key and secret key, and the restic
password (`vault_restic_password` in the Ansible vault). **Without the
password nothing can be read.**
## One file or one service, on a running host
```sh
restic-backup hel1 snapshots
restic-backup hel1 ls latest /opt/xmpp
restic-backup fsn1 restore latest --target /tmp/r --include /opt/xmpp
```
Restore beside the live data, compare, then stop the service and move
the files into place.
## A whole host, onto a fresh system
On a host built by `nixos/README.md` (or any Linux with restic):
```sh
export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=...
export RESTIC_PASSWORD=...
export RESTIC_REPOSITORY=s3:https://hel1.your-objectstorage.com/asxpio-backups-main/restic/asxpio-ops
restic snapshots --host asxpio-ops # pick one; "latest" below
```
Keep every service stopped until its data is back, so nothing starts on
an empty directory and creates fresh state where the restore will land.
1. **Files.** `/etc` is restored aside, for reference only: the system's
configuration comes from the flake.
```sh
restic restore latest --target / --include /opt --include /var/backups/restic-stage
restic restore latest --target /root/restored-etc --include /etc
```
2. **Volumes** (while services still run in containers): create each
volume, then restore into it.
```sh
docker volume create storage_garage_meta # one per volume in the table
restic restore latest --target / --include /var/lib/docker/volumes/storage_garage_meta
```
Under Podman the volume lives in
`/var/lib/containers/storage/volumes/<name>`: restore to a temporary
target and move `_data` there.
3. **Databases**, from the staged copies rather than the live files:
- **Postgres** (ops): start Postgres alone on its empty data
directory, then load everything, roles included:
```sh
psql -U postgres -f /var/backups/restic-stage/pg_dumpall.sql
```
`asxpio.dump` is the same database in `pg_restore` format, for
restoring only that one.
- **Forgejo** (ops): `cp /var/backups/restic-stage/forgejo-gitea.db
/opt/forgejo/data/gitea/gitea.db`, owner as the file it replaces.
- **Garage** (ops): if it does not start on the restored metadata, use
the snapshot inside the metadata volume (`snapshots/`), as described
in Garage's [recovery documentation](https://garagehq.deuxfleurs.fr/documentation/operations/recovering/).
- **ejabberd** (services): replace `ejabberd.sqlite` in `xmpp_database`
with the staged copy; if Mnesia does not come up clean,
`ejabberdctl restore /opt/ejabberd/database/nightly.backup`.
4. **Start the services**, then check: the sites answer, a `git clone`
from Forgejo works, an XMPP client logs in, the Minecraft world is the
expected one, and the next nightly backup succeeds.
The app stacks on ops (asxpio, datacenterbingo, blog, czsk, vhpbot,
storage) come back with `/opt/<app>` (compose file and `.env`); their
images are pulled from the registry in Forgejo, so Forgejo and storage
come first. If the registry copy is gone, re-run each app's CI.
## Onto a NixOS host
The backup made by a NixOS host holds the new layout (`/var/lib/forgejo`,
`/var/lib/garage`, `/var/lib/minecraft`, ...): restore to `/`, load the
Postgres dump, `touch /var/lib/.data-in-place`, start the services.
A backup made while the host was still Debian holds the layout described
above. Restore it to a side directory and let the migration script move
it into place; this is what was rehearsed on 2026-11-16:
```sh
restic restore latest --host asxpio-ops --target /restore
bash nixos/migration/ops-data.sh /restore # or services-data.sh
```
## Keeping this true
A restore that was never tried is a hope. After any change to what is
backed up, and at least twice a year, restore the latest snapshot of
each host onto a rehearsal server (`nixos/README.md`) and walk through
this page. Last walk-through: 2026-11-16, both hosts, onto the NixOS
rehearsal pair (Traefik, monitoring, the app stacks and XMPP not yet
part of it).

2
known_hosts Normal file
View file

@ -0,0 +1,2 @@
10.10.0.10,10.20.0.10 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEzuhnXIFERF+slCGpjnQFhaO5iTVqVn9OMbt7jeFOUf
10.10.0.20,10.20.0.20 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDArwdI8bHpQhNnMqz7vOIGJvb5eYE7GahtkbxrNgtvp

19
nixos/.sops.yaml Normal file
View file

@ -0,0 +1,19 @@
# Who can decrypt what. A host decrypts with its SSH host key (converted
# with ssh-to-age); the admin key edits everything.
keys:
- &admin age19xvmm6j3h2u6mc3w6k65ufry4p5aa5lwu96p55h3e42p9wfzwc0qp2w7pk
- &asxpio_ops age1jxcl9cwk64wak2gyzf22vm3dpj80wtl76c7krywlrj7jjxftscrskrg3tf
- &asxpio_services age15ws8alg3ftsgmzvqxft09556g87s4n8c8v39nmvhaz6k50gp4e7se8acmg
# Throwaway servers: replace with the new host's key, then
# sops updatekeys secrets/rehearsal-*.yaml
- &rehearsal_ops age1hfaf7h2h43ahhql8zc6u3yr67yx4utnrlw57h6r32wnm4axvzves8pcl0r
- &rehearsal_services age1au6f8m6l245ddrunqf2a62xprnlevn9yrducynlay2tgknfxeeusj94j5l
creation_rules:
- path_regex: secrets/asxpio-ops\.yaml$
key_groups: [{ age: [*admin, *asxpio_ops] }]
- path_regex: secrets/asxpio-services\.yaml$
key_groups: [{ age: [*admin, *asxpio_services] }]
- path_regex: secrets/rehearsal-ops\.yaml$
key_groups: [{ age: [*admin, *rehearsal_ops] }]
- path_regex: secrets/rehearsal-services\.yaml$
key_groups: [{ age: [*admin, *rehearsal_services] }]

214
nixos/README.md Normal file
View file

@ -0,0 +1,214 @@
# NixOS
Each server's whole system, as one flake. A server is created by OpenTofu
(`../terraform`), converts itself to NixOS on first boot, and gets its
configuration from here. Production is moving over from `../ansible`;
the plan and its state are in `../MIGRATION.md`.
```
flake.nix inputs (nixpkgs 26.05, unstable for a few packages, sops-nix), hosts, dev shell
modules/hetzner.nix disk, boot and network of a Hetzner Cloud VM
modules/base.nix users, SSH, fail2ban, firewall, journal cap, Nix settings
modules/wireguard.nix the admin network; ops is the hub
modules/podman.nix Podman, and the Docker CLI on its socket
modules/backup.nix nightly restic backup, `restic-backup` command
modules/alert.nix mail when a unit fails
modules/monitoring-agent.nix node, container and security metrics, logs to Loki
hosts/asxpio-ops/ Traefik, Forgejo, Postgres, Garage, monitoring, app stacks
hosts/asxpio-services/ runners, Minecraft, XMPP, Xray, SillyTavern, one file each
hosts/rehearsal/ overrides that turn the two hosts into a test pair
migration/ one-off scripts: Debian-era data into place, rehearsal clean-up
secrets/*.yaml sops-encrypted, one file per host
```
Services run as native NixOS services wherever nixpkgs has a module;
the rest are Podman containers declared here (XMPP) or deployed by their
own repositories (the app stacks on ops). There is no Docker daemon:
`docker` is the Docker CLI talking to Podman's socket, so `docker ps`,
`docker compose` and the apps' CI deploys work as they did.
Each service file also says what it adds to the backup
(`asxpio.backup`), which ports and users the security baseline should
expect (`asxpio.security`), and whether it waits for restored data
(`asxpio.waitForData`).
All tools used below come from the dev shell: `nix develop ./nixos`.
## Changing something
Edit, push a branch (CI evaluates every host), merge to `main`: CI
builds each host on itself and switches to it, ops first. A host that
does not run NixOS yet is skipped. By hand, over WireGuard:
```sh
nixos-rebuild switch --flake .#asxpio-services \
--target-host root@10.20.0.20 --build-host root@10.20.0.20
```
Only units whose definition changed restart. Undo with
`nixos-rebuild switch --rollback` on the host, or pick the previous
generation in the boot menu (Hetzner console). Package updates come from
Renovate (`flake.lock` weekly, pinned images and versions as they are
released); by hand: `nix flake update`, commit `flake.lock`.
Try anything risky on the rehearsal pair first (below).
## Building the servers from scratch
What you need: a Hetzner Cloud project and its API token, Object Storage
keys (hel1 and fsn1), an SSH key listed in `../terraform/keys.tf`, and,
to restore data, the restic password (`../RESTORE.md`).
The existing servers are billed below today's list price, and a new
server is not. **For asxpio-ops and asxpio-services use "Reinstalling in
place" below**; this section is for a new project or a lost server.
1. **Create the infrastructure** (network, firewalls, DNS, buckets,
servers):
```sh
cd terraform
cp terraform.tfvars.example terraform.tfvars # fill in the token and keys
export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... # for the state bucket
tofu init
tofu apply
```
In a new project the state bucket does not exist yet: comment out the
`backend "s3"` block for the first apply, then restore it and run
`tofu init -migrate-state`.
2. **Wait about four minutes.** Each server boots Debian, and cloud-init
(`../terraform/cloud-init/nixos.yaml.tftpl`) runs a pinned
nixos-infect, which installs NixOS over the running system and
reboots. The result is a bare NixOS: root login with the keys from
`keys.tf`, public and private network, nothing else.
```sh
ssh root@<ops public IP> nixos-version
ssh -J root@<ops public IP> root@10.10.0.20 nixos-version # services: no public SSH
```
If a server still answers as Debian after ten minutes, read
`/var/log/nixos-infect.log` on it.
3. **Set the host's facts** in `hosts/<name>/default.nix`: the public
addresses (`tofu output`), and on ops the WireGuard endpoint the
others use. Add the host's age recipient to `.sops.yaml` and
re-encrypt its secrets:
```sh
ssh root@<ip> cat /etc/ssh/ssh_host_ed25519_key.pub | ssh-to-age
sops updatekeys secrets/<name>.yaml
```
4. **Install the configuration** (same addresses as in step 2; add
`NIX_SSHOPTS="-J root@<ops public IP>"` for services):
```sh
cd nixos
nixos-rebuild switch --flake .#asxpio-ops \
--target-host root@<ip> --build-host root@<ip>
ssh root@<ip> reboot # once: new kernel command line, interface names
```
From here on root and the admin users log in only from WireGuard and
the private network (`asxpio.sshFrom`): connect your WireGuard client
to ops first, or go through the other server over the private network.
5. **Restore the data**: `../RESTORE.md`.
6. Remove what the conversion left behind: `rm -rf /old-root` (the
Debian image, about 2 GB).
## Reinstalling in place
Keeps the server, its addresses and its price; **wipes the disk**.
```sh
cd terraform
hcloud server disable-protection asxpio-services rebuild
tofu output -json user_data | jq -r '."asxpio-services"' |
hcloud server rebuild --image debian-13 --user-data-from-file - asxpio-services
tofu apply # puts the rebuild protection back
```
Then continue at step 2 above. The server gets new SSH host keys, so
step 3's `sops updatekeys` is needed, and `known_hosts` entries change.
## Secrets
`secrets/<host>.yaml` is encrypted with [sops](https://github.com/getsops/sops)
for the keys in `.sops.yaml`: the admin's age key and the host's SSH host
key. The host decrypts at boot into `/run/secrets`.
```sh
sops secrets/asxpio-services.yaml # edit; needs ~/.config/sops/age/keys.txt
```
The SSH host key is therefore part of a host's identity. It survives the
in-place conversion and is in the backup (`/etc/ssh`); a rebuilt server
has a new one and needs `sops updatekeys`.
## Data and the marker file
Services that own data (`asxpio.waitForData`: Postgres, Garage, Forgejo,
Minecraft, SillyTavern, XMPP, the backup itself) do not start until
`/var/lib/.data-in-place` exists. A fresh install
therefore never creates empty state where a restore is about to land,
and never backs up an empty host over a full one. After restoring or
moving the data: `touch /var/lib/.data-in-place`, then start the units
or reboot.
## Rehearsal
`.#rehearsal-ops` and `.#rehearsal-services` are the two hosts' own
configurations plus `hosts/rehearsal/`: other keys and addresses, dummy
secrets, SSH open to the world, backups into local directories, and
anything that would act as production (the XMPP server) started by hand
only. **Every change is tried there first**, and the pair should be able
to do everything production does before a production host is converted.
Two servers on a private network with the production addresses:
```sh
hcloud network create --name rehearsal --ip-range 10.10.0.0/20
hcloud network add-subnet rehearsal --type cloud --network-zone eu-central --ip-range 10.10.0.0/23
tofu -chdir=../terraform output -json user_data | jq -r '."asxpio-ops"' > /tmp/ops.yaml
tofu -chdir=../terraform output -json user_data | jq -r '."asxpio-services"' > /tmp/services.yaml
hcloud server create --name rehearsal-ops --type cx23 --image debian-13 --location hel1 \
--ssh-key <your key> --network rehearsal --user-data-from-file /tmp/ops.yaml
hcloud server create --name rehearsal-services --type cx23 --image debian-13 --location hel1 \
--ssh-key <your key> --network rehearsal --user-data-from-file /tmp/services.yaml
```
Then, per server: put its age recipient in `.sops.yaml` (`&rehearsal_*`)
and `sops updatekeys secrets/rehearsal-<role>.yaml`; put its addresses in
`hosts/rehearsal/<role>.nix` (and ops's public key in services' file,
the other way round for WireGuard); `nixos-rebuild switch --flake
.#rehearsal-<role> --target-host root@<ip> --build-host root@<ip>`;
reboot once.
With test data: `touch /var/lib/.data-in-place`. With a restored copy of
production: restore last night's snapshot to `/restore`, run
`migration/ops-data.sh /restore` or `services-data.sh /restore`, and on
ops `migration/rehearsal-sanitize-forgejo.sh` before the runner starts.
Read the rehearsal rules in `../MIGRATION.md` first: restored data
carries production credentials.
## How the first boot works, and its limits
- nixos-infect is pinned by commit and checksum in
`../terraform/servers.tf`; it replaces the operating system, so bump it
deliberately and rehearse.
- It keeps the Debian image's partitions (`modules/hetzner.nix` matches
them) and moves the old system to `/old-root`.
- `bootstrap.nix` in the cloud-init corrects three things for the first
generation: the scripted initrd (the takeover does not exist in the
systemd initrd, which NixOS 26.05 uses by default), the IPv4 default
route, and the private network's route. All three were found and
verified on test servers on 2026-11-16.
- The scripted initrd is deprecated upstream. When a NixOS release drops
it, keep `nix_channel` at the last release that has it (the flake then
upgrades the system), or switch the first boot to
[nixos-anywhere](https://github.com/nix-community/nixos-anywhere).

65
nixos/flake.lock generated Normal file
View file

@ -0,0 +1,65 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1794552581,
"narHash": "sha256-qXFIqA6FCcx7XeDzw0ZNlkDT9UiCzrNDwK8RuU8RcHM=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "f1e5c356f35d07e7b71a6b5e6c9338e0b029e0c0",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-26.05",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-unstable": {
"locked": {
"lastModified": 1794537146,
"narHash": "sha256-Wpz/7x/YWnDIBu7yj6ixe8j6fIMsidd9Y+o1PqPF3iM=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "d5cc6833999746cffdfe0598f7bc801a57b887a9",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs",
"nixpkgs-unstable": "nixpkgs-unstable",
"sops-nix": "sops-nix"
}
},
"sops-nix": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1794624949,
"narHash": "sha256-3q/hxp/flW1PnV3Dx+H3p8kHGEHJ7251BqVMNsAAB9E=",
"owner": "Mic92",
"repo": "sops-nix",
"rev": "11e5885d241743ff0193465d533b20e754bc3ce0",
"type": "github"
},
"original": {
"owner": "Mic92",
"repo": "sops-nix",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

78
nixos/flake.nix Normal file
View file

@ -0,0 +1,78 @@
{
description = "asxp.io servers";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
# For the few packages 26.05 has older than what production runs
nixpkgs-unstable.url = "github:NixOS/nixpkgs/nixos-unstable";
sops-nix = {
url = "github:Mic92/sops-nix";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs =
{
nixpkgs,
nixpkgs-unstable,
sops-nix,
...
}:
let
mkHost =
modules:
nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
specialArgs.unstable = nixpkgs-unstable.legacyPackages.x86_64-linux;
modules = [
sops-nix.nixosModules.sops
./modules/hetzner.nix
./modules/base.nix
./modules/shell.nix
./modules/podman.nix
./modules/wireguard.nix
./modules/alert.nix
./modules/backup.nix
./modules/monitoring-agent.nix
]
++ modules;
};
in
{
# `nix develop ./nixos`: every tool the READMEs call
devShells.x86_64-linux.default =
let
pkgs = nixpkgs.legacyPackages.x86_64-linux;
in
pkgs.mkShell {
packages = with pkgs; [
opentofu
hcloud
nixos-rebuild
sops
ssh-to-age
age
restic
rclone
jq
openssh
];
};
nixosConfigurations = {
asxpio-ops = mkHost [ ./hosts/asxpio-ops ];
asxpio-services = mkHost [ ./hosts/asxpio-services ];
# Both hosts on throwaway servers, with their own keys and
# addresses: everything is tried there first.
rehearsal-ops = mkHost [
./hosts/asxpio-ops
./hosts/rehearsal/ops.nix
];
rehearsal-services = mkHost [
./hosts/asxpio-services
./hosts/rehearsal/services.nix
];
};
};
}

View file

@ -0,0 +1,38 @@
# The app stacks (asxpio, datacenterbingo, blog, czsk, vhpbot) deploy
# themselves from their own repositories: CI copies a compose file and a
# .env to /opt/<app> and runs `docker compose up -d` as user deploy.
#
# Their compose files still expect the Docker-era storage stack: a
# network named "storage" and the hosts "postgres" and "garage" on it.
# Postgres and Garage are native services now, so every container on
# this host resolves those two names to the host, and the network exists
# empty. Nothing in the app repositories has to change for the move;
# dropping the storage network from their compose files is a later
# clean-up.
{ config, pkgs, ... }:
let
hosts = pkgs.writeText "container-hosts" ''
10.10.0.10 postgres garage
'';
in
{
virtualisation.containers.containersConf.settings.containers.base_hosts_file = "${hosts}";
# The API service (the socket the Docker CLI and Traefik use) reads it
# at start only
systemd.services.podman.restartTriggers = [ hosts ];
# `docker compose up --build` (vhpbot-prod builds on the host) starts
# BuildKit in a privileged container
asxpio.security.containers."buildx_buildkit_.*" = [ "privileged" ];
systemd.services.podman-network-storage = {
description = "Podman network storage (empty; see apps.nix)";
wantedBy = [ "multi-user.target" ];
path = [ config.virtualisation.podman.package ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = "podman network exists storage || podman network create storage";
};
}

View file

@ -0,0 +1,878 @@
#!/usr/bin/env python3
"""Crawler watch for a Traefik-fronted Forgejo (or any Traefik site).
Separates real AI crawlers from traffic that only claims to be, by
checking the source IP against each vendor's published range list.
Modes:
(default) daily threshold alert: mail only if yesterday exceeded
CRAWLER_THRESHOLD requests
--weekly summary: always mail stats for the past 7 days
--dry-run print instead of mailing (combinable with --weekly)
Configuration is by environment variable; see README.md. The only
value with no sensible default is CRAWLER_RECIPIENT.
"""
import configparser, glob, gzip, ipaddress, json, os, re, smtplib, socket, subprocess, sys, urllib.request
from collections import Counter
from datetime import date, timedelta
from email.mime.text import MIMEText
# --- configuration ------------------------------------------------------
THRESHOLD = int(os.environ.get("CRAWLER_THRESHOLD", "100000"))
RECIPIENT = os.environ.get("CRAWLER_RECIPIENT", "")
SITE = os.environ.get("CRAWLER_SITE", "this site")
LOG_GLOB = os.environ.get("CRAWLER_LOG", "/var/log/traefik/access.log*")
# Traefik router name to filter on, e.g. "forgejo@docker". Empty = all
# traffic reaching Traefik, which is what you want for a single-site host.
ROUTER = os.environ.get("CRAWLER_ROUTER", "")
# Container to read SMTP settings from (Forgejo/Gitea app.ini [mailer]).
# Set CRAWLER_SMTP_* instead to configure SMTP directly.
MAIL_CONTAINER = os.environ.get("CRAWLER_MAIL_CONTAINER", "forgejo")
MAIL_INI = os.environ.get("CRAWLER_MAIL_INI", "/data/gitea/conf/app.ini")
WEEKLY = "--weekly" in sys.argv
DRY = "--dry-run" in sys.argv
if not RECIPIENT and not DRY:
sys.exit("CRAWLER_RECIPIENT is not set (no --dry-run either); refusing "
"to run. See README.md.")
# --- verified-crawler support -------------------------------------------
# Vendors publishing machine-readable IP ranges. A UA token alone proves
# nothing: on the instance this was written for, ~83% of AI-bot-labelled
# traffic came from hosts outside these ranges. Only IP-verified hits count.
RANGE_SOURCES = {
"openai": ["https://openai.com/chatgpt-user.json",
"https://openai.com/gptbot.json",
"https://openai.com/searchbot.json"],
"anthropic": ["https://claude.com/crawling/bots.json"],
"perplexity":["https://www.perplexity.ai/perplexitybot.json"],
"apple": ["https://search.developer.apple.com/applebot.json"],
"google": ["https://developers.google.com/static/crawling/ipranges/special-crawlers.json",
"https://developers.google.com/static/crawling/ipranges/common-crawlers.json",
"https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers.json",
"https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers-google.json"],
}
# UA token -> vendor whose ranges must contain the source IP
BOT_VENDOR = {
"ChatGPT-User": "openai", "GPTBot": "openai", "OAI-SearchBot": "openai",
"ClaudeBot": "anthropic", "Claude-User": "anthropic", "Claude-SearchBot": "anthropic",
"PerplexityBot": "perplexity", "Perplexity-User": "perplexity",
"Applebot-Extended": "apple", "Applebot": "apple",
"Googlebot": "google", "Google-Extended": "google", "GoogleOther": "google",
}
# --- reverse-DNS verification -------------------------------------------
# For vendors that publish no IP ranges. The check is forward-confirmed
# (FCrDNS): PTR of the address must end in one of the vendor's domains,
# AND that hostname must resolve back to the same address. The forward
# step is what makes it meaningful - a PTR record alone is set by
# whoever controls the address block, so it proves nothing on its own.
BOT_RDNS = {
"Amazonbot": (".crawl.amazonbot.amazon",),
"meta-externalagent": (".facebook.com", ".fbsv.net"),
"meta-externalfetcher": (".facebook.com", ".fbsv.net"),
"FacebookBot": (".facebook.com", ".fbsv.net"),
"YouBot": (".search.you.com",),
"Bytespider": (".bytedance.com", ".byteoversea.com"),
"PetalBot": (".petalsearch.com", ".aspiegel.com"),
"DuckAssistBot": (".duckduckgo.com",),
# Apple and Google publish ranges, but also answer rDNS; listed so a
# range miss can still be resolved when the published file is stale.
"Applebot": (".applebot.apple.com",),
"Googlebot": (".googlebot.com", ".google.com"),
}
# rDNS is slow (two lookups per address), so only unique IPs are probed
# and results are memoised for the run.
RDNS_MAX = int(os.environ.get("CRAWLER_RDNS_MAX", "400"))
RDNS_ENABLE = os.environ.get("CRAWLER_RDNS", "1") != "0"
# --- ASN verification, for single-tenant networks only -------------------
# An ASN match usually proves nothing: genuine YouBot and genuine
# Amazonbot both live in AS14618, which is also every EC2 instance a
# spoofer could rent. It is only evidence when the ASN belongs to the
# vendor exclusively and sells no compute in it. Meta qualifies -
# AS32934 is Meta's own network and cannot be rented - and Meta
# publishes no IP range file (their docs say to email webmasters@meta.com),
# so without this there is nothing to check them against at all.
BOT_ASN = {
"meta-externalagent": {"32934"},
"meta-externalfetcher": {"32934"},
"FacebookBot": {"32934"},
"facebookexternalhit": {"32934"},
}
ASN_ENABLE = os.environ.get("CRAWLER_ASN", "1") != "0"
# Team Cymru's DNS interface: <reversed-addr>.origin[6].asn.cymru.com TXT
CYMRU4 = "origin.asn.cymru.com"
CYMRU6 = "origin6.asn.cymru.com"
# robots.txt to audit verified crawlers against. Fetched once per run;
# empty or unreachable simply skips the compliance check.
ROBOTS_URL = os.environ.get("CRAWLER_ROBOTS", "")
CACHE = os.environ.get("CRAWLER_CACHE", "/var/cache/crawler-alert/ranges.json")
CF_URL = "https://www.cloudflare.com/ips-v4"
# claude.com and cloudflare.com sit behind Cloudflare, which 403s the
# default Python-urllib UA. Send a real one.
UA = "Mozilla/5.0 (compatible; crawler-alert/1.0; +https://codeberg.org/)"
def fetch(url, timeout=20):
req = urllib.request.Request(url, headers={"User-Agent": UA})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read()
def load_ranges():
"""Fetch vendor prefixes; fall back to cache so a vendor outage
degrades the report instead of breaking the mail."""
out, stale = {}, []
for vendor, urls in RANGE_SOURCES.items():
nets = []
for u in urls:
try:
for p in json.loads(fetch(u)).get("prefixes", []):
for k, v in p.items():
if k.startswith("ipv"):
nets.append(v)
except Exception:
stale.append(vendor)
if nets:
out[vendor] = nets
cf = []
try:
cf = [l.strip() for l in fetch(CF_URL).decode().splitlines() if l.strip()]
except Exception:
stale.append("cloudflare")
try:
cached = json.load(open(CACHE))
except Exception:
cached = {}
for vendor in RANGE_SOURCES:
if vendor not in out and vendor in cached.get("vendors", {}):
out[vendor] = cached["vendors"][vendor]
if not cf:
cf = cached.get("cloudflare", [])
if out:
try:
os.makedirs(os.path.dirname(CACHE), exist_ok=True)
json.dump({"vendors": out, "cloudflare": cf}, open(CACHE, "w"))
except Exception:
pass
# bucket by first octet so lookups stay cheap over ~1425 prefixes
idx = {}
for vendor, nets in out.items():
b = {}
for s in nets:
n = ipaddress.ip_network(s)
b.setdefault(int(n.network_address) >> 24 if n.version == 4 else -1, []).append(n)
idx[vendor] = b
cfnets = [ipaddress.ip_network(s) for s in cf]
return idx, cfnets, sorted(set(stale))
def in_index(idx_v, addr):
if idx_v is None:
return False
key = int(addr) >> 24 if addr.version == 4 else -1
return any(addr in n for n in idx_v.get(key, []))
def load_robots():
"""Disallow patterns from robots.txt, as (prefix, contains) pairs.
Only the `User-agent: *` group is read: the point is to audit what
well-behaved crawlers were asked not to fetch, not to model every
per-agent rule. Returns [] when unset or unreachable, which disables
the compliance check rather than reporting false violations.
"""
if not ROBOTS_URL:
return []
try:
txt = fetch(ROBOTS_URL, timeout=15).decode("utf-8", "replace")
except Exception:
return []
rules, in_star = [], False
for line in txt.splitlines():
line = line.split("#")[0].strip()
if not line:
continue
k, _, v = line.partition(":")
k, v = k.strip().lower(), v.strip()
if k == "user-agent":
in_star = (v == "*")
elif k == "disallow" and in_star and v:
# Forgejo-style /*/*/thing/ means "contains /thing/".
if v.startswith("/*"):
rules.append(("", v.lstrip("/*")))
else:
rules.append((v.rstrip("*"), ""))
return rules
def robots_blocked(path, rules):
for prefix, contains in rules:
if prefix and path.startswith(prefix):
return True
if contains and contains in path:
return True
return False
_asn_cache = {}
def asn_of(ip):
"""Origin ASN for an address via Team Cymru's DNS interface.
Returns the ASN as a string, or "" if it cannot be determined.
Needs `dig`; absence degrades to no ASN evidence, never an error.
"""
if ip in _asn_cache:
return _asn_cache[ip]
asn = ""
try:
a = ipaddress.ip_address(ip)
if a.version == 4:
q = ".".join(reversed(ip.split("."))) + "." + CYMRU4
else:
nibbles = a.exploded.replace(":", "")
q = ".".join(reversed(nibbles)) + "." + CYMRU6
out = subprocess.run(["dig", "+short", "+time=3", "+tries=1", q, "TXT"],
capture_output=True, text=True, timeout=12).stdout
# "32934 | 2a03:2880:f814::/48 | IE | ripencc | 2011-08-22"
first = out.strip().strip('"').split("|")[0].strip()
if first.split(" ")[0].isdigit():
asn = first.split(" ")[0]
except (OSError, ValueError, subprocess.SubprocessError):
pass
_asn_cache[ip] = asn
return asn
_rdns_cache = {}
def fcrdns(ip, suffixes):
"""Forward-confirmed reverse DNS.
PTR must end in one of `suffixes`, and the name it gives must resolve
back to `ip`. Returns (ok, hostname). Without the forward step this
would only prove the address owner can write their own PTR record.
"""
key = (ip, suffixes)
if key in _rdns_cache:
return _rdns_cache[key]
result = (False, "", "mismatch")
try:
host = socket.gethostbyaddr(ip)[0].rstrip(".").lower()
if any(host.endswith(s) or host == s.lstrip(".") for s in suffixes):
_, _, addrs = socket.gethostbyname_ex(host)
try:
v6 = socket.getaddrinfo(host, None, socket.AF_INET6)
addrs = addrs + [a[4][0] for a in v6]
except OSError:
pass
if ip in addrs:
result = (True, host, "ok")
else:
result = (False, host, "mismatch")
else:
result = (False, host, "mismatch")
except OSError:
# No PTR at all. This is absence of evidence, not evidence of
# forgery: Meta's IPv6 crawler space, for one, publishes no PTR
# records. Kept distinct so a real mismatch stays visible.
result = (False, "", "no-ptr")
_rdns_cache[key] = result
return result
# --- --metrics: Prometheus counters for Grafana --------------------------
# Run every few minutes from a timer. Reads only what the live log gained
# since the last run (byte offset + inode in a state file, so rotation and
# truncation restart at 0), classifies each request the same way as the
# weekly report, and writes cumulative counters to node_exporter's
# textfile directory. Verdicts per (bot, IP) are cached for a week, so DNS
# is only asked about addresses it hasn't seen.
METRICS = "--metrics" in sys.argv
TEXTFILE = os.environ.get("CRAWLER_TEXTFILE", "/var/lib/node_exporter/textfile/crawler.prom")
STATE = os.environ.get("CRAWLER_STATE", "/var/cache/crawler-alert/metrics.json")
LIVE_LOG = os.environ.get("CRAWLER_LIVE_LOG", sorted(glob.glob(LOG_GLOB) or [""])[0])
ALL_BOTS = sorted(set(BOT_VENDOR) | set(BOT_RDNS) | set(BOT_ASN), key=len, reverse=True)
GENERIC_BOT = re.compile(r"bot|crawler|spider|scrapy|externalagent", re.I)
UA_RE = re.compile(r"\"[^\"]*\" \"([^\"]*)\" \d+ \"")
# The mail reports watch one router (Forgejo); the dashboard wants them all.
METRICS_ROUTER = os.environ.get("CRAWLER_METRICS_ROUTER", ROUTER)
def vendor_of(bot):
if bot in BOT_VENDOR:
return BOT_VENDOR[bot]
if bot in BOT_ASN:
return "meta"
return bot.lower()
def index_ranges(vendors, cf):
idx = {}
for vendor, nets in vendors.items():
b = {}
for s in nets:
n = ipaddress.ip_network(s)
b.setdefault(int(n.network_address) >> 24 if n.version == 4 else -1, []).append(n)
idx[vendor] = b
return idx, [ipaddress.ip_network(s) for s in cf]
def cached_ranges(max_age=86400):
"""Range files change rarely: refetch once a day, not every run."""
import time
try:
if time.time() - os.path.getmtime(CACHE) < max_age:
c = json.load(open(CACHE))
return index_ranges(c["vendors"], c.get("cloudflare", []))
except Exception:
pass
idx, cf, _stale = load_ranges()
return idx, cf
def judge(bot, ip, ranges, cfnets, cache, budget):
"""verified | spoofed | proxied | private | unknown, like the report:
IP ranges first, then forward-confirmed rDNS, then single-tenant ASN."""
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return "unknown"
if addr.is_private:
return "private"
if any(addr in n for n in cfnets):
return "proxied"
if bot in BOT_VENDOR and in_index(ranges.get(BOT_VENDOR[bot]), addr):
return "verified"
if bot not in BOT_RDNS and bot not in BOT_ASN:
return "spoofed" # range-only vendor, address outside ranges
key = f"{bot}|{ip}"
if key in cache:
return cache[key][0]
if budget[0] <= 0:
return "unknown" # over this run's DNS budget; retried next run
budget[0] -= 1
v = "unknown"
ok, why = False, "no-ptr"
if bot in BOT_RDNS:
ok, _host, why = fcrdns(ip, BOT_RDNS[bot])
if ok:
v = "verified"
elif why == "no-ptr":
if ASN_ENABLE and bot in BOT_ASN and asn_of(ip) in BOT_ASN[bot]:
v = "verified"
else:
v = "spoofed" # a PTR exists and points elsewhere
cache[key] = [v, int(date.today().toordinal())]
return v
def run_metrics():
try:
st = json.load(open(STATE))
except Exception:
st = {}
counts = Counter(st.get("counts", {}))
cache = {k: v for k, v in st.get("verdicts", {}).items()
if v[1] > date.today().toordinal() - 7}
try:
fs = os.stat(LIVE_LOG)
except OSError:
sys.exit(f"cannot read {LIVE_LOG}")
if "inode" not in st:
offset = fs.st_size # first run: start at the end, not the backlog
elif st["inode"] != fs.st_ino or fs.st_size < st.get("offset", 0):
offset = 0 # rotated or truncated
else:
offset = st["offset"]
ranges, cfnets = cached_ranges()
socket.setdefaulttimeout(3)
budget = [RDNS_MAX]
with open(LIVE_LOG, "rb") as f:
f.seek(offset)
for raw in f:
if not raw.endswith(b"\n"):
break # half-written line: take it next run
offset += len(raw)
line = raw.decode("utf-8", "replace")
if METRICS_ROUTER and METRICS_ROUTER not in line:
continue
parts = line.split()
counts["requests"] += 1
m = UA_RE.search(line)
u = m.group(1) if m else "-"
bot = next((b for b in ALL_BOTS if b in u), None)
if bot:
v = judge(bot, parts[0], ranges, cfnets, cache, budget)
counts[f"ai|{vendor_of(bot)}|{bot}|{v}"] += 1
if v == "verified" and len(parts) > 9 and parts[9].isdigit():
counts[f"bytes|{vendor_of(bot)}"] += int(parts[9])
elif u == "-":
counts["class|none"] += 1
elif GENERIC_BOT.search(u):
counts["class|other-bot"] += 1
else:
counts["class|browser-like"] += 1
if len(cache) > 50000: # keep the newest verdicts only
cache = dict(sorted(cache.items(), key=lambda kv: kv[1][1])[-50000:])
os.makedirs(os.path.dirname(STATE), exist_ok=True)
json.dump({"inode": fs.st_ino, "offset": offset, "counts": counts,
"verdicts": cache}, open(STATE + ".tmp", "w"))
os.replace(STATE + ".tmp", STATE)
out = ["# HELP crawler_requests_total Requests seen in the Traefik access log.",
"# TYPE crawler_requests_total counter",
f"crawler_requests_total {counts['requests']}",
"# HELP crawler_class_requests_total Requests without an AI-bot user agent, by user-agent class.",
"# TYPE crawler_class_requests_total counter"]
for k, c in sorted(counts.items()):
if k.startswith("class|"):
out.append(f'crawler_class_requests_total{{class="{k[6:]}"}} {c}')
out += ["# HELP crawler_ai_requests_total Requests claiming an AI-bot user agent, by verification verdict.",
"# TYPE crawler_ai_requests_total counter"]
for k, c in sorted(counts.items()):
if k.startswith("ai|"):
_, vendor, bot, v = k.split("|")
out.append(f'crawler_ai_requests_total{{vendor="{vendor}",bot="{bot}",verdict="{v}"}} {c}')
out += ["# HELP crawler_ai_verified_bytes_total Bytes served to verified AI crawlers.",
"# TYPE crawler_ai_verified_bytes_total counter"]
for k, c in sorted(counts.items()):
if k.startswith("bytes|"):
out.append(f'crawler_ai_verified_bytes_total{{vendor="{k[6:]}"}} {c}')
import time
out += ["# HELP crawler_metrics_last_run_timestamp_seconds Last successful --metrics run.",
"# TYPE crawler_metrics_last_run_timestamp_seconds gauge",
f"crawler_metrics_last_run_timestamp_seconds {int(time.time())}"]
with open(TEXTFILE + ".tmp", "w") as f:
f.write("\n".join(out) + "\n")
os.replace(TEXTFILE + ".tmp", TEXTFILE)
if METRICS:
run_metrics()
sys.exit(0)
days = [date.today() - timedelta(days=i) for i in range(7 if WEEKLY else 1, 0, -1)]
stamps = [d.strftime("%d/%b/%Y") for d in days]
RANGES, CFNETS, STALE = (load_ranges() if WEEKLY else ({}, [], []))
per_day = {s: [0, set()] for s in stamps}
repos = Counter()
uas = Counter()
verified = Counter() # bot -> IP-verified hits
spoofed = Counter() # bot -> UA claimed, IP outside vendor ranges
proxied = Counter() # bot -> arrived via Cloudflare, unverifiable
ver_paths = Counter() # paths fetched by verified bots
ver_ips = {} # bot -> set of verified source IPs
# What the verified crawlers actually did, once confirmed: status mix,
# bytes served, and any path robots.txt asked them not to fetch.
ver_status = Counter()
ver_bytes = [0]
ver_violations = Counter() # path -> hits, robots.txt disallowed
ver_bot_bytes = Counter() # bot -> bytes served
# Repository *content* fetched by verified crawlers, as opposed to
# policy files and chrome. This is the question a permissive robots.txt
# is asking: now that they may read the code, do they? Counting top
# paths cannot answer it - robots.txt and sitemap.xml drown everything.
ver_content = Counter() # bot -> content hits
ver_content_paths = Counter()
CONTENT_RE = re.compile(r"/(src|raw|commit|commits|media|blame|archive|compare)/")
# Which repositories each vendor is actually interested in.
ver_repos = {} # bot -> Counter(owner/repo)
ver_pkgs = Counter() # "type/name" -> hits, registry artifacts
ver_pkg_index = Counter() # owner -> hits on the bare package index
# Forge paths are /owner/repo/...; these first segments are not owners,
# and a two-segment path like /pix/photo.jpg on another vhost is a file,
# not a repository - hence the extension check.
NOT_OWNER = {"assets", "fonts", "explore", "user", "api", "avatars",
"repo-avatars", "swagger.v1.json", "attachments", "notifications",
"issues", "pulls", "milestones", "admin", "org", "repo", "login",
"-", "favicon.ico", "robots.txt", "sitemap.xml", "pix", "static"}
# Container/package registry: /{owner}/-/packages/{type}/{name}[/{version}]
# Worth counting separately from repositories - it says which published
# artifacts crawlers are indexing, not which source they are reading.
PKG_RE = re.compile(r"^/([^/]+)/-/packages(?:/([^/?]+)/([^/?]+))?")
def package_of(path):
"""(owner, 'type/name') for a registry path, else None. Bare
/owner/-/packages (the index) returns name None."""
m = PKG_RE.match(path.split("?")[0])
if not m:
return None
owner, ptype, name = m.group(1), m.group(2), m.group(3)
return (owner, f"{ptype}/{name}" if ptype and name else None)
def repo_of(path):
"""owner/repo for a forge path, else None."""
seg = path.lstrip("/").split("?")[0].split("/")
if len(seg) < 2 or not seg[0] or not seg[1]:
return None
if seg[0].lower() in NOT_OWNER or seg[1].lower() in NOT_OWNER:
return None
if "." in seg[1] and len(seg) == 2: # /pix/photo.jpg -> a file
return None
return f"{seg[0]}/{seg[1]}"
# rDNS-verified vendors: {bot: {ip: hits}}, resolved after the log pass
rdns_hits = {b: Counter() for b in BOT_RDNS}
rdns_proxied = Counter()
# {bot: {ip: Counter(path)}} - kept so that once an address is confirmed
# by DNS/ASN its paths can join the verified-path breakdown, which
# otherwise only ever showed IP-range-verified vendors.
rdns_paths = {b: {} for b in BOT_RDNS}
ROBOTS_RULES = load_robots() if WEEKLY else []
def record_verified(bot, path, status, nbytes):
"""Log what a confirmed crawler did. Called only after verification,
so these counters describe legitimate traffic and nothing else."""
ver_paths[path] += 1
ver_status[status] += 1
ver_bytes[0] += nbytes
ver_bot_bytes[bot] += nbytes
if CONTENT_RE.search(path):
ver_content[bot] += 1
ver_content_paths[path] += 1
pkg = package_of(path)
if pkg:
owner, name = pkg
if name:
ver_pkgs[f"{owner}/{name}"] += 1
else:
ver_pkg_index[owner] += 1
r = repo_of(path)
if r:
ver_repos.setdefault(bot, Counter())[r] += 1
if ROBOTS_RULES and robots_blocked(path, ROBOTS_RULES):
ver_violations[path] += 1
for path in sorted(glob.glob(LOG_GLOB)):
opener = gzip.open if path.endswith(".gz") else open
with opener(path, "rt", errors="replace") as f:
for line in f:
if ROUTER and ROUTER not in line:
continue
for s in stamps:
if s in line:
per_day[s][0] += 1
per_day[s][1].add(line.split(" ", 1)[0])
parts = line.split()
if len(parts) > 6 and parts[6].count("/") >= 2:
repos["/".join(parts[6].split("/")[1:3])] += 1
# Traefik CLF: ... "<referer>" "<user-agent>" <n> "<router>" ...
# Anchor on the request counter so this works whatever
# the router is called.
ua = re.search(r"\"[^\"]*\" \"([^\"]*)\" \d+ \"", line)
if ua:
u = ua.group(1)
m = re.search(r"(bot|crawler|spider|scrapy|externalagent|gpt|claude|perplexity)[\w./-]*", u, re.I)
uas[m.group(0) if m else ("(none)" if u == "-" else "(browser-like)")] += 1
if WEEKLY:
# longest token first so Applebot-Extended wins over Applebot
bot = next((b for b in sorted(BOT_VENDOR, key=len, reverse=True) if b in u), None)
if bot:
try:
addr = ipaddress.ip_address(parts[0])
except ValueError:
addr = None
if addr is None:
pass
elif any(addr in n for n in CFNETS):
proxied[bot] += 1
elif in_index(RANGES.get(BOT_VENDOR[bot]), addr):
verified[bot] += 1
ver_ips.setdefault(bot, set()).add(parts[0])
if len(parts) > 9:
record_verified(
bot, parts[6][:60], parts[8],
int(parts[9]) if parts[9].isdigit() else 0)
else:
spoofed[bot] += 1
if WEEKLY and RDNS_ENABLE:
rb = next((b for b in sorted(BOT_RDNS, key=len, reverse=True)
if b in u), None)
# skip if already counted by IP-range check
if rb and not (rb in BOT_VENDOR and rb == bot):
try:
a2 = ipaddress.ip_address(parts[0])
except ValueError:
a2 = None
if a2 is None:
pass
elif any(a2 in n for n in CFNETS):
rdns_proxied[rb] += 1
else:
rdns_hits[rb][parts[0]] += 1
if len(parts) > 9 and not a2.is_private:
rdns_paths[rb].setdefault(parts[0], []).append(
(parts[6][:60], parts[8],
int(parts[9]) if parts[9].isdigit() else 0))
break
total = sum(v[0] for v in per_day.values())
all_ips = set().union(*(v[1] for v in per_day.values()))
# --- resolve rDNS candidates ---------------------------------------------
# One pass over unique addresses, busiest first, capped by RDNS_MAX so a
# flood of distinct forgeries cannot stall the report on DNS timeouts.
rdns_ok = Counter() # bot -> forward-confirmed by PTR
rdns_mismatch = Counter() # bot -> PTR exists but points elsewhere: forgery
rdns_noptr = Counter() # bot -> no PTR at all: cannot be judged by DNS
rdns_asn = Counter() # bot -> no PTR, but origin ASN is the vendor's
rdns_skipped = Counter() # bot -> hits left unresolved by the cap
rdns_private = Counter() # bot -> hits from RFC1918/loopback (see below)
rdns_ok_ips = {}
if WEEKLY and RDNS_ENABLE:
socket.setdefaulttimeout(3)
for bot, counter in rdns_hits.items():
budget = RDNS_MAX
for ip, hits in counter.most_common():
# A private source address means the real client IP never
# reached the log: something in front (Docker's bridge
# gateway, a local proxy) is rewriting it. Neither verified
# nor spoofed - the evidence simply is not there.
if ipaddress.ip_address(ip).is_private:
rdns_private[bot] += hits
continue
if budget <= 0:
rdns_skipped[bot] += hits
continue
budget -= 1
ok, _host, why = fcrdns(ip, BOT_RDNS[bot])
confirmed = False
if ok:
rdns_ok[bot] += hits
rdns_ok_ips.setdefault(bot, set()).add(ip)
confirmed = True
elif why == "no-ptr":
# Fall back to ASN, but only for vendors whose network is
# single-tenant (see BOT_ASN). Otherwise leave it unknown.
if ASN_ENABLE and bot in BOT_ASN and asn_of(ip) in BOT_ASN[bot]:
rdns_asn[bot] += hits
rdns_ok_ips.setdefault(bot, set()).add(ip)
confirmed = True
else:
rdns_noptr[bot] += hits
else:
rdns_mismatch[bot] += hits
if confirmed:
for p, st, nb in rdns_paths.get(bot, {}).get(ip, ()):
record_verified(bot, p, st, nb)
socket.setdefaulttimeout(None)
if not WEEKLY:
s0 = stamps[0]
count, ips = per_day[s0][0], len(per_day[s0][1])
print(f"{s0}: {count} requests, {ips} unique IPs (threshold {THRESHOLD})")
if DRY or count <= THRESHOLD:
sys.exit(0)
subject = f"{SITE}: {count} requests on {s0} (over {THRESHOLD}/day threshold)"
body = (f"Forgejo served {count} requests from {ips} unique IPs on {s0} - "
f"above the {THRESHOLD}/day watch threshold.\n\n"
"Time to consider Anubis (PoW challenge) in front of Forgejo.\n")
else:
lines = [f"{SITE} weekly crawler report ({stamps[0]} - {stamps[-1]})", ""]
lines.append(f"Total: {total} requests, {len(all_ips)} unique IPs")
lines.append(f"Daily threshold alert fires above {THRESHOLD} req/day (none = quiet week)")
lines.append("")
lines.append("Per day:")
for s in stamps:
lines.append(f" {s}: {per_day[s][0]:>7} requests, {len(per_day[s][1]):>6} unique IPs")
lines.append("")
lines.append("Top repos:")
for r, c in repos.most_common(5):
lines.append(f" {c:>7} {r}")
lines.append("")
lines.append("User-agent classes (browser-like = mostly the spoofing swarm):")
for u, c in uas.most_common(8):
lines.append(f" {c:>7} {u}")
lines.append("")
# --- legitimate (IP-verified) crawlers -------------------------------
lines.append("=" * 62)
lines.append("LEGITIMATE CRAWLERS (source IP inside vendor's published ranges)")
lines.append("=" * 62)
if STALE:
lines.append(f"NOTE: range fetch failed for {', '.join(STALE)} - used cache")
tv, ts, tp = sum(verified.values()), sum(spoofed.values()), sum(proxied.values())
claimed = tv + ts + tp
if not claimed:
lines.append(" No AI-bot user-agents seen this week.")
else:
lines.append(f" {'bot':<20}{'verified':>9}{'spoofed':>9}{'via CF':>8} {'IPs':>4}")
for bot in sorted(set(verified) | set(spoofed) | set(proxied),
key=lambda b: -(verified[b] + spoofed[b] + proxied[b])):
lines.append(f" {bot:<20}{verified[bot]:>9}{spoofed[bot]:>9}"
f"{proxied[bot]:>8} {len(ver_ips.get(bot, ())):>4}")
pct = tv / claimed * 100
lines.append("")
lines.append(f" {claimed} requests claimed an AI-bot identity; {tv} verified ({pct:.1f}%).")
lines.append(f" {ts} failed IP verification (spoofed). {tp} arrived via Cloudflare")
lines.append(" and cannot be verified by IP - not counted either way.")
# --- vendors verified by reverse DNS ---------------------------------
if RDNS_ENABLE and (rdns_ok or rdns_mismatch or rdns_noptr or rdns_asn
or rdns_proxied or rdns_private):
lines.append("")
lines.append("-" * 62)
lines.append("VERIFIED BY DNS / ASN (vendors publishing no IP ranges)")
lines.append("-" * 62)
lines.append(f" {'bot':<20}{'PTR ok':>7}{'ASN ok':>7}{'FORGED':>8}"
f"{'no-PTR':>7}{'CF':>6}{'priv':>7} {'IPs':>4}")
allbots = (set(rdns_ok) | set(rdns_mismatch) | set(rdns_noptr)
| set(rdns_asn) | set(rdns_proxied) | set(rdns_private))
for bot in sorted(allbots, key=lambda b: -(rdns_ok[b] + rdns_mismatch[b]
+ rdns_noptr[b] + rdns_asn[b]
+ rdns_proxied[b] + rdns_private[b])):
lines.append(f" {bot:<20}{rdns_ok[bot]:>7}{rdns_asn[bot]:>7}"
f"{rdns_mismatch[bot]:>8}{rdns_noptr[bot]:>7}"
f"{rdns_proxied[bot]:>6}{rdns_private[bot]:>7}"
f" {len(rdns_ok_ips.get(bot, ())):>4}")
if rdns_skipped:
sk = ", ".join(f"{b} {c}" for b, c in rdns_skipped.most_common(4))
lines.append(f" (unresolved, over CRAWLER_RDNS_MAX={RDNS_MAX}: {sk})")
lines.append("")
lines.append(" PTR ok forward-confirmed: PTR ends in a vendor domain AND")
lines.append(" that hostname resolves back to the same address.")
lines.append(" ASN ok no PTR, but the address sits in an ASN belonging")
lines.append(" solely to the vendor (Meta's AS32934). Only used")
lines.append(" where the ASN sells no compute - never for clouds.")
lines.append(" FORGED a PTR exists and points somewhere else. This is")
lines.append(" the only column that is evidence of forgery.")
lines.append(" no-PTR no PTR record and no usable ASN: unknown, not bad.")
if sum(rdns_private.values()):
lines.append(" priv logged source was RFC1918: a proxy or Docker")
lines.append(" bridge masked the client. Unjudgeable. See README.")
# --- what the verified crawlers actually fetched ---------------------
# Last, because it spans both tables above: an address only counts here
# once it has been confirmed, whether by IP range, PTR or ASN.
if ver_paths:
lines.append("")
lines.append("=" * 62)
lines.append("WHAT THE VERIFIED CRAWLERS DID (all methods)")
lines.append("=" * 62)
tot_v = sum(ver_paths.values())
mb = ver_bytes[0] / 1048576
lines.append(f" {tot_v} requests, {mb:.1f} MB served.")
if ver_status:
mix = " ".join(f"{s}:{c}" for s, c in ver_status.most_common(6))
lines.append(f" Status: {mix}")
if ver_bot_bytes:
top = " ".join(f"{b} {v/1048576:.1f}MB"
for b, v in ver_bot_bytes.most_common(4))
lines.append(f" Bandwidth: {top}")
lines.append("")
if not ROBOTS_RULES:
lines.append(" robots.txt compliance: not checked "
"(set CRAWLER_ROBOTS to enable)")
elif ver_violations:
n = sum(ver_violations.values())
lines.append(f" ROBOTS.TXT VIOLATIONS: {n} requests to disallowed paths")
for p, c in ver_violations.most_common(6):
lines.append(f" {c:>6} {p}")
lines.append(" A verified crawler ignoring robots.txt is a policy")
lines.append(" problem, not a security one - the identity is genuine.")
else:
lines.append(f" robots.txt compliance: clean, 0 violations in "
f"{tot_v} requests")
lines.append("")
# Repository content vs everything else. If robots.txt permits
# /src/ and /raw/, this is what says whether anyone took it up.
nc = sum(ver_content.values())
pct_c = nc / tot_v * 100 if tot_v else 0
lines.append(f" Repository content fetched: {nc} of {tot_v} requests "
f"({pct_c:.1f}%)")
if nc:
by_bot = " ".join(f"{b} {c}" for b, c in ver_content.most_common(5))
lines.append(f" by: {by_bot}")
for p, c in ver_content_paths.most_common(8):
lines.append(f" {c:>6} {p}")
else:
lines.append(" none - crawlers indexed the site but read no code")
# Which repositories each vendor cares about. Grouped by vendor
# rather than by UA token: OpenAI alone sends three tokens, and
# "what is OpenAI reading" is the useful question.
if ver_repos:
groups = {}
for b, c in ver_repos.items():
if b in BOT_VENDOR:
v = BOT_VENDOR[b] # openai, anthropic, ...
elif b in BOT_ASN:
v = "meta"
elif b in BOT_RDNS:
v = b.lower() # amazonbot, youbot, ...
else:
v = b.lower()
groups.setdefault(v, Counter()).update(c)
lines.append("")
lines.append(" Repositories by vendor:")
for v in sorted(groups, key=lambda x: -sum(groups[x].values())):
tot = sum(groups[v].values())
top = ", ".join(f"{r} ({n})" for r, n in groups[v].most_common(3))
lines.append(f" {v:<12} {tot:>5} hits {top}")
if ver_pkgs or ver_pkg_index:
np = sum(ver_pkgs.values()) + sum(ver_pkg_index.values())
lines.append("")
lines.append(f" Package registry: {np} requests")
for p, c in ver_pkgs.most_common(6):
lines.append(f" {c:>6} {p}")
if ver_pkg_index:
idx = ", ".join(f"{o} ({n})" for o, n in ver_pkg_index.most_common(4))
lines.append(f" index pages: {idx}")
lines.append("")
lines.append(" Top paths overall:")
for p, c in ver_paths.most_common(12):
lines.append(f" {c:>6} {p}")
body = "\n".join(lines) + "\n"
subject = f"{SITE} weekly crawler report: {total} requests, {len(all_ips)} IPs"
if DRY:
print(subject); print(); print(body)
sys.exit(0)
# SMTP settings: use CRAWLER_SMTP_* if given, otherwise borrow them from
# a Forgejo/Gitea app.ini [mailer] section so there is no second copy of
# the credentials to keep in sync.
if os.environ.get("CRAWLER_SMTP_ADDR"):
addr = os.environ["CRAWLER_SMTP_ADDR"]
port = int(os.environ.get("CRAWLER_SMTP_PORT", "587"))
user = os.environ.get("CRAWLER_SMTP_USER", "")
passwd = os.environ.get("CRAWLER_SMTP_PASSWORD", "")
sender = os.environ.get("CRAWLER_SMTP_FROM", user or RECIPIENT)
proto = os.environ.get("CRAWLER_SMTP_PROTOCOL", "smtp+starttls")
else:
ini = subprocess.run(["docker", "exec", MAIL_CONTAINER, "cat", MAIL_INI],
capture_output=True, text=True).stdout
if not ini.strip():
sys.exit(f"could not read {MAIL_INI} from container "
f"'{MAIL_CONTAINER}' and CRAWLER_SMTP_ADDR is unset")
cp = configparser.ConfigParser(interpolation=None, strict=False)
cp.read_string("[DEFAULT]\n" + ini)
m = cp["mailer"]
proto = m.get("PROTOCOL", "smtps").strip()
addr, port = m.get("SMTP_ADDR").strip(), int(m.get("SMTP_PORT", "465").strip())
user, passwd = m.get("USER", "").strip(), m.get("PASSWD", "").strip().strip("`\"")
sender = m.get("FROM", user).strip()
msg = MIMEText(body)
msg["Subject"], msg["From"], msg["To"] = subject, sender, RECIPIENT
if proto == "smtps":
s = smtplib.SMTP_SSL(addr, port, timeout=30)
else:
s = smtplib.SMTP(addr, port, timeout=30)
if proto != "smtp": # plain smtp = no TLS (local relay)
s.starttls()
if user: # unauthenticated local relays exist
s.login(user, passwd)
s.sendmail(sender, [RECIPIENT], msg.as_string())
s.quit()
print(f"mailed to {RECIPIENT}")

View file

@ -0,0 +1,82 @@
# Crawler watch for Forgejo: separates real AI crawlers from traffic that
# only claims to be one, from Traefik's access log. A daily mail when
# yesterday crossed the threshold, a weekly summary, and metrics every
# five minutes for the Crawlers dashboard.
{
config,
lib,
pkgs,
...
}:
let
# flag: "" (daily alert), "--weekly" or "--metrics"
run = flag: extra: {
description = "Crawler report ${flag}";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
environment = {
CRAWLER_SITE = "git.asxp.io";
CRAWLER_THRESHOLD = "100000";
CRAWLER_ROBOTS = "https://git.czsk.it/robots.txt";
CRAWLER_LOG = "/var/log/traefik/access.log*";
CRAWLER_LIVE_LOG = "/var/log/traefik/access.log";
CRAWLER_ROUTER = "forgejo@file";
CRAWLER_TEXTFILE = "/var/lib/node_exporter/textfile/crawler.prom";
CRAWLER_SMTP_ADDR = "smtp.fastmail.com";
CRAWLER_SMTP_PORT = "587";
CRAWLER_SMTP_FROM = "Czechoslovakia Git <noreply@asxp.io>";
}
// extra;
serviceConfig = {
Type = "oneshot";
EnvironmentFile = config.sops.templates."crawler.env".path;
CacheDirectory = "crawler-alert";
ExecStart = "${pkgs.python3}/bin/python3 ${./crawler-alert.py} ${flag}";
};
};
in
{
sops.templates."crawler.env".content = ''
CRAWLER_RECIPIENT=${config.sops.placeholder."alert/recipient"}
CRAWLER_SMTP_USER=${config.sops.placeholder."alert/smtp_user"}
CRAWLER_SMTP_PASSWORD=${config.sops.placeholder."alert/smtp_password"}
'';
systemd.services = {
crawler-alert = run "" { };
crawler-weekly = run "--weekly" { };
# Every router, not only Forgejo's; fewer DNS lookups per run
crawler-metrics = lib.recursiveUpdate (run "--metrics" {
CRAWLER_METRICS_ROUTER = "";
CRAWLER_RDNS_MAX = "100";
}) {
serviceConfig = {
Nice = 10;
TimeoutStartSec = "4min";
};
};
};
systemd.timers = {
crawler-alert = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "*-*-* 00:15:00";
Persistent = true;
};
};
crawler-weekly = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "Mon *-*-* 12:00:00";
Persistent = true;
};
};
crawler-metrics = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "*:0/5";
RandomizedDelaySec = 30;
};
};
};
}

View file

@ -0,0 +1,74 @@
# asxpio-ops: Traefik, Forgejo, storage, the app stacks.
# Services are added here as they move over from ../../ansible (see
# MIGRATION.md at the repo root); until then this is the base system only.
{ lib, ... }:
{
imports = [
./apps.nix
./crawler.nix
./forgejo.nix
./garage.nix
./monitoring
./options.nix
./postgres.nix
./traefik.nix
./xmpp-cert-sync.nix
];
networking.hostName = lib.mkDefault "asxpio-ops";
networking.domain = "asxp.io";
asxpio.privateIPv4 = "10.10.0.10";
system.stateVersion = "26.05";
systemd.network.networks."10-public".address = [ "2a01:4f9:c013:3258::1/64" ];
sops.defaultSopsFile = lib.mkDefault ../../secrets/asxpio-ops.yaml;
# --- WireGuard hub -------------------------------------------------------
asxpio.wireguard = {
interface = "wg0";
address = [
"10.20.0.10/24"
"fd69:69:69::1/64"
];
listenPort = 60101;
hub = true;
peers = lib.mkDefault (
map
(p: {
inherit (p) name publicKey;
allowedIPs = [
"10.20.0.${toString p.id}/32"
"fd69:69:69::${toString p.id}/128"
];
})
[
{ id = 20; name = "asxpio-services"; publicKey = "I2D4RvGHm0bW2mMlq9lPvbINHvnP9MsZg4XGMKTLiSU="; }
{ id = 2; name = "laptop"; publicKey = "6xYBPCiAa1MBusj7ilHGvwIoj26cXymvVksrOQLY52g="; }
{ id = 3; name = "aleks"; publicKey = "Csqd94oo6eRLUrlzeEkFxlW2IZtQG61ASXdK+ZjKzGI="; }
{ id = 4; name = "zerrtika"; publicKey = "uBRSmDuM25ciVaS9GxlCbjNPMUlmtphPDvtcEFzs8kI="; }
{ id = 5; name = "sanya"; publicKey = "tegWIorm7PjagnixbzQjCGLqDKVImynLNgk/bfx2PEk="; }
]
);
};
swapDevices = [
{
device = "/swapfile";
size = 2048;
}
];
# --- Backup ---------------------------------------------------------------
# Each service adds its own paths and hooks next to its definition:
# Postgres as a dump, Garage with a metadata snapshot, Forgejo's SQLite
# through the online backup API.
asxpio.backup = {
hostName = "asxpio-ops";
schedule = "*-*-* 03:30:00";
paths = [
"/etc/ssh" # the host key decrypts this host's secrets
"/opt"
];
};
}

View file

@ -0,0 +1,136 @@
# Forgejo at git.asxp.io (git.czsk.it is an alias), with its package
# registry and Actions. It runs as user git, so git@git.asxp.io reaches
# it through the host's sshd with no passthrough.
#
# State: /var/lib/forgejo (repositories/, data/forgejo.db, data/lfs, ...).
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.forgejo;
secret = name: config.sops.secrets."forgejo/${name}".path;
in
{
sops.secrets = lib.genAttrs (map (n: "forgejo/${n}") [
"secret_key"
"internal_token"
"jwt_secret"
"lfs_jwt_secret"
"smtp_user"
"smtp_password"
"metrics_token"
]) (_: { owner = cfg.user; });
users.users.git = {
isSystemUser = true;
group = "git";
home = cfg.stateDir;
# Forgejo's SSH commands run through it; not the zsh default
shell = pkgs.bashInteractive;
};
users.groups.git = { };
# Anyone may try a key against git; Forgejo decides what it may do
services.openssh.settings.AllowUsers = [ "git" ];
asxpio.security.loginUsers = [ "git" ];
# HTTP for Traefik and, over the private network, for the runners
asxpio.security.ports = [ "tcp/3000/.forgejo-wrappe" ];
asxpio.security.forgejoDb = "${cfg.stateDir}/data/forgejo.db";
services.forgejo = {
enable = true;
package = pkgs.forgejo; # the current release, not the LTS: the data is from 17
user = "git";
group = "git";
database.type = "sqlite3";
lfs.enable = true;
secrets = {
security.SECRET_KEY = lib.mkForce (secret "secret_key");
security.INTERNAL_TOKEN = lib.mkForce (secret "internal_token");
oauth2.JWT_SECRET = lib.mkForce (secret "jwt_secret");
server.LFS_JWT_SECRET = lib.mkForce (secret "lfs_jwt_secret");
mailer.USER = secret "smtp_user";
mailer.PASSWD = secret "smtp_password";
metrics.TOKEN = secret "metrics_token";
};
settings = {
DEFAULT.APP_NAME = "Git with a cup of tea";
server = {
DOMAIN = "git.asxp.io";
ROOT_URL = "https://git.asxp.io/";
HTTP_PORT = 3000;
SSH_DOMAIN = "git.asxp.io";
SSH_PORT = 22;
LANDING_PAGE = "explore";
};
repository = {
DEFAULT_BRANCH = "main";
DEFAULT_PRIVATE = "private";
ENABLE_PUSH_CREATE_USER = true;
ENABLE_PUSH_CREATE_ORG = false;
DEFAULT_REPO_UNITS = "repo.code,repo.releases,repo.issues,repo.pulls,repo.wiki,repo.projects,repo.packages,repo.actions";
};
"repository.pull-request".DEFAULT_MERGE_STYLE = "merge";
"repository.signing".DEFAULT_TRUST_MODEL = "collaborator";
ui = {
THEMES = "forgejo-auto,forgejo-light,forgejo-dark,gitea-auto,gitea-light,gitea-dark";
DEFAULT_THEME = "forgejo-auto";
};
security.PASSWORD_HASH_ALGO = "pbkdf2";
service = {
DISABLE_REGISTRATION = true;
REQUIRE_SIGNIN_VIEW = false;
REGISTER_EMAIL_CONFIRM = false;
ENABLE_NOTIFY_MAIL = true;
DEFAULT_KEEP_EMAIL_PRIVATE = true;
DEFAULT_ALLOW_CREATE_ORGANIZATION = true;
DEFAULT_ENABLE_TIMETRACKING = true;
NO_REPLY_ADDRESS = "noreply.git.asxp.io";
};
oauth2.ENABLED = true;
mailer = {
ENABLED = lib.mkDefault true;
FROM = "Czechoslovakia Git <noreply@asxp.io>";
PROTOCOL = "smtp+starttls";
SMTP_ADDR = "smtp.fastmail.com";
SMTP_PORT = 587;
};
session.PROVIDER = "file";
log.LEVEL = "Info";
actions = {
ENABLED = true;
DEFAULT_ACTIONS_URL = "https://github.com";
ARTIFACT_RETENTION_DAYS = 365;
};
packages.ENABLED = true;
other = {
SHOW_FOOTER_VERSION = false;
SHOW_FOOTER_TEMPLATE_LOAD_TIME = false;
SHOW_FOOTER_POWERED_BY = false;
};
metrics.ENABLED = true;
};
};
asxpio.waitForData = [
"forgejo"
"forgejo-secrets"
];
# `forgejo-admin regenerate keys`, `forgejo-admin user list`, ...
environment.systemPackages = [
(pkgs.writeShellScriptBin "forgejo-admin" ''
exec ${pkgs.util-linux}/bin/runuser -u ${cfg.user} -- env \
HOME=${cfg.stateDir} FORGEJO_WORK_DIR=${cfg.stateDir} FORGEJO_CUSTOM=${cfg.customDir} \
${lib.getExe cfg.package} --config ${cfg.customDir}/conf/app.ini admin "$@"
'')
];
asxpio.backup.paths = [ "/var/lib/forgejo" ];
asxpio.backup.hooks = [
''sqlite3 /var/lib/forgejo/data/forgejo.db ".backup '$STAGE/forgejo.db'"''
];
}

View file

@ -0,0 +1,174 @@
# Garage (S3) for the apps, single node. Buckets, keys and grants are set
# on every start from sops.
#
# asxpio-invoices asxpio rw
# datacenterbingo-photos asxpio rw, bingo ro
# public a website (anonymous reads through Traefik);
# asxpio and public-upload write only
#
# Garage only takes keys in its own format (GK + 24 hex, 64 hex). The
# apps' keys predate it and are hashed into that format, here and in each
# app's deploy workflow: keep the two in step.
{
config,
lib,
pkgs,
...
}:
let
garage = pkgs.garage_2;
rpcSecret = config.sops.secrets."garage/rpc_secret".path;
keys = [
"asxpio"
"bingo"
"public"
];
in
{
sops.secrets = {
"garage/rpc_secret" = { };
}
// lib.listToAttrs (
lib.concatMap (k: [
(lib.nameValuePair "garage/${k}_access_key" { })
(lib.nameValuePair "garage/${k}_secret_key" { })
]) keys
);
services.garage = {
enable = true;
package = garage;
# The RPC secret is a systemd credential: mode 0440, but in a
# directory only this service can enter
extraEnvironment.GARAGE_ALLOW_WORLD_READABLE_SECRETS = "true";
settings = {
# One node and no replica to repair from, so prefer the engine that
# survives an unclean stop, sync writes, and keep metadata snapshots
db_engine = "sqlite";
metadata_fsync = true;
data_fsync = true;
metadata_auto_snapshot_interval = "6h";
replication_factor = 1;
rpc_bind_addr = "[::]:3901";
rpc_public_addr = "127.0.0.1:3901";
rpc_secret_file = "/run/credentials/garage.service/rpc_secret";
# The apps sign for us-east-1, as they did against MinIO
s3_api = {
s3_region = "us-east-1";
api_bind_addr = "[::]:3900";
};
# Anonymous reads: a bucket marked as a website is served here,
# picked by Host: <bucket>.web.garage
s3_web = {
bind_addr = "[::]:3902";
root_domain = ".web.garage";
index = "index.html";
};
};
};
asxpio.waitForData = [
"garage"
"garage-bootstrap"
];
systemd.services.garage = {
serviceConfig = {
LoadCredential = [ "rpc_secret:${rpcSecret}" ];
ExecStart = lib.mkForce "${garage}/bin/garage server --single-node";
};
};
networking.firewall.interfaces."podman*".allowedTCPPorts = [ 3900 ];
asxpio.security.ports = [ "tcp/3900-3902/garage" ];
# `garage` for root, e.g. garage status, garage bucket list
environment.systemPackages = [
(pkgs.writeShellScriptBin "garage" ''
export GARAGE_RPC_SECRET_FILE=${rpcSecret}
exec ${garage}/bin/garage -c /etc/garage.toml "$@"
'')
];
systemd.services.garage-bootstrap = {
description = "Garage buckets, keys and grants";
after = [ "garage.service" ];
requires = [ "garage.service" ];
wantedBy = [ "multi-user.target" ];
path = [
garage
pkgs.gnugrep
pkgs.coreutils
];
environment.GARAGE_RPC_SECRET_FILE = rpcSecret;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = ''
set -eu
g() { garage -c /etc/garage.toml "$@"; }
secret() { cat "/run/secrets/garage/$1"; }
key_id() {
if printf '%s' "$1" | grep -Eq '^GK[0-9a-f]{24}$'; then printf '%s' "$1"
else printf 'GK%s' "$(printf '%s' "$1" | sha256sum | cut -c1-24)"; fi
}
key_secret() {
if printf '%s' "$1" | grep -Eq '^[0-9a-f]{64}$'; then printf '%s' "$1"
else printf '%s' "$1" | sha256sum | cut -c1-64; fi
}
i=0
until g status >/dev/null 2>&1; do
i=$((i + 1))
[ "$i" -le 60 ] || { echo "garage did not come up" >&2; exit 1; }
sleep 1
done
ensure_bucket() { g bucket info "$1" >/dev/null 2>&1 || g bucket create "$1" >/dev/null; }
# ensure_key <name> <sops prefix>: prints the key id
ensure_key() {
id="$(key_id "$(secret "$2_access_key")")"
sec="$(key_secret "$(secret "$2_secret_key")")"
if g key info --show-secret "$id" >/dev/null 2>&1; then
if ! g key info --show-secret "$id" | grep -q "$sec"; then
g key delete --yes "$id" >/dev/null
g key import --yes -n "$1" "$id" "$sec" >/dev/null
fi
else
g key import --yes -n "$1" "$id" "$sec" >/dev/null
fi
printf '%s' "$id"
}
grant() {
case "$3" in
rw) g bucket allow --read --write "$1" --key "$2" >/dev/null
g bucket deny --owner "$1" --key "$2" >/dev/null ;;
ro) g bucket allow --read "$1" --key "$2" >/dev/null
g bucket deny --write --owner "$1" --key "$2" >/dev/null ;;
wo) g bucket allow --write "$1" --key "$2" >/dev/null
g bucket deny --read --owner "$1" --key "$2" >/dev/null ;;
esac
}
ensure_bucket asxpio-invoices
ensure_bucket datacenterbingo-photos
ensure_bucket public
g bucket website --allow public >/dev/null
asxpio="$(ensure_key asxpio asxpio)"
grant asxpio-invoices "$asxpio" rw
grant datacenterbingo-photos "$asxpio" rw
grant public "$asxpio" wo
bingo="$(ensure_key bingo bingo)"
grant datacenterbingo-photos "$bingo" ro
uploader="$(ensure_key public-upload public)"
grant public "$uploader" wo
'';
};
asxpio.backup.paths = [ "/var/lib/garage" ];
asxpio.backup.hooks = [ "/run/current-system/sw/bin/garage meta snapshot --all" ];
}

View file

@ -0,0 +1,544 @@
# Managed by Ansible (role monitoring).
apiVersion: 1
groups:
- orgId: 1
name: asxpio
folder: Alerts
interval: 1m
rules:
- uid: host-down
title: "Host down"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "1 - up{job=\"node\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 2m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }} stopped answering (node_exporter over the VPC)" }
- uid: target-down
title: "Scrape target down"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "up{job!~\"node|probe_.*\"} == 0", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [-1] } } ] }
noDataState: OK
execErrState: Error
for: 5m
labels: { severity: warning }
annotations: { summary: "{{ $labels.job }} on {{ $labels.instance }} is not answering metrics scrapes" }
- uid: probe-down
title: "Service down (outside-in probe)"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "1 - probe_success", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 2m
labels: { severity: critical }
annotations: { summary: "{{ $labels.probe }} ({{ $labels.instance }}) is not reachable" }
- uid: cert-expiry
title: "Certificate expires soon"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "(probe_ssl_earliest_cert_expiry - time()) / 86400", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: lt, params: [14] } } ] }
noDataState: OK
execErrState: Error
for: 1h
labels: { severity: warning }
annotations: { summary: "{{ $labels.probe }}: certificate expires in {{ $values.A.Value | printf \"%.0f\" }} days" }
- uid: disk-full
title: "Disk almost full"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "100 * (1 - node_filesystem_avail_bytes{fstype!~\"tmpfs|overlay|squashfs|fuse.*\"} / node_filesystem_size_bytes{fstype!~\"tmpfs|overlay|squashfs|fuse.*\"})", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [85] } } ] }
noDataState: OK
execErrState: Error
for: 10m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }} {{ $labels.mountpoint }} is {{ $values.A.Value | printf \"%.0f\" }}% full" }
- uid: memory-low
title: "Memory almost exhausted"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "100 * (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [92] } } ] }
noDataState: OK
execErrState: Error
for: 10m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }} memory is {{ $values.A.Value | printf \"%.0f\" }}% used" }
- uid: container-restarting
title: "Container restart-looping"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "changes(container_start_time_seconds{name!=\"\"}[15m])", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [2] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.name }} on {{ $labels.host }} restarted {{ $values.A.Value | printf \"%.0f\" }} times in 15 minutes" }
- uid: postgres-down
title: "Postgres down"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "pg_up", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: lt, params: [1] } } ] }
noDataState: OK
execErrState: Error
for: 1m
labels: { severity: critical }
annotations: { summary: "Postgres (storage) is not answering" }
- uid: backup-stale
title: "Backup stale"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "(time() - restic_backup_last_success_timestamp_seconds) / 3600", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [26] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "restic on {{ $labels.host }}: last good backup {{ $values.A.Value | printf \"%.0f\" }} hours ago" }
- uid: xmpp-cert-sync-stale
title: "XMPP certificate sync stale"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "(time() - xmpp_cert_sync_last_success_timestamp_seconds) / 3600", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [50] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "xmpp-cert-sync on asxpio-ops last succeeded {{ $values.A.Value | printf \"%.0f\" }} hours ago (journalctl -u xmpp-cert-sync)" }
- uid: xmpp-cert-outdated
title: "XMPP serves an older certificate than Traefik has"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "((max(xmpp_cert_source_not_after_timestamp_seconds{cert=\"asxp.io\"}) - min(probe_ssl_earliest_cert_expiry{probe=\"xmpp c2s tls asxp.io\"})) / 86400 > 1) or ((max(xmpp_cert_source_not_after_timestamp_seconds{cert=\"xmpp.asxp.io\"}) - min(probe_ssl_earliest_cert_expiry{probe=\"xmpp c2s tls\"})) / 86400 > 1)", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [1] } } ] }
noDataState: OK
execErrState: Error
for: 6h
labels: { severity: warning }
annotations: { summary: "ejabberd's certificate expires {{ $values.A.Value | printf \"%.0f\" }} days before the one Traefik holds: the push or the reload failed" }
- uid: replica-stale
title: "Bucket replica stale"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "(time() - s3_replicate_last_success_timestamp_seconds) / 3600", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [26] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "hel1 -> fsn1 bucket replica: last good run {{ $values.A.Value | printf \"%.0f\" }} hours ago" }
# Security: unexpected peers, devices, accounts, ports and containers
# (metrics from security-metrics, role monitoring_agent) and logins
# (Loki). The baseline lives in that role's defaults and in host_vars.
- orgId: 1
name: security
folder: Alerts
interval: 1m
rules:
- uid: sec-wg-peer-unknown
title: "Unknown WireGuard peer"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_wg_peer_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "WireGuard peer {{ $labels.peer }} ({{ $labels.allowed_ips }}) on {{ $labels.host }} is not in wireguard_clients" }
- uid: sec-wg-endpoint-new
title: "WireGuard peer on a new network"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_wg_peer_endpoint_info unless on (host, interface, peer, net) max_over_time(security_wg_peer_endpoint_info[14d] offset 30m) and on (host) (security_audit_last_run_timestamp_seconds offset 1d)", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.peer }} connected to {{ $labels.host }} from {{ $labels.endpoint }}: no address in {{ $labels.net }} was seen for it in 14 days" }
- uid: sec-vpc-host-unknown
title: "Unknown device on the private network"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_vpc_host_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 2m
labels: { severity: critical }
annotations: { summary: "{{ $labels.ip }} answers on the VPC (seen from {{ $labels.host }}) and is not in security_vpc_hosts" }
- uid: sec-hcloud-server-unknown
title: "Unknown server in the Hetzner project"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "up{job=\"hcloud\",known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 2m
labels: { severity: critical }
annotations: { summary: "Server {{ $labels.server }} ({{ $labels.type }}, {{ $labels.public_ip }}, private {{ $labels.private_ip }}) exists in the Hetzner project and is not in monitoring_hcloud_servers" }
- uid: sec-hcloud-inventory-stale
title: "Hetzner server list not updating"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "absent(up{job=\"hcloud\"}) or increase(prometheus_sd_refresh_failures_total{mechanism=\"hetzner\"}[30m]) > 3", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 10m
labels: { severity: critical }
annotations: { summary: "Prometheus cannot list the servers of the Hetzner project (token revoked or API unreachable): new servers go unnoticed" }
- uid: sec-user-unknown
title: "Unknown login account"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_user_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }}: account {{ $labels.user }} (uid {{ $labels.uid }}, {{ $labels.shell }}) is not in security_login_users" }
- uid: sec-group-member-unknown
title: "Unknown member of sudo or docker"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_group_member_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }}: {{ $labels.user }} is in group {{ $labels.group }}" }
- uid: sec-files-changed
title: "Access files changed"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "changes(security_fileset_hash[15m])", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: a file in set {{ $labels.set }} changed (accounts, sudoers, sshd, wireguard or authorized_keys)" }
- uid: sec-port-unknown
title: "Unexpected listening port"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_listening_port_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 3m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: {{ $labels.process }} listens on {{ $labels.proto }}/{{ $labels.port }} ({{ $labels.scope }}), not in security_ports" }
- uid: sec-container-privileged
title: "Container with unexpected host access"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_container_privileged_info{known=\"false\"}", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }}: container {{ $labels.name }} runs with {{ $labels.flags }}" }
- uid: sec-container-new
title: "New container"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "group by (host, name) (container_last_seen{name!=\"\", name!~\"[a-z]+_[a-z]+\"}) unless on (host, name) group by (host, name) (max_over_time(container_last_seen{name!=\"\"}[7d] offset 30m))", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: container {{ $labels.name }} was not seen in the last 7 days" }
- uid: sec-forgejo-new
title: "Forgejo: new user, key or runner"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "security_forgejo_objects{kind=~\"users|admins|ssh_keys|deploy_keys|runners\"} - security_forgejo_objects offset 15m", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "Forgejo: {{ $labels.kind }} grew by {{ $values.A.Value | printf \"%.0f\" }}" }
- uid: sec-ssh-outside
title: "SSH login from outside WireGuard"
condition: C
data:
- refId: A
relativeTimeRange: { from: 300, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum by (host, user, src) (count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Accepted \\S+ for ` !~ `Accepted \\S+ for git from ` | regexp `Accepted \\S+ for (?P<user>\\S+) from (?P<src>\\S+)` | src !~ `10\\.20\\.0\\.\\d+|10\\.10\\.(\\d|1[0-5])\\.\\d+` [5m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: critical }
annotations: { summary: "{{ $labels.host }}: {{ $labels.user }} logged in over SSH from {{ $labels.src }}" }
- uid: sec-ssh-failed-internal
title: "Failed SSH logins from inside"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum by (host) (count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Failed \\S+ for |Invalid user |Connection closed by (authenticating|invalid) user ` |~ ` (10\\.20\\.0\\.\\d+|10\\.10\\.(\\d|1[0-5])\\.\\d+) port ` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [2] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: {{ $values.A.Value | printf \"%.0f\" }} failed SSH logins from WireGuard or VPC addresses in 10 minutes" }
- uid: sec-ssh-failed-burst
title: "Failed SSH logins spike"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum by (host) (count_over_time({job=\"journal\", unit=\"ssh.service\"} |~ `Failed \\S+ for |Invalid user |Connection closed by (authenticating|invalid) user ` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [150] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "{{ $labels.host }}: {{ $values.A.Value | printf \"%.0f\" }} failed SSH logins in 10 minutes (usual: about 10)" }
- uid: sec-login-failed-forgejo
title: "Failed logins: Forgejo"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum(count_over_time({unit=\"forgejo.service\"} |= `Failed authentication attempt` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [10] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "Forgejo: {{ $values.A.Value | printf \"%.0f\" }} failed logins in 10 minutes" }
- uid: sec-login-failed-grafana
title: "Failed logins: Grafana"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum(count_over_time({job=\"traefik-access\"} |= `\"grafana@file\"` |~ `\"POST /login HTTP/[0-9.]+\" 401 ` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [4] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "Grafana: {{ $values.A.Value | printf \"%.0f\" }} failed logins in 10 minutes" }
- uid: sec-login-failed-asxpio
title: "Failed logins: asxp.io admin"
condition: C
data:
- refId: A
relativeTimeRange: { from: 600, to: 0 }
datasourceUid: loki
model: { refId: A, expr: "sum(count_over_time({job=\"traefik-access\"} |= `\"asxpio@docker\"` |~ `\"POST /admin/login HTTP/[0-9.]+\" (401|429) ` [10m]))", queryType: instant, intervalMs: 60000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [4] } } ] }
noDataState: OK
execErrState: Error
for: 0m
labels: { severity: warning }
annotations: { summary: "asxp.io admin: {{ $values.A.Value | printf \"%.0f\" }} failed or rate-limited logins in 10 minutes" }
- uid: sec-logs-stopped
title: "Logs stopped arriving"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "sum by (host) (rate(loki_write_sent_entries_total[10m]))", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: lt, params: [0.001] } } ] }
noDataState: OK
execErrState: Error
for: 5m
labels: { severity: critical }
annotations: { summary: "Alloy on {{ $labels.host }} has sent Loki nothing for 10 minutes: every log-based alert is blind" }
- uid: sec-audit-stale
title: "Security metrics stale"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "(time() - security_audit_last_run_timestamp_seconds > 600) or on (host) (up{job=\"node\"} == 1 unless on (host) security_audit_last_run_timestamp_seconds)", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 5m
labels: { severity: critical }
annotations: { summary: "security-metrics on {{ $labels.host }} has not written its file for 10 minutes, or the file is gone" }
- uid: sec-audit-check-failed
title: "Security check failing"
condition: C
data:
- refId: A
relativeTimeRange: { from: 900, to: 0 }
datasourceUid: prometheus
model: { refId: A, expr: "1 - security_audit_check_ok", instant: true, intervalMs: 30000, maxDataPoints: 43200 }
- refId: C
datasourceUid: __expr__
model: { refId: C, type: threshold, expression: A, conditions: [ { evaluator: { type: gt, params: [0] } } ] }
noDataState: OK
execErrState: Error
for: 5m
labels: { severity: warning }
annotations: { summary: "security-metrics on {{ $labels.host }}: check {{ $labels.check }} fails (journalctl -u security-metrics)" }

View file

@ -0,0 +1,781 @@
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": 14282,
"graphTooltip": 0,
"id": null,
"iteration": 1617715580880,
"links": [],
"panels": [
{
"collapsed": false,
"datasource": "prometheus",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 0
},
"id": 8,
"panels": [],
"title": "CPU",
"type": "row"
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "prometheus",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 7,
"w": 24,
"x": 0,
"y": 1
},
"hiddenSeries": false,
"id": 15,
"legend": {
"alignAsTable": true,
"avg": true,
"current": false,
"max": true,
"min": false,
"rightSide": true,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null as zero",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.5",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": true,
"steppedLine": false,
"targets": [
{
"expr": "sum(rate(container_cpu_usage_seconds_total{instance=~\"$host\",name=~\"$container\",name=~\".+\"}[5m])) by (name) *100",
"hide": false,
"interval": "",
"legendFormat": "{{name}}",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "CPU Usage",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:606",
"format": "percent",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:607",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"collapsed": false,
"datasource": "prometheus",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 8
},
"id": 11,
"panels": [],
"title": "Memory",
"type": "row"
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "prometheus",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 9
},
"hiddenSeries": false,
"id": 9,
"legend": {
"alignAsTable": true,
"avg": true,
"current": false,
"max": true,
"min": false,
"rightSide": true,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null as zero",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.5",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": true,
"steppedLine": false,
"targets": [
{
"expr": "sum(container_memory_rss{instance=~\"$host\",name=~\"$container\",name=~\".+\"}) by (name)",
"hide": false,
"interval": "",
"legendFormat": "{{name}}",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Memory Usage",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:606",
"format": "bytes",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:607",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "prometheus",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 9
},
"hiddenSeries": false,
"id": 14,
"legend": {
"alignAsTable": true,
"avg": true,
"current": false,
"max": true,
"min": false,
"rightSide": true,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null as zero",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.5",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": true,
"steppedLine": false,
"targets": [
{
"expr": "sum(container_memory_cache{instance=~\"$host\",name=~\"$container\",name=~\".+\"}) by (name)",
"hide": false,
"interval": "",
"legendFormat": "{{name}}",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Memory Cached",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:606",
"format": "bytes",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:607",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"collapsed": false,
"datasource": "prometheus",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 17
},
"id": 2,
"panels": [],
"title": "Network",
"type": "row"
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "prometheus",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 18
},
"hiddenSeries": false,
"id": 4,
"legend": {
"alignAsTable": true,
"avg": true,
"current": false,
"hideEmpty": false,
"hideZero": false,
"max": true,
"min": false,
"rightSide": true,
"show": true,
"sideWidth": null,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.5",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "sum(rate(container_network_receive_bytes_total{instance=~\"$host\",name=~\"$container\",name=~\".+\"}[5m])) by (name)",
"hide": false,
"interval": "",
"legendFormat": "{{name}}",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Received Network Traffic",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:674",
"format": "Bps",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:675",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "prometheus",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 18
},
"hiddenSeries": false,
"id": 6,
"legend": {
"alignAsTable": true,
"avg": true,
"current": false,
"max": true,
"min": false,
"rightSide": true,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.5",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "sum(rate(container_network_transmit_bytes_total{instance=~\"$host\",name=~\"$container\",name=~\".+\"}[5m])) by (name)",
"interval": "",
"legendFormat": "{{name}}",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Sent Network Traffic",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:832",
"format": "Bps",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:833",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"collapsed": false,
"datasource": "prometheus",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 26
},
"id": 19,
"panels": [],
"title": "Misc",
"type": "row"
},
{
"datasource": "prometheus",
"fieldConfig": {
"defaults": {
"custom": {
"align": null,
"filterable": false
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "id"
},
"properties": [
{
"id": "custom.width",
"value": 260
}
]
},
{
"matcher": {
"id": "byName",
"options": "Running"
},
"properties": [
{
"id": "unit",
"value": "d"
},
{
"id": "decimals",
"value": 1
},
{
"id": "custom.displayMode",
"value": "color-text"
},
{
"id": "color",
"value": {
"fixedColor": "dark-green",
"mode": "fixed"
}
}
]
}
]
},
"gridPos": {
"h": 10,
"w": 24,
"x": 0,
"y": 27
},
"id": 17,
"options": {
"showHeader": true,
"sortBy": []
},
"pluginVersion": "7.4.5",
"targets": [
{
"expr": "(time() - container_start_time_seconds{instance=~\"$host\",name=~\"$container\",name=~\".+\"})/86400",
"format": "table",
"instant": true,
"interval": "",
"legendFormat": "{{name}}",
"refId": "A"
}
],
"timeFrom": null,
"timeShift": null,
"title": "Containers Info",
"transformations": [
{
"id": "filterFieldsByName",
"options": {
"include": {
"names": [
"container_label_com_docker_compose_project",
"container_label_com_docker_compose_project_working_dir",
"image",
"instance",
"name",
"Value",
"container_label_com_docker_compose_service"
]
}
}
},
{
"id": "organize",
"options": {
"excludeByName": {},
"indexByName": {},
"renameByName": {
"Value": "Running",
"container_label_com_docker_compose_project": "Label",
"container_label_com_docker_compose_project_working_dir": "Working dir",
"container_label_com_docker_compose_service": "Service",
"image": "Registry Image",
"instance": "Instance",
"name": "Name"
}
}
}
],
"type": "table"
}
],
"schemaVersion": 27,
"style": "dark",
"tags": [
"cadvisor",
"docker"
],
"templating": {
"list": [
{
"allValue": ".*",
"current": {},
"datasource": "prometheus",
"definition": "label_values({__name__=~\"container.*\"},instance)",
"description": null,
"error": null,
"hide": 0,
"includeAll": true,
"label": "Host",
"multi": false,
"name": "host",
"options": [],
"query": {
"query": "label_values({__name__=~\"container.*\"},instance)",
"refId": "Prometheus-host-Variable-Query"
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 5,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": ".*",
"current": {},
"datasource": "prometheus",
"definition": "label_values({__name__=~\"container.*\", instance=~\"$host\"},name)",
"description": null,
"error": null,
"hide": 0,
"includeAll": true,
"label": "Container",
"multi": false,
"name": "container",
"options": [],
"query": {
"query": "label_values({__name__=~\"container.*\", instance=~\"$host\"},name)",
"refId": "Prometheus-container-Variable-Query"
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
}
]
},
"time": {
"from": "now-6h",
"to": "now"
},
"timepicker": {},
"timezone": "",
"title": "Cadvisor exporter",
"uid": "gnet-14282",
"version": 1,
"description": "Simple exporter for cadvisor only"
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,248 @@
{
"annotations": {
"list": [
{
"$$hashKey": "object:75",
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"description": "Log Viewer Dashboard for Loki",
"editable": false,
"gnetId": 13639,
"graphTooltip": 0,
"id": null,
"iteration": 1608932746420,
"links": [
{
"$$hashKey": "object:59",
"icon": "bolt",
"includeVars": true,
"keepTime": true,
"tags": [],
"targetBlank": true,
"title": "View In Explore",
"type": "link",
"url": "/explore?orgId=1&left=[\"now-1h\",\"now\",\"Loki\",{\"expr\":\"{job=\\\"$app\\\"}\"},{\"ui\":[true,true,true,\"none\"]}]"
},
{
"$$hashKey": "object:61",
"icon": "external link",
"tags": [],
"targetBlank": true,
"title": "Learn LogQL",
"type": "link",
"url": "https://grafana.com/docs/loki/latest/logql/"
}
],
"panels": [
{
"aliasColors": {},
"bars": true,
"dashLength": 10,
"dashes": false,
"datasource": "loki",
"fieldConfig": {
"defaults": {
"custom": {},
"links": []
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 3,
"w": 24,
"x": 0,
"y": 0
},
"hiddenSeries": false,
"id": 6,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": false,
"total": false,
"values": false
},
"lines": false,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pluginVersion": "7.1.0",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "sum(count_over_time({job=\"$app\"} |= \"$search\" [$__interval]))",
"legendFormat": "",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:168",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": false
},
{
"$$hashKey": "object:169",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": false
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"datasource": "loki",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"gridPos": {
"h": 25,
"w": 24,
"x": 0,
"y": 3
},
"id": 2,
"maxDataPoints": "",
"options": {
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": false
},
"targets": [
{
"expr": "{job=\"$app\"} |= \"$search\" | logfmt",
"hide": false,
"legendFormat": "",
"refId": "A"
}
],
"timeFrom": null,
"timeShift": null,
"title": "",
"transparent": true,
"type": "logs"
}
],
"refresh": false,
"schemaVersion": 26,
"style": "dark",
"tags": [],
"templating": {
"list": [
{
"allValue": null,
"current": {},
"datasource": "loki",
"definition": "label_values(job)",
"hide": 0,
"includeAll": false,
"label": "App",
"multi": false,
"name": "app",
"options": [],
"query": "label_values(job)",
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"current": {
"selected": false,
"text": "",
"value": ""
},
"hide": 0,
"label": "String Match",
"name": "search",
"options": [
{
"selected": true,
"text": "",
"value": ""
}
],
"query": "",
"skipUrlSync": false,
"type": "textbox"
}
]
},
"time": {
"from": "now-1h",
"to": "now"
},
"timepicker": {
"hidden": false,
"refresh_intervals": [
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
]
},
"timezone": "",
"title": "Logs / App",
"uid": "gnet-13639",
"version": 13
}

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more