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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
e17e7aab41
commit
a9f94fc492
12 files changed
+638
-9
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user