From a9f94fc49235965940d9ffe742e38cc15ce34ed7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Mon, 23 Nov 2026 18:33:42 +0100 Subject: [PATCH 1/2] feat(agents): multi-arch checker and status page images on scratch uptimesebi-checker and uptimesebi-statuspage for linux/amd64, arm64, arm/v7 and arm/v6, from a Raspberry Pi Zero to servers. tools/image assembles them from the cross-compiled binaries without Docker or emulation: one layer on an empty base with the binary, a data volume owned by the unprivileged user and a HEALTHCHECK running the new `checker health` / `statuspage health` commands. The binaries embed time zone data and fallback CA roots, so no base image ever needs updating. CI pushes them with the same channel tags as the main image; releases carry tarballs for all four platforms. Refs #128 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .gitea/workflows/ci.yaml | 36 ++++- .gitea/workflows/release.yaml | 8 +- README.md | 9 +- cmd/checker/main.go | 17 +++ cmd/statuspage/main.go | 16 +++ go.mod | 8 ++ go.sum | 16 +++ internal/platform/probe.go | 36 +++++ internal/platform/roots.go | 9 ++ tools/image/build.go | 238 ++++++++++++++++++++++++++++++++++ tools/image/image_test.go | 169 ++++++++++++++++++++++++ tools/image/main.go | 85 ++++++++++++ 12 files changed, 638 insertions(+), 9 deletions(-) create mode 100644 internal/platform/probe.go create mode 100644 internal/platform/roots.go create mode 100644 tools/image/build.go create mode 100644 tools/image/image_test.go create mode 100644 tools/image/main.go diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 1b89d5b..f90158f 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -132,11 +132,39 @@ jobs: run: npm ci --no-audit --no-fund && npm run build - name: Build binaries run: | - for platform in linux/amd64 linux/arm64; do - CGO_ENABLED=0 GOOS=${platform%/*} GOARCH=${platform#*/} \ - go build -trimpath -ldflags "-s -w" -o "dist/${platform%/*}_${platform#*/}/" ./cmd/... + set -eu + pkg=git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo + case "$GITHUB_REF" in + refs/tags/v*) version="$GITHUB_REF_NAME" ;; + *) version="$(git log -1 --format=%cd --date=format:%Y%m%d%H%M%S)-$(git rev-parse --short=12 HEAD)" ;; + esac + echo "VERSION=$version" >> "$GITHUB_ENV" + for platform in linux/amd64 linux/arm64 linux/arm/v7 linux/arm/v6; do + IFS=/ read -r os arch variant <<< "$platform" + CGO_ENABLED=0 GOOS=$os GOARCH=$arch GOARM=${variant#v} go build -trimpath \ + -ldflags "-s -w -X $pkg.Version=$version -X $pkg.Commit=$(git rev-parse --short=12 HEAD)" \ + -o "dist/$(echo "$platform" | tr / _)/" ./cmd/... done - ls -R dist + ls -lR dist + # Checker and status page images for every platform, assembled from the + # binaries above without Docker; pushed like the main image. + - name: Agent images + env: + PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }} + run: | + set -eu + host="${GITHUB_SERVER_URL#*://}" + owner="$(printf '%s' "${GITHUB_REPOSITORY%/*}" | tr 'A-Z' 'a-z')" + flags="-version $VERSION -commit $GITHUB_SHA -ref $GITHUB_REF -created $(git log -1 --format=%ct) -source $GITHUB_SERVER_URL/$GITHUB_REPOSITORY" + case "$GITHUB_SERVER_URL" in http://*) flags="$flags -insecure" ;; esac + case "$GITHUB_REF" in + refs/heads/main|refs/tags/v*) + if [ -n "${PACKAGE_TOKEN:-}" ]; then flags="$flags -push"; else echo "PACKAGE_TOKEN is not set; building without pushing."; fi ;; + esac + export REGISTRY_USER="$GITHUB_ACTOR" REGISTRY_PASSWORD="${PACKAGE_TOKEN:-}" + go run ./tools/image -name checker -repo "$host/$owner/uptimesebi-checker" -port 8081/tcp $flags + go run ./tools/image -name statuspage -repo "$host/$owner/uptimesebi-statuspage" -port 8082/tcp \ + -env UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi $flags image: # Kaniko runs rootless from docker:cli, the same way as the other diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml index eee8ca1..59972fe 100644 --- a/.gitea/workflows/release.yaml +++ b/.gitea/workflows/release.yaml @@ -28,10 +28,10 @@ jobs: set -eu pkg=git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo commit="$(git rev-parse --short=12 HEAD)" - for platform in linux/amd64 linux/arm64; do - os=${platform%/*} arch=${platform#*/} - dir="uptimesebi_${GITHUB_REF_NAME#v}_${os}_${arch}" - CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -trimpath \ + for platform in linux/amd64 linux/arm64 linux/arm/v7 linux/arm/v6; do + IFS=/ read -r os arch variant <<< "$platform" + dir="uptimesebi_${GITHUB_REF_NAME#v}_${os}_${arch}${variant}" + CGO_ENABLED=0 GOOS=$os GOARCH=$arch GOARM=${variant#v} go build -trimpath \ -ldflags "-s -w -X $pkg.Version=$GITHUB_REF_NAME -X $pkg.Commit=$commit" \ -o "dist/$dir/" ./cmd/... cp LICENSE README.md .env.example "dist/$dir/" diff --git a/README.md b/README.md index 08e910d..db10227 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ One image contains all three commands; `api` is the default entrypoint. Images a | `beta` | the newest prerelease (`1.5.0-beta.N`) | | `edge` | every commit on `main` | -Each [release](https://git.zb-server.de/ZB-Server/uptimesebi/releases) also carries Linux binaries (amd64, arm64) with checksums and the changelog. Or build the image yourself: +Each [release](https://git.zb-server.de/ZB-Server/uptimesebi/releases) also carries Linux binaries (amd64, arm64, armv7, armv6) with checksums and the changelog. Or build the image yourself: ```sh docker build -t uptimesebi . @@ -87,6 +87,13 @@ docker run -d -e UPTIME_API_URL=https://uptime.example.com -e UPTIME_AGENT_TOKEN --entrypoint /usr/local/bin/checker uptimesebi ``` +Checkers and status page servers also come as small images of their own, `uptimesebi-checker` and `uptimesebi-statuspage` (same tags), for Linux on amd64, arm64, arm/v7 and arm/v6, so they run on anything from a Raspberry Pi Zero to a server; `docker pull` picks the right one. They contain only the binary, run as an unprivileged user and keep their data in the volume `/var/lib/uptimesebi`: + +```sh +docker run -d --restart unless-stopped -e UPTIME_API_URL=https://uptime.example.com -e UPTIME_AGENT_TOKEN=usa_… \ + git.zb-server.de/zb-server/uptimesebi-checker:latest +``` + Docker monitors ask the Docker API of the checker's host. Mount its socket read-only (`-v /var/run/docker.sock:/var/run/docker.sock:ro`) into checkers that may see private networks; shared checkers never use a socket, and installations without one can switch the Docker type off in the admin panel. All settings are environment variables; [`.env.example`](.env.example) lists them with explanations. In particular: diff --git a/cmd/checker/main.go b/cmd/checker/main.go index cc64489..dc6a87d 100644 --- a/cmd/checker/main.go +++ b/cmd/checker/main.go @@ -5,6 +5,7 @@ package main import ( + "context" "errors" "fmt" "log/slog" @@ -20,6 +21,13 @@ import ( ) func main() { + if len(os.Args) == 2 && os.Args[1] == "health" { + if err := health(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } log, level := platform.NewLogger("checker") // Route the standard log package and dependencies through the same handler. slog.SetDefault(log) @@ -68,3 +76,12 @@ func run(log *slog.Logger, level *slog.LevelVar) error { } return errors.Join(runErr, <-serveErr) } + +// health probes the running checker in this container. +func health() error { + cfg, err := config.Load[config.Checker]() + if err != nil { + return err + } + return platform.ProbeLocal(context.Background(), cfg.HealthListen) +} diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index f44fb12..575ca10 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -28,6 +28,13 @@ import ( ) func main() { + if len(os.Args) == 2 && os.Args[1] == "health" { + if err := health(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } log, level := platform.NewLogger("statuspage") // Route the standard log package and dependencies through the same handler. slog.SetDefault(log) @@ -168,3 +175,12 @@ func resolveCacheDir(dir string) (string, error) { } return filepath.Join(base, "uptimesebi-statuspage"), nil } + +// health probes the running statuspage in this container. +func health() error { + cfg, err := config.Load[config.StatusPage]() + if err != nil { + return err + } + return platform.ProbeLocal(context.Background(), cfg.Listen) +} diff --git a/go.mod b/go.mod index f30d388..04ab01d 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,7 @@ require ( github.com/go-jose/go-jose/v4 v4.1.9 github.com/go-playground/validator/v10 v10.30.6 github.com/go-sql-driver/mysql v1.10.2 + github.com/google/go-containerregistry v0.22.1 github.com/google/uuid v1.6.0 github.com/gosnmp/gosnmp v1.47.0 github.com/jackc/pgx/v5 v5.13.0 @@ -30,6 +31,7 @@ require ( go.mongodb.org/mongo-driver/v2 v2.5.0 go.uber.org/zap v1.28.0 golang.org/x/crypto v0.59.0 + golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259 golang.org/x/net v0.63.0 golang.org/x/oauth2 v0.38.0 golang.org/x/text v0.44.0 @@ -56,6 +58,8 @@ require ( github.com/cloudwego/base64x v0.1.6 // indirect github.com/decred/dcrd/crypto/blake256 v1.1.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect + github.com/docker/cli v29.7.2+incompatible // indirect + github.com/docker/docker-credential-helpers v0.9.3 // indirect github.com/fatih/color v1.19.0 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/gabriel-vasile/mimetype v1.4.16 // indirect @@ -85,6 +89,8 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/atomic v1.0.1 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pierrec/lz4/v4 v4.1.33 // indirect github.com/puzpuzpuz/xsync/v3 v3.5.1 // indirect @@ -93,6 +99,7 @@ require ( github.com/rs/xid v1.4.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect github.com/shopspring/decimal v1.6.0 // indirect + github.com/sirupsen/logrus v1.9.4 // indirect github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect @@ -115,6 +122,7 @@ require ( google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect google.golang.org/protobuf v1.36.12 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect + gotest.tools/v3 v3.5.2 // indirect ) tool github.com/a-h/templ/cmd/templ diff --git a/go.sum b/go.sum index 60276e7..5b55506 100644 --- a/go.sum +++ b/go.sum @@ -90,6 +90,10 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeC github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= +github.com/docker/cli v29.7.2+incompatible h1:dlkwallR8XqfeVnA2ELEhdwvb4lsSwuB4IgsG8Q9cLY= +github.com/docker/cli v29.7.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8= +github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/dvyukov/go-fuzz v0.0.0-20200318091601-be3528f3a813/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw= @@ -144,6 +148,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-containerregistry v0.22.1 h1:RZuuSYhTvlDvtsK+NkutoCZ//C0X2ebLK8X8l3ULs84= +github.com/google/go-containerregistry v0.22.1/go.mod h1:bJR35SK8XgisYmhg/FMQ/5RK0S/XrOAqLBV5/LR2XE0= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -227,6 +233,10 @@ github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5 github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.33 h1:GjG1TJ1V4IzKP8L96muuuDNpTwd7D+l2ccXrjAbe014= @@ -258,6 +268,8 @@ github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJ github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/shopspring/decimal v1.6.0 h1:DcTwjCj4tJPLuGZYsR9W0hyX9pQwMIkdo26Ig1T9xX4= github.com/shopspring/decimal v1.6.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -333,6 +345,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259 h1:wXcJiWf6AuFE+YJzfySrqJW1+yko6kcV2W+fg4n6WGk= +golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E= golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 h1:qr+tk4P56rtbVVAJDyAr5LAOiaD/XhZCoRTr4SfLxAk= golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -426,6 +440,8 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= +gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= layeh.com/radius v0.0.0-20231213012653-1006025d24f8 h1:orYXpi6BJZdvgytfHH4ybOe4wHnLbbS71Cmd8mWdZjs= layeh.com/radius v0.0.0-20231213012653-1006025d24f8/go.mod h1:QRf+8aRqXc019kHkpcs/CTgyWXFzf+bxlsyuo2nAl1o= modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A= diff --git a/internal/platform/probe.go b/internal/platform/probe.go new file mode 100644 index 0000000..9e9cfdd --- /dev/null +++ b/internal/platform/probe.go @@ -0,0 +1,36 @@ +package platform + +import ( + "context" + "fmt" + "net" + "net/http" + "time" +) + +// ProbeLocal asks the local health endpoint on listen (e.g. ":8081") whether +// the process is alive. Images without a shell run it as their HEALTHCHECK. +func ProbeLocal(ctx context.Context, listen string) error { + host, port, err := net.SplitHostPort(listen) + if err != nil { + return err + } + if host == "" || host == "0.0.0.0" || host == "::" { + host = "127.0.0.1" + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+net.JoinHostPort(host, port)+"/healthz", nil) + if err != nil { + return err + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + _ = resp.Body.Close() + if resp.StatusCode >= 300 { + return fmt.Errorf("platform: health endpoint answered %s", resp.Status) + } + return nil +} diff --git a/internal/platform/roots.go b/internal/platform/roots.go new file mode 100644 index 0000000..ac3c305 --- /dev/null +++ b/internal/platform/roots.go @@ -0,0 +1,9 @@ +package platform + +import ( + // Agent images are built FROM scratch and have no time zone database. + _ "time/tzdata" + + // Nor CA roots; these are used only when the host offers none. + _ "golang.org/x/crypto/x509roots/fallback" +) diff --git a/tools/image/build.go b/tools/image/build.go new file mode 100644 index 0000000..b6c2c4d --- /dev/null +++ b/tools/image/build.go @@ -0,0 +1,238 @@ +package main + +import ( + "archive/tar" + "bytes" + "context" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/google/go-containerregistry/pkg/authn" + "github.com/google/go-containerregistry/pkg/name" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/mutate" + "github.com/google/go-containerregistry/pkg/v1/remote" + "github.com/google/go-containerregistry/pkg/v1/tarball" + "github.com/google/go-containerregistry/pkg/v1/types" +) + +// platforms are the Linux targets: x86 servers, 64-bit ARM (Raspberry Pi +// 3/4/5 on a 64-bit OS, ARM servers), 32-bit Raspberry Pi OS and the +// Raspberry Pi Zero and 1. +var platforms = []struct { + dir string + v1.Platform +}{ + {"linux_amd64", v1.Platform{OS: "linux", Architecture: "amd64"}}, + {"linux_arm64", v1.Platform{OS: "linux", Architecture: "arm64"}}, + {"linux_arm_v7", v1.Platform{OS: "linux", Architecture: "arm", Variant: "v7"}}, + {"linux_arm_v6", v1.Platform{OS: "linux", Architecture: "arm", Variant: "v6"}}, +} + +func platformNames() []string { + var out []string + for _, p := range platforms { + out = append(out, p.String()) + } + return out +} + +// nonroot is the user the agents run as, the same ID as distroless' +// nonroot so volumes carry over. +const nonroot = 65532 + +// dataDir holds the status page cache and, in the autoupdate variant, the +// downloaded releases. +const dataDir = "/var/lib/uptimesebi" + +type options struct { + Name, Dist, Repo, Version, Commit, Source, Suffix string + Env, Ports []string + Created time.Time +} + +// build assembles the index of all platforms. +func build(o options) (v1.ImageIndex, error) { + idx := mutate.IndexMediaType(empty.Index, types.OCIImageIndex) + for _, p := range platforms { + img, err := image(o, filepath.Join(o.Dist, p.dir, o.Name), p.Platform) + if err != nil { + return nil, err + } + pl := p.Platform + idx = mutate.AppendManifests(idx, mutate.IndexAddendum{Add: img, Descriptor: v1.Descriptor{Platform: &pl}}) + } + return idx, nil +} + +func image(o options, binary string, p v1.Platform) (v1.Image, error) { + bin, err := os.ReadFile(binary) + if err != nil { + return nil, fmt.Errorf("image: %w", err) + } + layerTar, err := rootfs(o.Name, bin, o.Created) + if err != nil { + return nil, err + } + layer, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { + return io.NopCloser(bytes.NewReader(layerTar)), nil + }, tarball.WithMediaType(types.OCILayer)) + if err != nil { + return nil, err + } + img := mutate.MediaType(empty.Image, types.OCIManifestSchema1) + img = mutate.ConfigMediaType(img, types.OCIConfigJSON) + img, err = mutate.Append(img, mutate.Addendum{ + Layer: layer, + History: v1.History{Created: v1.Time{Time: o.Created}, CreatedBy: "uptimesebi tools/image", Comment: o.Name + " " + o.Version}, + MediaType: types.OCILayer, + }) + if err != nil { + return nil, err + } + cf, err := img.ConfigFile() + if err != nil { + return nil, err + } + cf = cf.DeepCopy() + cf.OS, cf.Architecture, cf.Variant = p.OS, p.Architecture, p.Variant + cf.Created = v1.Time{Time: o.Created} + entry := "/usr/local/bin/" + o.Name + cf.Config = v1.Config{ + Entrypoint: []string{entry}, + User: fmt.Sprintf("%d:%d", nonroot, nonroot), + WorkingDir: dataDir, + Env: append([]string{"HOME=" + dataDir}, o.Env...), + Volumes: map[string]struct{}{dataDir: {}}, + Healthcheck: &v1.HealthConfig{ + Test: []string{"CMD", entry, "health"}, + Interval: 30 * time.Second, Timeout: 5 * time.Second, StartPeriod: 20 * time.Second, Retries: 3, + }, + Labels: labels(o), + } + if len(o.Ports) > 0 { + cf.Config.ExposedPorts = map[string]struct{}{} + for _, port := range o.Ports { + cf.Config.ExposedPorts[port] = struct{}{} + } + } + return mutate.ConfigFile(img, cf) +} + +func labels(o options) map[string]string { + l := map[string]string{ + "org.opencontainers.image.title": "uptimesebi-" + o.Name, + "org.opencontainers.image.version": o.Version, + "org.opencontainers.image.licenses": "AGPL-3.0-only", + } + if o.Commit != "" { + l["org.opencontainers.image.revision"] = o.Commit + } + if o.Source != "" { + l["org.opencontainers.image.source"] = o.Source + } + return l +} + +// rootfs is the single layer: the binary, a data directory owned by the +// agent's user and a temporary directory. +func rootfs(binName string, bin []byte, mtime time.Time) ([]byte, error) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + dir := func(path string, mode int64, uid int) error { + return tw.WriteHeader(&tar.Header{Typeflag: tar.TypeDir, Name: path + "/", Mode: mode, Uid: uid, Gid: uid, ModTime: mtime, Format: tar.FormatPAX}) + } + for _, d := range []struct { + path string + mode int64 + uid int + }{ + {"tmp", 0o1777, 0}, + {"usr", 0o755, 0}, {"usr/local", 0o755, 0}, {"usr/local/bin", 0o755, 0}, + {"var", 0o755, 0}, {"var/lib", 0o755, 0}, {strings.TrimPrefix(dataDir, "/"), 0o700, nonroot}, + } { + if err := dir(d.path, d.mode, d.uid); err != nil { + return nil, err + } + } + if err := tw.WriteHeader(&tar.Header{ + Typeflag: tar.TypeReg, Name: "usr/local/bin/" + binName, Mode: 0o755, Size: int64(len(bin)), ModTime: mtime, Format: tar.FormatPAX, + }); err != nil { + return nil, err + } + if _, err := tw.Write(bin); err != nil { + return nil, err + } + if err := tw.Close(); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +var releaseTag = regexp.MustCompile(`^v(\d+)\.(\d+)\.(\d+)(-beta\.\d+)?$`) + +// channelTags are the tags an image gets: edge and a dated build tag from +// main, beta from prereleases, latest, stable, X.Y and X.Y.Z from releases. +// Other refs (pull requests, branches) publish nothing. A variant suffix +// is appended to every tag. +func channelTags(ref, version, commit string, created time.Time, suffix string) []string { + var tags []string + switch { + case ref == "refs/heads/main": + short := commit[:min(len(commit), 12)] + tags = []string{created.UTC().Format("20060102150405") + "-" + short, "edge"} + case strings.HasPrefix(ref, "refs/tags/"): + m := releaseTag.FindStringSubmatch(strings.TrimPrefix(ref, "refs/tags/")) + switch { + case m == nil: + return nil + case m[4] != "": + tags = []string{strings.TrimPrefix(m[0], "v"), "beta"} + default: + tags = []string{strings.TrimPrefix(m[0], "v"), m[1] + "." + m[2], "stable", "latest"} + } + default: + return nil + } + if suffix != "" { + for i := range tags { + tags[i] += "-" + suffix + } + } + return tags +} + +type credentials struct{ user, password string } + +// publish pushes the index under its first tag and adds the others. +func publish(ctx context.Context, idx v1.ImageIndex, repo string, tags []string, login credentials, insecure bool) error { + var nameOpts []name.Option + if insecure { + nameOpts = append(nameOpts, name.Insecure) + } + opts := []remote.Option{remote.WithContext(ctx)} + if login.user != "" { + opts = append(opts, remote.WithAuth(&authn.Basic{Username: login.user, Password: login.password})) + } + for i, t := range tags { + tag, err := name.NewTag(repo+":"+t, nameOpts...) + if err != nil { + return err + } + if i == 0 { + err = remote.WriteIndex(tag, idx, opts...) + } else { + err = remote.Tag(tag, idx, opts...) + } + if err != nil { + return fmt.Errorf("image: push %s: %w", tag, err) + } + } + return nil +} diff --git a/tools/image/image_test.go b/tools/image/image_test.go new file mode 100644 index 0000000..93f4da0 --- /dev/null +++ b/tools/image/image_test.go @@ -0,0 +1,169 @@ +package main + +import ( + "archive/tar" + "context" + "errors" + "io" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/google/go-containerregistry/pkg/name" + "github.com/google/go-containerregistry/pkg/registry" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/remote" +) + +func fakeDist(t *testing.T, bin string) string { + t.Helper() + dist := t.TempDir() + for _, p := range platforms { + if err := os.MkdirAll(filepath.Join(dist, p.dir), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dist, p.dir, bin), []byte("binary for "+p.dir), 0o755); err != nil { + t.Fatal(err) + } + } + return dist +} + +func TestBuild(t *testing.T) { + o := options{ + Name: "statuspage", Dist: fakeDist(t, "statuspage"), Version: "v1.2.3", Commit: "abc123", + Env: []string{"UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi"}, Ports: []string{"8082/tcp"}, + Created: time.Unix(1700000000, 0).UTC(), + } + idx, err := build(o) + if err != nil { + t.Fatal(err) + } + m, err := idx.IndexManifest() + if err != nil { + t.Fatal(err) + } + if len(m.Manifests) != 4 { + t.Fatalf("index has %d manifests", len(m.Manifests)) + } + for i, desc := range m.Manifests { + want := platforms[i] + if desc.Platform == nil || !desc.Platform.Equals(want.Platform) { + t.Errorf("manifest %d platform = %v, want %v", i, desc.Platform, want.Platform) + } + img, err := idx.Image(desc.Digest) + if err != nil { + t.Fatal(err) + } + cf, err := img.ConfigFile() + if err != nil { + t.Fatal(err) + } + if cf.Architecture != want.Architecture || cf.Variant != want.Variant || cf.Config.User != "65532:65532" || + !slices.Equal(cf.Config.Entrypoint, []string{"/usr/local/bin/statuspage"}) || + !slices.Equal(cf.Config.Healthcheck.Test, []string{"CMD", "/usr/local/bin/statuspage", "health"}) || + !slices.Contains(cf.Config.Env, "UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi") || + cf.Config.Labels["org.opencontainers.image.version"] != "v1.2.3" { + t.Errorf("%s config = %+v", want.dir, cf.Config) + } + files := layerFiles(t, img) + if got := files["usr/local/bin/statuspage"]; got.Mode != 0o755 || got.Size != int64(len("binary for "+want.dir)) { + t.Errorf("%s binary = %+v", want.dir, got) + } + if got := files["var/lib/uptimesebi/"]; got.Uid != nonroot { + t.Errorf("data directory owner = %d", got.Uid) + } + } + + // The same input gives the same image. + again, _ := build(o) + d1, _ := idx.Digest() + d2, _ := again.Digest() + if d1 != d2 { + t.Errorf("rebuild changed the digest: %s, %s", d1, d2) + } + + o.Dist = t.TempDir() + if _, err := build(o); err == nil { + t.Error("built without binaries") + } +} + +func layerFiles(t *testing.T, img v1.Image) map[string]*tar.Header { + t.Helper() + layers, err := img.Layers() + if err != nil || len(layers) != 1 { + t.Fatalf("layers = %d, %v", len(layers), err) + } + rc, err := layers[0].Uncompressed() + if err != nil { + t.Fatal(err) + } + defer func() { _ = rc.Close() }() + out := map[string]*tar.Header{} + tr := tar.NewReader(rc) + for { + h, err := tr.Next() + if errors.Is(err, io.EOF) { + return out + } + if err != nil { + t.Fatal(err) + } + out[h.Name] = h + } +} + +func TestChannelTags(t *testing.T) { + created := time.Date(2026, 11, 23, 18, 0, 0, 0, time.UTC) + for _, c := range []struct { + ref, suffix string + want []string + }{ + {"refs/heads/main", "", []string{"20261123180000-0123456789ab", "edge"}}, + {"refs/tags/v1.4.2", "", []string{"1.4.2", "1.4", "stable", "latest"}}, + {"refs/tags/v1.5.0-beta.3", "", []string{"1.5.0-beta.3", "beta"}}, + {"refs/tags/v1.4.2", "autoupdate", []string{"1.4.2-autoupdate", "1.4-autoupdate", "stable-autoupdate", "latest-autoupdate"}}, + {"refs/tags/nightly", "", nil}, + {"refs/pull/7/merge", "", nil}, + {"refs/heads/feature", "", nil}, + } { + if got := channelTags(c.ref, "v", "0123456789abcdef", created, c.suffix); !slices.Equal(got, c.want) { + t.Errorf("%s %s: tags = %v, want %v", c.ref, c.suffix, got, c.want) + } + } +} + +func TestPublish(t *testing.T) { + reg := httptest.NewServer(registry.New()) + defer reg.Close() + repo := strings.TrimPrefix(reg.URL, "http://") + "/zb/uptimesebi-checker" + idx, err := build(options{Name: "checker", Dist: fakeDist(t, "checker"), Version: "v1.0.0"}) + if err != nil { + t.Fatal(err) + } + if err := publish(context.Background(), idx, repo, []string{"1.0.0", "latest"}, credentials{}, true); err != nil { + t.Fatal(err) + } + want, _ := idx.Digest() + for _, tag := range []string{"1.0.0", "latest"} { + ref, _ := name.NewTag(repo+":"+tag, name.Insecure) + desc, err := remote.Get(ref) + if err != nil || desc.Digest != want { + t.Errorf("%s = %v, %v; want %s", tag, desc, err, want) + } + } + // A Raspberry Pi Zero pulls its own variant. + ref, _ := name.NewTag(repo+":latest", name.Insecure) + img, err := remote.Image(ref, remote.WithPlatform(v1.Platform{OS: "linux", Architecture: "arm", Variant: "v6"})) + if err != nil { + t.Fatal(err) + } + if got := layerFiles(t, img)["usr/local/bin/checker"]; got.Size != int64(len("binary for linux_arm_v6")) { + t.Errorf("arm/v6 pulled the wrong binary: %+v", got) + } +} diff --git a/tools/image/main.go b/tools/image/main.go new file mode 100644 index 0000000..bcfe4c8 --- /dev/null +++ b/tools/image/main.go @@ -0,0 +1,85 @@ +// Command image builds the multi-arch images of an agent (checker or status +// page server) from cross-compiled binaries, without Docker: one layer on +// an empty base per platform, combined into an OCI index. +// +// image -name checker -dist dist -repo registry/owner/uptimesebi-checker \ +// -version v1.2.3 -commit abc123 -ref refs/tags/v1.2.3 [-push] +// +// dist holds one directory per platform: linux_amd64, linux_arm64, +// linux_arm_v7 and linux_arm_v6, each with the binary. Without -push the +// index is only built and checked. The registry login comes from +// REGISTRY_USER and REGISTRY_PASSWORD. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "strings" + "time" +) + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +type listFlag []string + +func (l *listFlag) String() string { return strings.Join(*l, ",") } +func (l *listFlag) Set(v string) error { *l = append(*l, v); return nil } + +func run(args []string) error { + fs := flag.NewFlagSet("image", flag.ContinueOnError) + var o options + fs.StringVar(&o.Name, "name", "", "binary name: checker or statuspage") + fs.StringVar(&o.Dist, "dist", "dist", "directory with one subdirectory per platform") + fs.StringVar(&o.Repo, "repo", "", "image repository, e.g. git.example.com/owner/uptimesebi-checker") + fs.StringVar(&o.Version, "version", "dev", "release version") + fs.StringVar(&o.Commit, "commit", "", "git revision") + fs.StringVar(&o.Source, "source", "", "repository URL for the image labels") + fs.StringVar(&o.Suffix, "suffix", "", "tag suffix of an image variant, e.g. autoupdate") + fs.Var((*listFlag)(&o.Env), "env", "NAME=value baked into the image (repeatable)") + fs.Var((*listFlag)(&o.Ports), "port", "exposed port, e.g. 8081/tcp (repeatable)") + ref := fs.String("ref", "", "git ref being built, e.g. refs/heads/main or refs/tags/v1.2.3") + created := fs.Int64("created", 0, "creation time as Unix seconds, for reproducible images") + push := fs.Bool("push", false, "push to the registry") + insecure := fs.Bool("insecure", false, "talk plain HTTP to the registry") + if err := fs.Parse(args); err != nil { + return err + } + if o.Name == "" || o.Repo == "" { + return errors.New("image: -name and -repo are required") + } + o.Created = time.Unix(*created, 0).UTC() + + idx, err := build(o) + if err != nil { + return err + } + digest, err := idx.Digest() + if err != nil { + return err + } + tags := channelTags(*ref, o.Version, o.Commit, o.Created, o.Suffix) + fmt.Printf("built %s@%s for %s\n", o.Repo, digest, strings.Join(platformNames(), ", ")) + if !*push { + return nil + } + if len(tags) == 0 { + return fmt.Errorf("image: %q is not a ref that publishes images", *ref) + } + if *ref == "refs/heads/main" && (o.Commit == "" || *created == 0) { + return errors.New("image: builds of main need -commit and -created for their tag") + } + login := credentials{os.Getenv("REGISTRY_USER"), os.Getenv("REGISTRY_PASSWORD")} + if err := publish(context.Background(), idx, o.Repo, tags, login, *insecure); err != nil { + return err + } + fmt.Printf("pushed %s:%s\n", o.Repo, strings.Join(tags, ", :")) + return nil +} From a35dadd8f621b97fddcdc65007f9751244f2c39c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Mon, 23 Nov 2026 18:57:48 +0100 Subject: [PATCH 2/2] feat(agents): self-updating agent image variant The -autoupdate variant of the checker and status page images adds a launcher layer. The launcher runs the agent as a child process and keeps it on the platform's release: GET /agent/v1/update names the API's own release and the agent image for it, the launcher downloads the binary for its platform from the registry, accepts it only when the index is signed with a release key for exactly that version, swaps the agent gracefully and rolls back when the new release does not become ready or crashes right after starting. Agents never get ahead of the API, and installations on unreleased builds are not followed. CI pushes both variants and signs each index with RELEASE_SIGNING_KEY (minisign signature in a sha256-.minisig image next to it). The image builder moves to internal/agentimage; the API image job takes the build job's version so the API reports the release its agents are tagged with. Agents gain a version command. Closes #129 Closes #128 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .env.example | 4 + .gitea/workflows/ci.yaml | 28 ++- README.md | 2 + cmd/checker/main.go | 6 +- cmd/launcher/main.go | 94 +++++++++ cmd/statuspage/main.go | 6 +- internal/agentapi/agentapi.go | 18 ++ internal/agentimage/build.go | 292 +++++++++++++++++++++++++++ internal/agentimage/build_test.go | 198 +++++++++++++++++++ internal/agentimage/signature.go | 154 +++++++++++++++ internal/api/agent.go | 19 ++ internal/api/checker_test.go | 29 +++ internal/config/config.go | 5 +- internal/launcher/launcher.go | 291 +++++++++++++++++++++++++++ internal/launcher/launcher_test.go | 307 +++++++++++++++++++++++++++++ internal/launcher/process.go | 86 ++++++++ internal/platform/probe.go | 8 +- tools/image/build.go | 238 ---------------------- tools/image/image_test.go | 169 ---------------- tools/image/main.go | 66 +++++-- 20 files changed, 1577 insertions(+), 443 deletions(-) create mode 100644 cmd/launcher/main.go create mode 100644 internal/agentimage/build.go create mode 100644 internal/agentimage/build_test.go create mode 100644 internal/agentimage/signature.go create mode 100644 internal/launcher/launcher.go create mode 100644 internal/launcher/launcher_test.go create mode 100644 internal/launcher/process.go delete mode 100644 tools/image/build.go delete mode 100644 tools/image/image_test.go diff --git a/.env.example b/.env.example index 98d38e4..b0240ff 100644 --- a/.env.example +++ b/.env.example @@ -57,6 +57,10 @@ UPTIME_TEST_REDIS_URL=redis://localhost:6379/15 # What checkers saw of HTTP responses. # UPTIME_RETENTION_EVIDENCE=720h +# Image agents are installed and self-updated from (-checker or -statuspage +# is appended); set it to a mirror if agents cannot reach the default. +# UPTIME_AGENT_IMAGE=git.zb-server.de/zb-server/uptimesebi + # Status page server: hosts serving pages by slug; enable TLS for custom domains. UPTIME_STATUSPAGE_URL=http://localhost:8082 UPTIME_STATUSPAGE_HOSTS=localhost diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index f90158f..1c325e6 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -117,6 +117,8 @@ jobs: build: runs-on: ubuntu-latest + outputs: + version: ${{ steps.binaries.outputs.version }} steps: - uses: actions/checkout@v7 # The runners are ephemeral and clone every action from GitHub, which @@ -131,6 +133,7 @@ jobs: - name: Build frontend run: npm ci --no-audit --no-fund && npm run build - name: Build binaries + id: binaries run: | set -eu pkg=git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo @@ -139,6 +142,7 @@ jobs: *) version="$(git log -1 --format=%cd --date=format:%Y%m%d%H%M%S)-$(git rev-parse --short=12 HEAD)" ;; esac echo "VERSION=$version" >> "$GITHUB_ENV" + echo "version=$version" >> "$GITHUB_OUTPUT" for platform in linux/amd64 linux/arm64 linux/arm/v7 linux/arm/v6; do IFS=/ read -r os arch variant <<< "$platform" CGO_ENABLED=0 GOOS=$os GOARCH=$arch GOARM=${variant#v} go build -trimpath \ @@ -146,11 +150,13 @@ jobs: -o "dist/$(echo "$platform" | tr / _)/" ./cmd/... done ls -lR dist - # Checker and status page images for every platform, assembled from the - # binaries above without Docker; pushed like the main image. + # Checker and status page images for every platform, plain and + # self-updating, assembled from the binaries above without Docker; + # pushed like the main image and signed for the self-updating agents. - name: Agent images env: PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }} + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} run: | set -eu host="${GITHUB_SERVER_URL#*://}" @@ -162,9 +168,12 @@ jobs: if [ -n "${PACKAGE_TOKEN:-}" ]; then flags="$flags -push"; else echo "PACKAGE_TOKEN is not set; building without pushing."; fi ;; esac export REGISTRY_USER="$GITHUB_ACTOR" REGISTRY_PASSWORD="${PACKAGE_TOKEN:-}" - go run ./tools/image -name checker -repo "$host/$owner/uptimesebi-checker" -port 8081/tcp $flags - go run ./tools/image -name statuspage -repo "$host/$owner/uptimesebi-statuspage" -port 8082/tcp \ - -env UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi $flags + go build -o image ./tools/image + for variant in "" -autoupdate; do + ./image -name checker -repo "$host/$owner/uptimesebi-checker" -port 8081/tcp $variant $flags + ./image -name statuspage -repo "$host/$owner/uptimesebi-statuspage" -port 8082/tcp \ + -env UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi $variant $flags + done image: # Kaniko runs rootless from docker:cli, the same way as the other @@ -172,6 +181,9 @@ jobs: # CLI, and Kaniko's own image lacks what the runner needs to keep a job # container alive. Images are pushed only from main and tags, and only # once the PACKAGE_TOKEN secret (write:package) exists. + # The build job's version, so the API reports the release its agent + # images are tagged with. + needs: build runs-on: ubuntu-latest container: image: docker:cli@sha256:34507eb5069d8be82c95dd3b6987d4250fd5fee49b82e2509b7d7a7030740d6d @@ -183,15 +195,13 @@ jobs: env: GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }} + VERSION: ${{ needs.build.outputs.version }} run: | set -eu REGISTRY="${GITHUB_SERVER_URL#*://}" IMAGE="$(printf '%s/%s' "$REGISTRY" "$GITHUB_REPOSITORY" | tr 'A-Z' 'a-z')" SHORT="$(printf '%s' "$GITHUB_SHA" | cut -c1-12)" - case "$GITHUB_REF" in - refs/tags/v*) TAG="$GITHUB_REF_NAME" ;; - *) TAG="$(date -u +%Y%m%d%H%M%S)-$SHORT" ;; - esac + TAG="$VERSION" PUSH="--no-push" DEST="--destination ${IMAGE}:${TAG#v}" # Channels: edge follows main, beta the newest prerelease, latest diff --git a/README.md b/README.md index d5b5e04..ec1f2bd 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,8 @@ docker run -d --restart unless-stopped -e UPTIME_API_URL=https://uptime.example. git.zb-server.de/zb-server/uptimesebi-checker:latest ``` +To keep agents up to date without touching them, use the `-autoupdate` variant of the image (`uptimesebi-checker:latest-autoupdate`). Its launcher runs the agent and follows the release your platform runs: it asks the API every 15 minutes, downloads the new agent from the registry for its platform, accepts it only with a valid release signature, swaps the agent gracefully and rolls back if the new one does not become ready. Agents thus never get ahead of the API. The variant is a choice of image, not a setting; the plain image contains no update code. Agents of an installation running an unreleased build stay as they are. Set `UPTIME_AGENT_IMAGE` on the API if agents pull from a mirror. + Docker monitors ask the Docker API of the checker's host. Mount its socket read-only (`-v /var/run/docker.sock:/var/run/docker.sock:ro`) into checkers that may see private networks; shared checkers never use a socket, and installations without one can switch the Docker type off in the admin panel. All settings are environment variables; [`.env.example`](.env.example) lists them with explanations. In particular: diff --git a/cmd/checker/main.go b/cmd/checker/main.go index dc6a87d..5ab74e4 100644 --- a/cmd/checker/main.go +++ b/cmd/checker/main.go @@ -21,6 +21,10 @@ import ( ) func main() { + if len(os.Args) == 2 && os.Args[1] == "version" { + fmt.Println(buildinfo.Version) + return + } if len(os.Args) == 2 && os.Args[1] == "health" { if err := health(); err != nil { fmt.Fprintln(os.Stderr, err) @@ -83,5 +87,5 @@ func health() error { if err != nil { return err } - return platform.ProbeLocal(context.Background(), cfg.HealthListen) + return platform.ProbeLocal(context.Background(), cfg.HealthListen, "/healthz") } diff --git a/cmd/launcher/main.go b/cmd/launcher/main.go new file mode 100644 index 0000000..7b11737 --- /dev/null +++ b/cmd/launcher/main.go @@ -0,0 +1,94 @@ +// Command launcher is the entrypoint of the self-updating agent images. It +// runs the agent named by UPTIME_LAUNCHER_AGENT and keeps it on the +// release the platform runs, with signed downloads and rollback. +package main + +import ( + "context" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentimage" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/launcher" + "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" + "git.zb-server.de/ZB-Server/uptimesebi/internal/signing" +) + +func main() { + log, level := platform.NewLogger("launcher") + slog.SetDefault(log) + if err := run(log, level); err != nil { + log.Error("exit", "error", err) + os.Exit(1) + } +} + +// settings are what the launcher needs from the agent's configuration. +type settings struct { + common config.Common + agent config.Agent + listen string +} + +func load(agent string) (settings, error) { + switch agent { + case "checker": + c, err := config.Load[config.Checker]() + return settings{c.Common, c.Agent, c.HealthListen}, err + case "statuspage": + c, err := config.Load[config.StatusPage]() + return settings{c.Common, c.Agent, c.Listen}, err + } + return settings{}, fmt.Errorf("UPTIME_LAUNCHER_AGENT is %q, not checker or statuspage", agent) +} + +func run(log *slog.Logger, level *slog.LevelVar) error { + agent := os.Getenv("UPTIME_LAUNCHER_AGENT") + s, err := load(agent) + if err != nil { + return err + } + level.Set(s.common.LogLevel) + ctx, stop := platform.SignalContext() + defer stop() + + bundled := filepath.Join(agentimage.BinDir, agent) + current, err := launcher.BinaryVersion(bundled) + if err != nil { + return err + } + client := agentapi.NewClient(s.agent.APIURL, s.agent.Token, uuid.New(), current) + platformOf := launcher.Platform() + l := launcher.New(launcher.Config{ + Agent: agent, + Bundled: bundled, + Dir: filepath.Join(agentimage.DataDir, "launcher"), + Interval: 15 * time.Minute, + ReadyWait: 2 * time.Minute, + StopTimeout: s.common.ShutdownTimeout + 10*time.Second, + RetryAfter: 6 * time.Hour, + Log: log.With("agent", agent, "platform", platformOf.String()), + Updates: client.Update, + Fetch: func(ctx context.Context, u agentapi.Update) ([]byte, error) { + return agentimage.Fetch(ctx, u.Image, agent, u.Version, platformOf, signing.ReleaseKeys()) + }, + Start: launcher.StartProcess, + Ready: func(ctx context.Context) error { + return platform.ProbeLocal(ctx, s.listen, "/readyz") + }, + Version: launcher.BinaryVersion, + }) + err = l.Run(ctx) + if errors.Is(ctx.Err(), context.Canceled) { + return nil + } + return err +} diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index 575ca10..7e3140f 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -28,6 +28,10 @@ import ( ) func main() { + if len(os.Args) == 2 && os.Args[1] == "version" { + fmt.Println(buildinfo.Version) + return + } if len(os.Args) == 2 && os.Args[1] == "health" { if err := health(); err != nil { fmt.Fprintln(os.Stderr, err) @@ -182,5 +186,5 @@ func health() error { if err != nil { return err } - return platform.ProbeLocal(context.Background(), cfg.Listen) + return platform.ProbeLocal(context.Background(), cfg.Listen, "/healthz") } diff --git a/internal/agentapi/agentapi.go b/internal/agentapi/agentapi.go index b2e7e6d..de1f5ea 100644 --- a/internal/agentapi/agentapi.go +++ b/internal/agentapi/agentapi.go @@ -180,6 +180,24 @@ func (c *Client) Report(ctx context.Context, results []Result) error { return c.do(ctx, http.MethodPost, "/results", ResultsRequest{Results: results}, nil) } +// Update tells a self-updating agent which release to run. +type Update struct { + // Version is the platform's release; agents follow it. + Version string `json:"version"` + // Image is the agent image of that release, e.g. + // git.example.com/owner/uptimesebi-checker:1.4.2. Empty when the + // platform runs an unreleased build, which agents do not follow. + Image string `json:"image,omitempty"` +} + +// Update asks which release the agent should run. It does not count as a +// sign of life of an instance. +func (c *Client) Update(ctx context.Context) (Update, error) { + var u Update + err := c.do(ctx, http.MethodGet, "/update", nil, &u) + return u, err +} + // Release hands this instance's queued jobs back for other instances and // deregisters it. Call it during graceful shutdown. func (c *Client) Release(ctx context.Context) error { diff --git a/internal/agentimage/build.go b/internal/agentimage/build.go new file mode 100644 index 0000000..8bf46a0 --- /dev/null +++ b/internal/agentimage/build.go @@ -0,0 +1,292 @@ +// Package agentimage builds, signs and reads the images of the agents +// (checker and status page server): one layer on an empty base per +// platform, combined into an OCI index, built from cross-compiled binaries +// without Docker. The autoupdate variant adds a layer with the launcher. +package agentimage + +import ( + "archive/tar" + "bytes" + "context" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/google/go-containerregistry/pkg/authn" + "github.com/google/go-containerregistry/pkg/name" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/mutate" + "github.com/google/go-containerregistry/pkg/v1/remote" + "github.com/google/go-containerregistry/pkg/v1/tarball" + "github.com/google/go-containerregistry/pkg/v1/types" +) + +// Platform is a Linux target and the directory its binaries are built in. +type Platform struct { + Dir string + v1.Platform +} + +// Platforms are the targets: x86 servers, 64-bit ARM (Raspberry Pi 3/4/5 +// on a 64-bit OS, ARM servers), 32-bit Raspberry Pi OS and the Raspberry +// Pi Zero and 1. +var Platforms = []Platform{ + {"linux_amd64", v1.Platform{OS: "linux", Architecture: "amd64"}}, + {"linux_arm64", v1.Platform{OS: "linux", Architecture: "arm64"}}, + {"linux_arm_v7", v1.Platform{OS: "linux", Architecture: "arm", Variant: "v7"}}, + {"linux_arm_v6", v1.Platform{OS: "linux", Architecture: "arm", Variant: "v6"}}, +} + +// Nonroot is the user the agents run as, the same ID as distroless' +// nonroot so volumes carry over. +const Nonroot = 65532 + +// DataDir holds the status page cache and the launcher's releases. +const DataDir = "/var/lib/uptimesebi" + +// BinDir is where the binaries are in the image. +const BinDir = "/usr/local/bin" + +// Options describe the images of one agent. +type Options struct { + // Name is the binary: checker or statuspage. + Name string + // Dist holds one directory per platform (Platform.Dir) with the + // binaries. + Dist string + Version, Commit, Source string + Env, Ports []string + Created time.Time + // Launcher adds the launcher layer for the autoupdate variant. + Launcher bool +} + +// Build assembles the index of all platforms. +func Build(o Options) (v1.ImageIndex, error) { + idx := mutate.IndexMediaType(empty.Index, types.OCIImageIndex) + for _, p := range Platforms { + img, err := image(o, p) + if err != nil { + return nil, err + } + pl := p.Platform + idx = mutate.AppendManifests(idx, mutate.IndexAddendum{Add: img, Descriptor: v1.Descriptor{Platform: &pl}}) + } + return idx, nil +} + +func image(o Options, p Platform) (v1.Image, error) { + agent, err := os.ReadFile(filepath.Join(o.Dist, p.Dir, o.Name)) + if err != nil { + return nil, fmt.Errorf("agentimage: %w", err) + } + rootLayer, err := rootfs(o.Name, agent, o.Created) + if err != nil { + return nil, err + } + img, err := appendLayer(emptyImage(), rootLayer, v1.History{Created: v1.Time{Time: o.Created}, CreatedBy: "uptimesebi agentimage", Comment: o.Name + " " + o.Version}) + if err != nil { + return nil, err + } + if o.Launcher { + launcher, err := os.ReadFile(filepath.Join(o.Dist, p.Dir, "launcher")) + if err != nil { + return nil, fmt.Errorf("agentimage: %w", err) + } + raw, err := launcherLayer(launcher, o.Created) + if err != nil { + return nil, err + } + if img, err = appendLayer(img, raw, v1.History{Created: v1.Time{Time: o.Created}, CreatedBy: "uptimesebi agentimage", Comment: "launcher " + o.Version}); err != nil { + return nil, err + } + } + cf, err := img.ConfigFile() + if err != nil { + return nil, err + } + cf = cf.DeepCopy() + cf.OS, cf.Architecture, cf.Variant = p.OS, p.Architecture, p.Variant + cf.Created = v1.Time{Time: o.Created} + agentPath := BinDir + "/" + o.Name + entry := []string{agentPath} + env := append([]string{"HOME=" + DataDir}, o.Env...) + if o.Launcher { + entry = []string{BinDir + "/launcher"} + env = append(env, "UPTIME_LAUNCHER_AGENT="+o.Name) + } + cf.Config = v1.Config{ + Entrypoint: entry, + User: fmt.Sprintf("%d:%d", Nonroot, Nonroot), + WorkingDir: DataDir, + Env: env, + Volumes: map[string]struct{}{DataDir: {}}, + Healthcheck: &v1.HealthConfig{ + Test: []string{"CMD", agentPath, "health"}, + Interval: 30 * time.Second, Timeout: 5 * time.Second, StartPeriod: 20 * time.Second, Retries: 3, + }, + Labels: labels(o), + } + if len(o.Ports) > 0 { + cf.Config.ExposedPorts = map[string]struct{}{} + for _, port := range o.Ports { + cf.Config.ExposedPorts[port] = struct{}{} + } + } + return mutate.ConfigFile(img, cf) +} + +func labels(o Options) map[string]string { + l := map[string]string{ + "org.opencontainers.image.title": "uptimesebi-" + o.Name, + "org.opencontainers.image.version": o.Version, + "org.opencontainers.image.licenses": "AGPL-3.0-only", + } + if o.Commit != "" { + l["org.opencontainers.image.revision"] = o.Commit + } + if o.Source != "" { + l["org.opencontainers.image.source"] = o.Source + } + return l +} + +type tarEntry struct { + path string + mode int64 + uid int + data []byte + dir bool +} + +func writeTar(entries []tarEntry, mtime time.Time) ([]byte, error) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range entries { + h := &tar.Header{Name: e.path, Mode: e.mode, Uid: e.uid, Gid: e.uid, ModTime: mtime, Format: tar.FormatPAX} + if e.dir { + h.Typeflag, h.Name = tar.TypeDir, e.path+"/" + } else { + h.Typeflag, h.Size = tar.TypeReg, int64(len(e.data)) + } + if err := tw.WriteHeader(h); err != nil { + return nil, err + } + if _, err := tw.Write(e.data); err != nil { + return nil, err + } + } + if err := tw.Close(); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// rootfs is the agent layer: the binary, a data directory owned by the +// agent's user and a temporary directory. +func rootfs(binName string, bin []byte, mtime time.Time) ([]byte, error) { + bindir := strings.TrimPrefix(BinDir, "/") + return writeTar([]tarEntry{ + {path: "tmp", mode: 0o1777, dir: true}, + {path: "usr", mode: 0o755, dir: true}, {path: "usr/local", mode: 0o755, dir: true}, {path: bindir, mode: 0o755, dir: true}, + {path: "var", mode: 0o755, dir: true}, {path: "var/lib", mode: 0o755, dir: true}, + {path: strings.TrimPrefix(DataDir, "/"), mode: 0o700, uid: Nonroot, dir: true}, + {path: bindir + "/" + binName, mode: 0o755, data: bin}, + }, mtime) +} + +func launcherLayer(bin []byte, mtime time.Time) ([]byte, error) { + return writeTar([]tarEntry{{path: strings.TrimPrefix(BinDir, "/") + "/launcher", mode: 0o755, data: bin}}, mtime) +} + +var releaseTag = regexp.MustCompile(`^v(\d+)\.(\d+)\.(\d+)(-beta\.\d+)?$`) + +// ChannelTags are the tags an image gets: edge and its build version from +// main, beta from prereleases, latest, stable, X.Y and X.Y.Z from releases. +// Other refs (pull requests, branches) publish nothing. A variant suffix +// is appended to every tag. +// +// The first tag is the image of exactly this version, the one the +// platform names to self-updating agents. +func ChannelTags(ref, version, suffix string) []string { + var tags []string + switch { + case ref == "refs/heads/main": + tags = []string{strings.TrimPrefix(version, "v"), "edge"} + case strings.HasPrefix(ref, "refs/tags/"): + m := releaseTag.FindStringSubmatch(strings.TrimPrefix(ref, "refs/tags/")) + switch { + case m == nil: + return nil + case m[4] != "": + tags = []string{strings.TrimPrefix(m[0], "v"), "beta"} + default: + tags = []string{strings.TrimPrefix(m[0], "v"), m[1] + "." + m[2], "stable", "latest"} + } + default: + return nil + } + if suffix != "" { + for i := range tags { + tags[i] += "-" + suffix + } + } + return tags +} + +// Credentials log in to the registry; empty means anonymous. +type Credentials struct{ User, Password string } + +func remoteOptions(ctx context.Context, login Credentials) []remote.Option { + opts := []remote.Option{remote.WithContext(ctx)} + if login.User != "" { + opts = append(opts, remote.WithAuth(&authn.Basic{Username: login.User, Password: login.Password})) + } + return opts +} + +// Publish pushes the index under its first tag and adds the others. +func Publish(ctx context.Context, idx v1.ImageIndex, repo string, tags []string, login Credentials, nameOpts ...name.Option) error { + opts := remoteOptions(ctx, login) + for i, t := range tags { + tag, err := name.NewTag(repo+":"+t, nameOpts...) + if err != nil { + return err + } + if i == 0 { + err = remote.WriteIndex(tag, idx, opts...) + } else { + err = remote.Tag(tag, idx, opts...) + } + if err != nil { + return fmt.Errorf("agentimage: push %s: %w", tag, err) + } + } + return nil +} + +var timeZero = time.Unix(0, 0).UTC() + +func emptyImage() v1.Image { + img := mutate.MediaType(empty.Image, types.OCIManifestSchema1) + return mutate.ConfigMediaType(img, types.OCIConfigJSON) +} + +func appendLayer(img v1.Image, raw []byte, history v1.History) (v1.Image, error) { + layer, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { + return io.NopCloser(bytes.NewReader(raw)), nil + }, tarball.WithMediaType(types.OCILayer)) + if err != nil { + return nil, err + } + return mutate.Append(img, mutate.Addendum{Layer: layer, History: history, MediaType: types.OCILayer}) +} + +func singleLayer(raw []byte) (v1.Image, error) { + return appendLayer(emptyImage(), raw, v1.History{Created: v1.Time{Time: timeZero}}) +} diff --git a/internal/agentimage/build_test.go b/internal/agentimage/build_test.go new file mode 100644 index 0000000..9077fa7 --- /dev/null +++ b/internal/agentimage/build_test.go @@ -0,0 +1,198 @@ +package agentimage + +import ( + "context" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/google/go-containerregistry/pkg/name" + "github.com/google/go-containerregistry/pkg/registry" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/remote" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/signing" +) + +func fakeDist(t *testing.T, version string, bins ...string) string { + t.Helper() + dist := t.TempDir() + for _, p := range Platforms { + if err := os.MkdirAll(filepath.Join(dist, p.Dir), 0o755); err != nil { + t.Fatal(err) + } + for _, b := range bins { + if err := os.WriteFile(filepath.Join(dist, p.Dir, b), []byte(b+" "+version+" for "+p.Dir), 0o755); err != nil { + t.Fatal(err) + } + } + } + return dist +} + +func TestBuild(t *testing.T) { + o := Options{ + Name: "statuspage", Dist: fakeDist(t, "v1.2.3", "statuspage", "launcher"), Version: "v1.2.3", Commit: "abc123", + Env: []string{"UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi"}, Ports: []string{"8082/tcp"}, + Created: time.Unix(1700000000, 0).UTC(), + } + for _, launcher := range []bool{false, true} { + o.Launcher = launcher + idx, err := Build(o) + if err != nil { + t.Fatal(err) + } + m, err := idx.IndexManifest() + if err != nil { + t.Fatal(err) + } + if len(m.Manifests) != len(Platforms) { + t.Fatalf("index has %d manifests", len(m.Manifests)) + } + for i, desc := range m.Manifests { + want := Platforms[i] + if desc.Platform == nil || !desc.Platform.Equals(want.Platform) { + t.Errorf("manifest %d platform = %v, want %v", i, desc.Platform, want.Platform) + } + img, err := idx.Image(desc.Digest) + if err != nil { + t.Fatal(err) + } + cf, err := img.ConfigFile() + if err != nil { + t.Fatal(err) + } + entry := []string{"/usr/local/bin/statuspage"} + if launcher { + entry = []string{"/usr/local/bin/launcher"} + } + if cf.Architecture != want.Architecture || cf.Variant != want.Variant || cf.Config.User != "65532:65532" || + !slices.Equal(cf.Config.Entrypoint, entry) || + !slices.Equal(cf.Config.Healthcheck.Test, []string{"CMD", "/usr/local/bin/statuspage", "health"}) || + !slices.Contains(cf.Config.Env, "UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi") || + slices.Contains(cf.Config.Env, "UPTIME_LAUNCHER_AGENT=statuspage") != launcher || + cf.Config.Labels["org.opencontainers.image.version"] != "v1.2.3" { + t.Errorf("%s launcher=%v config = %+v", want.Dir, launcher, cf.Config) + } + bin, err := ReadFile(img, "usr/local/bin/statuspage", 1<<20) + if err != nil || string(bin) != "statuspage v1.2.3 for "+want.Dir { + t.Errorf("%s binary = %q, %v", want.Dir, bin, err) + } + _, err = ReadFile(img, "usr/local/bin/launcher", 1<<20) + if (err == nil) != launcher { + t.Errorf("launcher=%v but launcher file err = %v", launcher, err) + } + } + } + + // The same input gives the same image. + o.Launcher = false + a, _ := Build(o) + b, _ := Build(o) + d1, _ := a.Digest() + d2, _ := b.Digest() + if d1 != d2 { + t.Errorf("rebuild changed the digest: %s, %s", d1, d2) + } + + o.Dist = t.TempDir() + if _, err := Build(o); err == nil { + t.Error("built without binaries") + } +} + +func TestChannelTags(t *testing.T) { + for _, c := range []struct { + ref, suffix string + want []string + }{ + {"refs/heads/main", "", []string{"20261123180000-0123456789ab", "edge"}}, + {"refs/tags/v1.4.2", "", []string{"1.4.2", "1.4", "stable", "latest"}}, + {"refs/tags/v1.5.0-beta.3", "", []string{"1.5.0-beta.3", "beta"}}, + {"refs/tags/v1.4.2", "autoupdate", []string{"1.4.2-autoupdate", "1.4-autoupdate", "stable-autoupdate", "latest-autoupdate"}}, + {"refs/tags/nightly", "", nil}, + {"refs/pull/7/merge", "", nil}, + {"refs/heads/feature", "", nil}, + } { + if got := ChannelTags(c.ref, "20261123180000-0123456789ab", c.suffix); !slices.Equal(got, c.want) { + t.Errorf("%s %s: tags = %v, want %v", c.ref, c.suffix, got, c.want) + } + } +} + +// publishSigned builds and pushes a checker release to the registry. +func publishSigned(t *testing.T, host, version string, key signing.PrivateKey) v1.Hash { + t.Helper() + repo := host + "/zb/uptimesebi-checker" + idx, err := Build(Options{Name: "checker", Dist: fakeDist(t, version, "checker"), Version: version}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + tags := ChannelTags("refs/tags/"+version, version, "") + if err := Publish(ctx, idx, repo, tags, Credentials{}); err != nil { + t.Fatal(err) + } + if err := Sign(ctx, idx, repo, "checker", version, key, Credentials{}); err != nil { + t.Fatal(err) + } + d, _ := idx.Digest() + return d +} + +func TestSignFetch(t *testing.T) { + reg := httptest.NewServer(registry.New()) + defer reg.Close() + host := strings.TrimPrefix(reg.URL, "http://") + repo := host + "/zb/uptimesebi-checker" + key, _ := signing.GenerateKey() + keys := []signing.PublicKey{key.Public()} + ctx := context.Background() + piZero := v1.Platform{OS: "linux", Architecture: "arm", Variant: "v6"} + + digest := publishSigned(t, host, "v1.0.0", key) + for _, tag := range []string{"1.0.0", "latest"} { + ref, _ := name.NewTag(repo + ":" + tag) + if desc, err := remote.Get(ref); err != nil || desc.Digest != digest { + t.Errorf("%s = %v, %v", tag, desc, err) + } + } + bin, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", piZero, keys) + if err != nil || string(bin) != "checker v1.0.0 for linux_arm_v6" { + t.Fatalf("Fetch = %q, %v", bin, err) + } + + if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.1", piZero, keys); err == nil || !strings.Contains(err.Error(), "signed as") { + t.Errorf("an old release passed off as a new version: %v", err) + } + other, _ := signing.GenerateKey() + if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", piZero, []signing.PublicKey{other.Public()}); err == nil { + t.Error("accepted a signature by an unknown key") + } + if _, err := Fetch(ctx, repo+":1.0.0", "statuspage", "v1.0.0", piZero, keys); err == nil { + t.Error("the checker's signature passed for the status page") + } + if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", v1.Platform{OS: "linux", Architecture: "riscv64"}, keys); err == nil { + t.Error("fetched for a platform without image") + } + + // An attacker who can push moves the tag to an image signed by no one. + evil, _ := Build(Options{Name: "checker", Dist: fakeDist(t, "evil", "checker"), Version: "v1.0.0"}) + if err := Publish(ctx, evil, repo, []string{"1.0.0"}, Credentials{}); err != nil { + t.Fatal(err) + } + if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", piZero, keys); err == nil || !strings.Contains(err.Error(), "no signature") { + t.Errorf("unsigned image accepted: %v", err) + } + // ...or signs it with a key of their own. + if err := Sign(ctx, evil, repo, "checker", "v1.0.0", other, Credentials{}); err != nil { + t.Fatal(err) + } + if _, err := Fetch(ctx, repo+":1.0.0", "checker", "v1.0.0", piZero, keys); err == nil { + t.Error("image signed by a foreign key accepted") + } +} diff --git a/internal/agentimage/signature.go b/internal/agentimage/signature.go new file mode 100644 index 0000000..784846e --- /dev/null +++ b/internal/agentimage/signature.go @@ -0,0 +1,154 @@ +package agentimage + +import ( + "archive/tar" + "context" + "errors" + "fmt" + "io" + "strings" + + "github.com/google/go-containerregistry/pkg/name" + v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/remote" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/signing" +) + +// An image's signature is a minisign signature of Message, with the +// version as trusted comment, stored as a small image under SignatureTag +// next to it, as cosign does. The message names the agent but not the +// registry, so mirrors keep the signature valid. + +// Message is what the signature of an agent's image index covers. +func Message(agent string, digest v1.Hash) []byte { + return []byte("uptimesebi-" + agent + "@" + digest.String() + "\n") +} + +// SignatureTag is the tag holding the signature of the index digest. +func SignatureTag(digest v1.Hash) string { + return digest.Algorithm + "-" + digest.Hex + ".minisig" +} + +const signatureFile = "signature.minisig" + +// Sign pushes the signature of idx, published as the agent's image in +// repo at version. +func Sign(ctx context.Context, idx v1.ImageIndex, repo, agent, version string, key signing.PrivateKey, login Credentials, nameOpts ...name.Option) error { + digest, err := idx.Digest() + if err != nil { + return err + } + sig, err := signing.Sign(key, Message(agent, digest), version) + if err != nil { + return err + } + img, err := fileImage(signatureFile, sig) + if err != nil { + return err + } + tag, err := name.NewTag(repo+":"+SignatureTag(digest), nameOpts...) + if err != nil { + return err + } + return remote.Write(tag, img, remoteOptions(ctx, login)...) +} + +func fileImage(path string, data []byte) (v1.Image, error) { + raw, err := writeTar([]tarEntry{{path: path, mode: 0o644, data: data}}, timeZero) + if err != nil { + return nil, err + } + return singleLayer(raw) +} + +// Fetch resolves ref, checks that the index is signed by one of keys for +// version and returns the agent binary for platform. +func Fetch(ctx context.Context, ref, agent, version string, platform v1.Platform, keys []signing.PublicKey, nameOpts ...name.Option) ([]byte, error) { + r, err := name.ParseReference(ref, nameOpts...) + if err != nil { + return nil, err + } + opts := remoteOptions(ctx, Credentials{}) + desc, err := remote.Get(r, opts...) + if err != nil { + return nil, fmt.Errorf("agentimage: %s: %w", ref, err) + } + // Everything below is read by digest, which the client verifies. + pinned := r.Context().Digest(desc.Digest.String()) + sigImg, err := remote.Image(r.Context().Tag(SignatureTag(desc.Digest)), opts...) + if err != nil { + return nil, fmt.Errorf("agentimage: no signature for %s: %w", pinned, err) + } + sig, err := ReadFile(sigImg, signatureFile, 4096) + if err != nil { + return nil, err + } + signed, err := signing.Verify(keys, Message(agent, desc.Digest), sig) + if err != nil { + return nil, fmt.Errorf("agentimage: %s: %w", pinned, err) + } + if signed != version { + return nil, fmt.Errorf("agentimage: %s is signed as %q, not %q", pinned, signed, version) + } + idx, err := remote.Index(pinned, opts...) + if err != nil { + return nil, err + } + m, err := idx.IndexManifest() + if err != nil { + return nil, err + } + for _, d := range m.Manifests { + if d.Platform == nil || !d.Platform.Equals(platform) { + continue + } + img, err := idx.Image(d.Digest) + if err != nil { + return nil, err + } + return ReadFile(img, strings.TrimPrefix(BinDir, "/")+"/"+agent, 512<<20) + } + return nil, fmt.Errorf("agentimage: %s has no image for %s", pinned, platform) +} + +// ReadFile returns a file of an image's layers, up to max bytes. +func ReadFile(img v1.Image, path string, max int64) ([]byte, error) { + layers, err := img.Layers() + if err != nil { + return nil, err + } + for i := len(layers) - 1; i >= 0; i-- { + data, found, err := fileInLayer(layers[i], path, max) + if err != nil || found { + return data, err + } + } + return nil, fmt.Errorf("agentimage: %s is not in the image", path) +} + +func fileInLayer(l v1.Layer, path string, max int64) ([]byte, bool, error) { + rc, err := l.Uncompressed() + if err != nil { + return nil, false, err + } + defer func() { _ = rc.Close() }() + tr := tar.NewReader(rc) + for { + h, err := tr.Next() + if errors.Is(err, io.EOF) { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + if strings.TrimPrefix(h.Name, "./") != path || h.Typeflag != tar.TypeReg { + continue + } + if h.Size > max { + return nil, true, fmt.Errorf("agentimage: %s is larger than %d bytes", path, max) + } + data, err := io.ReadAll(io.LimitReader(tr, max)) + return data, true, err + } +} diff --git a/internal/api/agent.go b/internal/api/agent.go index 1748745..d014f34 100644 --- a/internal/api/agent.go +++ b/internal/api/agent.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "strconv" + "strings" "time" "unicode/utf8" @@ -14,6 +15,7 @@ import ( "github.com/redis/go-redis/v9" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" "git.zb-server.de/ZB-Server/uptimesebi/internal/check" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/schedule" @@ -34,6 +36,7 @@ const ( func (s *Server) mountAgentAPI(r gin.IRouter) { g := r.Group("/agent/v1", s.agentAuth()) g.GET("/hello", s.agentHello) + g.GET("/update", s.agentUpdate) sp := g.Group("", requireAgentKind("statuspage")) sp.GET("/pages", s.agentPage) sp.GET("/storage", s.storageGet) @@ -76,6 +79,11 @@ func (s *Server) agentAuth() gin.HandlerFunc { if a, err = q.GetAgentByHash(ctx, HashToken(tok)); err != nil { return err } + // The launcher of a self-updating agent asks for updates with + // an instance of its own; only the agent itself is a sign of life. + if strings.HasSuffix(c.FullPath(), "/agent/v1/update") { + return nil + } if err := q.TouchAgent(ctx, store.TouchAgentParams{ID: a.ID, Release: &release}); err != nil { return err } @@ -128,6 +136,17 @@ func (s *Server) agentHello(c *gin.Context) { }) } +// agentUpdate names the release self-updating agents run: the platform's +// own, so agents never get ahead of the API. Unreleased builds ("dev") +// are not followed. +func (s *Server) agentUpdate(c *gin.Context) { + u := agentapi.Update{Version: buildinfo.Version} + if buildinfo.Version != "dev" { + u.Image = s.cfg.AgentImage + "-" + agentOf(c).Kind + ":" + strings.TrimPrefix(buildinfo.Version, "v") + } + c.JSON(http.StatusOK, u) +} + func (s *Server) agentJobs(c *gin.Context) { var req agentapi.JobsRequest if !bind(c, &req) { diff --git a/internal/api/checker_test.go b/internal/api/checker_test.go index b0d2173..e3d183b 100644 --- a/internal/api/checker_test.go +++ b/internal/api/checker_test.go @@ -13,7 +13,9 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/api" + "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" "git.zb-server.de/ZB-Server/uptimesebi/internal/checker" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) @@ -191,6 +193,33 @@ func TestAgentAuth(t *testing.T) { } } +func TestAgentUpdate(t *testing.T) { + e := newEnvWith(t, func(c *config.API) { c.AgentImage = "mirror.example/acme/uptimesebi" }) + tok, _ := e.platformChecker(t, uniq("up-")) + ctx := context.Background() + instance := uuid.New() + client := agentapi.NewClient(e.srv.URL, tok, instance, "v1.0.0").WithHTTPClient(e.srv.Client()) + + u, err := client.Update(ctx) + if err != nil || u.Version != "dev" || u.Image != "" { + t.Errorf("unreleased platform: Update = %+v, %v", u, err) + } + old := buildinfo.Version + buildinfo.Version = "v1.4.2" + t.Cleanup(func() { buildinfo.Version = old }) + u, err = client.Update(ctx) + if err != nil || u.Version != "v1.4.2" || u.Image != "mirror.example/acme/uptimesebi-checker:1.4.2" { + t.Errorf("Update = %+v, %v", u, err) + } + // The launcher asking is not an instance of the agent. + if n := e.count(t, `SELECT count(*) FROM agent_instances WHERE id = $1`, instance); n != 0 { + t.Errorf("the update check registered an instance") + } + if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Update(ctx); !errors.Is(err, agentapi.ErrUnauthorized) { + t.Errorf("Update(wrong token) = %v", err) + } +} + func (b *browser) orgID() string { b.t.Helper() _, me := b.do("GET", "/api/v1/me", nil) diff --git a/internal/config/config.go b/internal/config/config.go index 77570d5..a4750a4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -98,7 +98,10 @@ type API struct { // StatusPageURL is where the platform's status page servers are // reachable; the console links pages as /. StatusPageURL string `env:"UPTIME_STATUSPAGE_URL" envDefault:"http://localhost:8082"` - Retention Retention + // AgentImage is the image name agents are installed and updated from; + // "-checker" or "-statuspage" is appended. Change it for a mirror. + AgentImage string `env:"UPTIME_AGENT_IMAGE" envDefault:"git.zb-server.de/zb-server/uptimesebi"` + Retention Retention } // Retention sets how long data is kept. Zero keeps it forever. diff --git a/internal/launcher/launcher.go b/internal/launcher/launcher.go new file mode 100644 index 0000000..e450adc --- /dev/null +++ b/internal/launcher/launcher.go @@ -0,0 +1,291 @@ +// Package launcher keeps a self-updating agent on the platform's release. +// It runs the agent as a child process, asks the API which release to run, +// downloads and verifies it, swaps the running agent gracefully and falls +// back to the previous release when the new one does not become ready. +package launcher + +import ( + "context" + "errors" + "fmt" + "log/slog" + "math/rand/v2" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" +) + +// Process is a running agent. +type Process interface { + // Stop asks the agent to shut down and kills it after timeout. + Stop(timeout time.Duration) + // Done is closed when the agent has exited. + Done() <-chan struct{} + // Err is the agent's exit error, once Done is closed. + Err() error +} + +// Config wires the launcher to its surroundings. +type Config struct { + // Agent is the binary name: checker or statuspage. + Agent string + // Bundled is the binary shipped in the image. + Bundled string + // Dir keeps downloaded releases and the current choice. + Dir string + + // Interval is the time between update checks, ±10%. + Interval time.Duration + // ReadyWait is how long a release has to become ready. + ReadyWait time.Duration + // StopTimeout is how long an agent may take to shut down. + StopTimeout time.Duration + // RetryAfter is how long a release that failed is not tried again. + RetryAfter time.Duration + + Log *slog.Logger + // Updates asks the API which release to run. + Updates func(context.Context) (agentapi.Update, error) + // Fetch downloads and verifies the agent binary of a release. + Fetch func(context.Context, agentapi.Update) ([]byte, error) + // Start runs an agent binary. + Start func(path string) (Process, error) + // Ready reports whether the running agent is ready. + Ready func(context.Context) error + // Version reads the release a binary was built as. + Version func(path string) (string, error) +} + +// release is an agent binary and its version. +type release struct { + version, path string +} + +// Launcher runs one agent. +type Launcher struct { + cfg Config + bundled release + failed map[string]time.Time +} + +// New returns a launcher for cfg. +func New(cfg Config) *Launcher { + return &Launcher{cfg: cfg, failed: map[string]time.Time{}} +} + +var safeVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`) + +func (l *Launcher) releasePath(version string) string { + return filepath.Join(l.cfg.Dir, "releases", version, l.cfg.Agent) +} + +func (l *Launcher) currentFile() string { return filepath.Join(l.cfg.Dir, "current") } + +// initial picks the release to start with: the one chosen last time if it +// is still there, otherwise the bundled one. +func (l *Launcher) initial() release { + raw, err := os.ReadFile(l.currentFile()) + v := strings.TrimSpace(string(raw)) + if err != nil || !safeVersion.MatchString(v) || v == l.bundled.version { + return l.bundled + } + p := l.releasePath(v) + if got, err := l.cfg.Version(p); err != nil || got != v { + return l.bundled + } + return release{v, p} +} + +// Run starts the agent and keeps it updated until ctx ends, then stops it. +// It returns when the agent exits on its own. +func (l *Launcher) Run(ctx context.Context) error { + v, err := l.cfg.Version(l.cfg.Bundled) + if err != nil { + return fmt.Errorf("launcher: bundled %s: %w", l.cfg.Agent, err) + } + l.bundled = release{v, l.cfg.Bundled} + cur := l.initial() + proc, err := l.cfg.Start(cur.path) + if err != nil { + return err + } + started := time.Now() + l.cfg.Log.Info("agent started", "release", cur.version, "bundled", cur == l.bundled) + + // The first check comes soon, so new installations catch up quickly. + timer := time.NewTimer(min(l.cfg.Interval, 30*time.Second)) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + proc.Stop(l.cfg.StopTimeout) + return nil + case <-proc.Done(): + if cur == l.bundled || time.Since(started) > l.cfg.ReadyWait { + return fmt.Errorf("launcher: %s %s exited: %w", l.cfg.Agent, cur.version, proc.Err()) + } + // A downloaded release that crashes right after starting is + // not run again for a while. + l.cfg.Log.Error("agent crashed right after starting; falling back to the bundled release", + "release", cur.version, "error", proc.Err()) + l.failed[cur.version] = time.Now() + _ = os.Remove(l.currentFile()) + cur = l.bundled + if proc, err = l.cfg.Start(cur.path); err != nil { + return err + } + started = time.Now() + case <-timer.C: + next, np := l.check(ctx, cur, proc) + if np != proc { + started = time.Now() + } + cur, proc = next, np + if proc == nil { + return errors.New("launcher: no agent could be started") + } + timer.Reset(time.Duration(float64(l.cfg.Interval) * (0.9 + 0.2*rand.Float64()))) + } + } +} + +// check updates the agent if the platform names another release. It +// returns the release and process running afterwards. +func (l *Launcher) check(ctx context.Context, cur release, proc Process) (release, Process) { + u, err := l.cfg.Updates(ctx) + switch { + case err != nil: + l.cfg.Log.Warn("asking for updates failed", "error", err) + return cur, proc + case u.Image == "" || u.Version == cur.version: + return cur, proc + case !safeVersion.MatchString(u.Version): + l.cfg.Log.Warn("ignoring an invalid release name", "release", u.Version) + return cur, proc + case time.Since(l.failed[u.Version]) < l.cfg.RetryAfter: + return cur, proc + } + log := l.cfg.Log.With("from", cur.version, "to", u.Version) + next, err := l.obtain(ctx, u) + if err != nil { + log.Error("downloading the release failed", "image", u.Image, "error", err) + return cur, proc + } + log.Info("switching release") + proc.Stop(l.cfg.StopTimeout) + np, err := l.cfg.Start(next.path) + if err == nil && l.ready(ctx, np) { + if err := l.remember(next, cur); err != nil { + log.Warn("saving the release choice failed", "error", err) + } + log.Info("release switched") + return next, np + } + if np != nil { + np.Stop(l.cfg.StopTimeout) + } + log.Error("the release did not become ready; rolling back", "error", err, "retry_in", l.cfg.RetryAfter) + l.failed[u.Version] = time.Now() + back, err := l.cfg.Start(cur.path) + if err != nil { + log.Error("restarting the previous release failed", "error", err) + return cur, nil + } + return cur, back +} + +// obtain returns the binary of u's release: the bundled one, one +// downloaded before, or a fresh download. +func (l *Launcher) obtain(ctx context.Context, u agentapi.Update) (release, error) { + if u.Version == l.bundled.version { + return l.bundled, nil + } + path := l.releasePath(u.Version) + if v, err := l.cfg.Version(path); err == nil && v == u.Version { + return release{u.Version, path}, nil + } + bin, err := l.cfg.Fetch(ctx, u) + if err != nil { + return release{}, err + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return release{}, err + } + tmp := path + ".tmp" + if err := writeFileSync(tmp, bin, 0o700); err != nil { + return release{}, err + } + if v, err := l.cfg.Version(tmp); err != nil || v != u.Version { + _ = os.Remove(tmp) + if err != nil { + return release{}, fmt.Errorf("launcher: the downloaded binary does not run: %w", err) + } + return release{}, fmt.Errorf("launcher: the downloaded binary is %q, not %s", v, u.Version) + } + if err := os.Rename(tmp, path); err != nil { + return release{}, err + } + return release{u.Version, path}, nil +} + +func writeFileSync(path string, data []byte, mode os.FileMode) error { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode) + if err != nil { + return err + } + if _, err := f.Write(data); err != nil { + _ = f.Close() + return err + } + if err := f.Sync(); err != nil { + _ = f.Close() + return err + } + return f.Close() +} + +// ready waits until the agent is ready, it exits or ReadyWait passes. +func (l *Launcher) ready(ctx context.Context, p Process) bool { + deadline := time.Now().Add(l.cfg.ReadyWait) + tick := time.NewTicker(min(time.Second, l.cfg.ReadyWait/10)) + defer tick.Stop() + for time.Now().Before(deadline) { + select { + case <-ctx.Done(): + return false + case <-p.Done(): + return false + case <-tick.C: + if l.cfg.Ready(ctx) == nil { + return true + } + } + } + return false +} + +// remember records next as the release to start with and deletes all other +// downloads except prev, the fallback. +func (l *Launcher) remember(next, prev release) error { + if next == l.bundled { + if err := os.Remove(l.currentFile()); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } else if err := writeFileSync(l.currentFile(), []byte(next.version+"\n"), 0o600); err != nil { + return err + } + entries, err := os.ReadDir(filepath.Join(l.cfg.Dir, "releases")) + if err != nil { + return nil + } + for _, e := range entries { + if e.Name() != next.version && e.Name() != prev.version { + _ = os.RemoveAll(filepath.Join(l.cfg.Dir, "releases", e.Name())) + } + } + return nil +} diff --git a/internal/launcher/launcher_test.go b/internal/launcher/launcher_test.go new file mode 100644 index 0000000..88648b9 --- /dev/null +++ b/internal/launcher/launcher_test.go @@ -0,0 +1,307 @@ +package launcher + +import ( + "context" + "errors" + "log/slog" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" +) + +// The fake world: a binary is a file holding "version "; a started +// release is ready unless listed in broken and exits at once if listed in +// crashing. + +type fakeProc struct { + version string + done chan struct{} + once sync.Once +} + +func (p *fakeProc) Stop(time.Duration) { p.once.Do(func() { close(p.done) }) } +func (p *fakeProc) Done() <-chan struct{} { return p.done } +func (p *fakeProc) Err() error { return errors.New("exit status 1") } + +type world struct { + t *testing.T + dir string + mu sync.Mutex + // target is what the API names; fetchErr fails downloads. + target agentapi.Update + fetchErr error + fetched int + wrongBin bool + broken map[string]bool + crashing map[string]bool + running *fakeProc + started []string +} + +func newWorld(t *testing.T) *world { + w := &world{t: t, dir: t.TempDir(), broken: map[string]bool{}, crashing: map[string]bool{}} + if err := os.WriteFile(filepath.Join(w.dir, "bundled"), []byte("version v1.0.0"), 0o755); err != nil { + t.Fatal(err) + } + return w +} + +func (w *world) config() Config { + return Config{ + Agent: "checker", Bundled: filepath.Join(w.dir, "bundled"), Dir: filepath.Join(w.dir, "state"), + Interval: 20 * time.Millisecond, ReadyWait: 100 * time.Millisecond, StopTimeout: time.Second, RetryAfter: time.Hour, + Log: slog.New(slog.DiscardHandler), + Updates: func(context.Context) (agentapi.Update, error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.target.Version == "" { + return agentapi.Update{}, errors.New("api down") + } + return w.target, nil + }, + Fetch: func(_ context.Context, u agentapi.Update) ([]byte, error) { + w.mu.Lock() + defer w.mu.Unlock() + w.fetched++ + if w.fetchErr != nil { + return nil, w.fetchErr + } + if w.wrongBin { + return []byte("version v6.6.6"), nil + } + return []byte("version " + u.Version), nil + }, + Start: func(path string) (Process, error) { + v, err := fakeVersion(path) + if err != nil { + return nil, err + } + w.mu.Lock() + defer w.mu.Unlock() + p := &fakeProc{version: v, done: make(chan struct{})} + if w.crashing[v] { + close(p.done) + } + w.running = p + w.started = append(w.started, v) + return p, nil + }, + Ready: func(context.Context) error { + w.mu.Lock() + defer w.mu.Unlock() + if w.running == nil || w.broken[w.running.version] { + return errors.New("not ready") + } + return nil + }, + Version: fakeVersion, + } +} + +func fakeVersion(path string) (string, error) { + raw, err := os.ReadFile(path) + if err != nil { + return "", err + } + v, ok := strings.CutPrefix(string(raw), "version ") + if !ok { + return "", errors.New("not a binary") + } + return v, nil +} + +func (w *world) set(fn func(w *world)) { + w.mu.Lock() + defer w.mu.Unlock() + fn(w) +} + +func (w *world) runningVersion() string { + w.mu.Lock() + defer w.mu.Unlock() + if w.running == nil { + return "" + } + return w.running.version +} + +// current is the release the launcher starts with next time. +func (w *world) current() string { + raw, _ := os.ReadFile(filepath.Join(w.dir, "state", "current")) + return strings.TrimSpace(string(raw)) +} + +// eventually waits for cond. +func eventually(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +func run(t *testing.T, w *world) (cancel func() error) { + t.Helper() + ctx, stop := context.WithCancel(context.Background()) + errc := make(chan error, 1) + go func() { errc <- New(w.config()).Run(ctx) }() + return func() error { + stop() + return <-errc + } +} + +func TestUpdateAndRestart(t *testing.T) { + w := newWorld(t) + stop := run(t, w) + eventually(t, "bundled start", func() bool { return w.runningVersion() == "v1.0.0" }) + + w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "reg/uptimesebi-checker:1.1.0"} }) + eventually(t, "update to v1.1.0", func() bool { return w.runningVersion() == "v1.1.0" && w.current() == "v1.1.0" }) + if err := stop(); err != nil { + t.Fatal(err) + } + + // A restart starts the release chosen last time, without downloading. + before := w.fetched + stop = run(t, w) + eventually(t, "restart with v1.1.0", func() bool { return w.runningVersion() == "v1.1.0" }) + time.Sleep(60 * time.Millisecond) + if w.fetched != before { + t.Error("the release was downloaded again") + } + + // Another update keeps the previous release as fallback and deletes + // older ones; going back to the bundled release needs no download. + w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.2.0", Image: "x"} }) + eventually(t, "update to v1.2.0", func() bool { return w.runningVersion() == "v1.2.0" }) + w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.0.0", Image: "x"} }) + gone := func(p ...string) bool { + _, err := os.Stat(filepath.Join(append([]string{w.dir, "state"}, p...)...)) + return os.IsNotExist(err) + } + eventually(t, "back to bundled, old releases deleted", func() bool { + return w.runningVersion() == "v1.0.0" && gone("current") && gone("releases", "v1.1.0") + }) + if gone("releases", "v1.2.0") { + t.Error("the fallback release was deleted") + } + if err := stop(); err != nil { + t.Fatal(err) + } +} + +func TestRollback(t *testing.T) { + w := newWorld(t) + w.broken["v2.0.0"] = true + stop := run(t, w) + eventually(t, "bundled start", func() bool { return w.runningVersion() == "v1.0.0" }) + w.set(func(w *world) { w.target = agentapi.Update{Version: "v2.0.0", Image: "x"} }) + eventually(t, "rollback", func() bool { + w.mu.Lock() + defer w.mu.Unlock() + n := len(w.started) + return n >= 3 && w.started[n-2] == "v2.0.0" && w.started[n-1] == "v1.0.0" + }) + // The failed release is not tried again right away. + time.Sleep(100 * time.Millisecond) + w.mu.Lock() + tries := strings.Count(strings.Join(w.started, " "), "v2.0.0") + w.mu.Unlock() + if tries != 1 || w.runningVersion() != "v1.0.0" { + t.Errorf("started %v", w.started) + } + if err := stop(); err != nil { + t.Fatal(err) + } +} + +func TestCrashAfterRestart(t *testing.T) { + w := newWorld(t) + stop := run(t, w) + w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "x"} }) + eventually(t, "update", func() bool { return w.runningVersion() == "v1.1.0" && w.current() == "v1.1.0" }) + if err := stop(); err != nil { + t.Fatal(err) + } + // After a restart the remembered release crashes at once: the bundled + // release takes over. + w.set(func(w *world) { w.crashing["v1.1.0"] = true; w.target = agentapi.Update{} }) + stop = run(t, w) + eventually(t, "fallback", func() bool { return w.runningVersion() == "v1.0.0" }) + if err := stop(); err != nil { + t.Fatal(err) + } + + // The bundled release crashing ends the launcher, so the container + // restarts. + w.set(func(w *world) { w.crashing["v1.0.0"] = true }) + if err := New(w.config()).Run(context.Background()); err == nil { + t.Error("a crashing bundled agent did not end the launcher") + } +} + +func TestBadDownloads(t *testing.T) { + w := newWorld(t) + w.fetchErr = errors.New("signature does not match") + stop := run(t, w) + w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "x"} }) + eventually(t, "retries", func() bool { w.mu.Lock(); defer w.mu.Unlock(); return w.fetched >= 2 }) + if w.runningVersion() != "v1.0.0" { + t.Error("switched without a verified download") + } + // A binary that is not the release asked for is never run. + w.set(func(w *world) { w.fetchErr = nil; w.wrongBin = true }) + eventually(t, "more retries", func() bool { w.mu.Lock(); defer w.mu.Unlock(); return w.fetched >= 4 }) + w.mu.Lock() + for _, v := range w.started { + if v != "v1.0.0" { + t.Errorf("started %s", v) + } + } + w.mu.Unlock() + // Unreleased platforms and nonsense release names are ignored. + w.set(func(w *world) { w.wrongBin = false; w.target = agentapi.Update{Version: "dev"} }) + time.Sleep(60 * time.Millisecond) + w.set(func(w *world) { w.target = agentapi.Update{Version: "../../etc", Image: "x"} }) + time.Sleep(60 * time.Millisecond) + if w.runningVersion() != "v1.0.0" { + t.Error("followed an unreleased or invalid release") + } + if err := stop(); err != nil { + t.Fatal(err) + } +} + +func TestBinaryVersion(t *testing.T) { + dir := t.TempDir() + script := func(name, body string) string { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil { + t.Fatal(err) + } + return p + } + if v, err := BinaryVersion(script("good", `[ "$1" = version ] && echo v1.2.3`)); err != nil || v != "v1.2.3" { + t.Errorf("BinaryVersion = %q, %v", v, err) + } + for name, body := range map[string]string{"silent": "true", "failing": "exit 3", "chatty": "echo hello world"} { + if v, err := BinaryVersion(script(name, body)); err == nil { + t.Errorf("%s: BinaryVersion = %q", name, v) + } + } + if _, err := BinaryVersion(filepath.Join(dir, "missing")); err == nil { + t.Error("read a missing file") + } + if p := Platform(); p.OS == "" || p.Architecture == "" { + t.Errorf("Platform = %v", p) + } +} diff --git a/internal/launcher/process.go b/internal/launcher/process.go new file mode 100644 index 0000000..475302a --- /dev/null +++ b/internal/launcher/process.go @@ -0,0 +1,86 @@ +package launcher + +import ( + "context" + "fmt" + "os" + "os/exec" + "runtime" + "runtime/debug" + "strings" + "syscall" + "time" + + v1 "github.com/google/go-containerregistry/pkg/v1" +) + +type process struct { + cmd *exec.Cmd + done chan struct{} + err error +} + +// StartProcess runs path with the launcher's environment and output. +func StartProcess(path string) (Process, error) { + cmd := exec.Command(path) + cmd.Stdout, cmd.Stderr, cmd.Env = os.Stdout, os.Stderr, os.Environ() + if err := cmd.Start(); err != nil { + return nil, err + } + p := &process{cmd: cmd, done: make(chan struct{})} + go func() { + p.err = cmd.Wait() + close(p.done) + }() + return p, nil +} + +// Done is closed when the agent has exited. +func (p *process) Done() <-chan struct{} { return p.done } + +// Err is the agent's exit error. +func (p *process) Err() error { return p.err } + +// Stop sends SIGTERM and kills the agent after timeout. +func (p *process) Stop(timeout time.Duration) { + _ = p.cmd.Process.Signal(syscall.SIGTERM) + select { + case <-p.done: + case <-time.After(timeout): + _ = p.cmd.Process.Kill() + <-p.done + } +} + +// BinaryVersion asks an agent binary which release it is. +func BinaryVersion(path string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, path, "version").Output() + if err != nil { + return "", err + } + v := strings.TrimSpace(string(out)) + if v == "" || strings.ContainsAny(v, " \n") { + return "", fmt.Errorf("launcher: %s reports no release", path) + } + return v, nil +} + +// Platform is the platform this launcher was built for, and so the agent +// binaries it runs. +func Platform() v1.Platform { + p := v1.Platform{OS: runtime.GOOS, Architecture: runtime.GOARCH} + if runtime.GOARCH != "arm" { + return p + } + p.Variant = "v7" // Go's default for linux/arm + if info, ok := debug.ReadBuildInfo(); ok { + for _, s := range info.Settings { + if s.Key == "GOARM" && s.Value != "" { + p.Variant = "v" + s.Value[:1] + } + } + } + return p +} diff --git a/internal/platform/probe.go b/internal/platform/probe.go index 9e9cfdd..beffc4c 100644 --- a/internal/platform/probe.go +++ b/internal/platform/probe.go @@ -8,9 +8,9 @@ import ( "time" ) -// ProbeLocal asks the local health endpoint on listen (e.g. ":8081") whether -// the process is alive. Images without a shell run it as their HEALTHCHECK. -func ProbeLocal(ctx context.Context, listen string) error { +// ProbeLocal asks a local health endpoint (path /healthz or /readyz) on +// listen, e.g. ":8081". Images without a shell run it as their HEALTHCHECK. +func ProbeLocal(ctx context.Context, listen, path string) error { host, port, err := net.SplitHostPort(listen) if err != nil { return err @@ -20,7 +20,7 @@ func ProbeLocal(ctx context.Context, listen string) error { } ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() - req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+net.JoinHostPort(host, port)+"/healthz", nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+net.JoinHostPort(host, port)+path, nil) if err != nil { return err } diff --git a/tools/image/build.go b/tools/image/build.go deleted file mode 100644 index b6c2c4d..0000000 --- a/tools/image/build.go +++ /dev/null @@ -1,238 +0,0 @@ -package main - -import ( - "archive/tar" - "bytes" - "context" - "fmt" - "io" - "os" - "path/filepath" - "regexp" - "strings" - "time" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/empty" - "github.com/google/go-containerregistry/pkg/v1/mutate" - "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/google/go-containerregistry/pkg/v1/tarball" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// platforms are the Linux targets: x86 servers, 64-bit ARM (Raspberry Pi -// 3/4/5 on a 64-bit OS, ARM servers), 32-bit Raspberry Pi OS and the -// Raspberry Pi Zero and 1. -var platforms = []struct { - dir string - v1.Platform -}{ - {"linux_amd64", v1.Platform{OS: "linux", Architecture: "amd64"}}, - {"linux_arm64", v1.Platform{OS: "linux", Architecture: "arm64"}}, - {"linux_arm_v7", v1.Platform{OS: "linux", Architecture: "arm", Variant: "v7"}}, - {"linux_arm_v6", v1.Platform{OS: "linux", Architecture: "arm", Variant: "v6"}}, -} - -func platformNames() []string { - var out []string - for _, p := range platforms { - out = append(out, p.String()) - } - return out -} - -// nonroot is the user the agents run as, the same ID as distroless' -// nonroot so volumes carry over. -const nonroot = 65532 - -// dataDir holds the status page cache and, in the autoupdate variant, the -// downloaded releases. -const dataDir = "/var/lib/uptimesebi" - -type options struct { - Name, Dist, Repo, Version, Commit, Source, Suffix string - Env, Ports []string - Created time.Time -} - -// build assembles the index of all platforms. -func build(o options) (v1.ImageIndex, error) { - idx := mutate.IndexMediaType(empty.Index, types.OCIImageIndex) - for _, p := range platforms { - img, err := image(o, filepath.Join(o.Dist, p.dir, o.Name), p.Platform) - if err != nil { - return nil, err - } - pl := p.Platform - idx = mutate.AppendManifests(idx, mutate.IndexAddendum{Add: img, Descriptor: v1.Descriptor{Platform: &pl}}) - } - return idx, nil -} - -func image(o options, binary string, p v1.Platform) (v1.Image, error) { - bin, err := os.ReadFile(binary) - if err != nil { - return nil, fmt.Errorf("image: %w", err) - } - layerTar, err := rootfs(o.Name, bin, o.Created) - if err != nil { - return nil, err - } - layer, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewReader(layerTar)), nil - }, tarball.WithMediaType(types.OCILayer)) - if err != nil { - return nil, err - } - img := mutate.MediaType(empty.Image, types.OCIManifestSchema1) - img = mutate.ConfigMediaType(img, types.OCIConfigJSON) - img, err = mutate.Append(img, mutate.Addendum{ - Layer: layer, - History: v1.History{Created: v1.Time{Time: o.Created}, CreatedBy: "uptimesebi tools/image", Comment: o.Name + " " + o.Version}, - MediaType: types.OCILayer, - }) - if err != nil { - return nil, err - } - cf, err := img.ConfigFile() - if err != nil { - return nil, err - } - cf = cf.DeepCopy() - cf.OS, cf.Architecture, cf.Variant = p.OS, p.Architecture, p.Variant - cf.Created = v1.Time{Time: o.Created} - entry := "/usr/local/bin/" + o.Name - cf.Config = v1.Config{ - Entrypoint: []string{entry}, - User: fmt.Sprintf("%d:%d", nonroot, nonroot), - WorkingDir: dataDir, - Env: append([]string{"HOME=" + dataDir}, o.Env...), - Volumes: map[string]struct{}{dataDir: {}}, - Healthcheck: &v1.HealthConfig{ - Test: []string{"CMD", entry, "health"}, - Interval: 30 * time.Second, Timeout: 5 * time.Second, StartPeriod: 20 * time.Second, Retries: 3, - }, - Labels: labels(o), - } - if len(o.Ports) > 0 { - cf.Config.ExposedPorts = map[string]struct{}{} - for _, port := range o.Ports { - cf.Config.ExposedPorts[port] = struct{}{} - } - } - return mutate.ConfigFile(img, cf) -} - -func labels(o options) map[string]string { - l := map[string]string{ - "org.opencontainers.image.title": "uptimesebi-" + o.Name, - "org.opencontainers.image.version": o.Version, - "org.opencontainers.image.licenses": "AGPL-3.0-only", - } - if o.Commit != "" { - l["org.opencontainers.image.revision"] = o.Commit - } - if o.Source != "" { - l["org.opencontainers.image.source"] = o.Source - } - return l -} - -// rootfs is the single layer: the binary, a data directory owned by the -// agent's user and a temporary directory. -func rootfs(binName string, bin []byte, mtime time.Time) ([]byte, error) { - var buf bytes.Buffer - tw := tar.NewWriter(&buf) - dir := func(path string, mode int64, uid int) error { - return tw.WriteHeader(&tar.Header{Typeflag: tar.TypeDir, Name: path + "/", Mode: mode, Uid: uid, Gid: uid, ModTime: mtime, Format: tar.FormatPAX}) - } - for _, d := range []struct { - path string - mode int64 - uid int - }{ - {"tmp", 0o1777, 0}, - {"usr", 0o755, 0}, {"usr/local", 0o755, 0}, {"usr/local/bin", 0o755, 0}, - {"var", 0o755, 0}, {"var/lib", 0o755, 0}, {strings.TrimPrefix(dataDir, "/"), 0o700, nonroot}, - } { - if err := dir(d.path, d.mode, d.uid); err != nil { - return nil, err - } - } - if err := tw.WriteHeader(&tar.Header{ - Typeflag: tar.TypeReg, Name: "usr/local/bin/" + binName, Mode: 0o755, Size: int64(len(bin)), ModTime: mtime, Format: tar.FormatPAX, - }); err != nil { - return nil, err - } - if _, err := tw.Write(bin); err != nil { - return nil, err - } - if err := tw.Close(); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -var releaseTag = regexp.MustCompile(`^v(\d+)\.(\d+)\.(\d+)(-beta\.\d+)?$`) - -// channelTags are the tags an image gets: edge and a dated build tag from -// main, beta from prereleases, latest, stable, X.Y and X.Y.Z from releases. -// Other refs (pull requests, branches) publish nothing. A variant suffix -// is appended to every tag. -func channelTags(ref, version, commit string, created time.Time, suffix string) []string { - var tags []string - switch { - case ref == "refs/heads/main": - short := commit[:min(len(commit), 12)] - tags = []string{created.UTC().Format("20060102150405") + "-" + short, "edge"} - case strings.HasPrefix(ref, "refs/tags/"): - m := releaseTag.FindStringSubmatch(strings.TrimPrefix(ref, "refs/tags/")) - switch { - case m == nil: - return nil - case m[4] != "": - tags = []string{strings.TrimPrefix(m[0], "v"), "beta"} - default: - tags = []string{strings.TrimPrefix(m[0], "v"), m[1] + "." + m[2], "stable", "latest"} - } - default: - return nil - } - if suffix != "" { - for i := range tags { - tags[i] += "-" + suffix - } - } - return tags -} - -type credentials struct{ user, password string } - -// publish pushes the index under its first tag and adds the others. -func publish(ctx context.Context, idx v1.ImageIndex, repo string, tags []string, login credentials, insecure bool) error { - var nameOpts []name.Option - if insecure { - nameOpts = append(nameOpts, name.Insecure) - } - opts := []remote.Option{remote.WithContext(ctx)} - if login.user != "" { - opts = append(opts, remote.WithAuth(&authn.Basic{Username: login.user, Password: login.password})) - } - for i, t := range tags { - tag, err := name.NewTag(repo+":"+t, nameOpts...) - if err != nil { - return err - } - if i == 0 { - err = remote.WriteIndex(tag, idx, opts...) - } else { - err = remote.Tag(tag, idx, opts...) - } - if err != nil { - return fmt.Errorf("image: push %s: %w", tag, err) - } - } - return nil -} diff --git a/tools/image/image_test.go b/tools/image/image_test.go deleted file mode 100644 index 93f4da0..0000000 --- a/tools/image/image_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package main - -import ( - "archive/tar" - "context" - "errors" - "io" - "net/http/httptest" - "os" - "path/filepath" - "slices" - "strings" - "testing" - "time" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/registry" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -func fakeDist(t *testing.T, bin string) string { - t.Helper() - dist := t.TempDir() - for _, p := range platforms { - if err := os.MkdirAll(filepath.Join(dist, p.dir), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dist, p.dir, bin), []byte("binary for "+p.dir), 0o755); err != nil { - t.Fatal(err) - } - } - return dist -} - -func TestBuild(t *testing.T) { - o := options{ - Name: "statuspage", Dist: fakeDist(t, "statuspage"), Version: "v1.2.3", Commit: "abc123", - Env: []string{"UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi"}, Ports: []string{"8082/tcp"}, - Created: time.Unix(1700000000, 0).UTC(), - } - idx, err := build(o) - if err != nil { - t.Fatal(err) - } - m, err := idx.IndexManifest() - if err != nil { - t.Fatal(err) - } - if len(m.Manifests) != 4 { - t.Fatalf("index has %d manifests", len(m.Manifests)) - } - for i, desc := range m.Manifests { - want := platforms[i] - if desc.Platform == nil || !desc.Platform.Equals(want.Platform) { - t.Errorf("manifest %d platform = %v, want %v", i, desc.Platform, want.Platform) - } - img, err := idx.Image(desc.Digest) - if err != nil { - t.Fatal(err) - } - cf, err := img.ConfigFile() - if err != nil { - t.Fatal(err) - } - if cf.Architecture != want.Architecture || cf.Variant != want.Variant || cf.Config.User != "65532:65532" || - !slices.Equal(cf.Config.Entrypoint, []string{"/usr/local/bin/statuspage"}) || - !slices.Equal(cf.Config.Healthcheck.Test, []string{"CMD", "/usr/local/bin/statuspage", "health"}) || - !slices.Contains(cf.Config.Env, "UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi") || - cf.Config.Labels["org.opencontainers.image.version"] != "v1.2.3" { - t.Errorf("%s config = %+v", want.dir, cf.Config) - } - files := layerFiles(t, img) - if got := files["usr/local/bin/statuspage"]; got.Mode != 0o755 || got.Size != int64(len("binary for "+want.dir)) { - t.Errorf("%s binary = %+v", want.dir, got) - } - if got := files["var/lib/uptimesebi/"]; got.Uid != nonroot { - t.Errorf("data directory owner = %d", got.Uid) - } - } - - // The same input gives the same image. - again, _ := build(o) - d1, _ := idx.Digest() - d2, _ := again.Digest() - if d1 != d2 { - t.Errorf("rebuild changed the digest: %s, %s", d1, d2) - } - - o.Dist = t.TempDir() - if _, err := build(o); err == nil { - t.Error("built without binaries") - } -} - -func layerFiles(t *testing.T, img v1.Image) map[string]*tar.Header { - t.Helper() - layers, err := img.Layers() - if err != nil || len(layers) != 1 { - t.Fatalf("layers = %d, %v", len(layers), err) - } - rc, err := layers[0].Uncompressed() - if err != nil { - t.Fatal(err) - } - defer func() { _ = rc.Close() }() - out := map[string]*tar.Header{} - tr := tar.NewReader(rc) - for { - h, err := tr.Next() - if errors.Is(err, io.EOF) { - return out - } - if err != nil { - t.Fatal(err) - } - out[h.Name] = h - } -} - -func TestChannelTags(t *testing.T) { - created := time.Date(2026, 11, 23, 18, 0, 0, 0, time.UTC) - for _, c := range []struct { - ref, suffix string - want []string - }{ - {"refs/heads/main", "", []string{"20261123180000-0123456789ab", "edge"}}, - {"refs/tags/v1.4.2", "", []string{"1.4.2", "1.4", "stable", "latest"}}, - {"refs/tags/v1.5.0-beta.3", "", []string{"1.5.0-beta.3", "beta"}}, - {"refs/tags/v1.4.2", "autoupdate", []string{"1.4.2-autoupdate", "1.4-autoupdate", "stable-autoupdate", "latest-autoupdate"}}, - {"refs/tags/nightly", "", nil}, - {"refs/pull/7/merge", "", nil}, - {"refs/heads/feature", "", nil}, - } { - if got := channelTags(c.ref, "v", "0123456789abcdef", created, c.suffix); !slices.Equal(got, c.want) { - t.Errorf("%s %s: tags = %v, want %v", c.ref, c.suffix, got, c.want) - } - } -} - -func TestPublish(t *testing.T) { - reg := httptest.NewServer(registry.New()) - defer reg.Close() - repo := strings.TrimPrefix(reg.URL, "http://") + "/zb/uptimesebi-checker" - idx, err := build(options{Name: "checker", Dist: fakeDist(t, "checker"), Version: "v1.0.0"}) - if err != nil { - t.Fatal(err) - } - if err := publish(context.Background(), idx, repo, []string{"1.0.0", "latest"}, credentials{}, true); err != nil { - t.Fatal(err) - } - want, _ := idx.Digest() - for _, tag := range []string{"1.0.0", "latest"} { - ref, _ := name.NewTag(repo+":"+tag, name.Insecure) - desc, err := remote.Get(ref) - if err != nil || desc.Digest != want { - t.Errorf("%s = %v, %v; want %s", tag, desc, err, want) - } - } - // A Raspberry Pi Zero pulls its own variant. - ref, _ := name.NewTag(repo+":latest", name.Insecure) - img, err := remote.Image(ref, remote.WithPlatform(v1.Platform{OS: "linux", Architecture: "arm", Variant: "v6"})) - if err != nil { - t.Fatal(err) - } - if got := layerFiles(t, img)["usr/local/bin/checker"]; got.Size != int64(len("binary for linux_arm_v6")) { - t.Errorf("arm/v6 pulled the wrong binary: %+v", got) - } -} diff --git a/tools/image/main.go b/tools/image/main.go index bcfe4c8..8e20e0d 100644 --- a/tools/image/main.go +++ b/tools/image/main.go @@ -1,14 +1,15 @@ -// Command image builds the multi-arch images of an agent (checker or status -// page server) from cross-compiled binaries, without Docker: one layer on -// an empty base per platform, combined into an OCI index. +// Command image builds and publishes the multi-arch images of an agent +// (checker or status page server) from cross-compiled binaries, without +// Docker. // // image -name checker -dist dist -repo registry/owner/uptimesebi-checker \ -// -version v1.2.3 -commit abc123 -ref refs/tags/v1.2.3 [-push] +// -version v1.2.3 -commit abc123 -ref refs/tags/v1.2.3 [-autoupdate] [-push] // // dist holds one directory per platform: linux_amd64, linux_arm64, -// linux_arm_v7 and linux_arm_v6, each with the binary. Without -push the -// index is only built and checked. The registry login comes from -// REGISTRY_USER and REGISTRY_PASSWORD. +// linux_arm_v7 and linux_arm_v6, each with the binaries. Without -push +// the index is only built. The registry login comes from REGISTRY_USER and +// REGISTRY_PASSWORD; when RELEASE_SIGNING_KEY is set, pushed images are +// signed so self-updating agents accept them. package main import ( @@ -19,6 +20,11 @@ import ( "os" "strings" "time" + + "github.com/google/go-containerregistry/pkg/name" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentimage" + "git.zb-server.de/ZB-Server/uptimesebi/internal/signing" ) func main() { @@ -35,16 +41,16 @@ func (l *listFlag) Set(v string) error { *l = append(*l, v); return nil } func run(args []string) error { fs := flag.NewFlagSet("image", flag.ContinueOnError) - var o options + var o agentimage.Options fs.StringVar(&o.Name, "name", "", "binary name: checker or statuspage") fs.StringVar(&o.Dist, "dist", "dist", "directory with one subdirectory per platform") - fs.StringVar(&o.Repo, "repo", "", "image repository, e.g. git.example.com/owner/uptimesebi-checker") - fs.StringVar(&o.Version, "version", "dev", "release version") + fs.StringVar(&o.Version, "version", "dev", "release version, as the binaries report it") fs.StringVar(&o.Commit, "commit", "", "git revision") fs.StringVar(&o.Source, "source", "", "repository URL for the image labels") - fs.StringVar(&o.Suffix, "suffix", "", "tag suffix of an image variant, e.g. autoupdate") + fs.BoolVar(&o.Launcher, "autoupdate", false, "build the self-updating variant (tags get -autoupdate)") fs.Var((*listFlag)(&o.Env), "env", "NAME=value baked into the image (repeatable)") fs.Var((*listFlag)(&o.Ports), "port", "exposed port, e.g. 8081/tcp (repeatable)") + repo := fs.String("repo", "", "image repository, e.g. git.example.com/owner/uptimesebi-checker") ref := fs.String("ref", "", "git ref being built, e.g. refs/heads/main or refs/tags/v1.2.3") created := fs.Int64("created", 0, "creation time as Unix seconds, for reproducible images") push := fs.Bool("push", false, "push to the registry") @@ -52,12 +58,12 @@ func run(args []string) error { if err := fs.Parse(args); err != nil { return err } - if o.Name == "" || o.Repo == "" { + if o.Name == "" || *repo == "" { return errors.New("image: -name and -repo are required") } o.Created = time.Unix(*created, 0).UTC() - idx, err := build(o) + idx, err := agentimage.Build(o) if err != nil { return err } @@ -65,21 +71,41 @@ func run(args []string) error { if err != nil { return err } - tags := channelTags(*ref, o.Version, o.Commit, o.Created, o.Suffix) - fmt.Printf("built %s@%s for %s\n", o.Repo, digest, strings.Join(platformNames(), ", ")) + fmt.Printf("built %s@%s\n", *repo, digest) if !*push { return nil } + suffix := "" + if o.Launcher { + suffix = "autoupdate" + } + tags := agentimage.ChannelTags(*ref, o.Version, suffix) if len(tags) == 0 { return fmt.Errorf("image: %q is not a ref that publishes images", *ref) } - if *ref == "refs/heads/main" && (o.Commit == "" || *created == 0) { - return errors.New("image: builds of main need -commit and -created for their tag") + var nameOpts []name.Option + if *insecure { + nameOpts = append(nameOpts, name.Insecure) } - login := credentials{os.Getenv("REGISTRY_USER"), os.Getenv("REGISTRY_PASSWORD")} - if err := publish(context.Background(), idx, o.Repo, tags, login, *insecure); err != nil { + ctx := context.Background() + login := agentimage.Credentials{User: os.Getenv("REGISTRY_USER"), Password: os.Getenv("REGISTRY_PASSWORD")} + if err := agentimage.Publish(ctx, idx, *repo, tags, login, nameOpts...); err != nil { return err } - fmt.Printf("pushed %s:%s\n", o.Repo, strings.Join(tags, ", :")) + fmt.Printf("pushed %s:%s\n", *repo, strings.Join(tags, ", :")) + + raw := os.Getenv("RELEASE_SIGNING_KEY") + if raw == "" { + fmt.Println("RELEASE_SIGNING_KEY is not set; self-updating agents will not accept this image.") + return nil + } + key, err := signing.ParsePrivateKey(raw) + if err != nil { + return err + } + if err := agentimage.Sign(ctx, idx, *repo, o.Name, o.Version, key, login, nameOpts...); err != nil { + return err + } + fmt.Printf("signed %s@%s as %s\n", *repo, digest, o.Version) return nil }