|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "os" |
| 8 | + "os/exec" |
| 9 | + "path/filepath" |
| 10 | + |
| 11 | + "github.com/containers/image/image" |
| 12 | + "github.com/containers/image/pkg/blobinfocache" |
| 13 | + "github.com/containers/image/transports/alltransports" |
| 14 | + "github.com/containers/image/types" |
| 15 | + "github.com/pkg/errors" |
| 16 | +) |
| 17 | + |
| 18 | +func main() { |
| 19 | + err := ConvertImage("docker-daemon:lambda-php:latest") |
| 20 | + if err != nil { |
| 21 | + fmt.Printf("Error: %+v", err) |
| 22 | + os.Exit(1) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +func ConvertImage(name string) (retErr error) { |
| 27 | + // Get image's layer data from image name |
| 28 | + ref, err := alltransports.ParseImageName(name) |
| 29 | + if err != nil { |
| 30 | + return err |
| 31 | + } |
| 32 | + |
| 33 | + sys := &types.SystemContext{} |
| 34 | + |
| 35 | + ctx := context.Background() |
| 36 | + |
| 37 | + cache := blobinfocache.DefaultCache(sys) |
| 38 | + |
| 39 | + rawSource, err := ref.NewImageSource(ctx, sys) |
| 40 | + if err != nil { |
| 41 | + return err |
| 42 | + } |
| 43 | + |
| 44 | + src, err := image.FromSource(ctx, sys, rawSource) |
| 45 | + if err != nil { |
| 46 | + if closeErr := rawSource.Close(); closeErr != nil { |
| 47 | + return errors.Wrapf(err, " (close error: %v)", closeErr) |
| 48 | + } |
| 49 | + |
| 50 | + return err |
| 51 | + } |
| 52 | + defer func() { |
| 53 | + if err := src.Close(); err != nil { |
| 54 | + retErr = errors.Wrapf(retErr, " (close error: %v)", err) |
| 55 | + } |
| 56 | + }() |
| 57 | + |
| 58 | + layerInfos := src.LayerInfos() |
| 59 | + |
| 60 | + dir, err := os.Getwd() |
| 61 | + if err != nil { |
| 62 | + log.Fatal(err) |
| 63 | + } |
| 64 | + |
| 65 | + // Unpack each layer onto disk |
| 66 | + for _, layerInfo := range layerInfos { |
| 67 | + blobStream, _, err := rawSource.GetBlob(ctx, layerInfo, cache) |
| 68 | + if err != nil { |
| 69 | + return err |
| 70 | + } |
| 71 | + |
| 72 | + imageDir := filepath.Join(dir, "image-output", name, string(layerInfo.Digest)) |
| 73 | + |
| 74 | + if err := os.MkdirAll(imageDir, 0777); err != nil { |
| 75 | + return err |
| 76 | + } |
| 77 | + |
| 78 | + fmt.Printf("Layer %s, size %d, media type %s\n", layerInfo.Digest, layerInfo.Size, layerInfo.MediaType) |
| 79 | + fmt.Printf("Dir %s\n", imageDir) |
| 80 | + |
| 81 | + tarCmd := exec.Command("tar", "-p", "-x", "-C", imageDir) |
| 82 | + tarCmd.Stdin = blobStream |
| 83 | + if output, err := tarCmd.CombinedOutput(); err != nil { |
| 84 | + fmt.Printf("combined out:\n%s\n", string(output)) |
| 85 | + return err |
| 86 | + } |
| 87 | + |
| 88 | + blobStream.Close() |
| 89 | + } |
| 90 | + |
| 91 | + return nil |
| 92 | +} |
0 commit comments