|
| 1 | +/* |
| 2 | +Copyright 2025 The Crossplane Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package xpkg |
| 18 | + |
| 19 | +import ( |
| 20 | + "archive/tar" |
| 21 | + "compress/gzip" |
| 22 | + "context" |
| 23 | + "io" |
| 24 | + "os" |
| 25 | + "path/filepath" |
| 26 | + "time" |
| 27 | + |
| 28 | + "github.com/google/go-containerregistry/pkg/name" |
| 29 | + v1 "github.com/google/go-containerregistry/pkg/v1" |
| 30 | + "github.com/google/go-containerregistry/pkg/v1/daemon" |
| 31 | + "github.com/google/go-containerregistry/pkg/v1/mutate" |
| 32 | + "github.com/google/go-containerregistry/pkg/v1/remote" |
| 33 | + "github.com/google/go-containerregistry/pkg/v1/tarball" |
| 34 | + "github.com/spf13/afero" |
| 35 | + |
| 36 | + "github.com/crossplane/crossplane-runtime/pkg/errors" |
| 37 | + "github.com/crossplane/crossplane-runtime/pkg/logging" |
| 38 | + |
| 39 | + "github.com/crossplane/crossplane/internal/xpkg" |
| 40 | + "github.com/crossplane/crossplane/internal/xpkg/upbound" |
| 41 | +) |
| 42 | + |
| 43 | +const ( |
| 44 | + errMustProvideTag = "must provide package tag if fetching from registry or daemon" |
| 45 | + errInvalidTag = "package tag is not a valid reference" |
| 46 | + errFetchPackage = "failed to fetch package from remote" |
| 47 | + errGetManifest = "failed to get package image manifest from remote" |
| 48 | + errFetchLayer = "failed to fetch annotated base layer from remote" |
| 49 | + errGetUncompressed = "failed to get uncompressed contents from layer" |
| 50 | + errMultipleAnnotatedLayers = "package is invalid due to multiple annotated base layers" |
| 51 | + errOpenPackageStream = "failed to open package stream file" |
| 52 | + errCreateOutputFile = "failed to create output file" |
| 53 | + errCreateGzipWriter = "failed to create gzip writer" |
| 54 | + errExtractPackageContents = "failed to extract package contents" |
| 55 | + cacheContentExt = ".gz" |
| 56 | +) |
| 57 | + |
| 58 | +// fetchFn fetches a package from a source. |
| 59 | +type fetchFn func(context.Context, name.Reference) (v1.Image, error) |
| 60 | + |
| 61 | +// registryFetch fetches a package from the registry. |
| 62 | +func registryFetch(ctx context.Context, r name.Reference) (v1.Image, error) { |
| 63 | + return remote.Image(r, remote.WithContext(ctx)) |
| 64 | +} |
| 65 | + |
| 66 | +// daemonFetch fetches a package from the Docker daemon. |
| 67 | +func daemonFetch(ctx context.Context, r name.Reference) (v1.Image, error) { |
| 68 | + return daemon.Image(r, daemon.WithContext(ctx)) |
| 69 | +} |
| 70 | + |
| 71 | +func xpkgFetch(path string) fetchFn { |
| 72 | + return func(_ context.Context, _ name.Reference) (v1.Image, error) { |
| 73 | + return tarball.ImageFromPath(filepath.Clean(path), nil) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +// AfterApply constructs and binds context to any subcommands |
| 78 | +// that have Run() methods that receive it. |
| 79 | +func (c *extractCmd) AfterApply() error { |
| 80 | + c.fs = afero.NewOsFs() |
| 81 | + c.fetch = registryFetch |
| 82 | + if c.FromDaemon { |
| 83 | + c.fetch = daemonFetch |
| 84 | + } |
| 85 | + if c.FromXpkg { |
| 86 | + // If package is not defined, attempt to find single package in current |
| 87 | + // directory. |
| 88 | + if c.Package == "" { |
| 89 | + wd, err := os.Getwd() |
| 90 | + if err != nil { |
| 91 | + return errors.Wrap(err, errGetwd) |
| 92 | + } |
| 93 | + path, err := xpkg.FindXpkgInDir(c.fs, wd) |
| 94 | + if err != nil { |
| 95 | + return errors.Wrap(err, errFindPackageinWd) |
| 96 | + } |
| 97 | + c.Package = path |
| 98 | + } |
| 99 | + c.fetch = xpkgFetch(c.Package) |
| 100 | + } |
| 101 | + if !c.FromXpkg { |
| 102 | + if c.Package == "" { |
| 103 | + return errors.New(errMustProvideTag) |
| 104 | + } |
| 105 | + upCtx, err := upbound.NewFromFlags(c.Flags) |
| 106 | + if err != nil { |
| 107 | + return err |
| 108 | + } |
| 109 | + |
| 110 | + name, err := name.ParseReference(c.Package, name.WithDefaultRegistry(upCtx.RegistryEndpoint.Hostname())) |
| 111 | + if err != nil { |
| 112 | + return errors.Wrap(err, errInvalidTag) |
| 113 | + } |
| 114 | + c.name = name |
| 115 | + } |
| 116 | + return nil |
| 117 | +} |
| 118 | + |
| 119 | +// extractCmd extracts package contents into a Crossplane cache compatible |
| 120 | +// format. |
| 121 | +type extractCmd struct { |
| 122 | + fs afero.Fs |
| 123 | + name name.Reference |
| 124 | + fetch fetchFn |
| 125 | + |
| 126 | + Package string `arg:"" help:"Name of the package to extract. Must be a valid OCI image tag or a path if using --from-xpkg." optional:""` |
| 127 | + FromDaemon bool `help:"Indicates that the image should be fetched from the Docker daemon."` |
| 128 | + FromXpkg bool `help:"Indicates that the image should be fetched from a local xpkg. If package is not specified and only one exists in current directory it will be used."` |
| 129 | + Output string `default:"out.gz" help:"Package output file path. Extension must be .gz or will be replaced." short:"o"` |
| 130 | + |
| 131 | + // Common API configuration |
| 132 | + Flags upbound.Flags `embed:""` |
| 133 | +} |
| 134 | + |
| 135 | +// Run runs the xpkg extract cmd. |
| 136 | +func (c *extractCmd) Run(logger logging.Logger) error { //nolint:gocyclo // xpkg extract for cli |
| 137 | + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 138 | + defer cancel() |
| 139 | + |
| 140 | + // Fetch package. |
| 141 | + img, err := c.fetch(ctx, c.name) |
| 142 | + if err != nil { |
| 143 | + return errors.Wrap(err, errFetchPackage) |
| 144 | + } |
| 145 | + |
| 146 | + // Get image manifest. |
| 147 | + manifest, err := img.Manifest() |
| 148 | + if err != nil { |
| 149 | + return errors.Wrap(err, errGetManifest) |
| 150 | + } |
| 151 | + |
| 152 | + // Determine if the image is using annotated layers. |
| 153 | + var tarc io.ReadCloser |
| 154 | + foundAnnotated := false |
| 155 | + for _, l := range manifest.Layers { |
| 156 | + if a, ok := l.Annotations[xpkg.AnnotationKey]; !ok || a != xpkg.PackageAnnotation { |
| 157 | + continue |
| 158 | + } |
| 159 | + if foundAnnotated { |
| 160 | + return errors.New(errMultipleAnnotatedLayers) |
| 161 | + } |
| 162 | + foundAnnotated = true |
| 163 | + layer, err := img.LayerByDigest(l.Digest) |
| 164 | + if err != nil { |
| 165 | + return errors.Wrap(err, errFetchLayer) |
| 166 | + } |
| 167 | + tarc, err = layer.Uncompressed() |
| 168 | + if err != nil { |
| 169 | + return errors.Wrap(err, errGetUncompressed) |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + // If we still don't have content then we need to flatten image filesystem. |
| 174 | + if !foundAnnotated { |
| 175 | + tarc = mutate.Extract(img) |
| 176 | + } |
| 177 | + |
| 178 | + // The ReadCloser is an uncompressed tarball, either consisting of annotated |
| 179 | + // layer contents or flattened filesystem content. Either way, we only want |
| 180 | + // the package YAML stream. |
| 181 | + t := tar.NewReader(tarc) |
| 182 | + var size int64 |
| 183 | + for { |
| 184 | + h, err := t.Next() |
| 185 | + if err != nil { |
| 186 | + return errors.Wrap(err, errOpenPackageStream) |
| 187 | + } |
| 188 | + if h.Name == xpkg.StreamFile { |
| 189 | + size = h.Size |
| 190 | + break |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + out := xpkg.ReplaceExt(filepath.Clean(c.Output), cacheContentExt) |
| 195 | + cf, err := c.fs.Create(out) |
| 196 | + if err != nil { |
| 197 | + return errors.Wrap(err, errCreateOutputFile) |
| 198 | + } |
| 199 | + defer cf.Close() //nolint:errcheck // defer close |
| 200 | + w, err := gzip.NewWriterLevel(cf, gzip.BestSpeed) |
| 201 | + if err != nil { |
| 202 | + return errors.Wrap(err, errCreateGzipWriter) |
| 203 | + } |
| 204 | + if _, err = io.CopyN(w, t, size); err != nil { |
| 205 | + return errors.Wrap(err, errExtractPackageContents) |
| 206 | + } |
| 207 | + if err := w.Close(); err != nil { |
| 208 | + return errors.Wrap(err, errExtractPackageContents) |
| 209 | + } |
| 210 | + |
| 211 | + logger.Debug("xpkg contents extracted to %s", out) |
| 212 | + return nil |
| 213 | +} |
0 commit comments