|
| 1 | +package oci |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "os" |
| 6 | + |
| 7 | + containerdCompression "github.com/containerd/containerd/archive/compression" |
| 8 | + "github.com/google/go-containerregistry/pkg/name" |
| 9 | + v1 "github.com/google/go-containerregistry/pkg/v1" |
| 10 | + "github.com/google/go-containerregistry/pkg/v1/empty" |
| 11 | + "github.com/google/go-containerregistry/pkg/v1/mutate" |
| 12 | + "github.com/google/go-containerregistry/pkg/v1/tarball" |
| 13 | + "github.com/pkg/errors" |
| 14 | +) |
| 15 | + |
| 16 | +func imageFromTar(imagename, architecture, OS string, opener func() (io.ReadCloser, error)) (name.Reference, v1.Image, error) { |
| 17 | + newRef, err := name.ParseReference(imagename) |
| 18 | + if err != nil { |
| 19 | + return nil, nil, err |
| 20 | + } |
| 21 | + |
| 22 | + layer, err := tarball.LayerFromOpener(opener) |
| 23 | + if err != nil { |
| 24 | + return nil, nil, err |
| 25 | + } |
| 26 | + |
| 27 | + baseImage := empty.Image |
| 28 | + cfg, err := baseImage.ConfigFile() |
| 29 | + if err != nil { |
| 30 | + return nil, nil, err |
| 31 | + } |
| 32 | + |
| 33 | + cfg.Architecture = architecture |
| 34 | + cfg.OS = OS |
| 35 | + |
| 36 | + baseImage, err = mutate.ConfigFile(baseImage, cfg) |
| 37 | + if err != nil { |
| 38 | + return nil, nil, err |
| 39 | + } |
| 40 | + img, err := mutate.Append(baseImage, mutate.Addendum{ |
| 41 | + Layer: layer, |
| 42 | + History: v1.History{ |
| 43 | + CreatedBy: "localai", |
| 44 | + Comment: "Custom image", |
| 45 | + }, |
| 46 | + }) |
| 47 | + if err != nil { |
| 48 | + return nil, nil, err |
| 49 | + } |
| 50 | + |
| 51 | + return newRef, img, nil |
| 52 | +} |
| 53 | + |
| 54 | +// CreateTar a imagetarball from a standard tarball |
| 55 | +func CreateTar(srctar, dstimageTar, imagename, architecture, OS string) error { |
| 56 | + |
| 57 | + dstFile, err := os.Create(dstimageTar) |
| 58 | + if err != nil { |
| 59 | + return errors.Wrap(err, "Cannot create "+dstimageTar) |
| 60 | + } |
| 61 | + defer dstFile.Close() |
| 62 | + |
| 63 | + newRef, img, err := imageFromTar(imagename, architecture, OS, func() (io.ReadCloser, error) { |
| 64 | + f, err := os.Open(srctar) |
| 65 | + if err != nil { |
| 66 | + return nil, errors.Wrap(err, "Cannot open "+srctar) |
| 67 | + } |
| 68 | + decompressed, err := containerdCompression.DecompressStream(f) |
| 69 | + if err != nil { |
| 70 | + return nil, errors.Wrap(err, "Cannot open "+srctar) |
| 71 | + } |
| 72 | + |
| 73 | + return decompressed, nil |
| 74 | + }) |
| 75 | + if err != nil { |
| 76 | + return err |
| 77 | + } |
| 78 | + |
| 79 | + // NOTE: We might also stream that back to the daemon with daemon.Write(tag, img) |
| 80 | + return tarball.Write(newRef, img, dstFile) |
| 81 | + |
| 82 | +} |
0 commit comments