-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdockerimage.go
44 lines (37 loc) · 1020 Bytes
/
dockerimage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main
import (
"context"
"io"
"log"
"os"
"path"
"strconv"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
)
// UnpackDockerimage unpack docker image to a tar file
func UnpackDockerImage(image string) (string, error) {
// create temp tar file to unpack
outFile := path.Join(os.TempDir(), "d2b"+strconv.Itoa(int(time.Now().Unix()))+".tar")
outf, err := os.Create(outFile)
if err != nil {
log.Fatalf("Failed to create file %s %s", outFile, err)
}
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
// create container and export
tmpContainer, err := cli.ContainerCreate(ctx, &container.Config{Image: image}, nil, nil, nil, "")
if err != nil {
log.Fatalf("fail to create container from image %s %s", image, err)
}
fe, err := cli.ContainerExport(ctx, tmpContainer.ID)
if err != nil {
return "", err
}
io.Copy(outf, fe)
return outFile, nil
}