forked from redenfire/docker-image-watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker.go
More file actions
249 lines (229 loc) · 6.52 KB
/
Copy pathdocker.go
File metadata and controls
249 lines (229 loc) · 6.52 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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"time"
)
var dockerSocket = "/var/run/docker.sock"
type dockerContainer struct {
ID string `json:"Id"`
Names []string `json:"Names"`
Image string `json:"Image"`
}
type dockerInspect struct {
ID string `json:"Id"`
Name string `json:"Name"`
Config json.RawMessage `json:"Config"`
HostConfig json.RawMessage `json:"HostConfig"`
}
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 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", 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 pullImageStream(image string, progressFn func(PullProgress)) error {
resp, err := dockerAPI("POST", "/images/create?fromImage="+image, nil)
if err != nil {
return fmt.Errorf("pull request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
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 {
break
}
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,
})
}
return nil
}
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 {
if _, after, ok := strings.Cut(d, "@"); ok {
return after, nil
}
return d, nil
}
return "", fmt.Errorf("no digest found")
}
func recreateContainer(id, image string) error {
inspect, err := inspectContainer(id)
if err != nil {
return fmt.Errorf("inspect: %w", err)
}
createBody := make(map[string]interface{})
json.Unmarshal(inspect.Config, &createBody)
createBody["Image"] = image
delete(createBody, "Hostname")
type hostCfg struct {
Binds []string `json:"Binds"`
PortBindings map[string]interface{} `json:"PortBindings"`
RestartPolicy map[string]interface{} `json:"RestartPolicy"`
NetworkMode string `json:"NetworkMode"`
Privileged bool `json:"Privileged"`
ExtraHosts []string `json:"ExtraHosts"`
DNS []string `json:"Dns"`
CapAdd []string `json:"CapAdd"`
CapDrop []string `json:"CapDrop"`
Devices []interface{} `json:"Devices"`
ShmSize int64 `json:"ShmSize"`
Sysctls map[string]string `json:"Sysctls"`
Runtime string `json:"Runtime"`
GroupAdd []string `json:"GroupAdd"`
IpcMode string `json:"IpcMode"`
PidMode string `json:"PidMode"`
UsernsMode string `json:"UsernsMode"`
UTSMode string `json:"UTSMode"`
}
var hc hostCfg
json.Unmarshal(inspect.HostConfig, &hc)
createBody["HostConfig"] = hc
if hc.NetworkMode != "" && hc.NetworkMode != "default" && hc.NetworkMode != "bridge" {
netConfig := map[string]interface{}{
"EndpointsConfig": map[string]interface{}{
hc.NetworkMode: map[string]interface{}{},
},
}
createBody["NetworkingConfig"] = netConfig
}
body, _ := json.Marshal(createBody)
// stop with 10s grace period
dockerAPI("POST", "/containers/"+id+"/stop?t=10", nil)
time.Sleep(1 * time.Second)
// inspect to confirm stopped, then remove
stopped, _ := inspectContainer(id)
if stopped != nil {
dockerAPI("DELETE", "/containers/"+id, nil)
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, _ := io.ReadAll(resp.Body)
return fmt.Errorf("create failed: %s %s", resp.Status, string(b))
}
var created struct {
ID string `json:"Id"`
}
json.NewDecoder(resp.Body).Decode(&created)
// start
dockerAPI("POST", "/containers/"+created.ID+"/start", nil)
return nil
}
func init() {
if s := os.Getenv("DOCKER_SOCK"); s != "" {
dockerSocket = s
}
}