/
docker.go
364 lines (293 loc) · 8.76 KB
/
docker.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
363
364
/***
Copyright 2014 Cisco Systems Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package docker
import (
"os"
"os/exec"
"path"
"strconv"
"strings"
"time"
"github.com/contiv/netplugin/core"
"github.com/contiv/netplugin/crtclient"
"github.com/samalba/dockerclient"
"github.com/vishvananda/netlink"
log "github.com/Sirupsen/logrus"
)
// Config contains configuration for docker client
type Config struct {
Docker struct {
Socket string
}
}
// Docker implements crt-client interface for docker
type Docker struct {
Client *dockerclient.DockerClient
}
// Init initializes the docker client
func (d *Docker) Init(config *crtclient.Config) error {
if config == nil {
return core.Errorf("null config!")
}
cfg, ok := config.V.(*Config)
if !ok {
return core.Errorf("Invalid config type passed!")
}
if cfg.Docker.Socket == "" {
return core.Errorf("Invalid arguments. cfg: %v", config)
}
// TODO: ADD TLS support
d.Client, _ = dockerclient.NewDockerClient(cfg.Docker.Socket, nil)
return nil
}
// Deinit is a no-op
func (d *Docker) Deinit() {
}
func (d *Docker) getContPid(ctx *crtclient.ContainerEPContext) (string, error) {
contNameOrID := ctx.NewContName
if ctx.NewAttachUUID != "" {
contNameOrID = ctx.NewAttachUUID
}
contInfo, err := d.Client.InspectContainer(contNameOrID)
if err != nil {
log.Errorf("unable to get container info for '%s'. Error: %s", contNameOrID, err)
return "", core.Errorf("couldn't obtain container info")
}
// the hack below works only for running containers
if !contInfo.State.Running {
return "", core.Errorf("container not running")
}
return strconv.Itoa(contInfo.State.Pid), nil
}
func setIfNs(ifname string, pid int) error {
link, err := netlink.LinkByName(ifname)
if err != nil {
if !strings.Contains(err.Error(), "Link not found") {
log.Errorf("unable to find link %q. Error: %q", ifname, err)
return err
}
// try once more as sometimes (somehow) link creation is taking
// sometime, causing link not found error
time.Sleep(1 * time.Second)
link, err = netlink.LinkByName(ifname)
if err != nil {
log.Errorf("unable to find link %q. Error %q", ifname, err)
return err
}
}
err = netlink.LinkSetNsPid(link, pid)
if err != nil {
log.Errorf("unable to move interface '%s' to pid %d. Error: %s",
ifname, pid, err)
}
return err
}
// Note: most of the work in this function is a temporary workaround for
// what docker daemon would eventually do; in the meanwhile
// the essense of the logic is borrowed from pipework
func (d *Docker) moveIfToContainer(ctx *crtclient.ContainerEPContext) error {
contPid, err := d.getContPid(ctx)
if err != nil {
log.Errorf("error querying container name %s, uuid %s, Error: %s",
ctx.NewContName, ctx.NewAttachUUID, err)
return err
}
netnsDir := "/var/run/netns"
err = os.Mkdir(netnsDir, 0700)
if err != nil && !os.IsExist(err) {
log.Errorf("error creating '%s' directory. Error: %s", netnsDir, err)
return err
}
netnsPidFile := path.Join(netnsDir, contPid)
err = os.Remove(netnsPidFile)
if err != nil && !os.IsNotExist(err) {
log.Errorf("error removing file '%s'. Error: %s", netnsPidFile, err)
return err
}
err = nil
procNetNs := path.Join("/proc", contPid, "ns/net")
err = os.Symlink(procNetNs, netnsPidFile)
if err != nil {
log.Errorf("error creating symlink file '%s' with '%s'. Error: %s",
procNetNs, netnsPidFile, err)
return err
}
intPid, _ := strconv.Atoi(contPid)
err = setIfNs(ctx.InterfaceID, intPid)
if err != nil {
log.Errorf("error moving if '%s' into container '%s' namespace. Error: %s",
ctx.InterfaceID, ctx.NewContName, err)
return err
}
return err
}
func (d *Docker) cleanupNetns(ctx *crtclient.ContainerEPContext) error {
contPid, err := d.getContPid(ctx)
if err != nil {
return err
}
netnsPidFile := path.Join("/var/run/netns", contPid)
_, err = os.Stat(netnsPidFile)
if err != nil && os.IsExist(err) {
os.Remove(netnsPidFile)
}
return nil
}
/*
func (d *Docker) configureIfAddress(ctx *crtclient.ContainerEPContext) error {
log.Printf("configuring ip: addr -%s/%d- on if %s for container %s\n",
ctx.IPAddress, ctx.SubnetLen, ctx.InterfaceID, ctx.NewContName)
if ctx.IPAddress == "" {
return nil
}
if ctx.SubnetLen == 0 {
core.Errorf("Subnet mask unspecified \n")
}
contPid, err := d.getContPid(ctx)
if err != nil {
return err
}
intPid, err := strconv.Atoi(contPid)
if err != nil {
return err
}
contNs, err := netns.GetFromPid(intPid)
if err != nil {
log.Printf("error '%s' getting namespace for pid %s \n",
err, contPid)
return err
}
defer contNs.Close()
origNs, err := netns.Get()
if err != nil {
log.Printf("error '%s' getting orig namespace\n", err)
return err
}
defer origNs.Close()
err = netns.Set(contNs)
if err != nil {
log.Printf("error '%s' setting netns \n", err)
return err
}
defer netns.Set(origNs)
link, err := netlink.LinkByName(ctx.InterfaceID)
if err != nil {
log.Printf("error '%s' getting if '%s' information \n", err,
ctx.InterfaceID)
return err
}
addr, err := netlink.ParseAddr(ctx.IPAddress + "/" +
strconv.Itoa((int)(ctx.SubnetLen)))
if err != nil {
log.Printf("error '%s' parsing ip %s/%d \n", err,
ctx.IPAddress, ctx.SubnetLen)
return err
}
err = netlink.AddrAdd(link, addr)
if err != nil {
log.Printf("## netlink add addr failed '%s' \n", err)
return err
}
err = netlink.LinkSetUp(link)
if err != nil {
log.Printf("## netlink set link up failed '%s' \n", err)
return err
}
return err
}
*/
func (d *Docker) configureIfAddress(ctx *crtclient.ContainerEPContext) error {
log.Infof("configuring ip: addr -%s/%d- on if %s for container %s",
ctx.IPAddress, ctx.SubnetLen, ctx.InterfaceID, ctx.NewContName)
if ctx.IPAddress == "" {
return nil
}
if ctx.SubnetLen == 0 {
core.Errorf("Subnet mask unspecified \n")
}
contPid, err := d.getContPid(ctx)
if err != nil {
return err
}
out, err := exec.Command("/sbin/ip", "netns", "exec", contPid, "/sbin/ip",
"addr", "add", ctx.IPAddress+"/"+strconv.Itoa(int(ctx.SubnetLen)),
"dev", ctx.InterfaceID).CombinedOutput()
if err != nil {
log.Errorf("error configuring ip address for interface %s output = '%s'. Error: %s",
ctx.InterfaceID, out, err)
return err
}
out, err = exec.Command("/sbin/ip", "netns", "exec", contPid, "/sbin/ip",
"link", "set", ctx.InterfaceID, "up").CombinedOutput()
if err != nil {
log.Errorf("error bringing interface %s up 'out = %s'. Error: %s",
ctx.InterfaceID, out, err)
return err
}
log.Infof("successfully configured ip and brought up the interface")
return err
}
// AttachEndpoint configures the network access and policies
// before the container becomes active
func (d *Docker) AttachEndpoint(ctx *crtclient.ContainerEPContext) error {
err := d.moveIfToContainer(ctx)
if err != nil {
return err
}
err = d.configureIfAddress(ctx)
if err != nil {
return err
}
// configure policies: acl/qos for the container on the host
// cleanup intermediate things (overdoing it?)
d.cleanupNetns(ctx)
return err
}
// DetachEndpoint uninstalls the policies and configuration during container stop/remove
func (d *Docker) DetachEndpoint(ctx *crtclient.ContainerEPContext) error {
var err error
log.Debugf("Detached called for container %s with %s interface\n",
ctx.CurrContName, ctx.InterfaceID)
// no need to move the interface out of containre, etc.
// usually deletion of ep takes care of that
// TODO: unconfigure policies
return err
}
// GetContainerID returns the uuid corresponding to the container name
func (d *Docker) GetContainerID(contName string) string {
contInfo, err := d.Client.InspectContainer(contName)
if err != nil {
log.Errorf("could not get contID for container %s. Error: %s",
contName, err)
return ""
}
// the hack below works only for running containers
if !contInfo.State.Running {
return ""
}
return contInfo.Id
}
// GetContainerName returns the name corresponding to the container uuid
func (d *Docker) GetContainerName(contID string) (string, error) {
contInfo, err := d.Client.InspectContainer(contID)
if err != nil {
log.Errorf("could not get contName for container %s. Error: %s",
contID, err)
return "", err
}
// the hack below works only for running containers
if !contInfo.State.Running {
return "", core.Errorf("container id %s not running", contID)
}
return contInfo.Name, nil
}