forked from aws/amazon-ecs-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
436 lines (375 loc) · 13.8 KB
/
plugin.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
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
// Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 ecscni
import (
"context"
"encoding/json"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/aws/amazon-ecs-agent/agent/logger"
"github.com/cihub/seelog"
"github.com/containernetworking/cni/libcni"
cnitypes "github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/pkg/errors"
)
const (
currentCNISpec = "0.3.1"
// CNIVersion and CNIGitHash needs to be updated every time CNI plugin is updated
currentCNIVersion = "2018.10.0"
currentCNIGitHash = "93f4377604504bff92e7555da73b0cba732a4fbb"
)
// CNIClient defines the method of setting/cleaning up container namespace
type CNIClient interface {
// Version returns the version of the plugin
Version(string) (string, error)
// Capabilities returns the capabilities supported by a plugin
Capabilities(string) ([]string, error)
// SetupNS sets up the namespace of container
SetupNS(context.Context, *Config, time.Duration) (*current.Result, error)
// CleanupNS cleans up the container namespace
CleanupNS(context.Context, *Config, time.Duration) error
// ReleaseIPResource marks the ip available in the ipam db
ReleaseIPResource(*Config) error
}
// cniClient is the client to call plugin and setup the network
type cniClient struct {
pluginsPath string
cniVersion string
subnet string
libcni libcni.CNI
}
// NewClient creates a client of ecscni which is used to invoke the plugin
func NewClient(cfg *Config) CNIClient {
libcniConfig := &libcni.CNIConfig{
Path: []string{cfg.PluginsPath},
}
return &cniClient{
pluginsPath: cfg.PluginsPath,
cniVersion: cfg.MinSupportedCNIVersion,
subnet: ecsSubnet,
libcni: libcniConfig,
}
}
// SetupNS will set up the namespace of container, including create the bridge
// and the veth pair, move the eni to container namespace, setup the routes
func (client *cniClient) SetupNS(ctx context.Context,
cfg *Config,
timeout time.Duration) (*current.Result, error) {
derivedCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
type output struct {
result *current.Result
err error
}
response := make(chan output)
go func(response chan output) {
result, err := client.setupNS(cfg)
response <- output{
result: result,
err: err,
}
}(response)
select {
case <-derivedCtx.Done():
return nil, errors.Wrap(derivedCtx.Err(), "cni setup: container namespace setup failed")
case result := <-response:
return result.result, result.err
}
}
func (client *cniClient) setupNS(cfg *Config) (*current.Result, error) {
runtimeConfig := libcni.RuntimeConf{
ContainerID: cfg.ContainerID,
NetNS: fmt.Sprintf(netnsFormat, cfg.ContainerPID),
}
seelog.Debugf("[ECSCNI] Starting ENI (%s) setup in the the container namespace: %s", cfg.ENIID, cfg.ContainerID)
os.Setenv("ECS_CNI_LOGLEVEL", logger.GetLevel())
defer os.Unsetenv("ECS_CNI_LOGLEVEL")
// Invoke eni plugin ADD command
result, err := client.add(runtimeConfig, cfg, client.createENINetworkConfig)
if err != nil {
return nil, errors.Wrap(err, "cni setup: invoke eni plugin failed")
}
seelog.Debugf("[ECSCNI] ENI setup done: %s", result.String())
// Invoke bridge plugin ADD command
result, err = client.add(runtimeConfig, cfg, client.createBridgeNetworkConfigWithIPAM)
if err != nil {
return nil, errors.Wrap(err, "cni setup: invoke bridge plugin failed")
}
seelog.Debugf("[ECSCNI] Set up container namespace done: %s", result.String())
if _, err = result.GetAsVersion(currentCNISpec); err != nil {
seelog.Warnf("[ECSCNI] Unable to convert result to spec version %s; error: %v; result is of version: %s",
currentCNISpec, err, result.Version())
return nil, err
}
var curResult *current.Result
curResult, ok := result.(*current.Result)
if !ok {
return nil, errors.Errorf(
"cni setup: unable to convert result to expected version '%s'",
result.String())
}
return curResult, nil
}
// CleanupNS will clean up the container namespace, including remove the veth
// pair and stop the dhclient
func (client *cniClient) CleanupNS(
ctx context.Context,
cfg *Config,
timeout time.Duration) error {
derivedCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
err := make(chan error)
go func(err chan error) {
err <- client.cleanupNS(cfg)
}(err)
select {
case <-derivedCtx.Done():
return errors.Wrap(derivedCtx.Err(), "cni cleanup: container namespace cleanup failed")
case err := <-err:
return err
}
}
func (client *cniClient) cleanupNS(cfg *Config) error {
runtimeConfig := libcni.RuntimeConf{
ContainerID: cfg.ContainerID,
NetNS: fmt.Sprintf(netnsFormat, cfg.ContainerPID),
}
os.Setenv("ECS_CNI_LOGLEVEL", logger.GetLevel())
defer os.Unsetenv("ECS_CNI_LOGLEVEL")
seelog.Debugf("[ECSCNI] Starting clean up the container namespace: %s", cfg.ContainerID)
// clean up the network namespace is separate from releasing the IP from IPAM
err := client.del(runtimeConfig, cfg, client.createBridgeNetworkConfigWithoutIPAM)
if err != nil {
return errors.Wrap(err, "cni cleanup: invoke bridge plugin failed")
}
seelog.Debugf("[ECSCNI] bridge cleanup done: %s", cfg.ContainerID)
err = client.del(runtimeConfig, cfg, client.createENINetworkConfig)
if err != nil {
return errors.Wrap(err, "cni cleanup: invoke eni plugin failed")
}
seelog.Debugf("[ECSCNI] container namespace cleanup done: %s", cfg.ContainerID)
return nil
}
// ReleaseIPResource marks the ip available in the ipam db
func (client *cniClient) ReleaseIPResource(cfg *Config) error {
runtimeConfig := libcni.RuntimeConf{
ContainerID: cfg.ContainerID,
NetNS: fmt.Sprintf(netnsFormat, cfg.ContainerPID),
}
seelog.Debugf("[ECSCNI] Releasing the ip resource from ipam db, id: [%s], ip: [%v]", cfg.ID, cfg.IPAMV4Address)
os.Setenv("ECS_CNI_LOGLEVEL", logger.GetLevel())
defer os.Unsetenv("ECS_CNI_LOGLEVEL")
return client.del(runtimeConfig, cfg, client.createIPAMNetworkConfig)
}
// add invokes the ADD command of the given plugin
func (client *cniClient) add(runtimeConfig libcni.RuntimeConf,
cfg *Config,
pluginConfigFunc func(*Config) (string, *libcni.NetworkConfig, error)) (cnitypes.Result, error) {
deviceName, networkConfig, err := pluginConfigFunc(cfg)
if err != nil {
return nil, err
}
runtimeConfig.IfName = deviceName
return client.libcni.AddNetwork(networkConfig, &runtimeConfig)
}
// del invokes the DEL command of the given plugin
func (client *cniClient) del(runtimeConfig libcni.RuntimeConf,
cfg *Config,
pluginConfigFunc func(*Config) (string, *libcni.NetworkConfig, error)) error {
deviceName, networkConfig, err := pluginConfigFunc(cfg)
if err != nil {
return err
}
runtimeConfig.IfName = deviceName
return client.libcni.DelNetwork(networkConfig, &runtimeConfig)
}
// createBridgeNetworkConfigWithIPAM creates the config of bridge for ADD command, where
// bridge plugin acquires the IP and route information from IPAM
func (client *cniClient) createBridgeNetworkConfigWithIPAM(cfg *Config) (string, *libcni.NetworkConfig, error) {
// Create the bridge config first
bridgeConfig := client.createBridgeConfig(cfg)
// Create the ipam config
ipamConfig, err := client.createIPAMConfig(cfg)
if err != nil {
return "", nil, errors.Wrap(err, "createBridgeNetworkConfigWithIPAM: create ipam configuration failed")
}
bridgeConfig.IPAM = ipamConfig
networkConfig, err := client.constructNetworkConfig(bridgeConfig, ECSBridgePluginName)
if err != nil {
return "", nil, errors.Wrap(err, "createBridgeNetworkConfigWithIPAM: construct bridge and ipam network configuration failed")
}
return defaultVethName, networkConfig, nil
}
// createBridgeNetworkConfigWithoutIPAM creates the config of the bridge for removal
func (client *cniClient) createBridgeNetworkConfigWithoutIPAM(cfg *Config) (string, *libcni.NetworkConfig, error) {
networkConfig, err := client.constructNetworkConfig(client.createBridgeConfig(cfg), ECSBridgePluginName)
if err != nil {
return "", nil, errors.Wrap(err, "createBridgeNetworkConfigWithoutIPAM: construct bridge network configuration failed")
}
return defaultVethName, networkConfig, nil
}
func (client *cniClient) createBridgeConfig(cfg *Config) BridgeConfig {
bridgeName := defaultBridgeName
if len(cfg.BridgeName) != 0 {
bridgeName = cfg.BridgeName
}
bridgeConfig := BridgeConfig{
Type: ECSBridgePluginName,
CNIVersion: client.cniVersion,
BridgeName: bridgeName,
}
return bridgeConfig
}
// constructNetworkConfig takes in the config from agent and construct the configuration
// that's accepted by the libcni
func (client *cniClient) constructNetworkConfig(cfg interface{}, plugin string) (*libcni.NetworkConfig, error) {
configBytes, err := json.Marshal(cfg)
if err != nil {
seelog.Errorf("[ECSCNI] Marshal configuration for plugin %s failed, error: %v", plugin, err)
return nil, err
}
networkConfig := &libcni.NetworkConfig{
Network: &cnitypes.NetConf{
Type: plugin,
},
Bytes: configBytes,
}
return networkConfig, nil
}
func (client *cniClient) createENINetworkConfig(cfg *Config) (string, *libcni.NetworkConfig, error) {
eniConf := ENIConfig{
Type: ECSENIPluginName,
CNIVersion: client.cniVersion,
ENIID: cfg.ENIID,
IPV4Address: cfg.ENIIPV4Address,
IPV6Address: cfg.ENIIPV6Address,
MACAddress: cfg.ENIMACAddress,
BlockInstanceMetdata: cfg.BlockInstanceMetdata,
SubnetGatewayIPV4Address: cfg.SubnetGatewayIPV4Address,
}
networkConfig, err := client.constructNetworkConfig(eniConf, ECSENIPluginName)
if err != nil {
return "", nil, errors.Wrap(err, "createENINetworkConfig: construct the eni network configuration failed")
}
return defaultENIName, networkConfig, nil
}
// createIPAMNetworkConfig constructs the ipam configuration accepted by libcni
func (client *cniClient) createIPAMNetworkConfig(cfg *Config) (string, *libcni.NetworkConfig, error) {
ipamConfig, err := client.createIPAMConfig(cfg)
if err != nil {
return defaultVethName, nil, errors.Wrap(err, "createIPAMNetworkConfig: create ipam network configuration failed")
}
ipamNetworkConfig := IPAMNetworkConfig{
Name: ECSIPAMPluginName,
CNIVersion: client.cniVersion,
IPAM: ipamConfig,
}
networkConfig, err := client.constructNetworkConfig(ipamNetworkConfig, ECSIPAMPluginName)
if err != nil {
return "", nil, errors.Wrap(err, "createIPAMNetworkConfig: construct ipam network configuration failed")
}
return defaultVethName, networkConfig, nil
}
func (client *cniClient) createIPAMConfig(cfg *Config) (IPAMConfig, error) {
_, dst, err := net.ParseCIDR(TaskIAMRoleEndpoint)
if err != nil {
return IPAMConfig{}, err
}
routes := []*cnitypes.Route{
{
Dst: *dst,
},
}
for _, route := range cfg.AdditionalLocalRoutes {
seelog.Debugf("[ECSCNI] Adding an additional route for %s", route)
ipNetRoute := (net.IPNet)(route)
routes = append(routes, &cnitypes.Route{Dst: ipNetRoute})
}
ipamConfig := IPAMConfig{
Type: ECSIPAMPluginName,
CNIVersion: client.cniVersion,
IPV4Subnet: client.subnet,
IPV4Address: cfg.IPAMV4Address,
ID: cfg.ID,
IPV4Routes: routes,
}
return ipamConfig, nil
}
// Version returns the version of the plugin
func (client *cniClient) Version(name string) (string, error) {
file := filepath.Join(client.pluginsPath, name)
// Check if the plugin file exists before executing it
_, err := os.Stat(file)
if err != nil {
return "", err
}
cmd := exec.Command(file, versionCommand)
versionInfo, err := cmd.Output()
if err != nil {
return "", err
}
version := &cniPluginVersion{}
// versionInfo is of the format
// {"version":"2017.06.0","dirty":true,"gitShortHash":"226db36"}
// Unmarshal this
err = json.Unmarshal(versionInfo, version)
if err != nil {
return "", errors.Wrapf(err, "ecscni: unmarshal version from string: %s", versionInfo)
}
return version.str(), nil
}
// cniPluginVersion is used to convert the JSON output of the
// '--version' command into a string
type cniPluginVersion struct {
Version string `json:"version"`
Dirty bool `json:"dirty"`
Hash string `json:"gitShortHash"`
}
// str generates a string version of the CNI plugin version
// Example:
// {"version":"2017.06.0","dirty":true,"gitShortHash":"226db36"} => @226db36-2017.06.0
// {"version":"2017.06.0","dirty":false,"gitShortHash":"326db36"} => 326db36-2017.06.0
func (version *cniPluginVersion) str() string {
ver := ""
if version.Dirty {
ver = "@"
}
return ver + version.Hash + "-" + version.Version
}
// Capabilities returns the capabilities supported by a plugin
func (client *cniClient) Capabilities(name string) ([]string, error) {
file := filepath.Join(client.pluginsPath, name)
// Check if the plugin file exists before executing it
_, err := os.Stat(file)
if err != nil {
return nil, errors.Wrapf(err, "ecscni: unable to describe file info for '%s'", file)
}
cmd := exec.Command(file, capabilitiesCommand)
capabilitiesInfo, err := cmd.Output()
if err != nil {
return nil, errors.Wrapf(err, "ecscni: failed invoking capabilities command for '%s'", name)
}
capabilities := &struct {
Capabilities []string `json:"capabilities"`
}{}
err = json.Unmarshal(capabilitiesInfo, capabilities)
if err != nil {
return nil, errors.Wrapf(err, "ecscni: failed to unmarshal capabilities for '%s' from string: %s", name, capabilitiesInfo)
}
return capabilities.Capabilities, nil
}