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 }