This repository has been archived by the owner on Aug 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
362 lines (313 loc) · 9.77 KB
/
client.go
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
package docker
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/http"
"strings"
"time"
)
func statusCode(statusCode, want int) error {
if statusCode != want {
return fmt.Errorf("invalid response code want=%d, got=%d",
want, statusCode)
}
return nil
}
// Client offers the possibility to communicate with dockerd.
// A local http connection is established via unix socket. This allows to
// create and delete containers and networks.
// Note: this is not a complete docker client implementation.
// Only the requirements for the simulator are covered. And it tries not to
// include docker as an external dependency in the project.
type Client struct {
http *http.Client
}
const baseAddr = "http://localhost/"
// NewClient returns a new docker client. The arguments are the path to the
// docker sock which is necessary to control dockerd.
// e.g.: c := NewClient(&logger, "/var/run/docker.sock")
func NewClient(sock string) *Client {
return &Client{
http: &http.Client{
Transport: &http.Transport{
Dial: func(proto, addr string) (conn net.Conn, err error) {
return net.Dial("unix", sock)
},
},
Timeout: time.Second * 5,
},
}
}
// Ping pings the server and returns true if the daemon responds with
// http.StatusOK and false if an error occures.
// docs.: https://docs.docker.com/engine/api/v1.36/#operation/SystemPing
func (c *Client) Ping() bool {
endpoint := fmt.Sprintf("%s/_ping", baseAddr)
r, err := c.http.Get(endpoint)
if err != nil {
return false
}
return statusCode(r.StatusCode, http.StatusOK) == nil
}
// ContainerIDByName returns the containerID for the given name. If this fails,
// an error is returned.
func (c *Client) ContainerIDByName(name string) (string, error) {
endpoint := fmt.Sprintf("%scontainers/json", baseAddr)
r, err := c.http.Get(endpoint)
if err != nil {
return "", err
}
containers := []struct {
ID string `json:"ID"`
Status string `json:"Status"`
Image string `json:"Image"`
Names []string `json:"Names"`
}{}
if err = statusCode(r.StatusCode, http.StatusOK); err != nil {
return "", err
}
if err := json.NewDecoder(r.Body).Decode(&containers); err != nil {
return "", err
}
for _, container := range containers {
for _, cn := range container.Names {
if ok := strings.Contains(cn, name); ok {
return container.ID, nil
}
}
}
return "", fmt.Errorf("can not extract containerID for %s", name)
}
// CreateContainer tries to create a container with the given name based on the
// image. If this is successful the containerID is returned. If it fails,
// an error is returend.
// cmd and exposedPorts can be used to overwrite the command to execute and
// expose ports when creating a container. Createcontainer gets only minimal set
// of options tailored to the needs of the simulator.
// Cmd should look like this: ["sleep", "3600"]
// ExposedPorts shall be so specified: ["<port>/<tcp|udp>", "<port>/<tcp|udp>"]
// Mounts e.g.: ["/var/run/docker.sock:/var/run/docker.sock"]
// All options can also be left empty. Then the defaults of the image are used.
func (c *Client) CreateContainer(name, image string, cmd, exposedPorts, mounts []string) (string, error) {
endpoint := fmt.Sprintf("%scontainers/create?name=%s", baseAddr, name)
type Mount struct {
Target string `json:"Target"`
Source string `json:"Source"`
ReadOnly bool `json:"ReadOnly"`
Type string `json:"Type"`
Consistency string `json:"Consistency"`
}
min := struct {
Name string `json:"Name"`
ExposedPorts map[string]struct{} `json:"ExposedPorts,omitempty"`
Image string `json:"Image"`
Cmd []string `json:"Cmd,omitempty"`
HostConfig struct {
Mounts []Mount `json:"Mounts,omitempty"`
PortBindings map[string]struct {
HostIP string `json:"HostIp"`
HostPort string `json:"HostPort"`
} `json:"PortBindings,omitempty"`
} `json:"HostConfig"`
}{
Name: name,
Image: image,
Cmd: cmd,
ExposedPorts: make(map[string]struct{}),
}
min.HostConfig.Mounts = make([]Mount, len(mounts))
for _, port := range exposedPorts {
min.ExposedPorts[port] = struct{}{}
}
for i, m := range mounts {
if ss := strings.Split(m, ":"); len(ss) == 2 {
min.HostConfig.Mounts[i] = Mount{
Source: ss[0],
Target: ss[1],
Type: "bind",
Consistency: "default",
}
}
}
b, err := json.Marshal(&min)
if err != nil {
return "", err
}
r, err := c.http.Post(endpoint, "application/json", bytes.NewReader(b))
if err != nil {
return "", err
}
if err := statusCode(r.StatusCode, http.StatusCreated); err != nil {
return "", err
}
res := struct {
ID string `json:"Id"`
Warnings []interface{} `json:"Warnings"`
}{}
return res.ID, json.NewDecoder(r.Body).Decode(&res)
}
// DeleteContainer remove a container by the given ContainerID. If it fails,
// an error is returend.
func (c *Client) DeleteContainer(id string) error {
endpoint := fmt.Sprintf("%scontainers/%s", baseAddr, id)
r, err := http.NewRequest("DELETE", endpoint, nil)
if err != nil {
return err
}
resp, err := c.http.Do(r)
if err != nil {
return err
}
return statusCode(resp.StatusCode, http.StatusNoContent)
}
// StartContainer by given containerID. If it fails, an error is returend.
func (c *Client) StartContainer(id string) error {
endpoint := fmt.Sprintf("%scontainers/%s/start", baseAddr, id)
r, err := c.http.Post(endpoint, "application/json", nil)
if err != nil {
return err
}
return statusCode(r.StatusCode, http.StatusNoContent)
}
// StopContainer by given containerID. If it fails, an error is returend.
func (c *Client) StopContainer(id string) error {
endpoint := fmt.Sprintf("%scontainers/%s/stop", baseAddr, id)
r, err := c.http.Post(endpoint, "application/json", nil)
if err != nil {
return err
}
return statusCode(r.StatusCode, http.StatusNoContent)
}
// NetworkIDByName returns the networkID for the given Network name.
// if this fails, an error is returned.
func (c *Client) NetworkIDByName(name string) (string, error) {
endpoint := fmt.Sprintf("%snetworks", baseAddr)
r, err := c.http.Get(endpoint)
if err != nil {
return "", err
}
if err = statusCode(r.StatusCode, http.StatusOK); err != nil {
return "", err
}
networks := []struct {
Driver string `json:"Driver"`
ID string `json:"ID"`
Name string `json:"Name"`
}{}
if err := json.NewDecoder(r.Body).Decode(&networks); err != nil {
return "", err
}
for _, n := range networks {
if ok := strings.Contains(n.Name, name); ok {
return n.ID, nil
}
}
return "", fmt.Errorf("can not extract containerID for %s", name)
}
// CreateNetwork creates a default network with the given name.
// This network uses the bridge driver and is attachable.
// After success the NetworkID is returned. If it fails, an error is returned.
func (c *Client) CreateNetwork(name string) (string, error) {
endpoint := fmt.Sprintf("%snetworks/create", baseAddr)
min := struct {
Name string `json:"Name"`
Driver string `json:"Driver"`
Attachable bool `json:"Attachable"`
}{
Name: name,
Driver: "bridge",
Attachable: true,
}
b, err := json.Marshal(&min)
if err != nil {
return "", err
}
r, err := c.http.Post(endpoint, "application/json", bytes.NewReader(b))
if err != nil {
return "", err
}
if err = statusCode(r.StatusCode, http.StatusCreated); err != nil {
return "", err
}
res := struct {
ID string `json:"Id"`
Warnings []interface{} `json:"Warnings"`
}{}
return res.ID, json.NewDecoder(r.Body).Decode(&res)
}
// DeleteNetwork by the given NetworkID. If it fails an error is returned.
func (c *Client) DeleteNetwork(id string) error {
endpoint := fmt.Sprintf("%snetworks/%s", baseAddr, id)
r, err := http.NewRequest("DELETE", endpoint, nil)
if err != nil {
return err
}
resp, err := c.http.Do(r)
if err != nil {
return err
}
return statusCode(resp.StatusCode, http.StatusNoContent)
}
// ConnectNetwork connects a container to a network. for doin this container
// and network are identified by their ID. If it fails an error is returned.
func (c *Client) ConnectNetwork(nwid string, cid string, aliases []string) error {
endpoint := fmt.Sprintf("%snetworks/%s/connect", baseAddr, nwid)
type endpointConfig struct {
Aliases []string `json:"Aliases"`
}
min := struct {
Container string `json:"Container"`
EndpointConfig *endpointConfig `json:"EndpointConfig"`
}{
Container: cid,
EndpointConfig: &endpointConfig{
Aliases: aliases,
},
}
b, err := json.Marshal(&min)
if err != nil {
return err
}
r, err := c.http.Post(endpoint, "application/json", bytes.NewReader(b))
if err != nil {
return err
}
return statusCode(r.StatusCode, http.StatusOK)
}
// DisconnectNetwork removes a container from a network. container and network
// are identified by theier ID. If it fails, an error is returned.
func (c *Client) DisconnectNetwork(nwid string, cid string) error {
endpoint := fmt.Sprintf("%snetworks/%s/disconnect", baseAddr, nwid)
min := struct {
Container string `json:"Container"`
}{
Container: cid,
}
b, err := json.Marshal(&min)
if err != nil {
return err
}
r, err := c.http.Post(endpoint, "application/json", bytes.NewReader(b))
if err != nil {
return err
}
return statusCode(r.StatusCode, http.StatusOK)
}
// Labels returns a map of all labels belonging to the given containerID
func (c *Client) Labels(containerID string) (map[string]string, error) {
r, err := c.http.Get(fmt.Sprintf("%scontainers/%s/json", baseAddr, containerID))
if err != nil {
return nil, err
}
if err = statusCode(r.StatusCode, http.StatusOK); err != nil {
return nil, err
}
inspect := struct {
Config struct {
Labels map[string]string `json:"Labels"`
} `json:"Config"`
}{}
return inspect.Config.Labels, json.NewDecoder(r.Body).Decode(&inspect)
}