~dricottone/moby-demo

ref: 91966fcbbd6dbf9f10806fe86145a904546a2278 moby-demo/main.go -rw-r--r-- 4.1 KiB
91966fcbDominic Ricottone Initial commit 1 year, 4 months ago
                                                                                
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package main

import (
	"bufio"
	"context"
	"path/filepath"
	"fmt"
	"io"
	"os"
	"os/signal"
	"strings"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/mount"
	"github.com/docker/docker/api/types/network"
	"github.com/docker/docker/client"
	specs "github.com/opencontainers/image-spec/specs-go/v1"
)

// Bind mounts require absolute paths for the source directory.
func makeAbsolute(rel_path string) string {
	abs_path, err := filepath.Abs(rel_path)
	if err != nil {
		panic(err)
	}
	return abs_path
}

// Create a container, start it, wait for it to stop running, and remove it.
func runContainer(cli *client.Client, ctx context.Context, args []string) {
	pullImage(cli, ctx)

	id := createContainer(cli, ctx, args)

	start_opts := types.ContainerStartOptions{
	}
	cli.ContainerStart(ctx, id, start_opts)

	watchContainer(cli, ctx, id)

	rm_opts := types.ContainerRemoveOptions{
		Force: true,
	}
	cli.ContainerRemove(ctx, id, rm_opts)
}

func createContainer(cli *client.Client, ctx context.Context, args []string) string {
	conf := container.Config{
		Image: "alpine:latest",
		Cmd: args,
	}

	con_conf := container.HostConfig{
		Mounts: []mount.Mount{
			{
				Type: mount.TypeBind,
				Source: makeAbsolute("dir1"),
				Target: "/dir1",
				ReadOnly: true,
			},
			{
				Type: mount.TypeBind,
				Source: makeAbsolute("dir2"),
				Target: "/dir2",
				ReadOnly: false,
			},
		},
	}

	net_conf := network.NetworkingConfig{
	}

	plats := specs.Platform{
		Architecture: "amd64", //"arm64"
		OS: "linux",
	}

	con, err := cli.ContainerCreate(ctx, &conf, &con_conf, &net_conf, &plats, "")
	if err != nil {
		panic(err)
	}

	return con.ID
}

// Pull an image from DockerHub. We aren't particularly concerned about the
// output so it's thrown away.
func pullImage(cli *client.Client, ctx context.Context) {
	opts := types.ImagePullOptions{
		Platform: "amd64", // "arm64"
	}

	out, err := cli.ImagePull(ctx, "alpine:latest", opts)
	if err != nil {
		panic(err)
	}
	defer out.Close()

	buf := make([]byte, 512)
	for {
		if _, err := out.Read(buf); err == io.EOF {
			break
		}
	}
}

// Watch for a container to stop running. Also handle user interrupts.
func watchContainer(cli *client.Client, ctx context.Context, id string) {
	statusC, errC := cli.ContainerWait(ctx, id, container.WaitConditionNotRunning)

	sigC := make(chan os.Signal)
	signal.Notify(sigC, os.Interrupt)

	select {
	case _ = <-sigC:
		fmt.Println("(caught SIGINT)")

	case err := <-errC:
		if err != nil {
			fmt.Println("An error occured with the docker daemon")
		}

	case status := <-statusC:
		fmt.Printf("(exited with %d)\n", status.StatusCode)
	}

	dumpContainerLogs(cli, ctx, id)

	imageRemove(cli, ctx)
}

// Print logs from a container.
func dumpContainerLogs(cli *client.Client, ctx context.Context, id string) {
	conf := types.ContainerLogsOptions{
		ShowStdout: true,
	}

	out, err := cli.ContainerLogs(ctx, id, conf)
	if err != nil {
		panic(err)
	}
	defer out.Close()

	scanner := bufio.NewScanner(out)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
}

// Remove an image.
func imageRemove(cli *client.Client, ctx context.Context) {
	opts := types.ImageRemoveOptions{
		Force: true,
	}

	id := identifyImage(cli, ctx)

	_, err := cli.ImageRemove(ctx, id, opts)
	if err != nil {
		panic(err)
	}
}

// Get the ID of an image.
func identifyImage(cli *client.Client, ctx context.Context) string {
	opts := types.ImageListOptions{}

	images, err := cli.ImageList(ctx, opts)
	if err != nil {
		panic(err)
	}

	for _, image := range images {
		for _, tag := range image.RepoTags {
			if tag == "alpine:latest" {
				return image.ID
			}
		}
	}

	return ""
}

func main() {
	// Need a client to communicate with `dockerd(8)`
	cli, err := client.NewClientWithOpts(client.FromEnv)
	if err != nil {
		panic(err)
	}

	// Need a context for execution
	ctx := context.Background()

	// A command to run in an Alpine `sh(1)`
	args := os.Args[1:]
	if len(args) == 0 {
		args = []string{"uname", "-a"}
	}
	fmt.Println(strings.Join(args, " "))

	// Run the container
	runContainer(cli, ctx, args)
}