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-<digest>.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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
293 lines
9.1 KiB
Go
293 lines
9.1 KiB
Go
// 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}})
|
|
}
|