File: util.go

package info (click to toggle)
golang-github-mudler-docker-companion 0.4.5%2Bgit20250528.7d707b9%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 184 kB
  • sloc: makefile: 31
file content (80 lines) | stat: -rw-r--r-- 2,245 bytes parent folder | download
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package api

import (
	"bufio"
	"context"
	"io"
	"os"

	archive "github.com/containerd/containerd/archive"
	dockerarchive "github.com/docker/docker/pkg/archive"
	docker "github.com/fsouza/go-dockerclient"
	layer "github.com/opencontainers/umoci/oci/layer"
	jww "github.com/spf13/jwalterweatherman"
	"github.com/urfave/cli"
)

type ExtractOpts struct {
	Source, Destination                string
	Compressed, KeepDirlinks, Rootless bool
	UnpackMode                         string
}

func ExtractLayer(opts *ExtractOpts) error {
	file, err := os.Open(opts.Source)
	if err != nil {
		return err
	}
	var r io.Reader
	r = file

	if opts.Compressed {
		decompressedArchive, err := dockerarchive.DecompressStream(bufio.NewReader(file))
		if err != nil {
			return err
		}
		defer decompressedArchive.Close()
		r = decompressedArchive
	}

	buf := bufio.NewReader(r)
	switch opts.UnpackMode {
	case "umoci": // more fixes are in there
		return layer.UnpackLayer(opts.Destination, buf, &layer.UnpackOptions{KeepDirlinks: opts.KeepDirlinks, OnDiskFormat: layer.DirRootfs{MapOptions: layer.MapOptions{Rootless: opts.Rootless}}})
	case "containerd": // more cross-compatible
		_, err := archive.Apply(context.Background(), opts.Destination, buf)
		return err
	default: // moby way
		return Untar(buf, opts.Destination, !opts.Compressed)
	}
}

// PullImage pull the specified image
func PullImage(client *docker.Client, image string) error {
	var err error
	// Pulling the image
	jww.INFO.Printf("Pulling the docker image %s\n", image)
	if err = client.PullImage(docker.PullImageOptions{Repository: image}, docker.AuthConfiguration{}); err != nil {
		jww.ERROR.Printf("error pulling %s image: %s\n", image, err)
		return err
	}

	jww.INFO.Println("Image", image, "pulled correctly")

	return nil
}

// NewDocker Creates a new instance of *docker.Client, respecting env settings
func NewDocker() (*docker.Client, error) {
	var err error
	var client *docker.Client
	if os.Getenv("DOCKER_SOCKET") != "" {
		client, err = docker.NewClient(os.Getenv("DOCKER_SOCKET"))
	} else {
		client, err = docker.NewClient("unix:///var/run/docker.sock")
	}
	if err != nil {
		return nil, cli.NewExitError("could not connect to the Docker daemon", 87)
	}
	return client, nil
}