Repository navigation
Expand file tree
/
Copy pathdocker.go
More file actions
459 lines (432 loc) · 11.8 KB
/
Copy pathdocker.go
File metadata and controls
459 lines (432 loc) · 11.8 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var dockerSocket = "/var/run/docker.sock"
type dockerContainer struct {
ID string `json:"Id"`
Names []string `json:"Names"`
Image string `json:"Image"`
ImageID string `json:"ImageID"`
Labels map[string]string `json:"Labels"`
}
type dockerInspect struct {
ID string `json:"Id"`
Name string `json:"Name"`
Config json.RawMessage `json:"Config"`
HostConfig json.RawMessage `json:"HostConfig"`
NetworkSettings json.RawMessage `json:"NetworkSettings"`
}
func dockerClient() *http.Client {
return &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", dockerSocket)
},
},
}
}
func pullStreamDockerClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
dialer := &net.Dialer{Timeout: 30 * time.Second}
return dialer.DialContext(ctx, "unix", dockerSocket)
},
ResponseHeaderTimeout: 30 * time.Second,
},
}
}
func dockerAPI(method, path string, body io.Reader) (*http.Response, error) {
client := dockerClient()
url := "http://localhost" + path
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return client.Do(req)
}
func listContainers() ([]dockerContainer, error) {
resp, err := dockerAPI("GET", "/containers/json?all=false&digests=1", nil)
if err != nil {
return nil, fmt.Errorf("list containers: %w", err)
}
defer resp.Body.Close()
var containers []dockerContainer
if err := json.NewDecoder(resp.Body).Decode(&containers); err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
return containers, nil
}
func inspectContainer(id string) (*dockerInspect, error) {
resp, err := dockerAPI("GET", "/containers/"+id+"/json", nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var inspect dockerInspect
if err := json.NewDecoder(resp.Body).Decode(&inspect); err != nil {
return nil, err
}
return &inspect, nil
}
type PullProgress struct {
Layer string `json:"layer"`
Current int64 `json:"current"`
Total int64 `json:"total"`
Percent int `json:"percent"`
Status string `json:"status"`
}
func IsRateLimitError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "429") ||
strings.Contains(msg, "toomanyrequests") ||
strings.Contains(msg, "pull rate limit") ||
strings.Contains(msg, "too many requests")
}
func registryAliases(hostname string) []string {
switch hostname {
case "registry-1.docker.io", "docker.io", "index.docker.io", "https://index.docker.io/v1/":
return []string{"https://index.docker.io/v1/", "registry-1.docker.io", "docker.io", "index.docker.io"}
default:
return []string{hostname}
}
}
func buildRegistryAuthHeader(serverAddress, auth string) (string, error) {
username, password, ok := strings.Cut(auth, ":")
if !ok || username == "" || password == "" {
return "", fmt.Errorf("invalid registry auth, expected username:password")
}
payload, err := json.Marshal(struct {
Username string `json:"username"`
Password string `json:"password"`
ServerAddress string `json:"serveraddress,omitempty"`
}{
Username: username,
Password: password,
ServerAddress: serverAddress,
})
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(payload), nil
}
func pullImageStream(image string, progressFn func(PullProgress)) error {
v := url.Values{}
v.Set("fromImage", image)
client := pullStreamDockerClient()
req, err := http.NewRequest("POST", "http://localhost/images/create?"+v.Encode(), nil)
if err != nil {
return fmt.Errorf("pull request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
auth := strings.TrimSpace(os.Getenv("DOCKER_REGISTRY_AUTH"))
if auth != "" {
registry := ""
if host, _, _, ok := parseImage(image); ok {
registry = host
}
aliases := registryAliases(registry)
header := ""
var authByRegistry map[string]string
if strings.HasPrefix(auth, "{") {
if err := json.Unmarshal([]byte(auth), &authByRegistry); err != nil {
return fmt.Errorf("registry auth: invalid JSON auth map: %w", err)
}
for _, alias := range aliases {
if creds, ok := authByRegistry[alias]; ok && strings.TrimSpace(creds) != "" {
header, err = buildRegistryAuthHeader(alias, creds)
if err != nil {
return fmt.Errorf("registry auth: %w", err)
}
break
}
}
} else {
for _, alias := range aliases {
if alias == "https://index.docker.io/v1/" {
header, err = buildRegistryAuthHeader(alias, auth)
if err != nil {
return fmt.Errorf("registry auth: %w", err)
}
break
}
}
}
if header != "" {
req.Header.Set("X-Registry-Auth", header)
}
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("pull request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read error body: %w", err)
}
return fmt.Errorf("pull failed: %s %s", resp.Status, strings.TrimSpace(string(body)))
}
dec := json.NewDecoder(resp.Body)
type layerProg struct {
current, total int64
}
layers := make(map[string]*layerProg)
for {
var evt struct {
Status string `json:"status"`
ID string `json:"id"`
ProgressDetail *struct {
Current int64 `json:"current"`
Total int64 `json:"total"`
} `json:"progressDetail"`
Error string `json:"error"`
}
if err := dec.Decode(&evt); err != nil {
if err == io.EOF {
return nil
}
return fmt.Errorf("pull stream decode: %w", err)
}
if evt.Error != "" {
return fmt.Errorf("pull error: %s", evt.Error)
}
if evt.ID == "" || evt.ProgressDetail == nil {
progressFn(PullProgress{Status: evt.Status})
continue
}
cur, tot := evt.ProgressDetail.Current, evt.ProgressDetail.Total
if tot > 0 {
layers[evt.ID] = &layerProg{current: cur, total: tot}
} else if lp, ok := layers[evt.ID]; ok {
lp.current = cur
}
var sumCur, sumTot int64
for _, lp := range layers {
sumCur += lp.current
sumTot += lp.total
}
pct := 0
if sumTot > 0 {
pct = int(sumCur * 100 / sumTot)
}
progressFn(PullProgress{
Layer: evt.ID,
Current: sumCur,
Total: sumTot,
Percent: pct,
Status: evt.Status,
})
}
}
func getLocalDigest(image string) (string, error) {
resp, err := dockerAPI("GET", "/images/"+image+"/json", nil)
if err != nil {
return "", err
}
defer resp.Body.Close()
var data struct {
RepoDigests []string `json:"RepoDigests"`
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return "", err
}
for _, d := range data.RepoDigests {
_, after, ok := strings.Cut(d, "@")
if ok {
return after, nil
}
}
return "", fmt.Errorf("no valid digest found")
}
func getImageDigest(imageID string) (string, error) {
resp, err := dockerAPI("GET", "/images/"+imageID+"/json", nil)
if err != nil {
return "", err
}
defer resp.Body.Close()
var data struct {
RepoDigests []string `json:"RepoDigests"`
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return "", err
}
for _, d := range data.RepoDigests {
_, after, ok := strings.Cut(d, "@")
if ok {
return after, nil
}
}
return "", fmt.Errorf("no digest found")
}
func localDigestMatches(imageID, imageTag, remoteDigest string) bool {
for _, ref := range []string{imageID, imageTag} {
if ref == "" {
continue
}
resp, err := dockerAPI("GET", "/images/"+ref+"/json", nil)
if err != nil {
continue
}
var data struct {
RepoDigests []string `json:"RepoDigests"`
}
json.NewDecoder(resp.Body).Decode(&data)
resp.Body.Close()
for _, d := range data.RepoDigests {
_, after, ok := strings.Cut(d, "@")
if ok && after == remoteDigest {
return true
}
}
}
return false
}
func resolveImageName(imageID string) string {
resp, err := dockerAPI("GET", "/images/"+imageID+"/json", nil)
if err != nil {
return ""
}
defer resp.Body.Close()
var data struct {
RepoTags []string `json:"RepoTags"`
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return ""
}
for _, tag := range data.RepoTags {
if tag != "<none>:<none>" {
return tag
}
}
return ""
}
func recreateContainer(id, image string) error {
inspect, err := inspectContainer(id)
if err != nil {
return fmt.Errorf("inspect: %w", err)
}
createBody := make(map[string]interface{})
if err := json.Unmarshal(inspect.Config, &createBody); err != nil {
return fmt.Errorf("unmarshal container config: %w", err)
}
createBody["Image"] = image
delete(createBody, "Hostname")
var hostConfig map[string]interface{}
if err := json.Unmarshal(inspect.HostConfig, &hostConfig); err != nil {
return fmt.Errorf("unmarshal host config: %w", err)
}
createBody["HostConfig"] = hostConfig
if inspect.NetworkSettings != nil {
var netSettings struct {
Networks map[string]map[string]interface{} `json:"Networks"`
}
if err := json.Unmarshal(inspect.NetworkSettings, &netSettings); err == nil && len(netSettings.Networks) > 0 {
endpoints := make(map[string]interface{}, len(netSettings.Networks))
for netName, netData := range netSettings.Networks {
ep := map[string]interface{}{}
for _, k := range []string{"IPAMConfig", "Aliases", "Links", "DriverOpts"} {
if v, ok := netData[k]; ok {
ep[k] = v
}
}
endpoints[netName] = ep
}
createBody["NetworkingConfig"] = map[string]interface{}{
"EndpointsConfig": endpoints,
}
}
}
body, err := json.Marshal(createBody)
if err != nil {
return fmt.Errorf("marshal create body: %w", err)
}
// stop with 10s grace period (best effort — container may already be stopped)
resp, err := dockerAPI("POST", "/containers/"+id+"/stop?t=10", nil)
if resp != nil {
resp.Body.Close()
}
if err != nil {
return fmt.Errorf("stop container %s: %w", id, err)
}
time.Sleep(1 * time.Second)
// inspect to confirm stopped, then remove
stopped, err := inspectContainer(id)
if err != nil {
return fmt.Errorf("inspect after stop %s: %w", id, err)
}
if stopped != nil {
resp, err = dockerAPI("DELETE", "/containers/"+id, nil)
if resp != nil {
resp.Body.Close()
}
if err != nil {
return fmt.Errorf("remove container %s: %w", id, err)
}
time.Sleep(500 * time.Millisecond)
}
// create
resp, err = dockerAPI("POST", "/containers/create?name="+strings.TrimPrefix(inspect.Name, "/"), bytes.NewReader(body))
if err != nil {
return fmt.Errorf("create: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
b, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read create error body: %w", err)
}
return fmt.Errorf("create failed: %s %s", resp.Status, string(b))
}
var created struct {
ID string `json:"Id"`
}
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
return fmt.Errorf("decode create response: %w", err)
}
// start
resp, err = dockerAPI("POST", "/containers/"+created.ID+"/start", nil)
if resp != nil {
resp.Body.Close()
}
if err != nil {
return fmt.Errorf("start container %s: %w", created.ID, err)
}
if resp != nil && resp.StatusCode >= 400 {
return fmt.Errorf("start container %s: daemon returned %s", created.ID, resp.Status)
}
return nil
}
func pruneUnusedImages() {
resp, err := dockerAPI("POST", "/images/prune?filters="+url.QueryEscape(`{"dangling":{"true":true}}`), nil)
if resp != nil {
resp.Body.Close()
}
if err != nil {
log.Printf("prune images: %v", err)
}
}
func init() {
if s := os.Getenv("DOCKER_SOCK"); s != "" {
dockerSocket = s
}
}