~bigbes/ci-cacher

ref: c22d27ee9830bc6ed3152c1df526b47ef59e5315 ci-cacher/cmd/docker.go -rw-r--r-- 6.4 KiB
c22d27ee — Eugene Blikh test.yml: collapse cache_garage_image to single 'cacher docker download --pull' a day 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package cmd

import (
	"context"
	"fmt"
	"io"
	"os/exec"

	"github.com/klauspost/compress/zstd"
	"github.com/spf13/cobra"
)

var dockerCmd = &cobra.Command{
	Use:   "docker",
	Short: "Docker image cache (tar+zstd streamed to S3)",
}

var dockerExistsCmd = &cobra.Command{
	Use:   "exists <key>",
	Short: "Exit 0 if a cached docker image is present at key, 1 if missing",
	Args:  cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		cli, cfg, err := client()
		if err != nil {
			return err
		}
		key, err := resolveKey(args[0], cfg)
		if err != nil {
			return err
		}
		ok, err := cli.Exists(context.Background(), key)
		if err != nil {
			return err
		}
		fmt.Fprintln(cmd.OutOrStdout(), key)
		if !ok {
			return ErrNotFound
		}
		return nil
	},
}

var flagDockerPull bool

var dockerDownloadCmd = &cobra.Command{
	Use:   "download <key> <image:tag>",
	Short: "Pull a cached image from S3 into the local docker daemon",
	Long: `Streams s3://bucket/key through zstd-decode into ` + "`docker load`" + `.

With --pull, a cache miss falls back to ` + "`docker pull <image:tag>`" + ` then
seeds the S3 cache via ` + "`docker save`" + `. This makes a single invocation
into the full cache-or-fetch pattern callable from a CI manifest:

  cacher docker download garage/v2.3.0.tar.zst dxflrs/garage:v2.3.0 --pull`,
	Args: cobra.ExactArgs(2),
	RunE: func(cmd *cobra.Command, args []string) error {
		cli, cfg, err := client()
		if err != nil {
			return err
		}
		key, err := resolveKey(args[0], cfg)
		if err != nil {
			return err
		}
		// The <image:tag> arg is for the caller's own ergonomics + logging;
		// docker load reads the tag from the tar stream itself.
		tag := args[1]
		ctx := context.Background()
		ok, err := cli.Exists(ctx, key)
		if err != nil {
			return err
		}
		if ok {
			fmt.Fprintf(cmd.ErrOrStderr(), "Cache HIT  — %s → load %s\n", key, tag)
			body, err := cli.Get(ctx, key)
			if err != nil {
				return err
			}
			defer body.Close()
			dec, err := zstd.NewReader(body)
			if err != nil {
				return err
			}
			defer dec.Close()
			return runDockerLoad(ctx, dec)
		}
		fmt.Fprintf(cmd.ErrOrStderr(), "Cache MISS — %s\n", key)
		if !flagDockerPull {
			return fmt.Errorf("%w: %s", ErrNotFound, key)
		}
		fmt.Fprintf(cmd.ErrOrStderr(), "Pulling %s\n", tag)
		if err := runDockerPull(ctx, tag); err != nil {
			return err
		}
		// Image is now in the local daemon. Seed the S3 cache so the
		// next run hits. Treat the upload as best-effort — the pull
		// already gave us what we needed locally.
		if err := saveTagToS3(ctx, cli, key, tag); err != nil {
			fmt.Fprintf(cmd.ErrOrStderr(), "warn: seed upload failed: %v\n", err)
			return nil
		}
		fmt.Fprintf(cmd.ErrOrStderr(), "Cached  → %s\n", key)
		return nil
	},
}

var dockerUploadCmd = &cobra.Command{
	Use:   "upload <key> <image:tag>",
	Short: "Save a local docker image to the S3 cache",
	Long: `Pipes ` + "`docker save image:tag`" + ` through zstd-encode into a streamed
S3 multipart upload. No on-disk tempfile.`,
	Args: cobra.ExactArgs(2),
	RunE: func(cmd *cobra.Command, args []string) error {
		cli, cfg, err := client()
		if err != nil {
			return err
		}
		key, err := resolveKey(args[0], cfg)
		if err != nil {
			return err
		}
		tag := args[1]
		ctx := context.Background()

		if !flagForce {
			ok, err := cli.Exists(ctx, key)
			if err != nil {
				return err
			}
			if ok {
				fmt.Fprintf(cmd.ErrOrStderr(), "Skipped — %s already present (use --force)\n", key)
				return nil
			}
		}
		fmt.Fprintf(cmd.ErrOrStderr(), "Saving %s → %s\n", tag, key)
		return saveTagToS3(ctx, cli, key, tag)
	},
}

