~bigbes/ci-cacher

ref: e8e2b2f17cf11feb30d2cfc6fd306d9dab1775c4 ci-cacher/cmd/docker.go -rw-r--r-- 4.9 KiB
e8e2b2f1 — Eugene Blikh Add docs/index.html landing page; publish.yml substitutes build info 2 days 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
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 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`" + `.`,
	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 {
			return fmt.Errorf("%w: %s", ErrNotFound, key)
		}
		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)
	},
}

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")
	dockerCmd.AddCommand(dockerExistsCmd, dockerDownloadCmd, dockerUploadCmd)
	rootCmd.AddCommand(dockerCmd)
}

// 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
}