forked from projectcalico/cni-plugin
/
utils.go
601 lines (517 loc) · 15.9 KB
/
utils.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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
// Copyright (c) 2015-2019 Tigera, 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 testutils
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net"
"os"
"os/exec"
"path"
"strings"
"syscall"
"github.com/containernetworking/cni/pkg/invoke"
"github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
"github.com/mcuadros/go-version"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega/gexec"
"github.com/projectcalico/libcalico-go/lib/apiconfig"
api "github.com/projectcalico/libcalico-go/lib/apis/v3"
"github.com/projectcalico/libcalico-go/lib/backend"
k8sconversion "github.com/projectcalico/libcalico-go/lib/backend/k8s/conversion"
client "github.com/projectcalico/libcalico-go/lib/clientv3"
"github.com/projectcalico/libcalico-go/lib/names"
"github.com/projectcalico/libcalico-go/lib/options"
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
log "github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
)
const K8S_TEST_NS = "test"
const TEST_DEFAULT_NS = "default"
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Delete everything under /calico from etcd.
func WipeDatastore() {
spec := apiconfig.CalicoAPIConfig{
Spec: apiconfig.CalicoAPIConfigSpec{
EtcdConfig: apiconfig.EtcdConfig{
EtcdEndpoints: os.Getenv("ETCD_ENDPOINTS"),
},
KubeConfig: apiconfig.KubeConfig{
K8sAPIEndpoint: os.Getenv("K8S_API_ENDPOINT"),
},
},
}
if os.Getenv("DATASTORE_TYPE") == "etcdv3" {
spec.Spec.DatastoreType = apiconfig.EtcdV3
} else {
spec.Spec.DatastoreType = apiconfig.Kubernetes
}
be, err := backend.NewClient(spec)
if err != nil {
panic(err)
}
_ = be.Clean()
// Set the ready flag so calls to the CNI plugin can proceed
calicoClient, _ := client.NewFromEnv()
newClusterInfo := api.NewClusterInformation()
newClusterInfo.Name = "default"
datastoreReady := true
newClusterInfo.Spec.DatastoreReady = &datastoreReady
ci, err := calicoClient.ClusterInformation().Create(context.Background(), newClusterInfo, options.SetOptions{})
if err != nil {
panic(err)
}
log.Printf("Set ClusterInformation: %v %v\n", ci, *ci.Spec.DatastoreReady)
}
// MustCreateNewIPPool creates a new Calico IPAM IP Pool.
func MustCreateNewIPPool(c client.Interface, cidr string, ipip, natOutgoing, ipam bool) string {
log.SetLevel(log.DebugLevel)
log.SetOutput(os.Stderr)
name := strings.Replace(cidr, ".", "-", -1)
name = strings.Replace(name, ":", "-", -1)
name = strings.Replace(name, "/", "-", -1)
var mode api.IPIPMode
if ipip {
mode = api.IPIPModeAlways
} else {
mode = api.IPIPModeNever
}
pool := api.NewIPPool()
pool.Name = name
pool.Spec.CIDR = cidr
pool.Spec.NATOutgoing = natOutgoing
pool.Spec.Disabled = !ipam
pool.Spec.IPIPMode = mode
_, err := c.IPPools().Create(context.Background(), pool, options.SetOptions{})
if err != nil {
panic(err)
}
return pool.Name
}
func MustDeleteIPPool(c client.Interface, cidr string) {
log.SetLevel(log.DebugLevel)
log.SetOutput(os.Stderr)
name := strings.Replace(cidr, ".", "-", -1)
name = strings.Replace(name, ":", "-", -1)
name = strings.Replace(name, "/", "-", -1)
_, err := c.IPPools().Delete(context.Background(), name, options.DeleteOptions{})
if err != nil {
panic(err)
}
}
// GetResultForCurrent takes the output with cniVersion and returns the Result in current.Result format.
func GetResultForCurrent(session *gexec.Session, cniVersion string) (*current.Result, error) {
// Check if the version is older than 0.3.0.
// Convert it to Current standard spec version if that is the case.
if version.Compare(cniVersion, "0.3.0", "<") {
r020 := types020.Result{}
if err := json.Unmarshal(session.Out.Contents(), &r020); err != nil {
log.Errorf("Error unmarshaling output to Result: %v\n", err)
return nil, err
}
rCurrent, err := current.NewResultFromResult(&r020)
if err != nil {
return nil, err
}
return rCurrent, nil
}
r := current.Result{}
if err := json.Unmarshal(session.Out.Contents(), &r); err != nil {
log.Errorf("Error unmarshaling output to Result: %v\n", err)
return nil, err
}
return &r, nil
}
// RunIPAMPlugin sets ENV vars required then calls the IPAM plugin
// specified in the config and returns the result and exitCode.
func RunIPAMPlugin(netconf, command, args, cid, cniVersion string) (*current.Result, types.Error, int) {
conf := types.NetConf{}
if err := json.Unmarshal([]byte(netconf), &conf); err != nil {
panic(fmt.Errorf("failed to load netconf: %v", err))
}
// Run the CNI plugin passing in the supplied netconf
cmd := &exec.Cmd{
Env: []string{
fmt.Sprintf("CNI_CONTAINERID=%s", cid),
"CNI_NETNS=b",
"CNI_IFNAME=c",
"CNI_PATH=d",
fmt.Sprintf("CNI_COMMAND=%s", command),
fmt.Sprintf("CNI_ARGS=%s", args),
},
Path: fmt.Sprintf("%s/%s", os.Getenv("BIN"), conf.IPAM.Type),
}
stdin, err := cmd.StdinPipe()
if err != nil {
panic("some error found")
}
_, err = io.WriteString(stdin, netconf)
if err != nil {
panic(err)
}
_, err = io.WriteString(stdin, "\n")
if err != nil {
panic(err)
}
err = stdin.Close()
if err != nil {
panic(err)
}
session, err := gexec.Start(cmd, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter)
if err != nil {
panic("some error found")
}
session.Wait(5)
exitCode := session.ExitCode()
result := ¤t.Result{}
e := types.Error{}
stdout := session.Out.Contents()
if exitCode == 0 {
if command == "ADD" {
result, err = GetResultForCurrent(session, cniVersion)
if err != nil {
log.Errorf("Error getting result from the session: %v \n %v\n", session, err)
panic(err)
}
}
} else {
if err := json.Unmarshal(stdout, &e); err != nil {
panic(fmt.Errorf("failed to load error: %s %v", stdout, err))
}
}
return result, e, exitCode
}
func CreateContainerNamespace() (containerNs ns.NetNS, containerId string, err error) {
containerNs, err = testutils.NewNS()
if err != nil {
return nil, "", err
}
netnsname := path.Base(containerNs.Path())
containerId = netnsname[:10]
err = containerNs.Do(func(_ ns.NetNS) error {
lo, err := netlink.LinkByName("lo")
if err != nil {
return err
}
return netlink.LinkSetUp(lo)
})
return
}
func CreateContainer(netconf, podName, podNamespace, ip string) (containerID string, result *current.Result, contVeth netlink.Link, contAddr []netlink.Addr, contRoutes []netlink.Route, targetNs ns.NetNS, err error) {
targetNs, containerID, err = CreateContainerNamespace()
if err != nil {
return "", nil, nil, nil, nil, nil, err
}
result, contVeth, contAddr, contRoutes, err = RunCNIPluginWithId(netconf, podName, podNamespace, ip, containerID, "", targetNs)
return
}
// Create container with the giving containerId when containerId is not empty
//
// Deprecated: Please call CreateContainerNamespace and then RunCNIPluginWithID directly.
func CreateContainerWithId(netconf, podName, podNamespace, ip, overrideContainerID string) (containerID string, result *current.Result, contVeth netlink.Link, contAddr []netlink.Addr, contRoutes []netlink.Route, targetNs ns.NetNS, err error) {
targetNs, containerID, err = CreateContainerNamespace()
if err != nil {
return "", nil, nil, nil, nil, nil, err
}
if overrideContainerID != "" {
containerID = overrideContainerID
}
result, contVeth, contAddr, contRoutes, err = RunCNIPluginWithId(netconf, podName, podNamespace, ip, containerID, "", targetNs)
return
}
// Used for passing arguments to the CNI plugin.
type cniArgs struct {
Env []string
}
func (c *cniArgs) AsEnv() []string {
return c.Env
}
// RunCNIPluginWithId calls CNI plugin with a containerID and targetNs passed to it.
// This is for when you want to call CNI for an existing container.
func RunCNIPluginWithId(
netconf,
podName,
podNamespace,
ip,
containerId,
ifName string,
targetNs ns.NetNS,
) (
result *current.Result,
contVeth netlink.Link,
contAddr []netlink.Addr,
contRoutes []netlink.Route,
err error,
) {
// Set up the env for running the CNI plugin
k8sEnv := ""
if podName != "" {
k8sEnv = fmt.Sprintf("CNI_ARGS=K8S_POD_NAME=%s;K8S_POD_NAMESPACE=%s;K8S_POD_INFRA_CONTAINER_ID=whatever", podName, podNamespace)
// Append IP=<ip> to CNI_ARGS only if it's not an empty string.
if ip != "" {
k8sEnv = fmt.Sprintf("%s;IP=%s", k8sEnv, ip)
}
}
if ifName == "" {
ifName = "eth0"
}
env := []string{
"CNI_COMMAND=ADD",
fmt.Sprintf("CNI_IFNAME=%s", ifName),
fmt.Sprintf("CNI_PATH=%s", os.Getenv("BIN")),
fmt.Sprintf("CNI_CONTAINERID=%s", containerId),
fmt.Sprintf("CNI_NETNS=%s", targetNs.Path()),
k8sEnv,
}
args := &cniArgs{env}
// Invoke the CNI plugin, returning any errors to the calling code to handle.
log.Debugf("Calling CNI plugin with the following env vars: %v", env)
var r types.Result
pluginPath := fmt.Sprintf("%s/%s", os.Getenv("BIN"), os.Getenv("PLUGIN"))
r, err = invoke.ExecPluginWithResult(pluginPath, []byte(netconf), args, nil)
if err != nil {
return
}
// Extract the target CNI version from the provided network config.
var nc types.NetConf
if err = json.Unmarshal([]byte(netconf), &nc); err != nil {
panic(err)
}
// Parse the result as the target CNI version.
if version.Compare(nc.CNIVersion, "0.3.0", "<") {
// Special case for older CNI verisons.
var out []byte
out, err = json.Marshal(r)
log.Infof("CNI output: %s", out)
r020 := types020.Result{}
if err = json.Unmarshal(out, &r020); err != nil {
log.Errorf("Error unmarshaling output to Result: %v\n", err)
return
}
result, err = current.NewResultFromResult(&r020)
if err != nil {
return
}
} else {
result, err = current.GetResult(r)
if err != nil {
return
}
}
err = targetNs.Do(func(_ ns.NetNS) error {
contVeth, err = netlink.LinkByName(ifName)
if err != nil {
return err
}
contAddr, err = netlink.AddrList(contVeth, syscall.AF_INET)
if err != nil {
return err
}
contRoutes, err = netlink.RouteList(contVeth, syscall.AF_INET)
if err != nil {
return err
}
return nil
})
return
}
// Create veth pair on host
func CreateHostVeth(containerId, k8sName, k8sNamespace, nodename string) error {
hostVethName := "cali" + containerId[:min(11, len(containerId))]
if k8sName != "" {
ids := names.WorkloadEndpointIdentifiers{
Node: nodename,
Orchestrator: "k8s",
Endpoint: "eth0",
Pod: k8sName,
ContainerID: containerId,
}
workloadName, err := ids.CalculateWorkloadEndpointName(false)
if err != nil {
return err
}
hostVethName = k8sconversion.VethNameForWorkload(k8sNamespace, workloadName)
}
peerVethName := "calipeer"
// Clean up if peer Veth exists.
if oldPeerVethName, err := netlink.LinkByName(peerVethName); err == nil {
if err = netlink.LinkDel(oldPeerVethName); err != nil {
return fmt.Errorf("failed to delete old peer Veth %v: %v", oldPeerVethName, err)
}
}
veth := &netlink.Veth{
LinkAttrs: netlink.LinkAttrs{
Name: hostVethName,
Flags: net.FlagUp,
MTU: 1500,
},
PeerName: peerVethName,
}
if err := netlink.LinkAdd(veth); err != nil {
return err
}
return nil
}
// Executes the Calico CNI plugin and return the error code of the command.
func DeleteContainer(netconf, netnspath, podName, podNamespace string) (exitCode int, err error) {
return DeleteContainerWithId(netconf, netnspath, podName, podNamespace, "")
}
func DeleteContainerWithId(netconf, netnspath, podName, podNamespace, containerId string) (exitCode int, err error) {
return DeleteContainerWithIdAndIfaceName(netconf, netnspath, podName, podNamespace, containerId, "eth0")
}
func DeleteContainerWithIdAndIfaceName(netconf, netnspath, podName, podNamespace, containerId, ifaceName string) (exitCode int, err error) {
netnsname := path.Base(netnspath)
container_id := netnsname[:10]
if containerId != "" {
container_id = containerId
}
k8sEnv := ""
if podName != "" {
k8sEnv = fmt.Sprintf("CNI_ARGS=K8S_POD_NAME=%s;K8S_POD_NAMESPACE=%s;K8S_POD_INFRA_CONTAINER_ID=whatever", podName, podNamespace)
}
// Set up the env for running the CNI plugin
env := []string{
"CNI_COMMAND=DEL",
fmt.Sprintf("CNI_CONTAINERID=%s", container_id),
fmt.Sprintf("CNI_NETNS=%s", netnspath),
"CNI_IFNAME=" + ifaceName,
fmt.Sprintf("CNI_PATH=%s", os.Getenv("BIN")),
k8sEnv,
}
log.Debugf("Deleting container with ID %v CNI plugin with the following env vars: %v", containerId, env)
// Run the CNI plugin passing in the supplied netconf
subProcess := exec.Command(fmt.Sprintf("%s/%s", os.Getenv("BIN"), os.Getenv("PLUGIN")), netconf)
subProcess.Env = env
stdin, err := subProcess.StdinPipe()
if err != nil {
return
}
_, err = io.WriteString(stdin, netconf)
if err != nil {
return 1, err
}
_, err = io.WriteString(stdin, "\n")
if err != nil {
return 1, err
}
err = stdin.Close()
if err != nil {
return 1, err
}
session, err := gexec.Start(subProcess, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter)
if err != nil {
return
}
// Call the plugin. Will force a test failure if it hangs longer than 5s.
session.Wait(5)
exitCode = session.ExitCode()
return
}
func Cmd(cmd string) string {
_, _ = ginkgo.GinkgoWriter.Write([]byte(fmt.Sprintf("Running command [%s]\n", cmd)))
out, err := exec.Command("bash", "-c", cmd).Output()
if err != nil {
_, err = ginkgo.GinkgoWriter.Write(out)
if err != nil {
panic(err)
}
_, err = ginkgo.GinkgoWriter.Write(err.(*exec.ExitError).Stderr)
if err != nil {
panic(err)
}
ginkgo.Fail("Command failed")
}
return strings.TrimSpace(string(out))
}
// CheckSysctlValue is a utility function to assert sysctl value is set to what is expected.
func CheckSysctlValue(sysctlPath, value string) error {
fh, err := os.Open(sysctlPath)
if err != nil {
return err
}
f := bufio.NewReader(fh)
// Ignoring second output (isPrefix) since it's not necessory
buf, _, err := f.ReadLine()
if err != nil {
// EOF without a match
return err
}
if string(buf) != value {
return fmt.Errorf("error asserting sysctl value: expected: %s, got: %s for sysctl path: %s", value, string(buf), sysctlPath)
}
err = fh.Close()
if err != nil {
return err
}
return nil
}
func AddNode(c client.Interface, kc *kubernetes.Clientset, host string) error {
var err error
err = nil
if os.Getenv("DATASTORE_TYPE") == "kubernetes" {
// create the node in Kubernetes.
n := corev1.Node{
TypeMeta: metav1.TypeMeta{
Kind: "Node",
APIVersion: "v1",
},
}
n.Name = host
// Create/Update the node
newNode, err := kc.CoreV1().Nodes().Create(&n)
if err != nil {
if kerrors.IsAlreadyExists(err) {
return nil
}
}
log.WithField("node", newNode).WithError(err).Info("node applied")
} else {
// Otherwise, create it in Calico.
n := api.NewNode()
n.Name = host
_, err = c.Nodes().Create(context.Background(), n, options.SetOptions{})
}
return err
}
func DeleteNode(c client.Interface, kc *kubernetes.Clientset, host string) error {
var err error
err = nil
if os.Getenv("DATASTORE_TYPE") == "kubernetes" {
// delete the node in Kubernetes.
err := kc.CoreV1().Nodes().Delete(host, &metav1.DeleteOptions{})
log.WithError(err).Info("node deleted")
} else {
// Otherwise, delete it in Calico.
n := api.NewNode()
n.Name = host
_, err = c.Nodes().Delete(context.Background(), host, options.DeleteOptions{})
log.WithError(err).Info("node deleted")
}
return err
}