diff --git a/.github/actions/build/action.yaml b/.github/actions/build/action.yaml index 33a31050..a2f74745 100644 --- a/.github/actions/build/action.yaml +++ b/.github/actions/build/action.yaml @@ -5,6 +5,12 @@ inputs: pin-images: description: Pin images in the collection default: "true" + manifest: + description: >- + Release manifest (file or OCI reference) to pin the images from. When + empty, a manifest is generated from the source tree and written to + $RUNNER_TEMP/release-manifest.yaml. + default: "" runs: using: composite @@ -37,7 +43,15 @@ runs: fi - shell: bash - if: ${{ inputs.pin-images == 'true' }} + if: ${{ inputs.pin-images == 'true' && inputs.manifest == '' }} run: | - go run cmd/pinimages/pinimages.go + go run ./cmd/atmosphere-release generate --write-vars --output "${RUNNER_TEMP}/release-manifest.yaml" + cat ./roles/defaults/vars/main.yml + + - shell: bash + if: ${{ inputs.pin-images == 'true' && inputs.manifest != '' }} + env: + MANIFEST: ${{ inputs.manifest }} + run: | + go run ./cmd/atmosphere-release write-vars "${MANIFEST}" cat ./roles/defaults/vars/main.yml diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index dd6f942b..7e5a96b5 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -63,8 +63,30 @@ jobs: pin-images: false - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 + python-test: + runs-on: ubuntu-latest + steps: + - name: Harden the runner (Audit all outbound calls) + uses: step-security/harden-runner@a90bcbc6539c36a85cdfeb73f7e2f433735f215b # v2.15.0 + with: + egress-policy: audit + + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - uses: step-security/setup-uv@ccf0a26ce9117d9e99292b0ce953ea5d9ffe778e # v7.3.0 + - name: Run release manifest plugin tests + run: | + uv run --no-project --python 3.12 \ + --with 'ansible-core>=2.15.9' --with pytest --with pytest-ansible --with pyyaml \ + python -m pytest \ + tests/unit/plugins/filter/test_resolve_images.py \ + tests/unit/plugins/lookup/test_release_manifest.py + build: runs-on: ubuntu-latest + permissions: + contents: read + packages: write + pull-requests: read steps: - name: Harden the runner (Audit all outbound calls) uses: step-security/harden-runner@a90bcbc6539c36a85cdfeb73f7e2f433735f215b # v2.15.0 @@ -75,3 +97,42 @@ jobs: with: fetch-depth: 0 - uses: ./.github/actions/build + + - name: Login to GitHub Container Registry + if: github.event_name == 'push' + uses: step-security/docker-login-action@c3e677aae8393bc9c81cfdf9709648720ea4bd4d # v3.6.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Generate release manifest tags + id: meta + if: github.event_name == 'push' + uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 + with: + images: ghcr.io/vexxhost/atmosphere-release + flavor: | + latest=false + tags: | + type=sha,prefix=,format=long + type=ref,event=branch + + # NOTE: Publish the release manifest that Zuul tested for the merged pull + # request when its image inputs match this commit; otherwise the + # manifest generated above is published and marked as untested. + - name: Publish release manifest + if: github.event_name == 'push' + env: + GH_TOKEN: ${{ github.token }} + TAGS: ${{ steps.meta.outputs.tags }} + run: | + mapfile -t refs <<< "${TAGS}" + lookup=() + pr=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls" \ + --jq '([.[] | select(.merged_at != null)][0] // empty) | "\(.number) \(.head.sha)"' || true) + if [ -n "${pr}" ]; then + read -r change patchset <<< "${pr}" + lookup=(--zuul-api https://zuul.oss.vexxhost.dev/api --change "${change}" --patchset "${patchset}") + fi + go run ./cmd/atmosphere-release publish --file "${RUNNER_TEMP}/release-manifest.yaml" "${lookup[@]}" "${refs[@]}" diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 4e1eba57..bcb22b79 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -9,6 +9,9 @@ permissions: {} jobs: build: runs-on: ubuntu-latest + permissions: + contents: write + packages: write steps: - name: Harden the runner (Audit all outbound calls) uses: step-security/harden-runner@a90bcbc6539c36a85cdfeb73f7e2f433735f215b # v2.15.0 @@ -18,7 +21,52 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: fetch-depth: 0 + + - name: Login to GitHub Container Registry + uses: step-security/docker-login-action@c3e677aae8393bc9c81cfdf9709648720ea4bd4d # v3.6.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Generate release manifest tags + id: meta + uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 + with: + images: ghcr.io/vexxhost/atmosphere-release + flavor: | + latest=false + tags: | + type=ref,event=tag + + # NOTE: The release ships exactly the manifest CI published for the + # released commit; no image is resolved again. + - name: Promote release manifest + env: + TAGS: ${{ steps.meta.outputs.tags }} + run: | + mapfile -t refs <<< "${TAGS}" + go run ./cmd/atmosphere-release promote --from "${GITHUB_SHA}" --generate-if-missing "${refs[@]}" + go run ./cmd/atmosphere-release show "${refs[0]}" > "${RUNNER_TEMP}/release-manifest.yaml" + + - name: Attach atmosphere-release binaries and the release manifest + uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0 + with: + distribution: goreleaser + version: "~> v2" + args: release --clean + env: + GITHUB_TOKEN: ${{ github.token }} + RELEASE_MANIFEST: ${{ runner.temp }}/release-manifest.yaml + + # NOTE: Keep the GoReleaser output out of the Ansible collection. + - name: Remove GoReleaser output + run: rm -rf dist + - uses: ./.github/actions/build + with: + manifest: ${{ runner.temp }}/release-manifest.yaml + - uses: ansible/ansible-publish-action@a56a0328c92c1d4feedf5bd7f7cf7ec7a4ae3f09 # v1.0.0 with: api_key: ${{ secrets.ANSIBLE_GALAXY_TOKEN }} diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 00000000..c32f7911 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,43 @@ +# Builds the atmosphere-release command and attaches it, with the release +# manifest, to the GitHub release created for each Atmosphere version. +version: 2 + +project_name: atmosphere-release + +builds: + - id: atmosphere-release + main: ./cmd/atmosphere-release + binary: atmosphere-release + env: + - CGO_ENABLED=0 + goos: + - linux + - darwin + goarch: + - amd64 + - arm64 + flags: + - -trimpath + ldflags: + - -s -w + +archives: + - id: atmosphere-release + formats: + - tar.gz + name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}" + files: + - none* + +checksum: + name_template: "{{ .ProjectName }}_{{ .Version }}_checksums.txt" + +changelog: + disable: true + +release: + # NOTE: The release and its notes are created before this runs; only add + # assets to it. + mode: keep-existing + extra_files: + - glob: "{{ .Env.RELEASE_MANIFEST }}" diff --git a/cmd/atmosphere-release/main.go b/cmd/atmosphere-release/main.go new file mode 100644 index 00000000..5047ea0a --- /dev/null +++ b/cmd/atmosphere-release/main.go @@ -0,0 +1,657 @@ +// Command atmosphere-release generates, publishes, inspects and mirrors +// Atmosphere release manifests. +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "strings" + + log "github.com/sirupsen/logrus" + "github.com/spf13/cobra" + "oras.land/oras-go/v2/errdef" + + "github.com/goccy/go-yaml" + "github.com/vexxhost/atmosphere/internal/releasemanifest" +) + +const ( + defaultVarsPath = "roles/defaults/vars/main.yml" + defaultDefaultsPath = "roles/defaults/defaults/main.yml" + defaultSource = "https://github.com/vexxhost/atmosphere" +) + +type globalOptions struct { + plainHTTP bool +} + +func main() { + if err := newRootCommand().Execute(); err != nil { + log.Fatal(err) + } +} + +func newRootCommand() *cobra.Command { + opts := &globalOptions{} + + root := &cobra.Command{ + Use: "atmosphere-release", + Short: "Generate, publish, inspect and mirror Atmosphere release manifests", + SilenceUsage: true, + SilenceErrors: true, + } + root.PersistentFlags().BoolVar(&opts.plainHTTP, "plain-http", false, "use HTTP instead of HTTPS for registries (local test registries only)") + + root.AddCommand( + newGenerateCommand(), + newWriteVarsCommand(opts), + newPushCommand(opts), + newDigestCommand(), + newPublishCommand(opts), + newPromoteCommand(opts), + newShowCommand(opts), + newDiffCommand(opts), + newCheckCommand(opts), + newMirrorCommand(opts), + ) + return root +} + +func (o *globalOptions) factory() (releasemanifest.TargetFactory, error) { + return releasemanifest.NewRemoteFactory(releasemanifest.RemoteOptions{PlainHTTP: o.plainHTTP}) +} + +func (o *globalOptions) load(ctx context.Context, location string) (*releasemanifest.Manifest, error) { + factory, err := o.factory() + if err != nil { + return nil, err + } + return releasemanifest.Load(ctx, location, factory) +} + +func currentCommit() string { + if sha := os.Getenv("GITHUB_SHA"); sha != "" { + return sha + } + out, err := exec.Command("git", "rev-parse", "HEAD").Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} + +func generate(ctx context.Context, varsPath, defaultsPath, commit, resolvePrefix string) (*releasemanifest.Manifest, error) { + src, err := releasemanifest.LoadSource(varsPath, defaultsPath) + if err != nil { + return nil, err + } + if commit == "" { + commit = currentCommit() + } + return releasemanifest.Generate(ctx, src, releasemanifest.DockerResolver{}, releasemanifest.GenerateOptions{ + Commit: commit, + ResolvePrefix: resolvePrefix, + }) +} + +func newGenerateCommand() *cobra.Command { + var varsPath, defaultsPath, commit, output, resolvePrefix string + var writeVars bool + + cmd := &cobra.Command{ + Use: "generate", + Short: "Resolve every image in the source tree into a release manifest", + Long: `Render the image list in the defaults role, keep existing digest pins and +resolve every image referenced only by tag to the digest it currently points to.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + m, err := generate(cmd.Context(), varsPath, defaultsPath, commit, resolvePrefix) + if err != nil { + return err + } + data, err := m.Marshal() + if err != nil { + return err + } + + if output == "" || output == "-" { + _, err = os.Stdout.Write(data) + } else { + err = os.WriteFile(output, data, 0o644) + log.WithField("images", len(m.Images)).Infof("Wrote %s", output) + } + if err != nil { + return err + } + + if writeVars { + if err := releasemanifest.WriteVars(varsPath, m); err != nil { + return err + } + log.Infof("Pinned images in %s", varsPath) + } + return nil + }, + } + cmd.Flags().StringVar(&varsPath, "vars", defaultVarsPath, "defaults role vars file") + cmd.Flags().StringVar(&defaultsPath, "defaults", defaultDefaultsPath, "defaults role defaults file") + cmd.Flags().StringVar(&commit, "commit", "", "source commit to record (default: $GITHUB_SHA or git HEAD)") + cmd.Flags().StringVarP(&output, "output", "o", "", "write the manifest to a file instead of stdout") + cmd.Flags().BoolVar(&writeVars, "write-vars", false, "also pin the images in the vars file") + cmd.Flags().StringVar(&resolvePrefix, "resolve-prefix", "", "resolve tags through this pull-through cache prefix first (e.g. harbor.example.com/)") + return cmd +} + +func newWriteVarsCommand(opts *globalOptions) *cobra.Command { + var varsPath string + + cmd := &cobra.Command{ + Use: "write-vars MANIFEST", + Short: "Pin the images in the vars file to a release manifest (file or OCI reference)", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + m, err := opts.load(cmd.Context(), args[0]) + if err != nil { + return err + } + if err := releasemanifest.WriteVars(varsPath, m); err != nil { + return err + } + log.Infof("Pinned images in %s from %s", varsPath, args[0]) + return nil + }, + } + cmd.Flags().StringVar(&varsPath, "vars", defaultVarsPath, "defaults role vars file") + return cmd +} + +func newPushCommand(opts *globalOptions) *cobra.Command { + var file, source string + + cmd := &cobra.Command{ + Use: "push REFERENCE...", + Short: "Publish a release manifest file as an OCI artifact", + Long: `Publish a release manifest file to one repository under every given tag. +References are repository:tag, for example the "tags" output of +docker/metadata-action; empty arguments are ignored.`, + Example: ` atmosphere-release push --file release-manifest.yaml \ + ghcr.io/vexxhost/atmosphere-release:"$GITHUB_SHA" ghcr.io/vexxhost/atmosphere-release:main`, + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + repository, tags, err := releasemanifest.SplitReferences(args) + if err != nil { + return err + } + data, err := os.ReadFile(file) + if err != nil { + return err + } + m, err := releasemanifest.Unmarshal(data) + if err != nil { + return err + } + factory, err := opts.factory() + if err != nil { + return err + } + repo, err := factory(repository) + if err != nil { + return err + } + desc, err := releasemanifest.Push(cmd.Context(), repo, m, tags, releasemanifest.PushOptions{Source: source}) + if err != nil { + return err + } + for _, tag := range tags { + fmt.Printf("%s:%s@%s\n", repository, tag, desc.Digest) + } + return nil + }, + } + cmd.Flags().StringVarP(&file, "file", "f", releasemanifest.FileName, "manifest file to publish") + cmd.Flags().StringVar(&source, "source", defaultSource, "source repository annotation") + return cmd +} + +func newDigestCommand() *cobra.Command { + var file, source string + + cmd := &cobra.Command{ + Use: "digest", + Short: "Print the artifact digest that push would publish for a manifest file", + Long: `Print the digest of the OCI artifact that "push" creates for a manifest +file. Pushes are reproducible, so the same manifest always has the same +digest, wherever it is pushed.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + data, err := os.ReadFile(file) + if err != nil { + return err + } + m, err := releasemanifest.Unmarshal(data) + if err != nil { + return err + } + dgst, err := releasemanifest.Digest(cmd.Context(), m, releasemanifest.PushOptions{Source: source}) + if err != nil { + return err + } + fmt.Println(dgst) + return nil + }, + } + cmd.Flags().StringVarP(&file, "file", "f", releasemanifest.FileName, "manifest file") + cmd.Flags().StringVar(&source, "source", defaultSource, "source repository annotation") + return cmd +} + +func newPublishCommand(opts *globalOptions) *cobra.Command { + var ( + file, varsPath, defaultsPath, source string + lookup releasemanifest.ZuulLookup + dryRun bool + ) + + cmd := &cobra.Command{ + Use: "publish REFERENCE...", + Short: "Publish the release manifest that CI tested for the merged change", + Long: `Publish the release manifest for a commit. When --change and --patchset +are given, the release manifest generated by the newest Zuul buildset in which +every job passed for that change is published unchanged, as long as it was +generated from the same image inputs as the manifest in --file (or a newly +generated one) for this commit. Otherwise that manifest is published instead +and annotated as untested.`, + Example: ` atmosphere-release publish --file release-manifest.yaml \ + --zuul-api https://zuul.oss.vexxhost.dev/api --change 4420 --patchset "$HEAD_SHA" \ + ghcr.io/vexxhost/atmosphere-release:"$GITHUB_SHA" ghcr.io/vexxhost/atmosphere-release:main`, + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + repository, tags, err := releasemanifest.SplitReferences(args) + if err != nil { + return err + } + + var fallback *releasemanifest.Manifest + if file != "" { + data, err := os.ReadFile(file) + if err != nil { + return err + } + if fallback, err = releasemanifest.Unmarshal(data); err != nil { + return err + } + } else if fallback, err = generate(ctx, varsPath, defaultsPath, "", ""); err != nil { + return err + } + + var l *releasemanifest.ZuulLookup + if lookup.Change != "" { + if lookup.Patchset == "" || lookup.API == "" { + return fmt.Errorf("--change needs --patchset and --zuul-api") + } + l = &lookup + } + + // NOTE: The fallback manifest was generated from the source of this + // commit, before the vars file may have been pinned in place, + // so its inputs are the inputs of this commit. + inputs := fallback.Inputs + if inputs == "" { + return fmt.Errorf("the manifest in %s does not record its image inputs; regenerate it", file) + } + + d, err := releasemanifest.DecidePublish(ctx, l, inputs, fallback, releasemanifest.PushOptions{Source: source}) + if err != nil { + return err + } + dgst, err := releasemanifest.Digest(ctx, d.Manifest, d.Options) + if err != nil { + return err + } + if d.Tested != nil { + log.WithField("digest", dgst).Infof("Publishing the tested release manifest: %s (%s)", d.Reason, d.Tested.URL) + } else { + log.WithField("digest", dgst).Warnf("Publishing an untested release manifest: %s", d.Reason) + } + if dryRun { + return nil + } + + factory, err := opts.factory() + if err != nil { + return err + } + repo, err := factory(repository) + if err != nil { + return err + } + desc, err := releasemanifest.Push(ctx, repo, d.Manifest, tags, d.Options) + if err != nil { + return err + } + for _, tag := range tags { + fmt.Printf("%s:%s@%s\n", repository, tag, desc.Digest) + } + return nil + }, + } + cmd.Flags().StringVarP(&file, "file", "f", "", "manifest to publish when no tested manifest is used (default: generate one)") + cmd.Flags().StringVar(&varsPath, "vars", defaultVarsPath, "defaults role vars file") + cmd.Flags().StringVar(&defaultsPath, "defaults", defaultDefaultsPath, "defaults role defaults file") + cmd.Flags().StringVar(&source, "source", defaultSource, "source repository annotation") + cmd.Flags().StringVar(&lookup.API, "zuul-api", "", "Zuul tenant API URL") + cmd.Flags().StringVar(&lookup.Project, "zuul-project", "vexxhost/atmosphere", "Zuul project name") + cmd.Flags().StringVar(&lookup.Change, "change", "", "pull request number that was merged") + cmd.Flags().StringVar(&lookup.Patchset, "patchset", "", "head commit of the merged pull request") + cmd.Flags().StringSliceVar(&lookup.Pipelines, "pipeline", []string{"gate", "check"}, "Zuul pipelines to search, in order") + cmd.Flags().StringVar(&lookup.Job, "zuul-job", releasemanifest.DefaultZuulJob, "Zuul job that generates the manifest") + cmd.Flags().StringVar(&lookup.Artifact, "zuul-artifact", releasemanifest.DefaultZuulArtifact, "Zuul artifact name of the manifest") + cmd.Flags().BoolVar(&dryRun, "dry-run", false, "only report which manifest would be published") + return cmd +} + +func newPromoteCommand(opts *globalOptions) *cobra.Command { + var from, varsPath, defaultsPath, source string + var generateIfMissing bool + + cmd := &cobra.Command{ + Use: "promote --from TAG REFERENCE...", + Short: "Tag an existing release manifest with release tags", + Long: `Add tags to the manifest published for a commit, without resolving any +image again, so a release ships exactly what CI produced for that commit. +References are repository:tag in one repository, for example the "tags" +output of docker/metadata-action. With --generate-if-missing, a manifest is +generated and pushed for --from first when none exists (for example for +commits made before manifests were published).`, + Example: ` atmosphere-release promote --from "$GITHUB_SHA" --generate-if-missing \ + ghcr.io/vexxhost/atmosphere-release:v7.9.0`, + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + repository, tags, err := releasemanifest.SplitReferences(args) + if err != nil { + return err + } + factory, err := opts.factory() + if err != nil { + return err + } + repo, err := factory(repository) + if err != nil { + return err + } + + if _, _, err := releasemanifest.Fetch(ctx, repo, from); err != nil { + if !errors.Is(err, errdef.ErrNotFound) || !generateIfMissing { + return err + } + log.Warnf("No manifest found for %s:%s, generating one", repository, from) + m, err := generate(ctx, varsPath, defaultsPath, from, "") + if err != nil { + return err + } + if _, err := releasemanifest.Push(ctx, repo, m, []string{from}, releasemanifest.PushOptions{Source: source}); err != nil { + return err + } + } + + for _, tag := range tags { + desc, err := releasemanifest.Promote(ctx, repo, from, tag) + if err != nil { + return err + } + fmt.Printf("%s:%s@%s\n", repository, tag, desc.Digest) + } + return nil + }, + } + cmd.Flags().StringVar(&from, "from", "", "existing tag, usually the commit SHA") + cmd.Flags().BoolVar(&generateIfMissing, "generate-if-missing", false, "generate and push a manifest for --from if none exists") + cmd.Flags().StringVar(&varsPath, "vars", defaultVarsPath, "defaults role vars file (with --generate-if-missing)") + cmd.Flags().StringVar(&defaultsPath, "defaults", defaultDefaultsPath, "defaults role defaults file (with --generate-if-missing)") + cmd.Flags().StringVar(&source, "source", defaultSource, "source repository annotation (with --generate-if-missing)") + _ = cmd.MarkFlagRequired("from") + return cmd +} + +func newShowCommand(opts *globalOptions) *cobra.Command { + return &cobra.Command{ + Use: "show MANIFEST", + Short: "Print a release manifest (file or OCI reference)", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + m, err := opts.load(cmd.Context(), args[0]) + if err != nil { + return err + } + data, err := m.Marshal() + if err != nil { + return err + } + _, err = os.Stdout.Write(data) + return err + }, + } +} + +func newDiffCommand(opts *globalOptions) *cobra.Command { + return &cobra.Command{ + Use: "diff FROM TO", + Short: "Show the image changes between two release manifests", + Example: " atmosphere-release diff ghcr.io/vexxhost/atmosphere-release:v7.8.0 ghcr.io/vexxhost/atmosphere-release:v7.8.1", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + a, err := opts.load(cmd.Context(), args[0]) + if err != nil { + return err + } + b, err := opts.load(cmd.Context(), args[1]) + if err != nil { + return err + } + return releasemanifest.WriteDiff(os.Stdout, a, b, releasemanifest.Diff(a, b)) + }, + } +} + +type rulesFile struct { + Mirrors []releasemanifest.MirrorRule `yaml:"atmosphere_image_mirrors"` +} + +func readRules(path string) ([]releasemanifest.MirrorRule, error) { + if path == "" { + return nil, nil + } + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var rules rulesFile + if err := yaml.Unmarshal(data, &rules); err != nil { + return nil, fmt.Errorf("parsing %s: %w", path, err) + } + return rules.Mirrors, nil +} + +func newCheckCommand(opts *globalOptions) *cobra.Command { + var prefix, rulesPath string + var printImages bool + + cmd := &cobra.Command{ + Use: "check MANIFEST", + Short: "Check that a prefix and mirror rules resolve every image of a release", + Long: `Resolve every image of a release manifest with an image prefix and mirror +rules, the same way a deployment does, and validate the result: every +reference must be valid and the Kubernetes control plane images must stay +under one image repository with their original names.`, + Example: " atmosphere-release check ghcr.io/vexxhost/atmosphere-release:v7.8.1 --rules mirror-rules.yml --print", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + m, err := opts.load(cmd.Context(), args[0]) + if err != nil { + return err + } + rules, err := readRules(rulesPath) + if err != nil { + return err + } + resolved, err := releasemanifest.ResolveImages(m.Images, releasemanifest.ResolveOptions{Prefix: prefix, Mirrors: rules}) + if err != nil { + return err + } + if printImages { + data, err := yaml.Marshal(map[string]interface{}{"atmosphere_images": resolved}) + if err != nil { + return err + } + if _, err := os.Stdout.Write(data); err != nil { + return err + } + } + if errs := releasemanifest.CheckResolved(m, resolved); len(errs) > 0 { + for _, err := range errs { + log.Error(err) + } + return fmt.Errorf("%d problem(s) found", len(errs)) + } + log.WithField("images", len(resolved)).Info("All images resolve") + return nil + }, + } + cmd.Flags().StringVar(&prefix, "prefix", "", "atmosphere_image_prefix value") + cmd.Flags().StringVar(&rulesPath, "rules", "", "YAML file with atmosphere_image_mirrors") + cmd.Flags().BoolVar(&printImages, "print", false, "print the resolved images") + return cmd +} + +func newMirrorCommand(opts *globalOptions) *cobra.Command { + var ( + to, toDir, fromDir, layout, kubePrefix, rulesOutput string + extra []string + ) + + cmd := &cobra.Command{ + Use: "mirror [MANIFEST]", + Short: "Copy a release to another registry or to a directory", + Long: `Copy every image of a release, and the release manifest itself, to a +registry, or export them to a directory for disconnected environments and +import that directory into a registry later. + +Images are copied completely (every platform), so their digests do not +change, and every digest is verified after copying. The command writes the +atmosphere_image_mirrors rules that point a deployment at the mirror. + +Layouts: + nested /quay.io/ceph/ceph (Harbor, Distribution, Quay with nested repositories) + flat /quay.io--ceph--ceph (registries that limit repository depth, e.g. GitLab) + single-repo :quay.io--ceph--ceph--v18.2.7 (registries that only allow one repository) + +kubeadm pulls the control plane images by tag from one image repository, so +they keep their original names under --kubernetes-prefix in every layout. +Add the etcd and CoreDNS images kubeadm uses for your Kubernetes version with +--extra-image.`, + Example: ` # Mirror a release into a registry + atmosphere-release mirror ghcr.io/vexxhost/atmosphere-release:v7.8.1 \ + --to registry.example.com/atmosphere --rules-output mirror-rules.yml + + # Disconnected: export to a directory, carry it over, then import it + atmosphere-release mirror ghcr.io/vexxhost/atmosphere-release:v7.8.1 --to-dir /media/atmosphere + atmosphere-release mirror --from-dir /media/atmosphere --to registry.internal/atmosphere --layout flat`, + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + progress := func(format string, a ...interface{}) { log.Infof(format, a...) } + + mopts := releasemanifest.MirrorOptions{ + Destination: to, + Layout: releasemanifest.Layout(layout), + KubernetesPrefix: kubePrefix, + ExtraImages: extra, + } + + factory, err := opts.factory() + if err != nil { + return err + } + + if fromDir != "" { + if len(args) > 0 || toDir != "" || to == "" { + return fmt.Errorf("--from-dir needs --to and no manifest argument") + } + plan, err := releasemanifest.Import(ctx, fromDir, mopts, factory, progress) + if err != nil { + return err + } + return writeMirrorResult(plan, rulesOutput) + } + + if len(args) != 1 { + return fmt.Errorf("a release manifest (file or OCI reference) is required") + } + m, err := releasemanifest.Load(ctx, args[0], factory) + if err != nil { + return err + } + + var manifestSrc releasemanifest.SourceFunc + if _, statErr := os.Stat(args[0]); os.IsNotExist(statErr) { + mopts.ManifestSource = args[0] + manifestSrc = releasemanifest.RemoteSource(factory) + } + + src := releasemanifest.RemoteSource(factory) + switch { + case toDir != "" && to != "": + return fmt.Errorf("use either --to or --to-dir") + case toDir != "": + if err := releasemanifest.Export(ctx, m, mopts, src, manifestSrc, toDir, progress); err != nil { + return err + } + log.Infof("Exported release to %s", toDir) + return nil + case to != "": + plan, err := releasemanifest.PlanMirror(m, mopts) + if err != nil { + return err + } + if err := releasemanifest.Mirror(ctx, m, plan, src, manifestSrc, factory, progress); err != nil { + return err + } + return writeMirrorResult(plan, rulesOutput) + default: + return fmt.Errorf("either --to or --to-dir is required") + } + }, + } + cmd.Flags().StringVar(&to, "to", "", "destination registry or namespace (repository for single-repo)") + cmd.Flags().StringVar(&toDir, "to-dir", "", "export to an OCI layout directory") + cmd.Flags().StringVar(&fromDir, "from-dir", "", "import from a directory written with --to-dir") + cmd.Flags().StringVar(&layout, "layout", string(releasemanifest.LayoutNested), "mirror layout: nested, flat or single-repo") + cmd.Flags().StringVar(&kubePrefix, "kubernetes-prefix", "", "image repository for the kubeadm images (required for single-repo)") + cmd.Flags().StringArrayVar(&extra, "extra-image", nil, "additional image to mirror (repeatable)") + cmd.Flags().StringVar(&rulesOutput, "rules-output", "", "write the atmosphere_image_mirrors rules to this file") + return cmd +} + +func writeMirrorResult(plan *releasemanifest.MirrorPlan, rulesOutput string) error { + data, err := yaml.Marshal(rulesFile{Mirrors: plan.Rules}) + if err != nil { + return err + } + header := fmt.Sprintf("# Generated by atmosphere-release mirror.\natmosphere_release_manifest: %s\n", plan.ManifestReference()) + out := append([]byte(header), data...) + + if rulesOutput != "" { + if err := os.WriteFile(rulesOutput, out, 0o644); err != nil { + return err + } + log.Infof("Wrote mirror rules to %s", rulesOutput) + return nil + } + _, err = os.Stdout.Write(out) + return err +} diff --git a/cmd/pinimages/pinimages.go b/cmd/pinimages/pinimages.go deleted file mode 100644 index ec668cea..00000000 --- a/cmd/pinimages/pinimages.go +++ /dev/null @@ -1,187 +0,0 @@ -package main - -import ( - "context" - "fmt" - "os" - "strings" - "sync" - - "github.com/containers/image/v5/docker" - "github.com/containers/image/v5/manifest" - "github.com/containers/image/v5/types" - "github.com/goccy/go-yaml" - "github.com/goccy/go-yaml/ast" - "github.com/goccy/go-yaml/parser" - "github.com/opencontainers/go-digest" - log "github.com/sirupsen/logrus" - "golang.org/x/sync/singleflight" -) - -var digestGroup singleflight.Group - -// GetImageDigest fetches the digest for a given image reference. -func GetImageDigest(ctx context.Context, reference string) (digest.Digest, error) { - ref, err := docker.ParseReference(reference) - if err != nil { - return "", fmt.Errorf("error parsing reference '%s': %w", reference, err) - } - - sysCtx := &types.SystemContext{} - imageSource, err := ref.NewImageSource(ctx, sysCtx) - if err != nil { - return "", fmt.Errorf("error creating image source for '%s': %w", reference, err) - } - defer imageSource.Close() - - rawManifest, _, err := imageSource.GetManifest(ctx, nil) - if err != nil { - return "", fmt.Errorf("error getting manifest for '%s': %w", reference, err) - } - - dgst, err := manifest.Digest(rawManifest) - if err != nil { - return "", fmt.Errorf("error getting digest for '%s': %w", reference, err) - } - - return dgst, nil -} - -// GetImageNameToPull normalizes the image name by replacing variables and adding necessary prefixes. -func GetImageNameToPull(image string, release string) string { - // Replace Jinja2 variables with actual values - image = strings.ReplaceAll(image, "{{ atmosphere_image_prefix }}", "") - image = strings.ReplaceAll(image, "{{ atmosphere_release }}", release) - - return image -} - -// AppendDigestToImage appends the digest to the original image reference. -func AppendDigestToImage(image string, dgst digest.Digest) string { - if strings.Contains(image, "@") { - // Replace existing digest if present - parts := strings.Split(image, "@") - return parts[0] + "@" + dgst.String() - } - // Append digest - return image + "@" + dgst.String() -} - -func main() { - varsFilePath := "roles/defaults/vars/main.yml" - - file, err := parser.ParseFile(varsFilePath, parser.ParseComments) - if err != nil { - log.WithError(err).Fatal("error parsing yaml file") - } - - if len(file.Docs) != 1 { - log.Fatal("expected exactly one yaml document") - } - - doc := file.Docs[0] - body := doc.Body.(*ast.MappingNode) - - var release string - var images *ast.MappingNode - - for _, item := range body.Values { - switch item.Key.(*ast.StringNode).Value { - case "atmosphere_release": - release = item.Value.(*ast.StringNode).Value - case "_atmosphere_images": - images = item.Value.(*ast.MappingNode) - } - } - - if release == "" { - log.Fatalf("atmosphere_release not found") - } - - if images == nil { - log.Fatalf("_atmosphere_images not found") - } - - type imageInfo struct { - Key string - Value string - Normalized string - Digest digest.Digest - } - - var imageInfos []imageInfo - uniqueImages := make(map[string][]int) - - for i, item := range images.Values { - normalized := GetImageNameToPull(item.Value.(*ast.StringNode).Value, release) - info := imageInfo{ - Key: item.Key.(*ast.StringNode).Value, - Value: item.Value.(*ast.StringNode).Value, - Normalized: normalized, - } - imageInfos = append(imageInfos, info) - uniqueImages[normalized] = append(uniqueImages[normalized], i) - } - - digestMap := make(map[string]digest.Digest) - var mapMutex sync.Mutex - var wg sync.WaitGroup - - for normImg := range uniqueImages { - wg.Add(1) - go func(normImg string) { - defer wg.Done() - - result, err, _ := digestGroup.Do(normImg, func() (interface{}, error) { - dgst, err := GetImageDigest(context.TODO(), "//"+normImg) - if err != nil { - return nil, err - } - return dgst, nil - }) - - if err != nil { - log.WithError(err).WithFields(log.Fields{ - "image": normImg, - }).Error("Error fetching digest") - return - } - - dgst := result.(digest.Digest) - - mapMutex.Lock() - digestMap[normImg] = dgst - mapMutex.Unlock() - - log.WithFields(log.Fields{ - "image": normImg, - "digest": dgst, - }).Info("Fetched image digest") - }(normImg) - } - - wg.Wait() - - // Update the image references with digests - for normImg, indices := range uniqueImages { - dgst, exists := digestMap[normImg] - if !exists { - log.WithField("image", normImg).Error("Digest not found, skipping update") - continue - } - for _, idx := range indices { - updatedImage, err := yaml.ValueToNode(AppendDigestToImage(imageInfos[idx].Value, dgst)) - if err != nil { - log.WithError(err).Fatal("error converting value to node") - } - - images.Values[idx].Value = updatedImage - } - } - - if err := os.WriteFile(varsFilePath, []byte(file.String()), 0644); err != nil { - log.WithError(err).Fatal("error writing updated yaml file") - } - - log.Info("Successfully updated YAML file with image digests") -} diff --git a/cmd/pinimages/pinimages_test.go b/cmd/pinimages/pinimages_test.go deleted file mode 100644 index 8aaf1c23..00000000 --- a/cmd/pinimages/pinimages_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGetImageNameToPull(t *testing.T) { - tests := []struct { - image string - release string - want string - }{ - { - image: "{{ atmosphere_image_prefix }}quay.io/ceph/ceph:v18.2.2", - release: "2024.1", - want: "quay.io/ceph/ceph:v18.2.2", - }, - { - image: "{{ atmosphere_image_prefix }}registry.atmosphere.dev/library/glance:{{ atmosphere_release }}", - release: "2024.1", - want: "registry.atmosphere.dev/library/glance:2024.1", - }, - } - - for _, tt := range tests { - t.Run(tt.image, func(t *testing.T) { - got := GetImageNameToPull(tt.image, tt.release) - - assert.Equal(t, tt.want, got) - }) - } -} diff --git a/doc/source/deploy/images.rst b/doc/source/deploy/images.rst new file mode 100644 index 00000000..d91dee98 --- /dev/null +++ b/doc/source/deploy/images.rst @@ -0,0 +1,237 @@ +############################ +Container images and mirrors +############################ + +Every Atmosphere commit and release is described by a *release manifest*: a +list of every container image it deploys, each pinned by digest. Deployments +can use a release manifest directly, pull through a registry cache with an +image prefix, redirect images with mirror rules, or run fully disconnected from +a mirror created with ``atmosphere-release``. + +Image references are resolved by Ansible when Atmosphere renders its +manifests, so these options work with any Kubernetes distribution and +container runtime. + +***************** +Release manifests +***************** + +Release manifests are published as OCI artifacts to +``ghcr.io/vexxhost/atmosphere-release``: + +* ```` for every commit on ``main`` and the ``stable/*`` branches +* ```` for the latest commit on a branch, such as ``main`` or + ``stable-2025.2`` +* ```` for every release, such as ``v7.9.0`` + +The manifest published for a merged pull request is the one that CI deployed +and tested for it, as long as no other change to the image list was merged in +between; otherwise it is generated again and annotated with +``com.vexxhost.atmosphere.tested: "false"``. A release does not resolve any +image again: it ships the manifest published for the released commit. The +manifest is also attached to each GitHub release as ``release-manifest.yaml``, +and the images in the Ansible collection on Ansible Galaxy are pinned to the +same digests. + +To deploy the images of a specific release manifest, set: + +.. code-block:: yaml + + atmosphere_release_manifest: ghcr.io/vexxhost/atmosphere-release:v7.9.0 + +An OCI reference is read through ``atmosphere_image_mirrors`` and +``atmosphere_image_prefix``, like every image, so a deployment that pulls +through a registry cache or mirror also reads the manifest from it. The value +can also be the path to a ``release-manifest.yaml`` file on the Ansible +controller, which is used as it is. + +If the registry uses a certificate from a private CA, point +``atmosphere_release_manifest_ca_file`` at that CA certificate on the Ansible +controller: + +.. code-block:: yaml + + atmosphere_release_manifest: registry.internal/atmosphere/ghcr.io/vexxhost/atmosphere-release:v7.9.0 + atmosphere_release_manifest_ca_file: /etc/pki/registry-ca.pem + +Registry credentials are read from the Docker configuration +(``~/.docker/config.json``) of the user running Ansible. When +``atmosphere_release_manifest`` is empty, the images listed in the +``defaults`` role of the installed collection are used. + +The Kubernetes control plane images are pinned for the default +``atmosphere_kubernetes_version``. If you deploy another Kubernetes version, +they use the tag for that version instead. + +************************* +Pull-through image prefix +************************* + +If you use a pull-through registry cache, such as Harbor proxy cache projects +named after each upstream registry (``docker.io``, ``ghcr.io``, ``quay.io``, +``registry.k8s.io``), set ``atmosphere_image_prefix``: + +.. code-block:: yaml + + atmosphere_image_prefix: harbor.example.com/ + +The prefix is added in front of every image reference, for example +``harbor.example.com/quay.io/ceph/ceph:v18.2.7@sha256:...``. Pulls by digest +work through pull-through caches, so the prefix can be combined with a release +manifest. Your cache needs a proxy project for every registry the release +uses. + +************ +Mirror rules +************ + +Mirror rules redirect images to other locations. Each rule has a ``source``, +which is a registry, a namespace or a single repository, and a ``mirror`` +that replaces the matching part of the image repository. The tag and digest +are kept. When several rules match an image, the most specific one wins, and +``atmosphere_image_prefix`` applies to the images that no rule matches. + +For example, with Harbor proxy cache projects that are not named after the +upstream registries: + +.. code-block:: yaml + + atmosphere_image_mirrors: + - source: docker.io + mirror: harbor.example.com/dockerhub-proxy + - source: quay.io + mirror: harbor.example.com/quay-proxy + - source: ghcr.io + mirror: harbor.example.com/ghcr-proxy + - source: registry.k8s.io + mirror: harbor.example.com/k8s-proxy + +With these rules, ``quay.io/ceph/ceph:v18.2.7@sha256:...`` is pulled from +``harbor.example.com/quay-proxy/ceph/ceph:v18.2.7@sha256:...``. + +kubeadm pulls the Kubernetes control plane images by tag from a single image +repository, so ``kube-apiserver``, ``kube-controller-manager``, +``kube-scheduler`` and ``kube-proxy`` must resolve to the same repository +prefix and keep their names. + +************************ +Overriding single images +************************ + +``atmosphere_image_overrides`` replaces individual images after the release +manifest, the mirror rules and the image prefix have been applied. The values +are used exactly as written: + +.. code-block:: yaml + + atmosphere_image_overrides: + haproxy: registry.example.com/haproxy:2.5@sha256:... + +Pin overrides by digest so that every deployment of the environment pulls the +same image. + +******************* +Mirroring a release +******************* + +``atmosphere-release`` copies a release to your own registry. Download it for +your platform from the assets of an Atmosphere release on GitHub, or install it +with Go: + +.. code-block:: console + + $ go install github.com/vexxhost/atmosphere/cmd/atmosphere-release@ + +Authenticate to the registries with ``docker login`` first; +``atmosphere-release`` uses the Docker credentials configuration. + +Images are copied completely, with every platform, so their digests do not +change, and every digest is verified after copying. This can take a lot of +space, because many upstream images include several architectures. + +Connected mirror +================ + +Mirror a release into a registry and write the variables for your inventory: + +.. code-block:: console + + $ atmosphere-release mirror ghcr.io/vexxhost/atmosphere-release:v7.9.0 \ + --to registry.example.com/atmosphere \ + --rules-output inventory/group_vars/all/mirror.yml + +The generated file sets ``atmosphere_release_manifest`` to the mirrored copy of +the release manifest and ``atmosphere_image_mirrors`` to the rules for the +mirror. + +The ``--layout`` option controls how images are named in the mirror: + +``nested`` (default) + Images keep their full path under the destination, for example + ``registry.example.com/atmosphere/quay.io/ceph/ceph``. Use it with + registries that allow nested repository paths, such as Harbor or the CNCF + Distribution registry. + +``flat`` + The full source path becomes one repository name, for example + ``registry.example.com/atmosphere/quay.io--ceph--ceph``. Use it with + registries that limit how deep repository paths can be, such as GitLab, or + Red Hat Quay without ``FEATURE_EXTENDED_REPOSITORY_NAMES``. + +``single-repo`` + Every image is stored in the destination repository and tagged with its + source, for example + ``registry.example.com/atmosphere:quay.io--ceph--ceph--v18.2.7``. This + layout needs ``--kubernetes-prefix``. + +In every layout, the images kubeadm uses keep their names under one prefix. +kubeadm also pulls the etcd and CoreDNS images that match your Kubernetes +version; add them with ``--extra-image``: + +.. code-block:: console + + $ atmosphere-release mirror ghcr.io/vexxhost/atmosphere-release:v7.9.0 \ + --to registry.example.com/atmosphere --layout flat \ + --extra-image registry.k8s.io/etcd:3.5.15-0 \ + --extra-image registry.k8s.io/coredns/coredns:v1.11.1 \ + --rules-output inventory/group_vars/all/mirror.yml + +Disconnected environments +========================= + +Export a release to a directory on a host with internet access, carry the +directory into the disconnected environment, then import it into your +registry: + +.. code-block:: console + + $ atmosphere-release mirror ghcr.io/vexxhost/atmosphere-release:v7.9.0 \ + --to-dir /media/atmosphere-v7.9.0 + $ atmosphere-release mirror --from-dir /media/atmosphere-v7.9.0 \ + --to registry.internal/atmosphere \ + --rules-output inventory/group_vars/all/mirror.yml + +The directory is an OCI image layout. The layout of the registry mirror is +chosen when importing. + +******************************* +Checking and comparing releases +******************************* + +Check that your image prefix and mirror rules resolve every image of a +release, and print the resulting references: + +.. code-block:: console + + $ atmosphere-release check ghcr.io/vexxhost/atmosphere-release:v7.9.0 \ + --prefix harbor.example.com/ --rules mirror-rules.yml --print + +Show the image changes between two releases: + +.. code-block:: console + + $ atmosphere-release diff ghcr.io/vexxhost/atmosphere-release:v7.8.0 \ + ghcr.io/vexxhost/atmosphere-release:v7.9.0 + +The ``image_manifest`` role and playbook are deprecated in favour of +``atmosphere-release mirror``, and will be removed in a future release. diff --git a/doc/source/deploy/index.rst b/doc/source/deploy/index.rst index 63101bda..6416d53f 100644 --- a/doc/source/deploy/index.rst +++ b/doc/source/deploy/index.rst @@ -16,6 +16,7 @@ and setup. inventory storage csi + images certificates glance neutron diff --git a/internal/releasemanifest/diff.go b/internal/releasemanifest/diff.go new file mode 100644 index 00000000..337a4bb7 --- /dev/null +++ b/internal/releasemanifest/diff.go @@ -0,0 +1,78 @@ +package releasemanifest + +import ( + "fmt" + "io" + "sort" + "strings" +) + +// Change is one image that differs between two manifests, with every +// manifest key that uses it. +type Change struct { + From string + To string + Keys []string +} + +// Diff returns the image changes between two manifests, grouped by +// (from, to) pair so an image shared by many keys is reported once. +func Diff(a, b *Manifest) []Change { + grouped := map[[2]string][]string{} + + keys := map[string]struct{}{} + for key := range a.Images { + keys[key] = struct{}{} + } + for key := range b.Images { + keys[key] = struct{}{} + } + + for key := range keys { + from, to := a.Images[key], b.Images[key] + if from == to { + continue + } + pair := [2]string{from, to} + grouped[pair] = append(grouped[pair], key) + } + + changes := make([]Change, 0, len(grouped)) + for pair, keys := range grouped { + sort.Strings(keys) + changes = append(changes, Change{From: pair[0], To: pair[1], Keys: keys}) + } + sort.Slice(changes, func(i, j int) bool { + return changes[i].Keys[0] < changes[j].Keys[0] + }) + return changes +} + +// WriteDiff prints changes in a human readable form. +func WriteDiff(w io.Writer, a, b *Manifest, changes []Change) error { + if a.Kubernetes.Version != b.Kubernetes.Version { + if _, err := fmt.Fprintf(w, "kubernetes: %s -> %s\n", a.Kubernetes.Version, b.Kubernetes.Version); err != nil { + return err + } + } + if len(changes) == 0 { + _, err := fmt.Fprintln(w, "no image changes") + return err + } + + for _, change := range changes { + var line string + switch { + case change.From == "": + line = fmt.Sprintf("+ %s", change.To) + case change.To == "": + line = fmt.Sprintf("- %s", change.From) + default: + line = fmt.Sprintf("~ %s\n -> %s", change.From, change.To) + } + if _, err := fmt.Fprintf(w, "%s\n keys: %s\n", line, strings.Join(change.Keys, ", ")); err != nil { + return err + } + } + return nil +} diff --git a/internal/releasemanifest/generate.go b/internal/releasemanifest/generate.go new file mode 100644 index 00000000..3c178944 --- /dev/null +++ b/internal/releasemanifest/generate.go @@ -0,0 +1,335 @@ +package releasemanifest + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "regexp" + "sort" + "strings" + "sync" + "time" + + "github.com/containers/image/v5/docker" + "github.com/containers/image/v5/manifest" + "github.com/containers/image/v5/types" + "github.com/goccy/go-yaml" + "github.com/opencontainers/go-digest" + "golang.org/x/sync/errgroup" +) + +const ( + imagesKey = "_atmosphere_images" + prefixVariable = "atmosphere_image_prefix" + releaseVariable = "atmosphere_release" + kubernetesVariable = "atmosphere_kubernetes_version" + defaultResolverLimit = 16 +) + +var templateVariable = regexp.MustCompile(`\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}`) + +// Resolver resolves an image tag to the digest it currently points to. +type Resolver interface { + Resolve(ctx context.Context, reference string) (digest.Digest, error) +} + +// Source describes the image list of an Atmosphere checkout. +type Source struct { + Release string + KubernetesVersion string + // Images holds the rendered, fully qualified image references without + // the image prefix. + Images map[string]string + // KubernetesImages lists the image keys whose tag follows the + // Kubernetes version. + KubernetesImages []string +} + +// LoadSource reads the defaults role vars and defaults files and renders the +// image list. Template variables are substituted from scalar values defined +// in either file; the image prefix is removed. +func LoadSource(varsPath, defaultsPath string) (*Source, error) { + vars, images, err := readImageVars(varsPath) + if err != nil { + return nil, err + } + + defaults := map[string]interface{}{} + defaultsData, err := os.ReadFile(defaultsPath) + if err != nil { + return nil, fmt.Errorf("reading %s: %w", defaultsPath, err) + } + if err := yaml.Unmarshal(defaultsData, &defaults); err != nil { + return nil, fmt.Errorf("parsing %s: %w", defaultsPath, err) + } + + values := map[string]string{prefixVariable: ""} + for _, source := range []map[string]interface{}{defaults, vars} { + for key, value := range source { + switch v := value.(type) { + case string: + values[key] = v + case int, int64, uint64, float64, bool: + values[key] = fmt.Sprint(v) + } + } + } + + src := &Source{ + Release: values[releaseVariable], + KubernetesVersion: values[kubernetesVariable], + Images: map[string]string{}, + } + + for key, raw := range images { + rendered, err := render(raw, values) + if err != nil { + return nil, fmt.Errorf("image %q: %w", key, err) + } + if _, err := ParseReference(rendered); err != nil { + return nil, fmt.Errorf("image %q: %w", key, err) + } + src.Images[key] = rendered + + if strings.Contains(raw, kubernetesVariable) { + src.KubernetesImages = append(src.KubernetesImages, key) + } + } + sort.Strings(src.KubernetesImages) + + return src, nil +} + +// Digest returns a digest of everything that determines the images of a +// release: the release, the Kubernetes version and images, and the rendered +// image references before any tag is resolved. Unrelated changes to the +// defaults role, such as the Atmosphere version, do not change it. +func (s *Source) Digest() string { + data, err := json.Marshal(struct { + Release string `json:"release"` + KubernetesVersion string `json:"kubernetesVersion"` + KubernetesImages []string `json:"kubernetesImages"` + Images map[string]string `json:"images"` + }{s.Release, s.KubernetesVersion, s.KubernetesImages, s.Images}) + if err != nil { + panic(err) // only strings, cannot fail + } + sum := sha256.Sum256(data) + return "sha256:" + hex.EncodeToString(sum[:]) +} + +func readImageVars(varsPath string) (map[string]interface{}, map[string]string, error) { + data, err := os.ReadFile(varsPath) + if err != nil { + return nil, nil, fmt.Errorf("reading %s: %w", varsPath, err) + } + + vars := map[string]interface{}{} + if err := yaml.Unmarshal(data, &vars); err != nil { + return nil, nil, fmt.Errorf("parsing %s: %w", varsPath, err) + } + + raw, ok := vars[imagesKey].(map[string]interface{}) + if !ok { + return nil, nil, fmt.Errorf("%s not found in %s", imagesKey, varsPath) + } + + images := make(map[string]string, len(raw)) + for key, value := range raw { + s, ok := value.(string) + if !ok { + return nil, nil, fmt.Errorf("image %q in %s is not a string", key, varsPath) + } + images[key] = s + } + + return vars, images, nil +} + +func render(raw string, values map[string]string) (string, error) { + var missing []string + rendered := templateVariable.ReplaceAllStringFunc(raw, func(match string) string { + name := templateVariable.FindStringSubmatch(match)[1] + value, ok := values[name] + if !ok { + missing = append(missing, name) + return match + } + return value + }) + if len(missing) > 0 { + return "", fmt.Errorf("undefined template variables %v in %q", missing, raw) + } + return rendered, nil +} + +// GenerateOptions controls manifest generation. +type GenerateOptions struct { + Commit string + Concurrency int + // Attempts is how many times a tag is resolved before giving up on + // rate limits and transient network errors (default 5). + Attempts int + // Backoff is the delay before the first retry; it doubles after each + // attempt (default 5s). + Backoff time.Duration + // ResolvePrefix resolves tags through a pull-through cache first, such as + // "harbor.example.com/" in front of the original reference, to avoid + // upstream rate limits. The manifest still records the original + // references, and resolution falls back to the source registry when the + // cache cannot resolve a tag. + ResolvePrefix string +} + +var retryable = []string{"toomanyrequests", "429", "timeout", "connection reset", "EOF", "502", "503", "504"} + +func isRetryable(err error) bool { + msg := err.Error() + for _, s := range retryable { + if strings.Contains(msg, s) { + return true + } + } + return false +} + +func resolveWithRetry(ctx context.Context, resolver Resolver, reference string, attempts int, backoff time.Duration) (digest.Digest, error) { + var err error + for attempt := 1; ; attempt++ { + var dgst digest.Digest + dgst, err = resolver.Resolve(ctx, reference) + if err == nil || attempt >= attempts || !isRetryable(err) { + return dgst, err + } + select { + case <-ctx.Done(): + return "", ctx.Err() + case <-time.After(backoff): + } + backoff *= 2 + } +} + +// Generate builds a release manifest from a rendered source. Images that are +// already pinned by digest keep their digest; images referenced by tag only +// are resolved to the digest the tag currently points to. +func Generate(ctx context.Context, src *Source, resolver Resolver, opts GenerateOptions) (*Manifest, error) { + refs := make(map[string]Reference, len(src.Images)) + toResolve := map[string]struct{}{} + for key, value := range src.Images { + ref, err := ParseReference(value) + if err != nil { + return nil, fmt.Errorf("image %q: %w", key, err) + } + refs[key] = ref + if ref.Digest == "" { + toResolve[ref.Repository+":"+ref.Tag] = struct{}{} + } + } + + limit := opts.Concurrency + if limit <= 0 { + limit = defaultResolverLimit + } + attempts := opts.Attempts + if attempts <= 0 { + attempts = 5 + } + backoff := opts.Backoff + if backoff <= 0 { + backoff = 5 * time.Second + } + + var ( + mu sync.Mutex + resolved = map[string]digest.Digest{} + failures []string + ) + g, gctx := errgroup.WithContext(ctx) + g.SetLimit(limit) + for tagged := range toResolve { + g.Go(func() error { + var ( + dgst digest.Digest + err error + ) + if opts.ResolvePrefix != "" { + dgst, err = resolveWithRetry(gctx, resolver, opts.ResolvePrefix+tagged, attempts, backoff) + } + if opts.ResolvePrefix == "" || err != nil { + dgst, err = resolveWithRetry(gctx, resolver, tagged, attempts, backoff) + } + mu.Lock() + defer mu.Unlock() + if err != nil { + failures = append(failures, fmt.Sprintf("%s: %v", tagged, err)) + return nil + } + resolved[tagged] = dgst + return nil + }) + } + if err := g.Wait(); err != nil { + return nil, err + } + if len(failures) > 0 { + sort.Strings(failures) + return nil, fmt.Errorf("failed to resolve %d image(s):\n %s", len(failures), strings.Join(failures, "\n ")) + } + + m := &Manifest{ + APIVersion: APIVersion, + Kind: Kind, + Release: src.Release, + Commit: opts.Commit, + Inputs: src.Digest(), + Kubernetes: Kubernetes{ + Version: src.KubernetesVersion, + Images: append([]string(nil), src.KubernetesImages...), + }, + Images: make(map[string]string, len(refs)), + } + for key, ref := range refs { + if ref.Digest == "" { + ref.Digest = resolved[ref.Repository+":"+ref.Tag].String() + } + m.Images[key] = ref.String() + } + + return m, m.Validate() +} + +// DockerResolver resolves tags using the containers/image docker transport, +// honouring the usual registry authentication and configuration files. +type DockerResolver struct { + SystemContext *types.SystemContext +} + +// Resolve returns the digest of the manifest (or manifest list) for a tag. +func (r DockerResolver) Resolve(ctx context.Context, reference string) (digest.Digest, error) { + ref, err := docker.ParseReference("//" + reference) + if err != nil { + return "", fmt.Errorf("parsing reference: %w", err) + } + + sysCtx := r.SystemContext + if sysCtx == nil { + sysCtx = &types.SystemContext{} + } + + src, err := ref.NewImageSource(ctx, sysCtx) + if err != nil { + return "", err + } + defer src.Close() + + raw, _, err := src.GetManifest(ctx, nil) + if err != nil { + return "", err + } + + return manifest.Digest(raw) +} diff --git a/internal/releasemanifest/manifest.go b/internal/releasemanifest/manifest.go new file mode 100644 index 00000000..841a5bf0 --- /dev/null +++ b/internal/releasemanifest/manifest.go @@ -0,0 +1,140 @@ +// Package releasemanifest builds, publishes, mirrors and resolves Atmosphere +// release manifests: immutable, digest-pinned lists of every image that a +// given Atmosphere commit or release deploys. +package releasemanifest + +import ( + "fmt" + "sort" + + "github.com/goccy/go-yaml" +) + +const ( + // APIVersion is the schema version of the release manifest document. + APIVersion = "atmosphere.vexxhost.com/v1alpha1" + + // Kind is the kind of the release manifest document. + Kind = "ReleaseManifest" + + // ArtifactType is the OCI artifact type used when publishing a manifest. + ArtifactType = "application/vnd.vexxhost.atmosphere.release.v1" + + // MediaType is the media type of the layer holding the manifest document. + MediaType = "application/vnd.vexxhost.atmosphere.release.v1+yaml" + + // FileName is the conventional file name of a release manifest. + FileName = "release-manifest.yaml" +) + +// Kubernetes describes the Kubernetes control plane images in a manifest. +// +// kubeadm pulls these images by tag from a single image repository, and +// operators may deploy a different Kubernetes version than the default one. +// Consumers use this information to fall back to the tag for the requested +// version when it differs from Version. +type Kubernetes struct { + Version string `yaml:"version"` + Images []string `yaml:"images"` +} + +// Manifest is an Atmosphere release manifest. +type Manifest struct { + APIVersion string `yaml:"apiVersion"` + Kind string `yaml:"kind"` + Release string `yaml:"release"` + Commit string `yaml:"commit,omitempty"` + // Inputs is a digest of the image list the manifest was generated from + // (see Source.Digest). Two manifests with the same Inputs were generated + // from identical image definitions, even at different commits. + Inputs string `yaml:"inputs,omitempty"` + Kubernetes Kubernetes `yaml:"kubernetes"` + Images map[string]string `yaml:"images"` +} + +// Validate checks that the manifest is well formed and that every image is +// fully qualified and pinned by digest. +func (m *Manifest) Validate() error { + if m.APIVersion != APIVersion { + return fmt.Errorf("unsupported apiVersion %q (expected %q)", m.APIVersion, APIVersion) + } + if m.Kind != Kind { + return fmt.Errorf("unsupported kind %q (expected %q)", m.Kind, Kind) + } + if len(m.Images) == 0 { + return fmt.Errorf("manifest contains no images") + } + + for key, value := range m.Images { + ref, err := ParseReference(value) + if err != nil { + return fmt.Errorf("image %q: %w", key, err) + } + if ref.Digest == "" { + return fmt.Errorf("image %q (%s) is not pinned by digest", key, value) + } + } + + for _, key := range m.Kubernetes.Images { + if _, ok := m.Images[key]; !ok { + return fmt.Errorf("kubernetes image %q is not part of the manifest images", key) + } + } + + return nil +} + +// Marshal serializes the manifest deterministically: fields in a fixed order +// and map keys sorted, so identical content always produces identical bytes. +func (m *Manifest) Marshal() ([]byte, error) { + if err := m.Validate(); err != nil { + return nil, err + } + + kubernetesImages := append([]string(nil), m.Kubernetes.Images...) + sort.Strings(kubernetesImages) + + keys := make([]string, 0, len(m.Images)) + for key := range m.Images { + keys = append(keys, key) + } + sort.Strings(keys) + + images := make(yaml.MapSlice, 0, len(keys)) + for _, key := range keys { + images = append(images, yaml.MapItem{Key: key, Value: m.Images[key]}) + } + + doc := yaml.MapSlice{ + {Key: "apiVersion", Value: m.APIVersion}, + {Key: "kind", Value: m.Kind}, + {Key: "release", Value: m.Release}, + } + if m.Commit != "" { + doc = append(doc, yaml.MapItem{Key: "commit", Value: m.Commit}) + } + if m.Inputs != "" { + doc = append(doc, yaml.MapItem{Key: "inputs", Value: m.Inputs}) + } + doc = append(doc, + yaml.MapItem{Key: "kubernetes", Value: yaml.MapSlice{ + {Key: "version", Value: m.Kubernetes.Version}, + {Key: "images", Value: kubernetesImages}, + }}, + yaml.MapItem{Key: "images", Value: images}, + ) + + return yaml.MarshalWithOptions(doc, yaml.IndentSequence(true)) +} + +// Unmarshal parses and validates a manifest document. +func Unmarshal(data []byte) (*Manifest, error) { + var m Manifest + if err := yaml.Unmarshal(data, &m); err != nil { + return nil, fmt.Errorf("parsing release manifest: %w", err) + } + if err := m.Validate(); err != nil { + return nil, fmt.Errorf("invalid release manifest: %w", err) + } + return &m, nil +} diff --git a/internal/releasemanifest/mirror.go b/internal/releasemanifest/mirror.go new file mode 100644 index 00000000..65bfc442 --- /dev/null +++ b/internal/releasemanifest/mirror.go @@ -0,0 +1,479 @@ +package releasemanifest + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + + "github.com/goccy/go-yaml" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "oras.land/oras-go/v2" + "oras.land/oras-go/v2/content/oci" +) + +// Layout describes how images are named in a mirror registry. +type Layout string + +const ( + // LayoutNested keeps the full source path under the destination: + // quay.io/ceph/ceph -> /quay.io/ceph/ceph. + LayoutNested Layout = "nested" + // LayoutFlat encodes the full source path into one component: + // quay.io/ceph/ceph -> /quay.io--ceph--ceph. + LayoutFlat Layout = "flat" + // LayoutSingleRepository stores every image in one repository and + // encodes the source in the tag. + LayoutSingleRepository Layout = "single-repo" + + // DefaultManifestRepository is where Atmosphere publishes manifests. + DefaultManifestRepository = "ghcr.io/vexxhost/atmosphere-release" + + extraImagesFile = "extra-images.yaml" + sourceFile = "source.yaml" + maxTagLength = 128 +) + +var invalidTagCharacters = regexp.MustCompile(`[^a-zA-Z0-9._-]`) + +// MirrorOptions controls how a release is mirrored. +type MirrorOptions struct { + // Destination is a registry or namespace (nested and flat layouts) or a + // repository (single-repo layout). + Destination string + Layout Layout + // KubernetesPrefix is the image repository kubeadm pulls the control + // plane images from. It defaults to /registry.k8s.io for + // the nested layout and for the flat layout, and must be + // set for the single-repo layout. + KubernetesPrefix string + // ExtraImages are additional fully qualified images to mirror, such as + // the etcd and CoreDNS images kubeadm uses for a Kubernetes version. + ExtraImages []string + // ManifestSource is the canonical location of the release manifest, + // e.g. ghcr.io/vexxhost/atmosphere-release:v7.8.1. + ManifestSource string +} + +// MirrorItem is one image to copy. +type MirrorItem struct { + Source Reference + Repository string + Tags []string +} + +// MirrorPlan is the result of planning a mirror. +type MirrorPlan struct { + Items []MirrorItem + // Rules redirect every mirrored image to its mirror location; they are + // the atmosphere_image_mirrors value for the mirrored deployment. + Rules []MirrorRule + // Manifest is where the release manifest itself is mirrored to. + Manifest MirrorItem +} + +// mirrorPath returns a source repository as a valid path inside a mirror; +// a port in the registry host ("localhost:5000") becomes "localhost-5000". +func mirrorPath(repository string) string { + return strings.Replace(repository, ":", "-", 1) +} + +func flatName(repository string) string { + return strings.ReplaceAll(mirrorPath(repository), "/", "--") +} + +func digestTag(dgst string) string { + return strings.Replace(dgst, ":", "-", 1) +} + +// uniqueTag builds a valid, collision-free tag from parts. +func uniqueTag(parts ...string) string { + tag := invalidTagCharacters.ReplaceAllString(strings.Join(parts, "--"), "-") + if len(tag) <= maxTagLength { + return tag + } + sum := sha256.Sum256([]byte(strings.Join(parts, "--"))) + suffix := "--" + hex.EncodeToString(sum[:])[:16] + return tag[:maxTagLength-len(suffix)] + suffix +} + +func isKubeadmImage(ref Reference) bool { + return ref.Registry() == "registry.k8s.io" && kubeadmImages[ref.Path()] +} + +// PlanMirror computes destinations, tags and mirror rules for a manifest. +func PlanMirror(m *Manifest, opts MirrorOptions) (*MirrorPlan, error) { + dest := strings.TrimSuffix(opts.Destination, "/") + if dest == "" { + return nil, fmt.Errorf("a destination is required") + } + + kubePrefix := strings.TrimSuffix(opts.KubernetesPrefix, "/") + natural := "" + switch opts.Layout { + case LayoutNested: + natural = dest + "/registry.k8s.io" + case LayoutFlat: + natural = dest + case LayoutSingleRepository: + if kubePrefix == "" { + return nil, fmt.Errorf("the %s layout needs --kubernetes-prefix: kubeadm pulls each control plane image from its own repository under one prefix", LayoutSingleRepository) + } + default: + return nil, fmt.Errorf("unknown layout %q (expected %s, %s or %s)", opts.Layout, LayoutNested, LayoutFlat, LayoutSingleRepository) + } + if kubePrefix == "" { + kubePrefix = natural + } + + refs := map[string]Reference{} + for key, value := range m.Images { + ref, err := ParseReference(value) + if err != nil { + return nil, fmt.Errorf("image %q: %w", key, err) + } + refs[ref.String()] = ref + } + for _, value := range opts.ExtraImages { + ref, err := ParseReference(value) + if err != nil { + return nil, fmt.Errorf("extra image: %w", err) + } + refs[ref.String()] = ref + } + + plan := &MirrorPlan{} + rules := map[string]string{} + occupied := map[string]string{} + + addRule := func(source, mirror string) error { + if existing, ok := rules[source]; ok && existing != mirror { + return fmt.Errorf("conflicting mirror locations for %s: %s and %s", source, existing, mirror) + } + rules[source] = mirror + return nil + } + + keys := make([]string, 0, len(refs)) + for key := range refs { + keys = append(keys, key) + } + sort.Strings(keys) + + for _, key := range keys { + ref := refs[key] + tag := ref.Tag + if tag == "" { + tag = digestTag(ref.Digest) + } + + item := MirrorItem{Source: ref} + switch { + case isKubeadmImage(ref): + item.Repository = kubePrefix + "/" + ref.Path() + item.Tags = []string{tag} + if opts.Layout == LayoutNested && kubePrefix == natural { + if err := addRule(ref.Registry(), dest+"/"+mirrorPath(ref.Registry())); err != nil { + return nil, err + } + } else if err := addRule(ref.Repository, item.Repository); err != nil { + return nil, err + } + case opts.Layout == LayoutNested: + item.Repository = dest + "/" + mirrorPath(ref.Repository) + item.Tags = []string{tag} + if err := addRule(ref.Registry(), dest+"/"+mirrorPath(ref.Registry())); err != nil { + return nil, err + } + case opts.Layout == LayoutFlat: + item.Repository = dest + "/" + flatName(ref.Repository) + item.Tags = []string{tag} + if err := addRule(ref.Repository, item.Repository); err != nil { + return nil, err + } + default: + item.Repository = dest + item.Tags = []string{uniqueTag(flatName(ref.Repository), tag)} + if err := addRule(ref.Repository, dest); err != nil { + return nil, err + } + } + + for _, t := range item.Tags { + location := item.Repository + ":" + t + if previous, ok := occupied[location]; ok && previous != ref.String() { + return nil, fmt.Errorf("%s and %s would both be mirrored to %s", previous, ref.String(), location) + } + occupied[location] = ref.String() + } + plan.Items = append(plan.Items, item) + } + + sources := make([]string, 0, len(rules)) + for source := range rules { + sources = append(sources, source) + } + sort.Strings(sources) + for _, source := range sources { + plan.Rules = append(plan.Rules, MirrorRule{Source: source, Mirror: rules[source]}) + } + + manifestSource := opts.ManifestSource + if manifestSource == "" { + manifestSource = DefaultManifestRepository + ":latest" + } + manifestRepository, manifestTag, err := splitTarget(manifestSource) + if err != nil { + return nil, err + } + if strings.HasPrefix(manifestTag, "sha256:") { + manifestTag = digestTag(manifestTag) + } + plan.Manifest = MirrorItem{Source: Reference{Repository: manifestRepository, Tag: manifestTag}} + switch opts.Layout { + case LayoutNested: + plan.Manifest.Repository = dest + "/" + mirrorPath(manifestRepository) + plan.Manifest.Tags = []string{manifestTag} + case LayoutFlat: + plan.Manifest.Repository = dest + "/" + flatName(manifestRepository) + plan.Manifest.Tags = []string{manifestTag} + default: + plan.Manifest.Repository = dest + plan.Manifest.Tags = []string{uniqueTag(flatName(manifestRepository), manifestTag)} + } + + // Validate that the rules resolve every image of the release in a way + // that kubeadm can use. + resolved, err := ResolveImages(m.Images, ResolveOptions{Mirrors: plan.Rules}) + if err != nil { + return nil, err + } + if errs := CheckResolved(m, resolved); len(errs) > 0 { + return nil, fmt.Errorf("mirror rules would not work: %v", errs) + } + + return plan, nil +} + +// ManifestReference returns the mirrored release manifest reference. +func (p *MirrorPlan) ManifestReference() string { + return p.Manifest.Repository + ":" + p.Manifest.Tags[0] +} + +// SourceFunc returns where to read an item from and the reference to read. +type SourceFunc func(item MirrorItem) (oras.ReadOnlyTarget, string, error) + +// RemoteSource reads items from their source registries. +func RemoteSource(factory TargetFactory) SourceFunc { + return func(item MirrorItem) (oras.ReadOnlyTarget, string, error) { + target, err := factory(item.Source.Repository) + if err != nil { + return nil, "", err + } + return target, item.Source.Pullable()[len(item.Source.Repository)+1:], nil + } +} + +// Progress receives mirror progress messages. +type Progress func(format string, args ...interface{}) + +// copyItem copies a complete image (all platforms) and verifies its digest. +func copyItem(ctx context.Context, item MirrorItem, src SourceFunc, dst oras.Target, dstTag string) (ocispec.Descriptor, error) { + srcTarget, srcRef, err := src(item) + if err != nil { + return ocispec.Descriptor{}, err + } + + desc, err := oras.Copy(ctx, srcTarget, srcRef, dst, dstTag, oras.DefaultCopyOptions) + if err != nil { + return ocispec.Descriptor{}, fmt.Errorf("copying %s: %w", item.Source.String(), err) + } + if item.Source.Digest != "" && desc.Digest.String() != item.Source.Digest { + return ocispec.Descriptor{}, fmt.Errorf("digest mismatch for %s: copied %s", item.Source.String(), desc.Digest) + } + + got, err := dst.Resolve(ctx, dstTag) + if err != nil { + return ocispec.Descriptor{}, fmt.Errorf("verifying %s: %w", dstTag, err) + } + if got.Digest != desc.Digest { + return ocispec.Descriptor{}, fmt.Errorf("digest mismatch after copying %s: destination has %s, expected %s", item.Source.String(), got.Digest, desc.Digest) + } + return desc, nil +} + +// Mirror copies every image in the plan, then the release manifest itself. +// manifestSrc reads the release manifest artifact; when it is nil the +// manifest is published to the mirror from m instead, which gives it a new +// artifact digest but identical content. +func Mirror(ctx context.Context, m *Manifest, plan *MirrorPlan, src SourceFunc, manifestSrc SourceFunc, dst TargetFactory, progress Progress) error { + if progress == nil { + progress = func(string, ...interface{}) {} + } + + for i, item := range plan.Items { + target, err := dst(item.Repository) + if err != nil { + return err + } + desc, err := copyItem(ctx, item, src, target, item.Tags[0]) + if err != nil { + return err + } + for _, tag := range item.Tags[1:] { + if err := target.Tag(ctx, desc, tag); err != nil { + return err + } + } + progress("[%d/%d] %s -> %s:%s", i+1, len(plan.Items), item.Source.String(), item.Repository, item.Tags[0]) + } + + target, err := dst(plan.Manifest.Repository) + if err != nil { + return err + } + if manifestSrc != nil { + if _, err := copyItem(ctx, plan.Manifest, manifestSrc, target, plan.Manifest.Tags[0]); err != nil { + return err + } + } else if _, err := Push(ctx, target, m, plan.Manifest.Tags, PushOptions{}); err != nil { + return err + } + progress("release manifest -> %s", plan.ManifestReference()) + + return nil +} + +// directoryKey is the tag used for an image inside an OCI layout directory. +func directoryKey(ref Reference) string { + tag := ref.Tag + if tag == "" { + tag = "untagged" + } + digest := strings.TrimPrefix(ref.Digest, "sha256:") + if len(digest) > 12 { + digest = digest[:12] + } + return uniqueTag(flatName(ref.Repository), tag, digest) +} + +type directorySource struct { + Manifest string `yaml:"manifest"` +} + +// Export copies a release, its manifest and extra images into an OCI image +// layout directory that can be carried into a disconnected environment. +func Export(ctx context.Context, m *Manifest, opts MirrorOptions, src SourceFunc, manifestSrc SourceFunc, dir string, progress Progress) error { + if progress == nil { + progress = func(string, ...interface{}) {} + } + + // The layout of the final mirror is decided at import time; plan with a + // placeholder destination to collect and validate the images. + planOpts := opts + planOpts.Destination = "export.invalid" + planOpts.Layout = LayoutNested + planOpts.KubernetesPrefix = "" + plan, err := PlanMirror(m, planOpts) + if err != nil { + return err + } + + store, err := oci.NewWithContext(ctx, dir) + if err != nil { + return err + } + + for i, item := range plan.Items { + if _, err := copyItem(ctx, item, src, store, directoryKey(item.Source)); err != nil { + return err + } + progress("[%d/%d] %s", i+1, len(plan.Items), item.Source.String()) + } + + manifestKey := uniqueTag("release-manifest", plan.Manifest.Source.Tag) + if manifestSrc != nil { + if _, err := copyItem(ctx, plan.Manifest, manifestSrc, store, manifestKey); err != nil { + return err + } + } else if _, err := Push(ctx, store, m, []string{manifestKey}, PushOptions{}); err != nil { + return err + } + + data, err := m.Marshal() + if err != nil { + return err + } + if err := os.WriteFile(filepath.Join(dir, FileName), data, 0o644); err != nil { + return err + } + + extra, err := yaml.Marshal(opts.ExtraImages) + if err != nil { + return err + } + if err := os.WriteFile(filepath.Join(dir, extraImagesFile), extra, 0o644); err != nil { + return err + } + + source := opts.ManifestSource + if source == "" { + source = DefaultManifestRepository + ":latest" + } + meta, err := yaml.Marshal(directorySource{Manifest: source}) + if err != nil { + return err + } + return os.WriteFile(filepath.Join(dir, sourceFile), meta, 0o644) +} + +// Import reads a directory written by Export and mirrors it to a registry. +func Import(ctx context.Context, dir string, opts MirrorOptions, dst TargetFactory, progress Progress) (*MirrorPlan, error) { + data, err := os.ReadFile(filepath.Join(dir, FileName)) + if err != nil { + return nil, err + } + m, err := Unmarshal(data) + if err != nil { + return nil, err + } + + if raw, err := os.ReadFile(filepath.Join(dir, extraImagesFile)); err == nil { + if err := yaml.Unmarshal(raw, &opts.ExtraImages); err != nil { + return nil, err + } + } + if raw, err := os.ReadFile(filepath.Join(dir, sourceFile)); err == nil { + var meta directorySource + if err := yaml.Unmarshal(raw, &meta); err != nil { + return nil, err + } + opts.ManifestSource = meta.Manifest + } + + plan, err := PlanMirror(m, opts) + if err != nil { + return nil, err + } + + store, err := oci.NewWithContext(ctx, dir) + if err != nil { + return nil, err + } + src := func(item MirrorItem) (oras.ReadOnlyTarget, string, error) { + return store, directoryKey(item.Source), nil + } + manifestSrc := func(item MirrorItem) (oras.ReadOnlyTarget, string, error) { + return store, uniqueTag("release-manifest", item.Source.Tag), nil + } + + if err := Mirror(ctx, m, plan, src, manifestSrc, dst, progress); err != nil { + return nil, err + } + return plan, nil +} diff --git a/internal/releasemanifest/oci.go b/internal/releasemanifest/oci.go new file mode 100644 index 00000000..995ba52a --- /dev/null +++ b/internal/releasemanifest/oci.go @@ -0,0 +1,252 @@ +package releasemanifest + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "strings" + + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "oras.land/oras-go/v2" + "oras.land/oras-go/v2/content" + "oras.land/oras-go/v2/content/memory" + "oras.land/oras-go/v2/registry/remote" + "oras.land/oras-go/v2/registry/remote/auth" + "oras.land/oras-go/v2/registry/remote/credentials" + "oras.land/oras-go/v2/registry/remote/retry" +) + +const ( + annotationRevision = "org.opencontainers.image.revision" + annotationSource = "org.opencontainers.image.source" + annotationTitle = "org.opencontainers.image.title" + annotationRelease = "com.vexxhost.atmosphere.release" +) + +// TargetFactory returns an OCI target for a repository. +type TargetFactory func(repository string) (oras.Target, error) + +// RemoteOptions configures access to remote registries. +type RemoteOptions struct { + // PlainHTTP uses HTTP instead of HTTPS (for local test registries). + PlainHTTP bool +} + +// NewRemoteFactory returns a TargetFactory for remote registries that uses +// the Docker credentials store (~/.docker/config.json and helpers). +func NewRemoteFactory(opts RemoteOptions) (TargetFactory, error) { + store, err := credentials.NewStoreFromDocker(credentials.StoreOptions{}) + if err != nil { + return nil, fmt.Errorf("loading docker credentials: %w", err) + } + + client := &auth.Client{ + Client: retry.DefaultClient, + Cache: auth.NewCache(), + Credential: credentials.Credential(store), + } + + return func(repository string) (oras.Target, error) { + repo, err := remote.NewRepository(repository) + if err != nil { + return nil, err + } + // docker.io does not serve the registry API itself. + if repo.Reference.Registry == "docker.io" { + repo.Reference.Registry = "registry-1.docker.io" + } + repo.Client = client + repo.PlainHTTP = opts.PlainHTTP + return repo, nil + }, nil +} + +// splitTarget splits "repository:tag" or "repository@digest" into the +// repository and the reference within it. +func splitTarget(value string) (string, string, error) { + if i := strings.Index(value, "@"); i >= 0 { + return value[:i], value[i+1:], nil + } + lastSlash := strings.LastIndex(value, "/") + if i := strings.LastIndex(value, ":"); i > lastSlash { + return value[:i], value[i+1:], nil + } + return "", "", fmt.Errorf("%q must include a tag or digest", value) +} + +// SplitReferences splits repository:tag references that must all point at +// the same repository, such as the tags output of docker/metadata-action. +// Surrounding whitespace and empty values are ignored. +func SplitReferences(references []string) (string, []string, error) { + var repository string + var tags []string + for _, value := range references { + for _, field := range strings.Fields(value) { + repo, tag, err := splitTarget(field) + if err != nil { + return "", nil, err + } + if strings.HasPrefix(tag, "sha256:") { + return "", nil, fmt.Errorf("%q must use a tag, not a digest", field) + } + if repository == "" { + repository = repo + } else if repo != repository { + return "", nil, fmt.Errorf("all references must use one repository: %q and %q differ", repository, repo) + } + tags = append(tags, tag) + } + } + if repository == "" { + return "", nil, fmt.Errorf("at least one repository:tag reference is required") + } + return repository, tags, nil +} + +// PushOptions controls publishing a manifest. +type PushOptions struct { + Source string + // Annotations are added to the artifact manifest. + Annotations map[string]string +} + +// createdEpoch is used as the creation time of every artifact, so that the +// same manifest always produces the same artifact digest. +const createdEpoch = "1970-01-01T00:00:00Z" + +// pack builds the OCI artifact for a manifest in a memory store. The result +// is reproducible: identical manifests and options give identical digests. +func pack(ctx context.Context, m *Manifest, opts PushOptions) (*memory.Store, ocispec.Descriptor, error) { + data, err := m.Marshal() + if err != nil { + return nil, ocispec.Descriptor{}, err + } + + store := memory.New() + layer := content.NewDescriptorFromBytes(MediaType, data) + layer.Annotations = map[string]string{annotationTitle: FileName} + if err := store.Push(ctx, layer, bytes.NewReader(data)); err != nil { + return nil, ocispec.Descriptor{}, err + } + + annotations := map[string]string{ + annotationRelease: m.Release, + ocispec.AnnotationCreated: createdEpoch, + } + if m.Commit != "" { + annotations[annotationRevision] = m.Commit + } + if opts.Source != "" { + annotations[annotationSource] = opts.Source + } + for key, value := range opts.Annotations { + annotations[key] = value + } + + desc, err := oras.PackManifest(ctx, store, oras.PackManifestVersion1_1, ArtifactType, oras.PackManifestOptions{ + Layers: []ocispec.Descriptor{layer}, + ManifestAnnotations: annotations, + }) + if err != nil { + return nil, ocispec.Descriptor{}, err + } + return store, desc, nil +} + +// Digest returns the digest of the artifact Push would publish for a +// manifest, without publishing it. +func Digest(ctx context.Context, m *Manifest, opts PushOptions) (string, error) { + _, desc, err := pack(ctx, m, opts) + if err != nil { + return "", err + } + return desc.Digest.String(), nil +} + +// Push publishes a manifest as an OCI artifact and tags it with every tag. +func Push(ctx context.Context, dst oras.Target, m *Manifest, tags []string, opts PushOptions) (ocispec.Descriptor, error) { + if len(tags) == 0 { + return ocispec.Descriptor{}, fmt.Errorf("at least one tag is required") + } + + store, desc, err := pack(ctx, m, opts) + if err != nil { + return ocispec.Descriptor{}, err + } + + if err := oras.CopyGraph(ctx, store, dst, desc, oras.DefaultCopyGraphOptions); err != nil { + return ocispec.Descriptor{}, err + } + for _, tag := range tags { + if err := dst.Tag(ctx, desc, tag); err != nil { + return ocispec.Descriptor{}, err + } + } + + return desc, nil +} + +// Fetch downloads and validates a manifest artifact. +func Fetch(ctx context.Context, src oras.ReadOnlyTarget, reference string) (*Manifest, ocispec.Descriptor, error) { + desc, raw, err := oras.FetchBytes(ctx, src, reference, oras.DefaultFetchBytesOptions) + if err != nil { + return nil, ocispec.Descriptor{}, err + } + + var artifact ocispec.Manifest + if err := json.Unmarshal(raw, &artifact); err != nil { + return nil, ocispec.Descriptor{}, fmt.Errorf("parsing artifact manifest: %w", err) + } + if artifact.ArtifactType != ArtifactType { + return nil, ocispec.Descriptor{}, fmt.Errorf("%s is not an Atmosphere release manifest (artifact type %q)", reference, artifact.ArtifactType) + } + + for _, layer := range artifact.Layers { + if layer.MediaType != MediaType { + continue + } + data, err := content.FetchAll(ctx, src, layer) + if err != nil { + return nil, ocispec.Descriptor{}, err + } + m, err := Unmarshal(data) + if err != nil { + return nil, ocispec.Descriptor{}, err + } + return m, desc, nil + } + + return nil, ocispec.Descriptor{}, fmt.Errorf("%s does not contain a %s layer", reference, MediaType) +} + +// Promote tags an existing manifest artifact with a new tag, without +// changing its content. +func Promote(ctx context.Context, repo oras.Target, from, to string) (ocispec.Descriptor, error) { + if _, _, err := Fetch(ctx, repo, from); err != nil { + return ocispec.Descriptor{}, err + } + return oras.Tag(ctx, repo, from, to) +} + +// Load reads a manifest from a local file or, if no such file exists, from +// an OCI reference such as ghcr.io/vexxhost/atmosphere-release:v7.8.1. +func Load(ctx context.Context, location string, factory TargetFactory) (*Manifest, error) { + if data, err := os.ReadFile(location); err == nil { + return Unmarshal(data) + } else if !os.IsNotExist(err) { + return nil, err + } + + repository, reference, err := splitTarget(location) + if err != nil { + return nil, fmt.Errorf("%s is neither a file nor an OCI reference: %w", location, err) + } + target, err := factory(repository) + if err != nil { + return nil, err + } + m, _, err := Fetch(ctx, target, reference) + return m, err +} diff --git a/internal/releasemanifest/publish.go b/internal/releasemanifest/publish.go new file mode 100644 index 00000000..61dcc54c --- /dev/null +++ b/internal/releasemanifest/publish.go @@ -0,0 +1,213 @@ +package releasemanifest + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +const ( + // DefaultZuulJob is the Zuul job that generates the release manifest a + // buildset tests. + DefaultZuulJob = "atmosphere-release-manifest" + // DefaultZuulArtifact is the name of the Zuul artifact holding it. + DefaultZuulArtifact = "Release manifest" + + // AnnotationTested records whether a published manifest is the one + // tested in CI. It is only set on manifests that were not. + AnnotationTested = "com.vexxhost.atmosphere.tested" + + maxManifestSize = 4 << 20 +) + +// ErrNoTestedManifest means no successful buildset tested a manifest for the +// change. +var ErrNoTestedManifest = errors.New("no tested release manifest found") + +// ZuulLookup finds the release manifest that Zuul tested for a change. +type ZuulLookup struct { + // API is the Zuul tenant API, e.g. https://zuul.example.com/api/tenant/oss. + API string + Project string + Change string + Patchset string + // Pipelines are searched in order, e.g. gate before check. + Pipelines []string + Job string + Artifact string + Client *http.Client +} + +// Tested is a release manifest that a Zuul buildset tested. +type Tested struct { + Manifest *Manifest + Pipeline string + Buildset string + URL string +} + +type zuulBuild struct { + UUID string `json:"uuid"` + Result string `json:"result"` + Artifacts []struct { + Name string `json:"name"` + URL string `json:"url"` + } `json:"artifacts"` + Buildset struct { + UUID string `json:"uuid"` + } `json:"buildset"` +} + +func (l ZuulLookup) client() *http.Client { + if l.Client != nil { + return l.Client + } + return &http.Client{Timeout: 60 * time.Second} +} + +func (l ZuulLookup) get(ctx context.Context, rawURL string, limit int64) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, err + } + resp, err := l.client().Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("GET %s: HTTP %d", rawURL, resp.StatusCode) + } + data, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > limit { + return nil, fmt.Errorf("GET %s: response larger than %d bytes", rawURL, limit) + } + return data, nil +} + +func (l ZuulLookup) getJSON(ctx context.Context, path string, query url.Values, v interface{}) error { + u := strings.TrimSuffix(l.API, "/") + path + if len(query) > 0 { + u += "?" + query.Encode() + } + data, err := l.get(ctx, u, maxManifestSize) + if err != nil { + return err + } + return json.Unmarshal(data, v) +} + +// Find returns the manifest generated by the newest buildset that tested the +// change's patchset and in which every job succeeded. +func (l ZuulLookup) Find(ctx context.Context) (*Tested, error) { + if l.API == "" || l.Project == "" || l.Change == "" || l.Patchset == "" { + return nil, fmt.Errorf("zuul lookup needs an API, project, change and patchset") + } + job, artifact := l.Job, l.Artifact + if job == "" { + job = DefaultZuulJob + } + if artifact == "" { + artifact = DefaultZuulArtifact + } + + for _, pipeline := range l.Pipelines { + var builds []zuulBuild + err := l.getJSON(ctx, "/builds", url.Values{ + "project": {l.Project}, + "change": {l.Change}, + "patchset": {l.Patchset}, + "pipeline": {pipeline}, + "job_name": {job}, + "result": {"SUCCESS"}, + "limit": {"20"}, + }, &builds) + if err != nil { + return nil, err + } + + for _, build := range builds { + var buildset struct { + Result string `json:"result"` + } + if err := l.getJSON(ctx, "/buildset/"+build.Buildset.UUID, nil, &buildset); err != nil { + return nil, err + } + if buildset.Result != "SUCCESS" { + continue + } + + for _, a := range build.Artifacts { + if a.Name != artifact { + continue + } + data, err := l.get(ctx, a.URL, maxManifestSize) + if err != nil { + return nil, err + } + m, err := Unmarshal(data) + if err != nil { + return nil, fmt.Errorf("%s: %w", a.URL, err) + } + return &Tested{Manifest: m, Pipeline: pipeline, Buildset: build.Buildset.UUID, URL: a.URL}, nil + } + } + } + + return nil, ErrNoTestedManifest +} + +// PublishDecision is the manifest to publish and why. +type PublishDecision struct { + Manifest *Manifest + Tested *Tested + Reason string + Options PushOptions +} + +// DecidePublish chooses the tested manifest when it was generated from the +// same image inputs as the commit being published, and the fallback manifest +// otherwise. A fallback manifest is annotated as untested. +func DecidePublish(ctx context.Context, lookup *ZuulLookup, inputs string, fallback *Manifest, opts PushOptions) (*PublishDecision, error) { + untested := func(reason string) *PublishDecision { + o := opts + o.Annotations = map[string]string{AnnotationTested: "false"} + for k, v := range opts.Annotations { + o.Annotations[k] = v + } + return &PublishDecision{Manifest: fallback, Reason: reason, Options: o} + } + + if lookup == nil { + return untested("no change to look up"), nil + } + + tested, err := lookup.Find(ctx) + switch { + case errors.Is(err, ErrNoTestedManifest): + return untested(fmt.Sprintf("no successful buildset tested change %s at %s", lookup.Change, lookup.Patchset)), nil + case err != nil: + return untested(fmt.Sprintf("looking up the tested manifest failed: %v", err)), nil + case tested.Manifest.Inputs == "": + return untested("the tested manifest does not record its image inputs"), nil + case tested.Manifest.Inputs != inputs: + return untested(fmt.Sprintf("image inputs changed since buildset %s tested the change (%s, now %s)", + tested.Buildset, tested.Manifest.Inputs, inputs)), nil + } + + return &PublishDecision{ + Manifest: tested.Manifest, + Tested: tested, + Reason: fmt.Sprintf("tested in %s buildset %s", tested.Pipeline, tested.Buildset), + Options: opts, + }, nil +} diff --git a/internal/releasemanifest/publish_test.go b/internal/releasemanifest/publish_test.go new file mode 100644 index 00000000..3c132d61 --- /dev/null +++ b/internal/releasemanifest/publish_test.go @@ -0,0 +1,196 @@ +package releasemanifest + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type fakeZuul struct { + server *httptest.Server + builds map[string][]map[string]interface{} // pipeline -> builds + results map[string]string // buildset -> result + manifest []byte + queries []string +} + +func newFakeZuul(t *testing.T, manifest *Manifest) *fakeZuul { + t.Helper() + data, err := manifest.Marshal() + require.NoError(t, err) + z := &fakeZuul{builds: map[string][]map[string]interface{}{}, results: map[string]string{}, manifest: data} + mux := http.NewServeMux() + mux.HandleFunc("/api/builds", func(w http.ResponseWriter, r *http.Request) { + z.queries = append(z.queries, r.URL.RawQuery) + q := r.URL.Query() + if q.Get("project") != "vexxhost/atmosphere" || q.Get("change") != "4420" || q.Get("patchset") != "abc" || + q.Get("job_name") != DefaultZuulJob || q.Get("result") != "SUCCESS" { + _ = json.NewEncoder(w).Encode([]interface{}{}) + return + } + _ = json.NewEncoder(w).Encode(z.builds[q.Get("pipeline")]) + }) + mux.HandleFunc("/api/buildset/", func(w http.ResponseWriter, r *http.Request) { + uuid := r.URL.Path[len("/api/buildset/"):] + _ = json.NewEncoder(w).Encode(map[string]string{"result": z.results[uuid]}) + }) + mux.HandleFunc("/logs/release-manifest.yaml", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write(z.manifest) + }) + z.server = httptest.NewServer(mux) + t.Cleanup(z.server.Close) + return z +} + +func (z *fakeZuul) addBuild(pipeline, buildset, result string) { + z.results[buildset] = result + z.builds[pipeline] = append(z.builds[pipeline], map[string]interface{}{ + "uuid": "build-" + buildset, + "result": "SUCCESS", + "buildset": map[string]string{"uuid": buildset}, + "artifacts": []map[string]string{ + {"name": "Zuul Manifest", "url": z.server.URL + "/logs/zuul-manifest.json"}, + {"name": DefaultZuulArtifact, "url": z.server.URL + "/logs/release-manifest.yaml"}, + }, + }) +} + +func (z *fakeZuul) lookup() *ZuulLookup { + return &ZuulLookup{API: z.server.URL + "/api", Project: "vexxhost/atmosphere", Change: "4420", Patchset: "abc", Pipelines: []string{"gate", "check"}} +} + +func TestDecidePublishUsesTestedManifest(t *testing.T) { + ctx := context.Background() + tested := testManifest() + tested.Inputs = "sha256:inputs" + z := newFakeZuul(t, tested) + z.addBuild("check", "failed-buildset", "FAILURE") + z.addBuild("check", "good-buildset", "SUCCESS") + + fallback := testManifest() + fallback.Images["ceph"] = "quay.io/ceph/ceph:v18.2.7@" + digestB + fallback.Inputs = "sha256:inputs" + + d, err := DecidePublish(ctx, z.lookup(), "sha256:inputs", fallback, PushOptions{Source: "src"}) + require.NoError(t, err) + require.NotNil(t, d.Tested) + assert.Equal(t, "good-buildset", d.Tested.Buildset) + assert.Equal(t, "check", d.Tested.Pipeline) + assert.Equal(t, tested, d.Manifest) + assert.Empty(t, d.Options.Annotations) + + // Publishing the tested manifest gives the same artifact digest as the + // one the producer job computed. + want, err := Digest(ctx, tested, PushOptions{Source: "src"}) + require.NoError(t, err) + got, err := Digest(ctx, d.Manifest, d.Options) + require.NoError(t, err) + assert.Equal(t, want, got) + + // gate is searched before check. + assert.Contains(t, z.queries[0], "pipeline=gate") +} + +func TestDecidePublishFallsBack(t *testing.T) { + ctx := context.Background() + tested := testManifest() + tested.Inputs = "sha256:old" + fallback := testManifest() + + cases := map[string]struct { + setup func(z *fakeZuul) *ZuulLookup + inputs string + reason string + }{ + "inputs changed": { + setup: func(z *fakeZuul) *ZuulLookup { z.addBuild("check", "bs", "SUCCESS"); return z.lookup() }, + inputs: "sha256:new", + reason: "image inputs changed", + }, + "no successful buildset": { + setup: func(z *fakeZuul) *ZuulLookup { z.addBuild("check", "bs", "FAILURE"); return z.lookup() }, + inputs: "sha256:old", + reason: "no successful buildset", + }, + "no change": { + setup: func(*fakeZuul) *ZuulLookup { return nil }, + inputs: "sha256:old", + reason: "no change", + }, + "zuul unreachable": { + setup: func(z *fakeZuul) *ZuulLookup { + l := z.lookup() + l.API = "http://127.0.0.1:1/api" + return l + }, + inputs: "sha256:old", + reason: "looking up the tested manifest failed", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + z := newFakeZuul(t, tested) + d, err := DecidePublish(ctx, tc.setup(z), tc.inputs, fallback, PushOptions{}) + require.NoError(t, err) + assert.Nil(t, d.Tested) + assert.Equal(t, fallback, d.Manifest) + assert.Contains(t, d.Reason, tc.reason) + assert.Equal(t, "false", d.Options.Annotations[AnnotationTested]) + }) + } +} + +func TestPushIsReproducible(t *testing.T) { + ctx := context.Background() + m := testManifest() + a, err := Digest(ctx, m, PushOptions{Source: "s"}) + require.NoError(t, err) + b, err := Digest(ctx, m, PushOptions{Source: "s"}) + require.NoError(t, err) + assert.Equal(t, a, b) + + other := testManifest() + other.Release = "2025.2" + c, err := Digest(ctx, other, PushOptions{Source: "s"}) + require.NoError(t, err) + assert.NotEqual(t, a, c) + + // Push and Digest agree. + reg := registry{} + repo, _ := reg.factory("example.com/release") + desc, err := Push(ctx, repo, m, []string{"x"}, PushOptions{Source: "s"}) + require.NoError(t, err) + assert.Equal(t, a, desc.Digest.String()) +} + +func TestSourceDigestIgnoresUnrelatedDefaults(t *testing.T) { + vars, defaults := writeSource(t) + a, err := LoadSource(vars, defaults) + require.NoError(t, err) + + require.NoError(t, appendFile(defaults, "atmosphere_version: 9.9.9\n")) + b, err := LoadSource(vars, defaults) + require.NoError(t, err) + assert.Equal(t, a.Digest(), b.Digest()) + + b.Images["ceph"] = "quay.io/ceph/ceph:v19.0.0" + assert.NotEqual(t, a.Digest(), b.Digest()) + assert.Regexp(t, `^sha256:[a-f0-9]{64}$`, a.Digest()) +} + +func appendFile(path, data string) error { + f, err := openAppend(path) + if err != nil { + return err + } + defer f.Close() + _, err = fmt.Fprint(f, data) + return err +} diff --git a/internal/releasemanifest/reference.go b/internal/releasemanifest/reference.go new file mode 100644 index 00000000..571e3357 --- /dev/null +++ b/internal/releasemanifest/reference.go @@ -0,0 +1,102 @@ +package releasemanifest + +import ( + "fmt" + "regexp" + "strings" +) + +var ( + // pathComponent follows the OCI distribution specification. + pathComponent = regexp.MustCompile(`^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*$`) + tagPattern = regexp.MustCompile(`^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$`) + digestPattern = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`) +) + +// Reference is a fully qualified image reference split into its parts. +type Reference struct { + // Repository includes the registry host, e.g. "quay.io/ceph/ceph". + Repository string + Tag string + Digest string +} + +// ParseReference parses a fully qualified image reference of the form +// host/path[:tag][@digest]. +func ParseReference(value string) (Reference, error) { + var ref Reference + + rest := value + if i := strings.Index(rest, "@"); i >= 0 { + ref.Digest = rest[i+1:] + rest = rest[:i] + if !digestPattern.MatchString(ref.Digest) { + return Reference{}, fmt.Errorf("invalid digest in %q", value) + } + } + + lastSlash := strings.LastIndex(rest, "/") + if i := strings.LastIndex(rest, ":"); i > lastSlash { + ref.Tag = rest[i+1:] + rest = rest[:i] + if !tagPattern.MatchString(ref.Tag) { + return Reference{}, fmt.Errorf("invalid tag in %q", value) + } + } + + if lastSlash < 0 { + return Reference{}, fmt.Errorf("image %q is not fully qualified (missing registry)", value) + } + + ref.Repository = rest + host := ref.Registry() + if host != "localhost" && !strings.ContainsAny(host, ".:") { + return Reference{}, fmt.Errorf("image %q is not fully qualified (missing registry)", value) + } + for _, component := range strings.Split(ref.Path(), "/") { + if !pathComponent.MatchString(component) { + return Reference{}, fmt.Errorf("invalid repository path component %q in %q", component, value) + } + } + + if ref.Tag == "" && ref.Digest == "" { + return Reference{}, fmt.Errorf("image %q has neither a tag nor a digest", value) + } + + return ref, nil +} + +// Registry returns the registry host of the reference. +func (r Reference) Registry() string { + return strings.SplitN(r.Repository, "/", 2)[0] +} + +// Path returns the repository path without the registry host. +func (r Reference) Path() string { + parts := strings.SplitN(r.Repository, "/", 2) + if len(parts) < 2 { + return "" + } + return parts[1] +} + +// String returns the reference in host/path[:tag][@digest] form. +func (r Reference) String() string { + s := r.Repository + if r.Tag != "" { + s += ":" + r.Tag + } + if r.Digest != "" { + s += "@" + r.Digest + } + return s +} + +// Pullable returns the reference used to pull the image: the digest when +// present, otherwise the tag. +func (r Reference) Pullable() string { + if r.Digest != "" { + return r.Repository + "@" + r.Digest + } + return r.Repository + ":" + r.Tag +} diff --git a/internal/releasemanifest/releasemanifest_test.go b/internal/releasemanifest/releasemanifest_test.go new file mode 100644 index 00000000..16f05b7b --- /dev/null +++ b/internal/releasemanifest/releasemanifest_test.go @@ -0,0 +1,592 @@ +package releasemanifest + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/goccy/go-yaml" + "github.com/opencontainers/go-digest" + "github.com/opencontainers/image-spec/specs-go" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "oras.land/oras-go/v2" + "oras.land/oras-go/v2/content" + "oras.land/oras-go/v2/content/memory" +) + +const ( + digestA = "sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0" + digestB = "sha256:3095eaa3964b6b37b55d9de8681fb3d06cc247da1cd402fcdf81a7abbfc2496b" +) + +func testManifest() *Manifest { + return &Manifest{ + APIVersion: APIVersion, + Kind: Kind, + Release: "main", + Commit: "811b7f90", + Kubernetes: Kubernetes{ + Version: "1.28.13", + Images: []string{"kube_apiserver", "kube_controller_manager", "kube_proxy", "kube_scheduler"}, + }, + Images: map[string]string{ + "ceph": "quay.io/ceph/ceph:v18.2.7@" + digestA, + "nova_api": "ghcr.io/vexxhost/nova:main@" + digestB, + "nova_conductor": "ghcr.io/vexxhost/nova:main@" + digestB, + "kube_apiserver": "registry.k8s.io/kube-apiserver:v1.28.13@" + digestA, + "kube_controller_manager": "registry.k8s.io/kube-controller-manager:v1.28.13@" + digestA, + "kube_proxy": "registry.k8s.io/kube-proxy:v1.28.13@" + digestA, + "kube_scheduler": "registry.k8s.io/kube-scheduler:v1.28.13@" + digestA, + }, + } +} + +func TestParseReference(t *testing.T) { + ref, err := ParseReference("localhost:5000/a/b:v1@" + digestA) + require.NoError(t, err) + assert.Equal(t, "localhost:5000/a/b", ref.Repository) + assert.Equal(t, "localhost:5000", ref.Registry()) + assert.Equal(t, "a/b", ref.Path()) + assert.Equal(t, "v1", ref.Tag) + assert.Equal(t, digestA, ref.Digest) + assert.Equal(t, "localhost:5000/a/b@"+digestA, ref.Pullable()) + + for _, invalid := range []string{ + "haproxy:2.5", + "library/haproxy:2.5", + "quay.io/ceph/ceph", + "quay.io/Ceph/ceph:v1", + "quay.io/ceph/ceph@sha256:abc", + } { + _, err := ParseReference(invalid) + assert.Error(t, err, invalid) + } +} + +func TestManifestRoundTripIsDeterministic(t *testing.T) { + m := testManifest() + + first, err := m.Marshal() + require.NoError(t, err) + second, err := m.Marshal() + require.NoError(t, err) + assert.Equal(t, first, second) + assert.True(t, strings.HasPrefix(string(first), "apiVersion: "+APIVersion+"\nkind: "+Kind+"\n")) + + parsed, err := Unmarshal(first) + require.NoError(t, err) + assert.Equal(t, m, parsed) +} + +func TestManifestValidate(t *testing.T) { + m := testManifest() + m.Images["ceph"] = "quay.io/ceph/ceph:v18.2.7" + assert.ErrorContains(t, m.Validate(), "not pinned by digest") + + m = testManifest() + m.Kubernetes.Images = append(m.Kubernetes.Images, "missing") + assert.ErrorContains(t, m.Validate(), "not part of the manifest images") + + m = testManifest() + m.APIVersion = "v0" + assert.ErrorContains(t, m.Validate(), "unsupported apiVersion") +} + +type fakeResolver map[string]digest.Digest + +func (f fakeResolver) Resolve(_ context.Context, reference string) (digest.Digest, error) { + if d, ok := f[reference]; ok { + return d, nil + } + return "", fmt.Errorf("not found") +} + +const testVars = `--- +# comment kept by write-vars +atmosphere_release: main +ceph_version: 18.2.7 + +_atmosphere_images: + ceph: "{{ atmosphere_image_prefix }}quay.io/ceph/ceph:v{{ ceph_version }}" + glance: "{{ atmosphere_image_prefix }}registry.atmosphere.dev/library/glance:{{ atmosphere_release }}" + nova_api: "{{ atmosphere_image_prefix }}ghcr.io/vexxhost/nova:main@` + digestB + `" + kube_apiserver: "{{ atmosphere_image_prefix }}registry.k8s.io/kube-apiserver:v{{ atmosphere_kubernetes_version }}" + +atmosphere_images: '{{ _atmosphere_images }}' +` + +const testDefaults = `--- +atmosphere_image_prefix: "" +atmosphere_kubernetes_version: "1.28.13" +` + +func writeSource(t *testing.T) (string, string) { + t.Helper() + dir := t.TempDir() + vars := filepath.Join(dir, "vars.yml") + defaults := filepath.Join(dir, "defaults.yml") + require.NoError(t, os.WriteFile(vars, []byte(testVars), 0o644)) + require.NoError(t, os.WriteFile(defaults, []byte(testDefaults), 0o644)) + return vars, defaults +} + +func TestGenerate(t *testing.T) { + vars, defaults := writeSource(t) + + src, err := LoadSource(vars, defaults) + require.NoError(t, err) + assert.Equal(t, "main", src.Release) + assert.Equal(t, "1.28.13", src.KubernetesVersion) + assert.Equal(t, []string{"kube_apiserver"}, src.KubernetesImages) + assert.Equal(t, "quay.io/ceph/ceph:v18.2.7", src.Images["ceph"]) + assert.Equal(t, "registry.atmosphere.dev/library/glance:main", src.Images["glance"]) + + resolver := fakeResolver{ + "quay.io/ceph/ceph:v18.2.7": digestA, + "registry.atmosphere.dev/library/glance:main": digestA, + "registry.k8s.io/kube-apiserver:v1.28.13": digestB, + } + m, err := Generate(context.Background(), src, resolver, GenerateOptions{Commit: "abc"}) + require.NoError(t, err) + assert.Equal(t, "abc", m.Commit) + assert.Equal(t, "quay.io/ceph/ceph:v18.2.7@"+digestA, m.Images["ceph"]) + // Existing digest pins are kept without resolving them again. + assert.Equal(t, "ghcr.io/vexxhost/nova:main@"+digestB, m.Images["nova_api"]) + assert.Equal(t, "registry.k8s.io/kube-apiserver:v1.28.13@"+digestB, m.Images["kube_apiserver"]) + + delete(resolver, "quay.io/ceph/ceph:v18.2.7") + _, err = Generate(context.Background(), src, resolver, GenerateOptions{}) + assert.ErrorContains(t, err, "quay.io/ceph/ceph:v18.2.7") +} + +func TestLoadSourceRejectsUnknownTemplate(t *testing.T) { + vars, defaults := writeSource(t) + data, err := os.ReadFile(vars) + require.NoError(t, err) + require.NoError(t, os.WriteFile(vars, []byte(strings.Replace(string(data), "ceph_version }}", "unknown }}", 1)), 0o644)) + + _, err = LoadSource(vars, defaults) + assert.ErrorContains(t, err, "undefined template variables") +} + +func TestWriteVars(t *testing.T) { + vars, defaults := writeSource(t) + src, err := LoadSource(vars, defaults) + require.NoError(t, err) + + m := &Manifest{ + APIVersion: APIVersion, + Kind: Kind, + Release: "main", + Kubernetes: Kubernetes{Version: "1.28.13", Images: []string{"kube_apiserver"}}, + Images: map[string]string{ + "ceph": "quay.io/ceph/ceph:v18.2.7@" + digestA, + "glance": "registry.atmosphere.dev/library/glance:main@" + digestA, + "nova_api": "ghcr.io/vexxhost/nova:main@" + digestA, + "kube_apiserver": "registry.k8s.io/kube-apiserver:v1.28.13@" + digestB, + }, + } + require.NoError(t, WriteVars(vars, m)) + + data, err := os.ReadFile(vars) + require.NoError(t, err) + assert.Contains(t, string(data), "# comment kept by write-vars") + + var parsed map[string]interface{} + require.NoError(t, yaml.Unmarshal(data, &parsed)) + images := parsed["_atmosphere_images"].(map[string]interface{}) + assert.Equal(t, "{{ atmosphere_image_prefix }}quay.io/ceph/ceph:v18.2.7@"+digestA, images["ceph"]) + assert.Equal(t, "{{ atmosphere_image_prefix }}ghcr.io/vexxhost/nova:main@"+digestA, images["nova_api"]) + assert.Equal(t, "{{ atmosphere_image_prefix }}registry.k8s.io/kube-apiserver:v{{ atmosphere_kubernetes_version }}", images["kube_apiserver"]) + assert.Equal(t, "{{ _atmosphere_images }}", parsed["atmosphere_images"]) + + // The rewritten file still renders to the manifest images. + again, err := LoadSource(vars, defaults) + require.NoError(t, err) + assert.Equal(t, m.Images["ceph"], again.Images["ceph"]) + assert.Equal(t, src.KubernetesImages, again.KubernetesImages) + + delete(m.Images, "glance") + assert.ErrorContains(t, WriteVars(vars, m), `image "glance" is missing`) +} + +func TestDiff(t *testing.T) { + a := testManifest() + b := testManifest() + b.Images["nova_api"] = "ghcr.io/vexxhost/nova:main@" + digestA + b.Images["nova_conductor"] = "ghcr.io/vexxhost/nova:main@" + digestA + delete(b.Images, "ceph") + + changes := Diff(a, b) + require.Len(t, changes, 2) + assert.Equal(t, []string{"ceph"}, changes[0].Keys) + assert.Equal(t, "", changes[0].To) + assert.Equal(t, []string{"nova_api", "nova_conductor"}, changes[1].Keys) + + var out bytes.Buffer + require.NoError(t, WriteDiff(&out, a, b, changes)) + assert.Contains(t, out.String(), "keys: nova_api, nova_conductor") + assert.Empty(t, Diff(a, a)) +} + +// registry is a set of in-memory repositories. +type registry map[string]*memory.Store + +func (r registry) factory(repository string) (oras.Target, error) { + if _, ok := r[repository]; !ok { + r[repository] = memory.New() + } + return r[repository], nil +} + +func pushJSON(t *testing.T, store *memory.Store, mediaType string, v interface{}) ocispec.Descriptor { + t.Helper() + data, err := json.Marshal(v) + require.NoError(t, err) + desc := content.NewDescriptorFromBytes(mediaType, data) + exists, err := store.Exists(context.Background(), desc) + require.NoError(t, err) + if !exists { + require.NoError(t, store.Push(context.Background(), desc, bytes.NewReader(data))) + } + return desc +} + +// pushImage pushes a two-platform image and tags it with tag and its digest. +func pushImage(t *testing.T, store *memory.Store, tag string) string { + t.Helper() + ctx := context.Background() + + var manifests []ocispec.Descriptor + for _, arch := range []string{"amd64", "arm64"} { + config := pushJSON(t, store, ocispec.MediaTypeImageConfig, map[string]string{"architecture": arch, "os": "linux", "tag": tag}) + layer := pushJSON(t, store, ocispec.MediaTypeImageLayer, map[string]string{"layer": arch + tag}) + m := pushJSON(t, store, ocispec.MediaTypeImageManifest, ocispec.Manifest{ + Versioned: specs.Versioned{SchemaVersion: 2}, + MediaType: ocispec.MediaTypeImageManifest, + Config: config, + Layers: []ocispec.Descriptor{layer}, + }) + m.Platform = &ocispec.Platform{Architecture: arch, OS: "linux"} + manifests = append(manifests, m) + } + index := pushJSON(t, store, ocispec.MediaTypeImageIndex, ocispec.Index{ + Versioned: specs.Versioned{SchemaVersion: 2}, + MediaType: ocispec.MediaTypeImageIndex, + Manifests: manifests, + }) + require.NoError(t, store.Tag(ctx, index, tag)) + require.NoError(t, store.Tag(ctx, index, index.Digest.String())) + return index.Digest.String() +} + +// sourceRegistry builds a source registry and a manifest pointing at it. +func sourceRegistry(t *testing.T) (registry, *Manifest) { + t.Helper() + src := registry{} + m := testManifest() + for key, value := range m.Images { + ref, err := ParseReference(value) + require.NoError(t, err) + target, _ := src.factory(ref.Repository) + ref.Digest = pushImage(t, target.(*memory.Store), ref.Tag) + m.Images[key] = ref.String() + } + return src, m +} + +func TestPushFetchPromote(t *testing.T) { + ctx := context.Background() + repo := memory.New() + m := testManifest() + + desc, err := Push(ctx, repo, m, []string{"abc", "main"}, PushOptions{Source: "https://github.com/vexxhost/atmosphere"}) + require.NoError(t, err) + + got, fetched, err := Fetch(ctx, repo, "main") + require.NoError(t, err) + assert.Equal(t, m, got) + assert.Equal(t, desc.Digest, fetched.Digest) + + promoted, err := Promote(ctx, repo, "abc", "v7.8.1") + require.NoError(t, err) + assert.Equal(t, desc.Digest, promoted.Digest) + + _, err = Promote(ctx, repo, "missing", "v7.8.2") + assert.Error(t, err) + + reg := registry{DefaultManifestRepository: repo} + loaded, err := Load(ctx, DefaultManifestRepository+":v7.8.1", reg.factory) + require.NoError(t, err) + assert.Equal(t, m, loaded) + + file := filepath.Join(t.TempDir(), FileName) + data, err := m.Marshal() + require.NoError(t, err) + require.NoError(t, os.WriteFile(file, data, 0o644)) + loaded, err = Load(ctx, file, reg.factory) + require.NoError(t, err) + assert.Equal(t, m, loaded) +} + +func TestFetchRejectsOtherArtifacts(t *testing.T) { + ctx := context.Background() + repo := memory.New() + pushImage(t, repo, "image") + _, _, err := Fetch(ctx, repo, "image") + assert.Error(t, err) +} + +func TestMirrorLayouts(t *testing.T) { + ctx := context.Background() + + tests := []struct { + layout Layout + kubePrefix string + ceph string + kube string + manifest string + }{ + {LayoutNested, "", "mirror.example.com/atmosphere/quay.io/ceph/ceph", "mirror.example.com/atmosphere/registry.k8s.io/kube-apiserver", "mirror.example.com/atmosphere/ghcr.io/vexxhost/atmosphere-release:v7.8.1"}, + {LayoutFlat, "", "mirror.example.com/atmosphere/quay.io--ceph--ceph", "mirror.example.com/atmosphere/kube-apiserver", "mirror.example.com/atmosphere/ghcr.io--vexxhost--atmosphere-release:v7.8.1"}, + {LayoutSingleRepository, "mirror.example.com/kubernetes", "mirror.example.com/atmosphere", "mirror.example.com/kubernetes/kube-apiserver", "mirror.example.com/atmosphere:ghcr.io--vexxhost--atmosphere-release--v7.8.1"}, + } + + for _, tc := range tests { + t.Run(string(tc.layout), func(t *testing.T) { + src, m := sourceRegistry(t) + manifestRepo := memory.New() + _, err := Push(ctx, manifestRepo, m, []string{"v7.8.1"}, PushOptions{}) + require.NoError(t, err) + src[DefaultManifestRepository] = manifestRepo + + plan, err := PlanMirror(m, MirrorOptions{ + Destination: "mirror.example.com/atmosphere", + Layout: tc.layout, + KubernetesPrefix: tc.kubePrefix, + ManifestSource: DefaultManifestRepository + ":v7.8.1", + }) + require.NoError(t, err) + assert.Equal(t, tc.manifest, plan.ManifestReference()) + + dst := registry{} + require.NoError(t, Mirror(ctx, m, plan, RemoteSource(src.factory), RemoteSource(src.factory), dst.factory, nil)) + + resolved, err := ResolveImages(m.Images, ResolveOptions{Mirrors: plan.Rules}) + require.NoError(t, err) + assert.True(t, strings.HasPrefix(resolved["ceph"], tc.ceph+":"), resolved["ceph"]) + assert.True(t, strings.HasPrefix(resolved["kube_apiserver"], tc.kube+":v1.28.13@"), resolved["kube_apiserver"]) + assert.Empty(t, CheckResolved(m, resolved)) + + // Every resolved image points at a mirrored repository that holds + // the image with an unchanged digest. + items := map[string]MirrorItem{} + for _, item := range plan.Items { + items[item.Source.String()] = item + } + for key, value := range resolved { + ref, err := ParseReference(value) + require.NoError(t, err) + item, ok := items[m.Images[key]] + require.True(t, ok, key) + assert.Equal(t, item.Repository, ref.Repository, key) + store, ok := dst[ref.Repository] + require.True(t, ok, "%s: repository %s not mirrored", key, ref.Repository) + desc, err := store.Resolve(ctx, item.Tags[0]) + require.NoError(t, err) + assert.Equal(t, ref.Digest, desc.Digest.String(), key) + } + + // kubeadm pulls the control plane images by tag. + kube, err := ParseReference(resolved["kube_apiserver"]) + require.NoError(t, err) + _, err = dst[kube.Repository].Resolve(ctx, kube.Tag) + assert.NoError(t, err) + + // The release manifest keeps its artifact digest. + mirroredManifest, _, err := splitTarget(plan.ManifestReference()) + require.NoError(t, err) + original, err := manifestRepo.Resolve(ctx, "v7.8.1") + require.NoError(t, err) + copied, err := dst[mirroredManifest].Resolve(ctx, plan.Manifest.Tags[0]) + require.NoError(t, err) + assert.Equal(t, original.Digest, copied.Digest) + }) + } +} + +func TestPlanMirrorRegistryWithPort(t *testing.T) { + m := testManifest() + m.Images["local"] = "localhost:5000/team/tool:v1@" + digestA + + for layout, expected := range map[Layout][2]string{ + LayoutNested: {"mirror.example.com/localhost-5000/team/tool", "mirror.example.com/localhost-5000/vexxhost/atmosphere-release:v1"}, + LayoutFlat: {"mirror.example.com/localhost-5000--team--tool", "mirror.example.com/localhost-5000--vexxhost--atmosphere-release:v1"}, + } { + plan, err := PlanMirror(m, MirrorOptions{ + Destination: "mirror.example.com", + Layout: layout, + ManifestSource: "localhost:5000/vexxhost/atmosphere-release:v1", + }) + require.NoError(t, err, layout) + resolved, err := ResolveImages(m.Images, ResolveOptions{Mirrors: plan.Rules}) + require.NoError(t, err) + assert.Equal(t, expected[0]+":v1@"+digestA, resolved["local"], layout) + assert.Equal(t, expected[1], plan.ManifestReference(), layout) + } +} + +func TestPlanMirrorRequiresKubernetesPrefixForSingleRepository(t *testing.T) { + _, err := PlanMirror(testManifest(), MirrorOptions{Destination: "mirror.example.com/atmosphere", Layout: LayoutSingleRepository}) + assert.ErrorContains(t, err, "--kubernetes-prefix") +} + +func TestMirrorDetectsDigestMismatch(t *testing.T) { + ctx := context.Background() + src, m := sourceRegistry(t) + ref, err := ParseReference(m.Images["ceph"]) + require.NoError(t, err) + + // Make the source serve different content for the pinned digest, as a + // broken or tampered registry would. + store := src[ref.Repository] + pushImage(t, store, "other") + other, err := store.Resolve(ctx, "other") + require.NoError(t, err) + require.NoError(t, store.Tag(ctx, other, ref.Digest)) + + plan, err := PlanMirror(m, MirrorOptions{Destination: "mirror.example.com/atmosphere", Layout: LayoutNested}) + require.NoError(t, err) + + dst := registry{} + err = Mirror(ctx, m, plan, RemoteSource(src.factory), nil, dst.factory, nil) + assert.ErrorContains(t, err, "digest mismatch") +} + +func TestExportImport(t *testing.T) { + ctx := context.Background() + src, m := sourceRegistry(t) + manifestRepo := memory.New() + _, err := Push(ctx, manifestRepo, m, []string{"v7.8.1"}, PushOptions{}) + require.NoError(t, err) + src[DefaultManifestRepository] = manifestRepo + + extraStore, _ := src.factory("registry.k8s.io/etcd") + pushImage(t, extraStore.(*memory.Store), "3.5.15-0") + + opts := MirrorOptions{ + ManifestSource: DefaultManifestRepository + ":v7.8.1", + ExtraImages: []string{"registry.k8s.io/etcd:3.5.15-0"}, + } + dir := t.TempDir() + require.NoError(t, Export(ctx, m, opts, RemoteSource(src.factory), RemoteSource(src.factory), dir, nil)) + assert.FileExists(t, filepath.Join(dir, FileName)) + assert.FileExists(t, filepath.Join(dir, "index.json")) + + dst := registry{} + plan, err := Import(ctx, dir, MirrorOptions{Destination: "registry.internal/atmosphere", Layout: LayoutFlat}, dst.factory, nil) + require.NoError(t, err) + assert.Equal(t, "registry.internal/atmosphere/ghcr.io--vexxhost--atmosphere-release:v7.8.1", plan.ManifestReference()) + + _, err = dst["registry.internal/atmosphere/etcd"].Resolve(ctx, "3.5.15-0") + assert.NoError(t, err, "extra kubeadm image is mirrored next to the control plane images") + + mirrored, err := Load(ctx, plan.ManifestReference(), dst.factory) + require.NoError(t, err) + assert.Equal(t, m, mirrored) +} + +type flakyResolver struct { + failures int + err error + calls int +} + +func (f *flakyResolver) Resolve(_ context.Context, _ string) (digest.Digest, error) { + f.calls++ + if f.calls <= f.failures { + return "", f.err + } + return digestA, nil +} + +func TestGenerateRetriesRateLimits(t *testing.T) { + src := &Source{Release: "main", Images: map[string]string{"ceph": "quay.io/ceph/ceph:v18.2.7"}} + + flaky := &flakyResolver{failures: 2, err: fmt.Errorf("toomanyrequests: rate limit")} + m, err := Generate(context.Background(), src, flaky, GenerateOptions{Attempts: 3, Backoff: time.Millisecond}) + require.NoError(t, err) + assert.Equal(t, 3, flaky.calls) + assert.Equal(t, "quay.io/ceph/ceph:v18.2.7@"+digestA, m.Images["ceph"]) + + permanent := &flakyResolver{failures: 10, err: fmt.Errorf("manifest unknown")} + _, err = Generate(context.Background(), src, permanent, GenerateOptions{Attempts: 3, Backoff: time.Millisecond}) + assert.ErrorContains(t, err, "manifest unknown") + assert.Equal(t, 1, permanent.calls, "permanent errors are not retried") +} + +func TestSplitReferences(t *testing.T) { + repo, tags, err := SplitReferences([]string{ + "ghcr.io/vexxhost/atmosphere-release:4f2c1ab0\nghcr.io/vexxhost/atmosphere-release:stable-2025.2\n", + "", + }) + require.NoError(t, err) + assert.Equal(t, "ghcr.io/vexxhost/atmosphere-release", repo) + assert.Equal(t, []string{"4f2c1ab0", "stable-2025.2"}, tags) + + _, _, err = SplitReferences([]string{"ghcr.io/a/b:x", "ghcr.io/a/c:y"}) + assert.ErrorContains(t, err, "one repository") + + _, _, err = SplitReferences([]string{"ghcr.io/a/b@" + digestA}) + assert.ErrorContains(t, err, "not a digest") + + _, _, err = SplitReferences([]string{" "}) + assert.Error(t, err) + + _, _, err = SplitReferences([]string{"localhost:5000/a/b"}) + assert.Error(t, err) +} + +type prefixResolver struct { + digests map[string]digest.Digest + calls []string +} + +func (p *prefixResolver) Resolve(_ context.Context, reference string) (digest.Digest, error) { + p.calls = append(p.calls, reference) + if d, ok := p.digests[reference]; ok { + return d, nil + } + return "", fmt.Errorf("manifest unknown") +} + +func TestGenerateResolvePrefix(t *testing.T) { + src := &Source{Release: "main", Images: map[string]string{ + "haproxy": "docker.io/library/haproxy:2.5", + "smartctl": "packages.vexxhost.com/smartctl-exporter:0.14.0-1", + }} + resolver := &prefixResolver{digests: map[string]digest.Digest{ + "harbor.example.com/docker.io/library/haproxy:2.5": digestA, + "packages.vexxhost.com/smartctl-exporter:0.14.0-1": digestB, + }} + + m, err := Generate(context.Background(), src, resolver, GenerateOptions{ResolvePrefix: "harbor.example.com/", Attempts: 1}) + require.NoError(t, err) + // The manifest records the original references. + assert.Equal(t, "docker.io/library/haproxy:2.5@"+digestA, m.Images["haproxy"]) + // Tags the cache cannot resolve fall back to the source registry. + assert.Equal(t, "packages.vexxhost.com/smartctl-exporter:0.14.0-1@"+digestB, m.Images["smartctl"]) + assert.NotContains(t, resolver.calls, "docker.io/library/haproxy:2.5") +} + +func openAppend(path string) (*os.File, error) { + return os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644) +} diff --git a/internal/releasemanifest/resolve.go b/internal/releasemanifest/resolve.go new file mode 100644 index 00000000..9d4f8820 --- /dev/null +++ b/internal/releasemanifest/resolve.go @@ -0,0 +1,166 @@ +package releasemanifest + +import ( + "fmt" + "path" + "sort" + "strings" +) + +// MirrorRule redirects images from a source location to a mirror location. +// +// Source is a registry host ("quay.io"), a namespace ("quay.io/ceph") or a +// single repository ("quay.io/ceph/ceph"). The part of an image repository +// matching Source is replaced by Mirror; the remainder of the path, the tag +// and the digest are kept. When several rules match, the most specific +// (longest) Source wins. +type MirrorRule struct { + Source string `yaml:"source" json:"source"` + Mirror string `yaml:"mirror" json:"mirror"` +} + +// Validate checks a mirror rule. +func (r MirrorRule) Validate() error { + for name, value := range map[string]string{"source": r.Source, "mirror": r.Mirror} { + if value == "" { + return fmt.Errorf("mirror rule %s must not be empty", name) + } + if strings.HasSuffix(value, "/") || strings.ContainsAny(value, "@ ") { + return fmt.Errorf("mirror rule %s %q must be a registry, namespace or repository without a tag or digest", name, value) + } + last := value[strings.LastIndex(value, "/")+1:] + if strings.Contains(last, ":") && strings.Contains(value, "/") { + return fmt.Errorf("mirror rule %s %q must not contain a tag", name, value) + } + } + return nil +} + +func (r MirrorRule) matches(repository string) bool { + return repository == r.Source || strings.HasPrefix(repository, r.Source+"/") +} + +// ResolveOptions controls how image references are resolved for deployment. +type ResolveOptions struct { + // Prefix is atmosphere_image_prefix. It applies to images that no mirror + // rule matches. + Prefix string + // Mirrors are the atmosphere_image_mirrors rules. + Mirrors []MirrorRule + // StripPrefix is set when the input comes from the source vars file, + // where values already carry the prefix. The prefix is removed before + // matching rules, and values that no rule matches are returned + // unchanged, exactly as they were before mirror rules existed. + StripPrefix bool +} + +// ResolveImage returns the reference to deploy for a canonical image. +func ResolveImage(value string, opts ResolveOptions) (string, error) { + if opts.StripPrefix && len(opts.Mirrors) == 0 { + return value, nil + } + + canonical := value + if opts.StripPrefix { + canonical = strings.TrimPrefix(canonical, opts.Prefix) + } + + ref, err := ParseReference(canonical) + if err != nil { + return "", err + } + + var best *MirrorRule + for i := range opts.Mirrors { + rule := opts.Mirrors[i] + if err := rule.Validate(); err != nil { + return "", err + } + if rule.matches(ref.Repository) && (best == nil || len(rule.Source) > len(best.Source)) { + best = &opts.Mirrors[i] + } + } + + if best == nil { + if opts.StripPrefix { + return value, nil + } + return opts.Prefix + canonical, nil + } + + ref.Repository = best.Mirror + strings.TrimPrefix(ref.Repository, best.Source) + return ref.String(), nil +} + +// ResolveImages resolves every image in a map. +func ResolveImages(images map[string]string, opts ResolveOptions) (map[string]string, error) { + out := make(map[string]string, len(images)) + for key, value := range images { + resolved, err := ResolveImage(value, opts) + if err != nil { + return nil, fmt.Errorf("image %q: %w", key, err) + } + out[key] = resolved + } + return out, nil +} + +// kubeadmImages are the images kubeadm pulls by tag from its single image +// repository setting. They must stay together, under their original names, +// wherever they are mirrored. +var kubeadmImages = map[string]bool{ + "kube-apiserver": true, + "kube-controller-manager": true, + "kube-scheduler": true, + "kube-proxy": true, + "etcd": true, + "pause": true, + "coredns/coredns": true, +} + +// CheckResolved validates resolved references for a manifest: every value +// must parse, and the Kubernetes control plane images must share one image +// repository and keep their original names, because kubeadm derives every +// control plane image from a single repository. +func CheckResolved(m *Manifest, resolved map[string]string) []error { + var errs []error + + keys := make([]string, 0, len(resolved)) + for key := range resolved { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + if _, err := ParseReference(resolved[key]); err != nil { + errs = append(errs, fmt.Errorf("image %q resolves to an invalid reference: %w", key, err)) + } + } + + parents := map[string][]string{} + for _, key := range m.Kubernetes.Images { + original, err := ParseReference(m.Images[key]) + if err != nil { + continue + } + ref, err := ParseReference(resolved[key]) + if err != nil { + continue + } + if path.Base(ref.Repository) != path.Base(original.Repository) { + errs = append(errs, fmt.Errorf("kubernetes image %q must keep its name %q, got %q", key, path.Base(original.Repository), ref.Repository)) + continue + } + dir := path.Dir(ref.Repository) + parents[dir] = append(parents[dir], key) + } + if len(parents) > 1 { + dirs := make([]string, 0, len(parents)) + for dir, keys := range parents { + dirs = append(dirs, fmt.Sprintf("%s (%s)", dir, strings.Join(keys, ", "))) + } + sort.Strings(dirs) + errs = append(errs, fmt.Errorf("kubernetes images must share one image repository, got: %s", strings.Join(dirs, "; "))) + } + + return errs +} diff --git a/internal/releasemanifest/resolve_test.go b/internal/releasemanifest/resolve_test.go new file mode 100644 index 00000000..3a0c10f0 --- /dev/null +++ b/internal/releasemanifest/resolve_test.go @@ -0,0 +1,71 @@ +package releasemanifest + +import ( + "os" + "testing" + + "github.com/goccy/go-yaml" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type resolveCase struct { + Name string `yaml:"name"` + Prefix string `yaml:"prefix"` + StripPrefix bool `yaml:"strip_prefix"` + Mirrors []MirrorRule `yaml:"mirrors"` + Input string `yaml:"input"` + Expected string `yaml:"expected"` + Error bool `yaml:"error"` +} + +func TestResolveImageSharedCases(t *testing.T) { + data, err := os.ReadFile("testdata/resolve.yaml") + require.NoError(t, err) + + var fixture struct { + Cases []resolveCase `yaml:"cases"` + } + require.NoError(t, yaml.Unmarshal(data, &fixture)) + require.NotEmpty(t, fixture.Cases) + + for _, tc := range fixture.Cases { + t.Run(tc.Name, func(t *testing.T) { + got, err := ResolveImage(tc.Input, ResolveOptions{ + Prefix: tc.Prefix, + Mirrors: tc.Mirrors, + StripPrefix: tc.StripPrefix, + }) + if tc.Error { + assert.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tc.Expected, got) + }) + } +} + +func TestCheckResolvedKubernetesImages(t *testing.T) { + m := testManifest() + + resolved, err := ResolveImages(m.Images, ResolveOptions{Prefix: "harbor.example.com/"}) + require.NoError(t, err) + assert.Empty(t, CheckResolved(m, resolved)) + + resolved, err = ResolveImages(m.Images, ResolveOptions{Mirrors: []MirrorRule{ + {Source: "registry.k8s.io/kube-apiserver", Mirror: "registry.internal/flat--kube-apiserver"}, + }}) + require.NoError(t, err) + errs := CheckResolved(m, resolved) + require.Len(t, errs, 1) + assert.Contains(t, errs[0].Error(), "must keep its name") + + resolved, err = ResolveImages(m.Images, ResolveOptions{Mirrors: []MirrorRule{ + {Source: "registry.k8s.io/kube-apiserver", Mirror: "registry.internal/a/kube-apiserver"}, + }}) + require.NoError(t, err) + errs = CheckResolved(m, resolved) + require.Len(t, errs, 1) + assert.Contains(t, errs[0].Error(), "share one image repository") +} diff --git a/internal/releasemanifest/testdata/resolve.yaml b/internal/releasemanifest/testdata/resolve.yaml new file mode 100644 index 00000000..ee2e9776 --- /dev/null +++ b/internal/releasemanifest/testdata/resolve.yaml @@ -0,0 +1,127 @@ +# Shared test cases for image resolution. They are run by the Go tests in +# internal/releasemanifest and by the Python tests for the +# vexxhost.atmosphere.resolve_images filter, so both implementations must +# agree on every case. +cases: + - name: no prefix and no rules returns the canonical reference + input: quay.io/ceph/ceph:v18.2.7@sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0 + expected: quay.io/ceph/ceph:v18.2.7@sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0 + + - name: prefix is applied to a canonical reference + prefix: harbor.example.com/ + input: ghcr.io/vexxhost/nova:main@sha256:3095eaa3964b6b37b55d9de8681fb3d06cc247da1cd402fcdf81a7abbfc2496b + expected: harbor.example.com/ghcr.io/vexxhost/nova:main@sha256:3095eaa3964b6b37b55d9de8681fb3d06cc247da1cd402fcdf81a7abbfc2496b + + - name: prefixed source value is unchanged when only a prefix is set + prefix: harbor.example.com/ + strip_prefix: true + input: harbor.example.com/docker.io/library/haproxy:2.5 + expected: harbor.example.com/docker.io/library/haproxy:2.5 + + - name: source value without the prefix is left unchanged when no rule matches + prefix: harbor.example.com/ + strip_prefix: true + mirrors: + - source: quay.io + mirror: mirror.example.com/quay + input: docker.io/library/haproxy:2.5 + expected: docker.io/library/haproxy:2.5 + + - name: source values pass through untouched when there are no rules + prefix: harbor.example.com/ + strip_prefix: true + input: haproxy:2.5 + expected: haproxy:2.5 + + - name: prefix without a trailing slash is concatenated as-is + prefix: harbor.example.com/proxy- + strip_prefix: true + input: harbor.example.com/proxy-quay.io/prometheus/alertmanager:v0.27.0 + expected: harbor.example.com/proxy-quay.io/prometheus/alertmanager:v0.27.0 + + - name: registry rule replaces the registry host + mirrors: + - source: quay.io + mirror: harbor.example.com/quay-proxy + input: quay.io/ceph/ceph:v18.2.7@sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0 + expected: harbor.example.com/quay-proxy/ceph/ceph:v18.2.7@sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0 + + - name: rule wins over the prefix + prefix: harbor.example.com/ + mirrors: + - source: docker.io + mirror: harbor.example.com/dockerhub-proxy + input: docker.io/library/memcached:1.6.26 + expected: harbor.example.com/dockerhub-proxy/library/memcached:1.6.26 + + - name: prefix still applies to images that no rule matches + prefix: harbor.example.com/ + mirrors: + - source: docker.io + mirror: harbor.example.com/dockerhub-proxy + input: quay.io/prometheus/alertmanager:v0.27.0 + expected: harbor.example.com/quay.io/prometheus/alertmanager:v0.27.0 + + - name: rule matches a source value after the prefix is stripped + prefix: harbor.example.com/ + strip_prefix: true + mirrors: + - source: quay.io + mirror: mirror.example.com/quay + input: harbor.example.com/quay.io/ceph/ceph:v18.2.7 + expected: mirror.example.com/quay/ceph/ceph:v18.2.7 + + - name: namespace rule + mirrors: + - source: ghcr.io/vexxhost + mirror: registry.internal/atmosphere/vexxhost + input: ghcr.io/vexxhost/keystone:main@sha256:cc47ed828419329971fbebd84b766b721821616ccc9f543cb5b603dc85ecf7f1 + expected: registry.internal/atmosphere/vexxhost/keystone:main@sha256:cc47ed828419329971fbebd84b766b721821616ccc9f543cb5b603dc85ecf7f1 + + - name: most specific rule wins + mirrors: + - source: quay.io + mirror: registry.internal/atmosphere/quay.io + - source: quay.io/ceph/ceph + mirror: registry.internal/atmosphere/quay.io--ceph--ceph + input: quay.io/ceph/ceph:v18.2.7@sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0 + expected: registry.internal/atmosphere/quay.io--ceph--ceph:v18.2.7@sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0 + + - name: rules only match whole path components + mirrors: + - source: quay.io/ceph + mirror: registry.internal/ceph + input: quay.io/cephcsi/cephcsi:v3.11.0 + expected: quay.io/cephcsi/cephcsi:v3.11.0 + + - name: single repository rule keeps tag and digest + mirrors: + - source: quay.io/ceph/ceph + mirror: registry.internal/atmosphere + input: quay.io/ceph/ceph:v18.2.7@sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0 + expected: registry.internal/atmosphere:v18.2.7@sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0 + + - name: digest-only reference + mirrors: + - source: ghcr.io + mirror: registry.internal/atmosphere/ghcr.io + input: ghcr.io/carvel-dev/secretgen-controller@sha256:59ec05ce5847bfd70c8e04f08b5195e918c8f6fbb947ffc91b456494a2958fd5 + expected: registry.internal/atmosphere/ghcr.io/carvel-dev/secretgen-controller@sha256:59ec05ce5847bfd70c8e04f08b5195e918c8f6fbb947ffc91b456494a2958fd5 + + - name: registry with a port + mirrors: + - source: registry.k8s.io + mirror: localhost:5000/atmosphere/registry.k8s.io + input: registry.k8s.io/kube-apiserver:v1.28.13 + expected: localhost:5000/atmosphere/registry.k8s.io/kube-apiserver:v1.28.13 + + - name: reference without a registry is rejected + input: library/haproxy:2.5 + error: true + + - name: mirror rule with a trailing slash is rejected + mirrors: + - source: quay.io/ + mirror: registry.internal/quay.io + input: quay.io/ceph/ceph:v18.2.7 + error: true diff --git a/internal/releasemanifest/writevars.go b/internal/releasemanifest/writevars.go new file mode 100644 index 00000000..a6bba462 --- /dev/null +++ b/internal/releasemanifest/writevars.go @@ -0,0 +1,76 @@ +package releasemanifest + +import ( + "fmt" + "os" + "strings" + + "github.com/goccy/go-yaml" + "github.com/goccy/go-yaml/ast" + "github.com/goccy/go-yaml/parser" +) + +// WriteVars rewrites the image list in the defaults role vars file so that +// every image is the digest-pinned reference from the manifest, keeping the +// "{{ atmosphere_image_prefix }}" template in front of each value. +// +// Images whose tag follows the Kubernetes version are left untouched so that +// operators can still deploy a different Kubernetes version. +func WriteVars(varsPath string, m *Manifest) error { + file, err := parser.ParseFile(varsPath, parser.ParseComments) + if err != nil { + return fmt.Errorf("parsing %s: %w", varsPath, err) + } + if len(file.Docs) != 1 { + return fmt.Errorf("expected exactly one YAML document in %s", varsPath) + } + + body, ok := file.Docs[0].Body.(*ast.MappingNode) + if !ok { + return fmt.Errorf("expected a mapping at the top of %s", varsPath) + } + + var images *ast.MappingNode + for _, item := range body.Values { + key, ok := item.Key.(*ast.StringNode) + if ok && key.Value == imagesKey { + images, _ = item.Value.(*ast.MappingNode) + } + } + if images == nil { + return fmt.Errorf("%s not found in %s", imagesKey, varsPath) + } + + seen := map[string]bool{} + for _, item := range images.Values { + key := item.Key.(*ast.StringNode).Value + value, ok := item.Value.(*ast.StringNode) + if !ok { + return fmt.Errorf("image %q in %s is not a string", key, varsPath) + } + seen[key] = true + + if strings.Contains(value.Value, kubernetesVariable) { + continue + } + + pinned, ok := m.Images[key] + if !ok { + return fmt.Errorf("image %q is missing from the release manifest", key) + } + + node, err := yaml.ValueToNode("{{ " + prefixVariable + " }}" + pinned) + if err != nil { + return fmt.Errorf("image %q: %w", key, err) + } + item.Value = node + } + + for key := range m.Images { + if !seen[key] { + return fmt.Errorf("release manifest image %q is not defined in %s", key, varsPath) + } + } + + return os.WriteFile(varsPath, []byte(file.String()), 0o644) +} diff --git a/plugins/filter/resolve_images.py b/plugins/filter/resolve_images.py new file mode 100644 index 00000000..db6dda4e --- /dev/null +++ b/plugins/filter/resolve_images.py @@ -0,0 +1,77 @@ +# Copyright (c) 2026 VEXXHOST, Inc. +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +from ansible.errors import AnsibleFilterError +from ansible_collections.vexxhost.atmosphere.plugins.module_utils.release_manifest import ( + ReleaseManifestError, +) +from ansible_collections.vexxhost.atmosphere.plugins.module_utils.release_manifest import ( + resolve_images as _resolve_images, +) + +DOCUMENTATION = """ + name: resolve_images + short_description: Apply the image prefix and mirror rules to image references + version_added: 1.0.0 + description: + - Resolve canonical image references (for example from a release + manifest) to the references a deployment pulls, applying + C(atmosphere_image_mirrors) rules and C(atmosphere_image_prefix). + - The most specific rule matching an image repository wins; images that + no rule matches get the image prefix. + options: + _input: + description: Mapping of image keys to image references. + type: dict + required: true + prefix: + description: The C(atmosphere_image_prefix) value. + type: str + default: "" + mirrors: + description: The C(atmosphere_image_mirrors) rules, each with a C(source) and a C(mirror). + type: list + elements: dict + default: [] + strip_prefix: + description: + - Remove the prefix from the input first, for references that + already include it (the source image list in the defaults role). + type: bool + default: false + author: + - VEXXHOST, Inc. +""" + +EXAMPLES = """ +- name: Resolve release images for a Harbor proxy + ansible.builtin.debug: + msg: >- + {{ manifest_images | vexxhost.atmosphere.resolve_images( + prefix='harbor.example.com/', + mirrors=[{'source': 'docker.io', 'mirror': 'harbor.example.com/dockerhub-proxy'}]) }} +""" + +RETURN = """ + _value: + description: Mapping of image keys to the references to deploy. + type: dict +""" + + +def resolve_images(images, prefix="", mirrors=None, strip_prefix=False): + try: + return _resolve_images( + images, prefix=prefix, mirrors=mirrors or [], strip_prefix=strip_prefix + ) + except ReleaseManifestError as e: + raise AnsibleFilterError(str(e)) + + +class FilterModule(object): + def filters(self): + return {"resolve_images": resolve_images} diff --git a/plugins/lookup/release_manifest.py b/plugins/lookup/release_manifest.py new file mode 100644 index 00000000..d255713b --- /dev/null +++ b/plugins/lookup/release_manifest.py @@ -0,0 +1,115 @@ +# Copyright (c) 2026 VEXXHOST, Inc. +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +import os + +from ansible.errors import AnsibleLookupError +from ansible.plugins.lookup import LookupBase +from ansible_collections.vexxhost.atmosphere.plugins.module_utils.release_manifest import ( + ReleaseManifestError, + images_for_kubernetes_version, + load_manifest, + resolve_location, +) + +DOCUMENTATION = """ + name: release_manifest + short_description: Read the images of an Atmosphere release manifest + version_added: 1.0.0 + description: + - Returns the digest-pinned images of an Atmosphere release manifest, read + from a local file or downloaded from an OCI registry. + - Manifests are cached for the lifetime of the Ansible process. + options: + _terms: + description: + - Path to a release manifest file, or an OCI reference such as + C(ghcr.io/vexxhost/atmosphere-release:v7.8.1). + required: true + kubernetes_version: + description: + - The Kubernetes version being deployed. If it differs from the + version the manifest pins, the Kubernetes control plane images use + the tag for this version instead. + type: str + prefix: + description: + - The C(atmosphere_image_prefix) value. It is applied to an OCI + reference like to every image, unless a mirror rule matches it. + type: str + default: "" + mirrors: + description: The C(atmosphere_image_mirrors) rules, applied to an OCI reference. + type: list + elements: dict + default: [] + ca_file: + description: + - A CA certificate file to trust, in addition to the system + certificates, when downloading the manifest from a registry. + type: str + plain_http: + description: Use HTTP instead of HTTPS to reach the registry. + type: bool + default: false + author: + - VEXXHOST, Inc. +""" + +EXAMPLES = """ +- name: Show the images of a release + ansible.builtin.debug: + msg: "{{ query('vexxhost.atmosphere.release_manifest', 'ghcr.io/vexxhost/atmosphere-release:v7.8.1') | first }}" +""" + +RETURN = """ + _list: + description: A list with one mapping of image keys to image references. + type: list + elements: dict +""" + +_CACHE = {} + + +def _cache_key(location): + if os.path.isfile(location): + return (location, os.path.getmtime(location)) + return (location, None) + + +class LookupModule(LookupBase): + def run(self, terms, variables=None, **kwargs): + self.set_options(var_options=variables, direct=kwargs) + kubernetes_version = self.get_option("kubernetes_version") + plain_http = self.get_option("plain_http") + prefix = self.get_option("prefix") or "" + mirrors = self.get_option("mirrors") or [] + ca_file = self.get_option("ca_file") or None + + results = [] + for term in terms: + location = str(term).strip() + if not location: + raise AnsibleLookupError("a release manifest location is required") + + try: + location = resolve_location(location, prefix=prefix, mirrors=mirrors) + key = _cache_key(location) + (plain_http, ca_file) + if key not in _CACHE: + _CACHE[key] = load_manifest( + location, plain_http=plain_http, ca_file=ca_file + ) + results.append( + images_for_kubernetes_version(_CACHE[key], kubernetes_version) + ) + except ReleaseManifestError as e: + raise AnsibleLookupError("release manifest %s: %s" % (location, e)) + except (IOError, OSError) as e: + raise AnsibleLookupError("release manifest %s: %s" % (location, e)) + + return results diff --git a/plugins/module_utils/release_manifest.py b/plugins/module_utils/release_manifest.py new file mode 100644 index 00000000..eac13e7e --- /dev/null +++ b/plugins/module_utils/release_manifest.py @@ -0,0 +1,424 @@ +# Copyright (c) 2026 VEXXHOST, Inc. +# SPDX-License-Identifier: Apache-2.0 + +"""Shared logic for Atmosphere release manifests. + +The resolution rules here must match ``internal/releasemanifest`` in Go; both +implementations run the shared cases in +``internal/releasemanifest/testdata/resolve.yaml``. +""" + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +import hashlib +import json +import os +import re +import ssl +from urllib.error import HTTPError +from urllib.parse import urlencode, urljoin +from urllib.request import HTTPRedirectHandler, HTTPSHandler, Request, build_opener + +import yaml + +API_VERSION = "atmosphere.vexxhost.com/v1alpha1" +KIND = "ReleaseManifest" +ARTIFACT_TYPE = "application/vnd.vexxhost.atmosphere.release.v1" +MEDIA_TYPE = "application/vnd.vexxhost.atmosphere.release.v1+yaml" + +_PATH_COMPONENT = re.compile(r"^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*$") +_TAG = re.compile(r"^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$") +_DIGEST = re.compile(r"^sha256:[a-f0-9]{64}$") +_CHALLENGE = re.compile(r'(\w+)="([^"]*)"') + +_MANIFEST_ACCEPT = ", ".join( + [ + "application/vnd.oci.image.manifest.v1+json", + "application/vnd.oci.artifact.manifest.v1+json", + ] +) + + +class ReleaseManifestError(Exception): + pass + + +class Reference(object): + """A fully qualified image reference: host/path[:tag][@digest].""" + + def __init__(self, repository, tag="", digest=""): + self.repository = repository + self.tag = tag + self.digest = digest + + @classmethod + def parse(cls, value): + if not isinstance(value, str): + raise ReleaseManifestError("image reference %r is not a string" % (value,)) + + rest, digest = value, "" + if "@" in rest: + rest, digest = rest.split("@", 1) + if not _DIGEST.match(digest): + raise ReleaseManifestError("invalid digest in %r" % value) + + tag = "" + last_slash = rest.rfind("/") + last_colon = rest.rfind(":") + if last_colon > last_slash: + tag_start = last_colon + 1 + rest, tag = rest[:last_colon], rest[tag_start:] + if not _TAG.match(tag): + raise ReleaseManifestError("invalid tag in %r" % value) + + if last_slash < 0: + raise ReleaseManifestError( + "image %r is not fully qualified (missing registry)" % value + ) + + host, path = rest.split("/", 1) + if host != "localhost" and "." not in host and ":" not in host: + raise ReleaseManifestError( + "image %r is not fully qualified (missing registry)" % value + ) + for component in path.split("/"): + if not _PATH_COMPONENT.match(component): + raise ReleaseManifestError( + "invalid repository path component %r in %r" % (component, value) + ) + + if not tag and not digest: + raise ReleaseManifestError( + "image %r has neither a tag nor a digest" % value + ) + + return cls(rest, tag, digest) + + @property + def registry(self): + return self.repository.split("/", 1)[0] + + @property + def path(self): + return self.repository.split("/", 1)[1] + + def __str__(self): + value = self.repository + if self.tag: + value += ":" + self.tag + if self.digest: + value += "@" + self.digest + return value + + +def _validate_rule(rule): + if not isinstance(rule, dict) or set(rule) != {"source", "mirror"}: + raise ReleaseManifestError( + "mirror rules must have exactly a 'source' and a 'mirror': %r" % (rule,) + ) + for name in ("source", "mirror"): + value = rule[name] + if not isinstance(value, str) or not value: + raise ReleaseManifestError("mirror rule %s must not be empty" % name) + if value.endswith("/") or "@" in value or " " in value: + raise ReleaseManifestError( + "mirror rule %s %r must be a registry, namespace or repository without a tag or digest" + % (name, value) + ) + last = value.rsplit("/", 1)[-1] + if ":" in last and "/" in value: + raise ReleaseManifestError( + "mirror rule %s %r must not contain a tag" % (name, value) + ) + + +def resolve_image(value, prefix="", mirrors=None, strip_prefix=False): + """Return the image reference to deploy for a canonical image. + + The most specific mirror rule matching the image repository replaces the + matching part of the repository. Images that no rule matches get the + image prefix. + + With ``strip_prefix``, the input already carries the prefix (the source + image list in the defaults role): the prefix is removed before matching + rules, and values that no rule matches are returned unchanged. + """ + prefix = prefix or "" + if strip_prefix and not mirrors: + return value + + canonical = value + if strip_prefix and prefix and canonical.startswith(prefix): + canonical = canonical[len(prefix) :] # noqa: E203 + + ref = Reference.parse(canonical) + + best = None + for rule in mirrors or []: + _validate_rule(rule) + source = rule["source"] + if ref.repository == source or ref.repository.startswith(source + "/"): + if best is None or len(source) > len(best["source"]): + best = rule + + if best is None: + return value if strip_prefix else prefix + canonical + + suffix = ref.repository[len(best["source"]) :] # noqa: E203 + ref.repository = best["mirror"] + suffix + return str(ref) + + +def resolve_images(images, prefix="", mirrors=None, strip_prefix=False): + if not isinstance(images, dict): + raise ReleaseManifestError( + "images must be a mapping, got %s" % type(images).__name__ + ) + resolved = {} + for key, value in images.items(): + try: + resolved[key] = resolve_image(value, prefix, mirrors, strip_prefix) + except ReleaseManifestError as e: + raise ReleaseManifestError("image %r: %s" % (key, e)) + return resolved + + +def validate_manifest(manifest): + if not isinstance(manifest, dict): + raise ReleaseManifestError("release manifest must be a mapping") + if manifest.get("apiVersion") != API_VERSION: + raise ReleaseManifestError( + "unsupported apiVersion %r (expected %r)" + % (manifest.get("apiVersion"), API_VERSION) + ) + if manifest.get("kind") != KIND: + raise ReleaseManifestError( + "unsupported kind %r (expected %r)" % (manifest.get("kind"), KIND) + ) + images = manifest.get("images") + if not isinstance(images, dict) or not images: + raise ReleaseManifestError("release manifest contains no images") + for key, value in images.items(): + if not Reference.parse(value).digest: + raise ReleaseManifestError( + "image %r (%s) is not pinned by digest" % (key, value) + ) + return manifest + + +def images_for_kubernetes_version(manifest, kubernetes_version): + """Return the manifest images for the Kubernetes version being deployed. + + The control plane images are pinned for the default Kubernetes version. + When another version is deployed, they fall back to the tag for that + version, which is how they are referenced without a manifest. + """ + images = dict(manifest["images"]) + kubernetes = manifest.get("kubernetes") or {} + pinned_version = str(kubernetes.get("version") or "") + if not kubernetes_version or str(kubernetes_version) == pinned_version: + return images + + for key in kubernetes.get("images") or []: + ref = Reference.parse(images[key]) + images[key] = "%s:v%s" % (ref.repository, kubernetes_version) + return images + + +def _docker_auth(host, docker_config=None): + path = docker_config or os.path.join( + os.environ.get("DOCKER_CONFIG", os.path.expanduser("~/.docker")), "config.json" + ) + try: + with open(path) as f: + auths = json.load(f).get("auths", {}) + except (IOError, OSError, ValueError): + return None + for name in ( + host, + "https://" + host, + "index.docker.io" if host == "registry-1.docker.io" else None, + ): + if name and auths.get(name, {}).get("auth"): + return auths[name]["auth"] + return None + + +class _NoRedirect(HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +class _RegistryClient(object): + def __init__( + self, host, plain_http=False, timeout=30, docker_config=None, ca_file=None + ): + self.api_host = "registry-1.docker.io" if host == "docker.io" else host + self.base = "%s://%s" % ("http" if plain_http else "https", self.api_host) + self.timeout = timeout + self.basic = _docker_auth(self.api_host, docker_config) + self.authorization = None + context = ssl.create_default_context() + if ca_file: + # Trust this CA in addition to the system certificates. + context.load_verify_locations(cafile=ca_file) + self.opener = build_opener(HTTPSHandler(context=context), _NoRedirect) + + def _open(self, url, headers): + try: + return self.opener.open(Request(url, headers=headers), timeout=self.timeout) + except HTTPError as e: + return e + + def _token(self, challenge): + params = dict(_CHALLENGE.findall(challenge)) + realm = params.pop("realm", None) + if not realm: + raise ReleaseManifestError( + "registry %s returned an invalid authentication challenge" + % self.api_host + ) + headers = {"Authorization": "Basic " + self.basic} if self.basic else {} + response = self._open(realm + "?" + urlencode(params), headers) + if response.getcode() != 200: + raise ReleaseManifestError( + "authentication with %s failed (HTTP %s)" + % (self.api_host, response.getcode()) + ) + body = json.loads(response.read().decode("utf-8")) + token = body.get("token") or body.get("access_token") + if not token: + raise ReleaseManifestError( + "registry %s did not return a token" % self.api_host + ) + return "Bearer " + token + + def get(self, path, accept=None): + url = self.base + path + for _ in range(5): + headers = {"Accept": accept} if accept else {} + if self.authorization: + headers["Authorization"] = self.authorization + response = self._open(url, headers) + code = response.getcode() + + if code == 401 and not self.authorization: + challenge = response.headers.get("WWW-Authenticate", "") + if challenge.lower().startswith("bearer"): + self.authorization = self._token(challenge) + elif self.basic: + self.authorization = "Basic " + self.basic + else: + raise ReleaseManifestError( + "registry %s requires credentials" % self.api_host + ) + continue + + if code in (301, 302, 303, 307, 308): + location = urljoin(url, response.headers["Location"]) + # Blob redirects point at storage that must not receive the + # registry credentials. + redirected = self._open(location, {"Accept": accept} if accept else {}) + if redirected.getcode() != 200: + raise ReleaseManifestError( + "fetching %s failed (HTTP %s)" + % (location, redirected.getcode()) + ) + return redirected.read() + + if code != 200: + raise ReleaseManifestError("fetching %s failed (HTTP %s)" % (url, code)) + return response.read() + + raise ReleaseManifestError("too many authentication attempts for %s" % url) + + +def _split_location(location): + if "@" in location: + repository, reference = location.split("@", 1) + return repository, reference + last_slash = location.rfind("/") + last_colon = location.rfind(":") + if last_colon > last_slash: + tag_start = last_colon + 1 + return location[:last_colon], location[tag_start:] + raise ReleaseManifestError( + "%s is neither a file nor an OCI reference with a tag or digest" % location + ) + + +def _verify(data, digest): + algorithm, expected = digest.split(":", 1) + if algorithm != "sha256" or hashlib.sha256(data).hexdigest() != expected: + raise ReleaseManifestError("content does not match digest %s" % digest) + + +def fetch_manifest( + location, plain_http=False, timeout=30, docker_config=None, ca_file=None +): + """Download a release manifest published as an OCI artifact.""" + repository, reference = _split_location(location) + if "/" not in repository: + raise ReleaseManifestError( + "%s is not a fully qualified OCI reference" % location + ) + host, path = repository.split("/", 1) + client = _RegistryClient( + host, + plain_http=plain_http, + timeout=timeout, + docker_config=docker_config, + ca_file=ca_file, + ) + + raw = client.get("/v2/%s/manifests/%s" % (path, reference), accept=_MANIFEST_ACCEPT) + if reference.startswith("sha256:"): + _verify(raw, reference) + + artifact = json.loads(raw.decode("utf-8")) + if artifact.get("artifactType") != ARTIFACT_TYPE: + raise ReleaseManifestError( + "%s is not an Atmosphere release manifest (artifact type %r)" + % (location, artifact.get("artifactType")) + ) + + for layer in artifact.get("layers") or []: + if layer.get("mediaType") != MEDIA_TYPE: + continue + data = client.get("/v2/%s/blobs/%s" % (path, layer["digest"])) + _verify(data, layer["digest"]) + return validate_manifest(yaml.safe_load(data)) + + raise ReleaseManifestError( + "%s does not contain a %s layer" % (location, MEDIA_TYPE) + ) + + +def resolve_location(location, prefix="", mirrors=None): + """Return where to read a release manifest from. + + File paths are used as they are. OCI references are resolved with the + image prefix and mirror rules, like every image, so that deployments + using a registry cache or mirror also read the manifest through it. + """ + if os.path.isfile(location): + return location + return resolve_image(location, prefix=prefix, mirrors=mirrors) + + +def load_manifest( + location, plain_http=False, timeout=30, docker_config=None, ca_file=None +): + """Load a release manifest from a file or an OCI reference.""" + if os.path.isfile(location): + with open(location) as f: + return validate_manifest(yaml.safe_load(f)) + return fetch_manifest( + location, + plain_http=plain_http, + timeout=timeout, + docker_config=docker_config, + ca_file=ca_file, + ) diff --git a/releasenotes/notes/release-manifests-5ae3cc3b5b5c4cb9.yaml b/releasenotes/notes/release-manifests-5ae3cc3b5b5c4cb9.yaml new file mode 100644 index 00000000..4add050b --- /dev/null +++ b/releasenotes/notes/release-manifests-5ae3cc3b5b5c4cb9.yaml @@ -0,0 +1,58 @@ +--- +features: + - | + Every commit on ``main`` and the ``stable/*`` branches now publishes a + release manifest, a digest-pinned list of every image Atmosphere deploys, + to ``ghcr.io/vexxhost/atmosphere-release`` (tagged with the commit SHA and + the branch). Releases promote the manifest of the released commit to the + release version instead of resolving image tags again, attach it to the + GitHub release, and pin the images of the Ansible collection to the same + digests. + - | + Set ``atmosphere_release_manifest`` to a release manifest, either an OCI + reference such as ``ghcr.io/vexxhost/atmosphere-release:v7.9.0`` or a file + path, to deploy exactly the images of that manifest. OCI references are + read through ``atmosphere_image_mirrors`` and ``atmosphere_image_prefix``, + and ``atmosphere_release_manifest_ca_file`` adds a private CA to trust. + - | + The release manifest published for a merged pull request is the one Zuul + generated and deployed when testing it, found through the Zuul API with + ``atmosphere-release publish``, unless the image list changed in between. + Manifests that were not tested are annotated with + ``com.vexxhost.atmosphere.tested: "false"``. Publishing is reproducible: + the same manifest always has the same artifact digest. + - | + The new ``atmosphere_image_mirrors`` variable redirects images to other + locations. Each rule maps a ``source`` registry, namespace or repository + to a ``mirror`` location, the most specific rule wins, and + ``atmosphere_image_prefix`` still applies to images that no rule matches. + This supports registry caches whose proxy projects are not named after + the upstream registries. + - | + The new ``atmosphere-release`` command (``cmd/atmosphere-release``, + attached to every GitHub release for Linux and macOS) generates, + publishes, compares (``diff``) and checks release manifests, and mirrors + a release to another registry or, for disconnected environments, to a + directory and back. Mirroring copies complete images so their digests do + not change, verifies every digest, supports ``nested``, ``flat`` and + ``single-repo`` registry layouts and writes the + ``atmosphere_release_manifest`` and ``atmosphere_image_mirrors`` settings + for the mirror. +upgrade: + - | + Deployments that do not set the new variables are unaffected: the + resolved images, including those using ``atmosphere_image_prefix`` and + ``atmosphere_image_overrides``, are identical to previous releases. +deprecations: + - | + The ``image_manifest`` role and playbook are deprecated in favour of + ``atmosphere-release mirror`` and will be removed in a future release. + Its registry rewrite keeps only the last path component of each image, + which maps different images such as ``rook/ceph`` and ``ceph/ceph`` to + the same name. +other: + - | + The ``cmd/pinimages`` tool has been replaced by + ``atmosphere-release generate --write-vars``, which also pins images whose + tag is templated from a release variable (such as Ceph) and fails instead + of silently skipping images it cannot resolve. diff --git a/roles/defaults/README.md b/roles/defaults/README.md index 59d24fb2..16ee7fed 100644 --- a/roles/defaults/README.md +++ b/roles/defaults/README.md @@ -7,3 +7,16 @@ these defaults are always available. ## Role Variables * `atmosphere_images`: List of images which will be used for the deployment. +* `atmosphere_image_prefix`: Prefix added in front of every image reference, + for pull-through registry caches. +* `atmosphere_image_mirrors`: Rules that redirect images from a `source` + registry, namespace or repository to a `mirror` location. +* `atmosphere_image_overrides`: Images that replace individual entries of + `atmosphere_images`, used exactly as written. +* `atmosphere_release_manifest`: Release manifest to deploy the images of, + either an OCI reference or a file path. When empty, `atmosphere_images` is + used. +* `atmosphere_release_manifest_ca_file`: CA certificate to trust when + downloading `atmosphere_release_manifest` from a registry. + +See the "Container images and mirrors" deployment guide for details. diff --git a/roles/defaults/defaults/main.yml b/roles/defaults/defaults/main.yml index b2606fdc..51a3107f 100644 --- a/roles/defaults/defaults/main.yml +++ b/roles/defaults/defaults/main.yml @@ -20,6 +20,27 @@ atmosphere_ingress_cluster_issuer: atmosphere atmosphere_ingress_annotations: {} atmosphere_image_prefix: "" +# Release manifest to deploy images from: a file path, or an OCI reference +# such as "ghcr.io/vexxhost/atmosphere-release:v7.9.0". An OCI reference is +# read through atmosphere_image_mirrors and atmosphere_image_prefix, like every +# image. When empty, the images listed in this role are used. +atmosphere_release_manifest: "" + +# CA certificate file on the Ansible controller to trust, in addition to the +# system certificates, when downloading atmosphere_release_manifest from a +# registry that uses a private CA. +atmosphere_release_manifest_ca_file: "" + +# Mirror rules applied to every image. Each rule redirects images from a +# "source" (registry, namespace or repository) to a "mirror" location; the +# most specific rule wins and atmosphere_image_prefix applies to images that +# no rule matches. "atmosphere-release mirror" writes these rules. +# +# atmosphere_image_mirrors: +# - source: docker.io +# mirror: harbor.example.com/dockerhub-proxy +atmosphere_image_mirrors: [] + # Kubernetes atmosphere_kubernetes_version: "1.28.13" diff --git a/roles/defaults/vars/main.yml b/roles/defaults/vars/main.yml index 6af267ff..57a9c01e 100644 --- a/roles/defaults/vars/main.yml +++ b/roles/defaults/vars/main.yml @@ -248,7 +248,30 @@ _atmosphere_images: valkey_sentinel: "{{ atmosphere_image_prefix }}docker.io/bitnamilegacy/valkey-sentinel:8.0.2-debian-12-r4" vector: "{{ atmosphere_image_prefix }}docker.io/timberio/vector:0.38.0-debian" -atmosphere_images: '{{ _atmosphere_images | combine(atmosphere_image_overrides, recursive=True) }}' +# NOTE: Images come from the release manifest when one is configured, or from +# the list above. The mirror rules and image prefix are applied next, +# then the per-image overrides. +atmosphere_images: >- + {{ + ( + ( + query('vexxhost.atmosphere.release_manifest', atmosphere_release_manifest, + kubernetes_version=atmosphere_kubernetes_version, + prefix=atmosphere_image_prefix, mirrors=atmosphere_image_mirrors, + ca_file=atmosphere_release_manifest_ca_file) | first + | vexxhost.atmosphere.resolve_images(prefix=atmosphere_image_prefix, + mirrors=atmosphere_image_mirrors) + ) + if atmosphere_release_manifest | default('', true) | length > 0 else + ( + _atmosphere_images + | vexxhost.atmosphere.resolve_images(prefix=atmosphere_image_prefix, + mirrors=atmosphere_image_mirrors, + strip_prefix=True) + ) + ) + | combine(atmosphere_image_overrides, recursive=True) + }} _atmosphere_storage: images: diff --git a/roles/image_manifest/README.md b/roles/image_manifest/README.md index da8e6f1f..49ae8afa 100644 --- a/roles/image_manifest/README.md +++ b/roles/image_manifest/README.md @@ -1,5 +1,14 @@ # `image_manifest` +> **Warning** +> +> This role is deprecated and will be removed in a future release. Use +> `atmosphere-release mirror` instead, which copies a release without changing +> image digests, supports registries that limit nested repository paths, works +> for disconnected environments and writes the `atmosphere_image_mirrors` rules +> for your inventory. See the "Container images and mirrors" section of the +> deployment guide. + Since Atmosphere uses containers for all of its components, it is important to make sure that the images are available to the cluster. By default, all of the images are loaded by default using the `vexxhost.atmosphere.defaults` role which diff --git a/roles/image_manifest/tasks/main.yml b/roles/image_manifest/tasks/main.yml index 7cdc9b75..15fee552 100644 --- a/roles/image_manifest/tasks/main.yml +++ b/roles/image_manifest/tasks/main.yml @@ -1,3 +1,12 @@ +- name: Warn that this role is deprecated + ansible.builtin.debug: + msg: >- + DEPRECATED: the image_manifest role will be removed in a future release. + Use "atmosphere-release mirror" instead: it mirrors a release without + changing image digests, supports registries that limit nested paths and + writes the atmosphere_image_mirrors rules for your inventory. See the + "Container images and mirrors" section of the deployment guide. + - name: Check if file already exists when: image_manifest_force is false block: diff --git a/tests/unit/plugins/filter/test_resolve_images.py b/tests/unit/plugins/filter/test_resolve_images.py new file mode 100644 index 00000000..04272677 --- /dev/null +++ b/tests/unit/plugins/filter/test_resolve_images.py @@ -0,0 +1,96 @@ +# Copyright (c) 2026 VEXXHOST, Inc. +# SPDX-License-Identifier: Apache-2.0 + +import os +import re + +import pytest +import yaml +from ansible.errors import AnsibleFilterError +from ansible_collections.vexxhost.atmosphere.plugins.filter.resolve_images import ( + FilterModule, + resolve_images, +) + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")) +FIXTURE = os.path.join(ROOT, "internal", "releasemanifest", "testdata", "resolve.yaml") +VARS = os.path.join(ROOT, "roles", "defaults", "vars", "main.yml") + +with open(FIXTURE) as f: + CASES = yaml.safe_load(f)["cases"] + + +@pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) +def test_shared_cases(case): + """Run the cases shared with the Go implementation.""" + kwargs = { + "prefix": case.get("prefix", ""), + "mirrors": case.get("mirrors") or [], + "strip_prefix": case.get("strip_prefix", False), + } + if case.get("error"): + with pytest.raises(AnsibleFilterError): + resolve_images({"image": case["input"]}, **kwargs) + return + assert resolve_images({"image": case["input"]}, **kwargs) == { + "image": case["expected"] + } + + +def _source_images(prefix): + with open(VARS) as f: + images = yaml.safe_load(f)["_atmosphere_images"] + values = { + "atmosphere_image_prefix": prefix, + "atmosphere_kubernetes_version": "1.28.13", + "ceph_version": "18.2.7", + } + return { + key: re.sub(r"\{\{\s*(\w+)\s*\}\}", lambda m: values[m.group(1)], value) + for key, value in images.items() + } + + +@pytest.mark.parametrize( + "prefix", ["", "harbor.example.com/", "harbor.example.com/proxy-"] +) +def test_source_images_are_unchanged_without_rules(prefix): + """Existing prefix users get exactly the references they got before.""" + images = _source_images(prefix) + assert resolve_images(images, prefix=prefix, strip_prefix=True) == images + + +def test_source_images_resolve_with_rules(): + images = _source_images("harbor.example.com/") + resolved = resolve_images( + images, + prefix="harbor.example.com/", + mirrors=[ + {"source": "docker.io", "mirror": "harbor.example.com/dockerhub-proxy"} + ], + strip_prefix=True, + ) + assert ( + resolved["haproxy"] == "harbor.example.com/dockerhub-proxy/library/haproxy:2.5" + ) + assert resolved["ceph"] == images["ceph"] + registries = {value.split("/", 1)[0] for value in resolved.values()} + assert registries == {"harbor.example.com"} + + +@pytest.mark.parametrize( + "rule", + [ + {"source": "quay.io"}, + {"source": "quay.io", "mirror": ""}, + {"source": "quay.io/ceph/ceph:v1", "mirror": "mirror.example.com/ceph"}, + {"source": "quay.io", "mirror": "mirror.example.com", "extra": True}, + ], +) +def test_invalid_rules(rule): + with pytest.raises(AnsibleFilterError): + resolve_images({"ceph": "quay.io/ceph/ceph:v18.2.7"}, mirrors=[rule]) + + +def test_filter_is_registered(): + assert FilterModule().filters()["resolve_images"] is resolve_images diff --git a/tests/unit/plugins/lookup/test_release_manifest.py b/tests/unit/plugins/lookup/test_release_manifest.py new file mode 100644 index 00000000..26ef0f59 --- /dev/null +++ b/tests/unit/plugins/lookup/test_release_manifest.py @@ -0,0 +1,430 @@ +# Copyright (c) 2026 VEXXHOST, Inc. +# SPDX-License-Identifier: Apache-2.0 + +import hashlib +import json +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +import pytest +import yaml +from ansible.errors import AnsibleLookupError +from ansible.plugins.loader import lookup_loader +from ansible_collections.vexxhost.atmosphere.plugins.lookup import release_manifest +from ansible_collections.vexxhost.atmosphere.plugins.module_utils.release_manifest import ( + ARTIFACT_TYPE, + MEDIA_TYPE, + ReleaseManifestError, + fetch_manifest, + images_for_kubernetes_version, +) + +DIGEST_A = "sha256:1b9158ce28975f95def6a0ad459fa19f1336506074267a4b47c1bd914a00fec0" +DIGEST_B = "sha256:3095eaa3964b6b37b55d9de8681fb3d06cc247da1cd402fcdf81a7abbfc2496b" + +MANIFEST = { + "apiVersion": "atmosphere.vexxhost.com/v1alpha1", + "kind": "ReleaseManifest", + "release": "main", + "kubernetes": {"version": "1.28.13", "images": ["kube_apiserver"]}, + "images": { + "ceph": "quay.io/ceph/ceph:v18.2.7@" + DIGEST_A, + "kube_apiserver": "registry.k8s.io/kube-apiserver:v1.28.13@" + DIGEST_B, + }, +} + + +def LookupModule(): + return lookup_loader.get("vexxhost.atmosphere.release_manifest") + + +@pytest.fixture(autouse=True) +def clear_cache(): + release_manifest._CACHE.clear() + yield + release_manifest._CACHE.clear() + + +@pytest.fixture +def manifest_file(tmp_path): + path = tmp_path / "release-manifest.yaml" + path.write_text(yaml.safe_dump(MANIFEST)) + return str(path) + + +def test_lookup_from_file(manifest_file): + assert LookupModule().run([manifest_file], {}) == [MANIFEST["images"]] + + +def test_lookup_same_kubernetes_version_keeps_digest(manifest_file): + result = LookupModule().run([manifest_file], {}, kubernetes_version="1.28.13") + assert result == [MANIFEST["images"]] + + +def test_lookup_other_kubernetes_version_uses_tag(manifest_file): + [images] = LookupModule().run([manifest_file], {}, kubernetes_version="1.29.4") + assert images["kube_apiserver"] == "registry.k8s.io/kube-apiserver:v1.29.4" + assert images["ceph"] == MANIFEST["images"]["ceph"] + + +def test_kubernetes_fallback_does_not_modify_manifest(): + images_for_kubernetes_version(MANIFEST, "1.29.4") + assert MANIFEST["images"]["kube_apiserver"].endswith(DIGEST_B) + + +@pytest.mark.parametrize( + "change", + [ + {"apiVersion": "v0"}, + {"kind": "Other"}, + {"images": {}}, + {"images": {"ceph": "quay.io/ceph/ceph:v18.2.7"}}, + ], +) +def test_lookup_rejects_invalid_manifests(tmp_path, change): + path = tmp_path / "bad.yaml" + path.write_text(yaml.safe_dump(dict(MANIFEST, **change))) + with pytest.raises(AnsibleLookupError): + LookupModule().run([str(path)], {}) + + +def test_lookup_requires_location(): + with pytest.raises(AnsibleLookupError): + LookupModule().run([""], {}) + + +class FakeRegistry(object): + """A minimal OCI registry with token authentication and blob redirects.""" + + def __init__(self): + self.layer = yaml.safe_dump(MANIFEST).encode() + self.layer_digest = "sha256:" + hashlib.sha256(self.layer).hexdigest() + self.artifact = json.dumps( + { + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "artifactType": ARTIFACT_TYPE, + "config": { + "mediaType": "application/vnd.oci.empty.v1+json", + "digest": "sha256:44136fa355b3", + "size": 2, + }, + "layers": [ + { + "mediaType": MEDIA_TYPE, + "digest": self.layer_digest, + "size": len(self.layer), + } + ], + } + ).encode() + self.artifact_digest = "sha256:" + hashlib.sha256(self.artifact).hexdigest() + self.requests = [] + + registry = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _send(self, code, body=b"", headers=None): + self.send_response(code) + for key, value in (headers or {}).items(): + self.send_header(key, value) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + auth = self.headers.get("Authorization") + registry.requests.append((self.path, auth)) + port = self.server.server_address[1] + + if self.path.startswith("/token"): + return self._send(200, json.dumps({"token": "secret"}).encode()) + if self.path.startswith("/storage/"): + if auth: + return self._send( + 400, b"credentials must not be sent to storage" + ) + return self._send(200, registry.layer) + if auth != "Bearer secret": + challenge = ( + 'Bearer realm="http://127.0.0.1:%d/token",service="fake",scope="repository:x:pull"' + % port + ) + return self._send(401, headers={"WWW-Authenticate": challenge}) + if self.path in ( + "/v2/vexxhost/atmosphere-release/manifests/v7.8.1", + "/v2/vexxhost/atmosphere-release/manifests/" + + registry.artifact_digest, + ): + return self._send(200, registry.artifact) + if self.path == "/v2/vexxhost/atmosphere-release/manifests/tampered": + return self._send(200, registry.artifact + b" ") + if ( + self.path + == "/v2/vexxhost/atmosphere-release/blobs/" + registry.layer_digest + ): + return self._send(307, headers={"Location": "/storage/layer"}) + return self._send(404) + + self.server = HTTPServer(("127.0.0.1", 0), Handler) + self.host = "127.0.0.1:%d" % self.server.server_address[1] + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + + def close(self): + self.server.shutdown() + self.server.server_close() + + +@pytest.fixture +def registry(): + registry = FakeRegistry() + yield registry + registry.close() + + +def test_fetch_manifest_from_registry(registry, tmp_path): + location = registry.host + "/vexxhost/atmosphere-release:v7.8.1" + assert ( + fetch_manifest( + location, plain_http=True, docker_config=str(tmp_path / "none.json") + ) + == MANIFEST + ) + + storage = [auth for path, auth in registry.requests if path.startswith("/storage/")] + assert storage == [None] + + +def test_fetch_manifest_by_digest(registry, tmp_path): + location = ( + registry.host + "/vexxhost/atmosphere-release@" + registry.artifact_digest + ) + assert ( + fetch_manifest( + location, plain_http=True, docker_config=str(tmp_path / "none.json") + ) + == MANIFEST + ) + + tampered = registry.host + "/vexxhost/atmosphere-release@" + DIGEST_A + with pytest.raises(ReleaseManifestError): + fetch_manifest( + tampered, plain_http=True, docker_config=str(tmp_path / "none.json") + ) + + +def test_lookup_from_registry_is_cached(registry): + location = registry.host + "/vexxhost/atmosphere-release:v7.8.1" + lookup = LookupModule() + assert lookup.run([location], {}, plain_http=True) == [MANIFEST["images"]] + count = len(registry.requests) + assert lookup.run([location], {}, plain_http=True) == [MANIFEST["images"]] + assert len(registry.requests) == count + + +def test_lookup_missing_reference(registry): + with pytest.raises(AnsibleLookupError): + LookupModule().run( + [registry.host + "/vexxhost/atmosphere-release:missing"], + {}, + plain_http=True, + ) + + +def _tls_files(tmp_path): + """Create a private CA and a server certificate for 127.0.0.1.""" + import datetime + import ipaddress + + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import NameOID + + now = datetime.datetime.now(datetime.timezone.utc) + validity = (now - datetime.timedelta(minutes=5), now + datetime.timedelta(hours=1)) + + ca_key = ec.generate_private_key(ec.SECP256R1()) + ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "test CA")]) + ca = ( + x509.CertificateBuilder() + .subject_name(ca_name) + .issuer_name(ca_name) + .public_key(ca_key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(validity[0]) + .not_valid_after(validity[1]) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) + .sign(ca_key, hashes.SHA256()) + ) + + key = ec.generate_private_key(ec.SECP256R1()) + cert = ( + x509.CertificateBuilder() + .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")])) + .issuer_name(ca_name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(validity[0]) + .not_valid_after(validity[1]) + .add_extension( + x509.SubjectAlternativeName( + [x509.IPAddress(ipaddress.ip_address("127.0.0.1"))] + ), + critical=False, + ) + .sign(ca_key, hashes.SHA256()) + ) + + ca_file = tmp_path / "ca.pem" + ca_file.write_bytes(ca.public_bytes(serialization.Encoding.PEM)) + cert_file = tmp_path / "cert.pem" + cert_file.write_bytes( + cert.public_bytes(serialization.Encoding.PEM) + + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + return str(ca_file), str(cert_file) + + +class TLSRegistry(object): + """An HTTPS registry with basic authentication serving one manifest under + any repository path.""" + + def __init__(self, cert_file, username="ci", password="secret"): + import base64 + import ssl + + self.layer = yaml.safe_dump(MANIFEST).encode() + self.layer_digest = "sha256:" + hashlib.sha256(self.layer).hexdigest() + self.artifact = json.dumps( + { + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "artifactType": ARTIFACT_TYPE, + "layers": [{"mediaType": MEDIA_TYPE, "digest": self.layer_digest}], + } + ).encode() + self.paths = [] + expected = ( + "Basic " + + base64.b64encode(("%s:%s" % (username, password)).encode()).decode() + ) + registry = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _send(self, code, body=b"", headers=None): + self.send_response(code) + for key, value in (headers or {}).items(): + self.send_header(key, value) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + registry.paths.append(self.path) + if self.headers.get("Authorization") != expected: + return self._send( + 401, headers={"WWW-Authenticate": 'Basic realm="registry"'} + ) + if "/manifests/" in self.path: + return self._send(200, registry.artifact) + if self.path.endswith("/blobs/" + registry.layer_digest): + return self._send(200, registry.layer) + return self._send(404) + + self.server = HTTPServer(("127.0.0.1", 0), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(cert_file) + self.server.socket = context.wrap_socket(self.server.socket, server_side=True) + self.host = "127.0.0.1:%d" % self.server.server_address[1] + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + + def close(self): + self.server.shutdown() + self.server.server_close() + + +@pytest.fixture +def tls_registry(tmp_path, monkeypatch): + import base64 + + ca_file, cert_file = _tls_files(tmp_path) + registry = TLSRegistry(cert_file) + docker_dir = tmp_path / "docker" + docker_dir.mkdir() + (docker_dir / "config.json").write_text( + json.dumps( + { + "auths": { + registry.host: {"auth": base64.b64encode(b"ci:secret").decode()} + } + } + ) + ) + monkeypatch.setenv("DOCKER_CONFIG", str(docker_dir)) + registry.ca_file = ca_file + yield registry + registry.close() + + +def test_lookup_tls_registry_with_ca_file(tls_registry): + location = tls_registry.host + "/vexxhost/atmosphere-release:ci" + result = LookupModule().run([location], {}, ca_file=tls_registry.ca_file) + assert result == [MANIFEST["images"]] + + +def test_lookup_tls_registry_rejects_unknown_ca(tls_registry): + location = tls_registry.host + "/vexxhost/atmosphere-release:ci" + with pytest.raises(AnsibleLookupError): + LookupModule().run([location], {}) + + +def test_lookup_tls_registry_requires_credentials(tls_registry, tmp_path, monkeypatch): + monkeypatch.setenv("DOCKER_CONFIG", str(tmp_path / "missing")) + location = tls_registry.host + "/vexxhost/atmosphere-release:ci" + with pytest.raises(AnsibleLookupError): + LookupModule().run([location], {}, ca_file=tls_registry.ca_file) + + +def test_lookup_applies_prefix_to_reference(tls_registry): + LookupModule().run( + ["ghcr.io/vexxhost/atmosphere-release:v7.9.0"], + {}, + prefix=tls_registry.host + "/", + ca_file=tls_registry.ca_file, + ) + assert tls_registry.paths[-2:] == [ + "/v2/ghcr.io/vexxhost/atmosphere-release/manifests/v7.9.0", + "/v2/ghcr.io/vexxhost/atmosphere-release/blobs/" + tls_registry.layer_digest, + ] + + +def test_lookup_applies_mirror_rules_to_reference(tls_registry): + LookupModule().run( + ["ghcr.io/vexxhost/atmosphere-release:v7.9.0"], + {}, + prefix="unused.example.com/", + mirrors=[ + {"source": "ghcr.io/vexxhost", "mirror": tls_registry.host + "/mirror"} + ], + ca_file=tls_registry.ca_file, + ) + assert tls_registry.paths[-1].startswith("/v2/mirror/atmosphere-release/blobs/") + + +def test_lookup_does_not_apply_prefix_to_files(manifest_file): + result = LookupModule().run([manifest_file], {}, prefix="harbor.example.com/") + assert result == [MANIFEST["images"]]