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 +}