func init() {
	for _, c := range []*cobra.Command{dockerExistsCmd, dockerDownloadCmd, dockerUploadCmd} {
		addS3Flags(c)
		addKeyFlags(c)
	}
	dockerUploadCmd.Flags().BoolVar(&flagForce, "force", false, "overwrite if key already exists")
	dockerDownloadCmd.Flags().BoolVar(&flagDockerPull, "pull", false, "on cache miss, docker pull <image:tag> and seed S3")
	dockerCmd.AddCommand(dockerExistsCmd, dockerDownloadCmd, dockerUploadCmd)
	rootCmd.AddCommand(dockerCmd)
}

// runDockerPull invokes `docker pull <tag>`, surfacing daemon output as
// a single warn line per chunk so the test log isn't dominated by pull
// progress bars.
func runDockerPull(ctx context.Context, tag string) error {
	pull := exec.CommandContext(ctx, "docker", "pull", tag)
	pull.Stdout = newWarnWriter("docker pull")
	pull.Stderr = newWarnWriter("docker pull")
	if err := pull.Run(); err != nil {
		return fmt.Errorf("docker pull %s: %w", tag, err)
	}
	return nil
}

// saveTagToS3 wires `docker save` stdout → zstd encoder → io.Pipe →
// s3.Put. The encoder runs in a goroutine writing into the pipe; the
// uploader goroutine reads from the pipe. Both ends signal errors back
// through pw.CloseWithError so the upload sees a clean EOF or a wrapped
// failure.
func saveTagToS3(ctx context.Context, cli s3Putter, key, tag string) error {
	save := exec.CommandContext(ctx, "docker", "save", tag)
	saveOut, err := save.StdoutPipe()
	if err != nil {
		return err
	}
	save.Stderr = newWarnWriter("docker save")
	if err := save.Start(); err != nil {
		return fmt.Errorf("docker save: %w", err)
	}

	pr, pw := io.Pipe()
	go func() {
		zw, zerr := zstd.NewWriter(pw, zstd.WithEncoderLevel(zstd.SpeedDefault))
		if zerr != nil {
			pw.CloseWithError(zerr)
			return
		}
		if _, cerr := io.Copy(zw, saveOut); cerr != nil {
			zw.Close()
			pw.CloseWithError(cerr)
			return
		}
		if zerr := zw.Close(); zerr != nil {
			pw.CloseWithError(zerr)
			return
		}
		pw.Close()
	}()

	upErr := cli.Put(ctx, key, pr)
	waitErr := save.Wait()
	if upErr != nil {
		return upErr
	}
	if waitErr != nil {
		return fmt.Errorf("docker save: %w", waitErr)
	}
	return nil
}

// runDockerLoad pipes r (already zstd-decoded) into `docker load`.
func runDockerLoad(ctx context.Context, r io.Reader) error {
	load := exec.CommandContext(ctx, "docker", "load")
	stdin, err := load.StdinPipe()
	if err != nil {
		return err
	}
	load.Stdout = newWarnWriter("docker load")
	load.Stderr = newWarnWriter("docker load")
	if err := load.Start(); err != nil {
		return fmt.Errorf("docker load: %w", err)
	}
	_, copyErr := io.Copy(stdin, r)
	stdin.Close()
	waitErr := load.Wait()
	if copyErr != nil {
		return fmt.Errorf("docker load write: %w", copyErr)
	}
	if waitErr != nil {
		return fmt.Errorf("docker load: %w", waitErr)
	}
	return nil
}

// s3Putter is satisfied by *s3.Client; declared here so saveTagToS3 is
// testable with a fake.
type s3Putter interface {
	Put(ctx context.Context, key string, r io.Reader) error
}