Debian Codegraph @

libcni/api_test.go

raw
1 // Copyright 2016 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package libcni_test
16
17 import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "net"
24 "os"
25 "path/filepath"
26 "reflect"
27 "strings"
28 "time"
29
30 . "github.com/onsi/ginkgo/v2"
31 . "github.com/onsi/gomega"
32
33 "github.com/containernetworking/cni/libcni"
34 "github.com/containernetworking/cni/pkg/skel"
35 "github.com/containernetworking/cni/pkg/types"
36 current "github.com/containernetworking/cni/pkg/types/100"
37 "github.com/containernetworking/cni/pkg/version"
38 noop_debug "github.com/containernetworking/cni/plugins/test/noop/debug"
39 )
40
41 type pluginInfo struct {
42 debugFilePath string
43 commandFilePath string
44 debug *noop_debug.Debug
45 config string
46 stdinData []byte
47 }
48
49 type portMapping struct {
50 HostPort int `json:"hostPort"`
51 ContainerPort int `json:"containerPort"`
52 Protocol string `json:"protocol"`
53 }
54
55 func stringInList(s string, list []string) bool {
56 for _, item := range list {
57 if s == item {
58 return true
59 }
60 }
61 return false
62 }
63
64 func newPluginInfo(cniVersion, configValue, prevResult string, injectDebugFilePath bool, result string, runtimeConfig map[string]interface{}, capabilities []string) pluginInfo {
65 debugFile, err := os.CreateTemp("", "cni_debug")
66 Expect(err).NotTo(HaveOccurred())
67 Expect(debugFile.Close()).To(Succeed())
68 debugFilePath := debugFile.Name()
69
70 commandLog, err := os.CreateTemp("", "cni_debug")
71 Expect(err).NotTo(HaveOccurred())
72 Expect(commandLog.Close()).To(Succeed())
73 commandFilePath := commandLog.Name()
74
75 debug := &noop_debug.Debug{
76 ReportResult: result,
77 }
78 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
79
80 // config is what would be in the plugin's on-disk configuration
81 // without runtime injected keys
82 config := fmt.Sprintf(`{"type": "noop", "some-key": "%s"`, configValue)
83 if prevResult != "" {
84 config += fmt.Sprintf(`, "prevResult": %s`, prevResult)
85 }
86 if injectDebugFilePath {
87 config += fmt.Sprintf(`, "debugFile": %q`, debugFilePath)
88 config += fmt.Sprintf(`, "commandLog": %q`, commandFilePath)
89 }
90 if len(capabilities) > 0 {
91 config += `, "capabilities": {`
92 for i, c := range capabilities {
93 if i > 0 {
94 config += ", "
95 }
96 config += fmt.Sprintf(`"%s": true`, c)
97 }
98 config += "}"
99 }
100 config += "}"
101
102 // stdinData is what the runtime should pass to the plugin's stdin,
103 // including injected keys like 'name', 'cniVersion', and 'runtimeConfig'
104 newConfig := make(map[string]interface{})
105 err = json.Unmarshal([]byte(config), &newConfig)
106 Expect(err).NotTo(HaveOccurred())
107 newConfig["name"] = "some-list"
108 newConfig["cniVersion"] = cniVersion
109
110 // Only include standard runtime config and capability args that this plugin advertises
111 newRuntimeConfig := make(map[string]interface{})
112 for key, value := range runtimeConfig {
113 if stringInList(key, capabilities) {
114 newRuntimeConfig[key] = value
115 }
116 }
117 if len(newRuntimeConfig) > 0 {
118 newConfig["runtimeConfig"] = newRuntimeConfig
119 }
120
121 stdinData, err := json.Marshal(newConfig)
122 Expect(err).NotTo(HaveOccurred())
123
124 return pluginInfo{
125 debugFilePath: debugFilePath,
126 commandFilePath: commandFilePath,
127 debug: debug,
128 config: config,
129 stdinData: stdinData,
130 }
131 }
132
133 func makePluginList(cniVersion, ipResult string, runtimeConfig map[string]interface{}) (*libcni.NetworkConfigList, []pluginInfo) {
134 plugins := make([]pluginInfo, 3)
135 plugins[0] = newPluginInfo(cniVersion, "some-value", "", true, ipResult, runtimeConfig, []string{"portMappings", "otherCapability"})
136 plugins[1] = newPluginInfo(cniVersion, "some-other-value", ipResult, true, "PASSTHROUGH", runtimeConfig, []string{"otherCapability"})
137 plugins[2] = newPluginInfo(cniVersion, "yet-another-value", ipResult, true, "INJECT-DNS", runtimeConfig, []string{})
138
139 configList := []byte(fmt.Sprintf(`{
140 "name": "some-list",
141 "cniVersion": "%s",
142 "plugins": [
143 %s,
144 %s,
145 %s
146 ]
147 }`, cniVersion, plugins[0].config, plugins[1].config, plugins[2].config))
148
149 netConfigList, err := libcni.ConfListFromBytes(configList)
150 Expect(err).NotTo(HaveOccurred())
151 return netConfigList, plugins
152 }
153
154 func resultCacheFilePath(cacheDirPath, netName string, rt *libcni.RuntimeConf) string {
155 fName := fmt.Sprintf("%s-%s-%s", netName, rt.ContainerID, rt.IfName)
156 return filepath.Join(cacheDirPath, "results", fName)
157 }
158
159 var _ = Describe("Invoking plugins", func() {
160 var cacheDirPath string
161
162 BeforeEach(func() {
163 var err error
164 cacheDirPath, err = os.MkdirTemp("", "cni_cachedir")
165 Expect(err).NotTo(HaveOccurred())
166 })
167
168 AfterEach(func() {
169 Expect(os.RemoveAll(cacheDirPath)).To(Succeed())
170 })
171
172 Describe("Capabilities", func() {
173 var (
174 debugFilePath string
175 debug *noop_debug.Debug
176 pluginConfig []byte
177 cniConfig *libcni.CNIConfig
178 runtimeConfig *libcni.RuntimeConf
179 netConfig *libcni.PluginConfig
180 ctx context.Context
181 )
182
183 BeforeEach(func() {
184 debugFile, err := os.CreateTemp("", "cni_debug")
185 Expect(err).NotTo(HaveOccurred())
186 Expect(debugFile.Close()).To(Succeed())
187 debugFilePath = debugFile.Name()
188
189 debug = &noop_debug.Debug{
190 ReportResult: `{
191 "cniVersion": "` + version.Current() + `",
192 "ips": [{"address": "10.1.2.3/24"}],
193 "dns": {}
194 }`,
195 }
196 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
197
198 pluginConfig = []byte(fmt.Sprintf(`{
199 "type": "noop",
200 "name": "apitest",
201 "cniVersion": "%s",
202 "capabilities": {
203 "portMappings": true,
204 "somethingElse": true,
205 "noCapability": false
206 }
207 }`, version.Current()))
208 netConfig, err = libcni.ConfFromBytes(pluginConfig)
209 Expect(err).NotTo(HaveOccurred())
210
211 cniConfig = libcni.NewCNIConfigWithCacheDir([]string{filepath.Dir(pluginPaths["noop"])}, cacheDirPath, nil)
212
213 runtimeConfig = &libcni.RuntimeConf{
214 ContainerID: "some-container-id",
215 NetNS: "/some/netns/path",
216 IfName: "some-eth0",
217 Args: [][2]string{{"DEBUG", debugFilePath}},
218 CapabilityArgs: map[string]interface{}{
219 "portMappings": []portMapping{
220 {HostPort: 8080, ContainerPort: 80, Protocol: "tcp"},
221 },
222 "somethingElse": []string{"foobar", "baz"},
223 "noCapability": true,
224 "notAdded": []bool{true, false},
225 },
226 }
227 ctx = context.TODO()
228 })
229
230 AfterEach(func() {
231 Expect(os.RemoveAll(debugFilePath)).To(Succeed())
232 })
233
234 It("adds correct runtime config for capabilities to stdin", func() {
235 _, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
236 Expect(err).NotTo(HaveOccurred())
237
238 debug, err = noop_debug.ReadDebug(debugFilePath)
239 Expect(err).NotTo(HaveOccurred())
240 Expect(debug.Command).To(Equal("ADD"))
241
242 conf := make(map[string]interface{})
243 err = json.Unmarshal(debug.CmdArgs.StdinData, &conf)
244 Expect(err).NotTo(HaveOccurred())
245
246 // We expect runtimeConfig keys only for portMappings and somethingElse
247 rawRc := conf["runtimeConfig"]
248 rc, ok := rawRc.(map[string]interface{})
249 Expect(ok).To(BeTrue())
250 expectedKeys := []string{"portMappings", "somethingElse"}
251 Expect(rc).To(HaveLen(len(expectedKeys)))
252 for _, key := range expectedKeys {
253 _, ok := rc[key]
254 Expect(ok).To(BeTrue())
255 }
256 })
257
258 It("adds no runtimeConfig when the plugin advertises no used capabilities", func() {
259 // Replace CapabilityArgs with ones we know the plugin
260 // doesn't support
261 runtimeConfig.CapabilityArgs = map[string]interface{}{
262 "portMappings22": []portMapping{
263 {HostPort: 8080, ContainerPort: 80, Protocol: "tcp"},
264 },
265 "somethingElse22": []string{"foobar", "baz"},
266 }
267
268 _, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
269 Expect(err).NotTo(HaveOccurred())
270
271 debug, err = noop_debug.ReadDebug(debugFilePath)
272 Expect(err).NotTo(HaveOccurred())
273 Expect(debug.Command).To(Equal("ADD"))
274
275 conf := make(map[string]interface{})
276 err = json.Unmarshal(debug.CmdArgs.StdinData, &conf)
277 Expect(err).NotTo(HaveOccurred())
278
279 // No intersection of plugin capabilities and CapabilityArgs,
280 // so plugin should not receive a "runtimeConfig" key
281 _, ok := conf["runtimeConfig"]
282 Expect(ok).Should(BeFalse())
283 })
284
285 It("outputs correct capabilities for validate", func() {
286 caps, err := cniConfig.ValidateNetwork(ctx, netConfig)
287 Expect(err).NotTo(HaveOccurred())
288 Expect(caps).To(ConsistOf("portMappings", "somethingElse"))
289 })
290 })
291
292 Describe("Invoking a single plugin", func() {
293 var (
294 debugFilePath string
295 debug *noop_debug.Debug
296 pluginConfig string
297 cniConfig *libcni.CNIConfig
298 netConfig *libcni.PluginConfig
299 runtimeConfig *libcni.RuntimeConf
300 ctx context.Context
301
302 expectedCmdArgs skel.CmdArgs
303 )
304
305 BeforeEach(func() {
306 debugFile, err := os.CreateTemp("", "cni_debug")
307 Expect(err).NotTo(HaveOccurred())
308 Expect(debugFile.Close()).To(Succeed())
309 debugFilePath = debugFile.Name()
310
311 debug = &noop_debug.Debug{
312 ReportResult: `{
313 "cniVersion": "` + version.Current() + `",
314 "ips": [{"address": "10.1.2.3/24"}],
315 "dns": {}
316 }`,
317 }
318 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
319
320 portMappings := []portMapping{
321 {HostPort: 8080, ContainerPort: 80, Protocol: "tcp"},
322 }
323
324 cniBinPath := filepath.Dir(pluginPaths["noop"])
325 pluginConfig = fmt.Sprintf(`{
326 "type": "noop",
327 "name": "apitest",
328 "some-key": "some-value",
329 "cniVersion": "%s",
330 "capabilities": { "portMappings": true }
331 }`, version.Current())
332 cniConfig = libcni.NewCNIConfigWithCacheDir([]string{cniBinPath}, cacheDirPath, nil)
333 netConfig, err = libcni.ConfFromBytes([]byte(pluginConfig))
334 Expect(err).NotTo(HaveOccurred())
335 runtimeConfig = &libcni.RuntimeConf{
336 ContainerID: "some-container-id",
337 NetNS: "/some/netns/path",
338 IfName: "some-eth0",
339 Args: [][2]string{{"DEBUG", debugFilePath}},
340 CapabilityArgs: map[string]interface{}{
341 "portMappings": portMappings,
342 },
343 }
344
345 // inject runtime args into the expected plugin config
346 conf := make(map[string]interface{})
347 err = json.Unmarshal([]byte(pluginConfig), &conf)
348 Expect(err).NotTo(HaveOccurred())
349 conf["runtimeConfig"] = map[string]interface{}{
350 "portMappings": portMappings,
351 }
352 newBytes, err := json.Marshal(conf)
353 Expect(err).NotTo(HaveOccurred())
354
355 expectedCmdArgs = skel.CmdArgs{
356 ContainerID: "some-container-id",
357 Netns: "/some/netns/path",
358 IfName: "some-eth0",
359 Args: "DEBUG=" + debugFilePath,
360 Path: cniBinPath,
361 StdinData: newBytes,
362 }
363 ctx = context.TODO()
364 })
365
366 AfterEach(func() {
367 Expect(os.RemoveAll(debugFilePath)).To(Succeed())
368 })
369
370 Describe("AddNetwork", func() {
371 It("executes the plugin with command ADD", func() {
372 r, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
373 Expect(err).NotTo(HaveOccurred())
374
375 result, err := current.GetResult(r)
376 Expect(err).NotTo(HaveOccurred())
377
378 Expect(result).To(Equal(&current.Result{
379 CNIVersion: current.ImplementedSpecVersion,
380 IPs: []*current.IPConfig{
381 {
382 Address: net.IPNet{
383 IP: net.ParseIP("10.1.2.3"),
384 Mask: net.IPv4Mask(255, 255, 255, 0),
385 },
386 },
387 },
388 }))
389
390 debug, err := noop_debug.ReadDebug(debugFilePath)
391 Expect(err).NotTo(HaveOccurred())
392 Expect(debug.Command).To(Equal("ADD"))
393 Expect(debug.CmdArgs).To(Equal(expectedCmdArgs))
394 Expect(string(debug.CmdArgs.StdinData)).To(ContainSubstring("\"portMappings\":"))
395
396 // Ensure the cached config matches the sent one
397 cachedConfig, newRt, err := cniConfig.GetNetworkCachedConfig(netConfig, runtimeConfig)
398 Expect(err).NotTo(HaveOccurred())
399 Expect(reflect.DeepEqual(cachedConfig, []byte(pluginConfig))).To(BeTrue())
400 Expect(reflect.DeepEqual(newRt.Args, runtimeConfig.Args)).To(BeTrue())
401 // CapabilityArgs are freeform, so we have to match their JSON not
402 // the Go structs (which could be unmarshalled differently than the
403 // struct that was marshalled).
404 expectedCABytes, err := json.Marshal(runtimeConfig.CapabilityArgs)
405 Expect(err).NotTo(HaveOccurred())
406 foundCABytes, err := json.Marshal(newRt.CapabilityArgs)
407 Expect(err).NotTo(HaveOccurred())
408 Expect(foundCABytes).To(MatchJSON(expectedCABytes))
409
410 // Ensure the cached result matches the returned one
411 cachedResult, err := cniConfig.GetNetworkCachedResult(netConfig, runtimeConfig)
412 Expect(err).NotTo(HaveOccurred())
413 result2, err := current.GetResult(cachedResult)
414 Expect(err).NotTo(HaveOccurred())
415 cachedJson, err := json.Marshal(result2)
416 Expect(err).NotTo(HaveOccurred())
417
418 returnedJson, err := json.Marshal(result)
419 Expect(err).NotTo(HaveOccurred())
420 Expect(cachedJson).To(MatchJSON(returnedJson))
421
422 // Ensure the cached attachments matches requested one
423 for _, containerID := range []string{"", runtimeConfig.ContainerID} {
424 expected, err := json.Marshal(libcni.NetworkAttachment{
425 ContainerID: runtimeConfig.ContainerID,
426 Network: netConfig.Network.Name,
427 NetNS: runtimeConfig.NetNS,
428 IfName: runtimeConfig.IfName,
429 Config: netConfig.Bytes,
430 CniArgs: runtimeConfig.Args,
431 CapabilityArgs: runtimeConfig.CapabilityArgs,
432 })
433 Expect(err).NotTo(HaveOccurred())
434 attachments, err := cniConfig.GetCachedAttachments(containerID)
435 Expect(err).NotTo(HaveOccurred())
436 if Expect(len(attachments)).To(Equal(1)) {
437 json, err := json.Marshal(attachments[0])
438 Expect(err).NotTo(HaveOccurred())
439 Expect(json).To(MatchJSON(expected))
440 }
441 }
442 })
443
444 Context("when finding the plugin fails", func() {
445 BeforeEach(func() {
446 netConfig.Network.Type = "does-not-exist"
447 })
448
449 It("returns the error", func() {
450 _, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
451 Expect(err).To(MatchError(ContainSubstring(`failed to find plugin "does-not-exist"`)))
452 })
453 })
454
455 Context("when the plugin errors", func() {
456 BeforeEach(func() {
457 debug.ReportError = "plugin error: banana"
458 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
459 })
460 It("unmarshals and returns the error", func() {
461 result, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
462 Expect(result).To(BeNil())
463 Expect(err).To(MatchError("plugin error: banana"))
464 })
465 })
466
467 Context("when the cache directory cannot be accessed", func() {
468 It("returns an error", func() {
469 // Make the results directory inaccessible by making it a
470 // file instead of a directory
471 tmpPath := filepath.Join(cacheDirPath, "results")
472 err := os.WriteFile(tmpPath, []byte("afdsasdfasdf"), 0o600)
473 Expect(err).NotTo(HaveOccurred())
474
475 result, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
476 Expect(result).To(BeNil())
477 Expect(err).To(HaveOccurred())
478 })
479 })
480 })
481
482 Describe("CheckNetwork", func() {
483 It("executes the plugin with command CHECK", func() {
484 cacheFile := resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
485 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
486 Expect(err).NotTo(HaveOccurred())
487 cachedJson := `{
488 "cniVersion": "` + version.Current() + `",
489 "ips": [{"address": "10.1.2.3/24"}]
490 }`
491 err = os.WriteFile(cacheFile, []byte(cachedJson), 0o600)
492 Expect(err).NotTo(HaveOccurred())
493
494 err = cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
495 Expect(err).NotTo(HaveOccurred())
496
497 debug, err := noop_debug.ReadDebug(debugFilePath)
498 Expect(err).NotTo(HaveOccurred())
499 Expect(debug.Command).To(Equal("CHECK"))
500 Expect(string(debug.CmdArgs.StdinData)).To(ContainSubstring("\"portMappings\":"))
501
502 // Explicitly match stdin data as json after
503 // inserting the expected prevResult
504 var data, data2 map[string]interface{}
505 err = json.Unmarshal(expectedCmdArgs.StdinData, &data)
506 Expect(err).NotTo(HaveOccurred())
507 err = json.Unmarshal([]byte(cachedJson), &data2)
508 Expect(err).NotTo(HaveOccurred())
509 data["prevResult"] = data2
510 expectedStdinJson, err := json.Marshal(data)
511 Expect(err).NotTo(HaveOccurred())
512 Expect(debug.CmdArgs.StdinData).To(MatchJSON(expectedStdinJson))
513
514 debug.CmdArgs.StdinData = nil
515 expectedCmdArgs.StdinData = nil
516 Expect(debug.CmdArgs).To(Equal(expectedCmdArgs))
517 })
518
519 Context("when finding the plugin fails", func() {
520 BeforeEach(func() {
521 netConfig.Network.Type = "does-not-exist"
522 })
523
524 It("returns the error", func() {
525 err := cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
526 Expect(err).To(MatchError(ContainSubstring(`failed to find plugin "does-not-exist"`)))
527 })
528 })
529
530 Context("when the plugin errors", func() {
531 BeforeEach(func() {
532 debug.ReportError = "plugin error: banana"
533 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
534 })
535 It("unmarshals and returns the error", func() {
536 err := cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
537 Expect(err).To(MatchError("plugin error: banana"))
538 })
539 })
540
541 Context("when CHECK is called with a configuration version", func() {
542 var cacheFile string
543
544 BeforeEach(func() {
545 cacheFile = resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
546 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
547 Expect(err).NotTo(HaveOccurred())
548 })
549
550 Context("less than 0.4.0", func() {
551 It("fails as CHECK is not supported before 0.4.0", func() {
552 // Generate plugin config with older version
553 var err error
554 netConfig, err = libcni.ConfFromBytes([]byte(`{
555 "type": "noop",
556 "name": "apitest",
557 "cniVersion": "0.3.1"
558 }`))
559 Expect(err).NotTo(HaveOccurred())
560 err = cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
561 Expect(err).To(MatchError("configuration version \"0.3.1\" does not support the CHECK command"))
562
563 debug, err := noop_debug.ReadDebug(debugFilePath)
564 Expect(err).NotTo(HaveOccurred())
565 Expect(string(debug.CmdArgs.StdinData)).NotTo(ContainSubstring("\"prevResult\":"))
566 })
567 })
568
569 Context("containing only a cached result", func() {
570 It("only passes a prevResult to the plugin", func() {
571 err := os.WriteFile(cacheFile, []byte(`{
572 "cniVersion": "`+version.Current()+`",
573 "ips": [{"address": "10.1.2.3/24"}],
574 "dns": {}
575 }`), 0o600)
576 Expect(err).NotTo(HaveOccurred())
577
578 err = cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
579 Expect(err).NotTo(HaveOccurred())
580 debug, err := noop_debug.ReadDebug(debugFilePath)
581 Expect(err).NotTo(HaveOccurred())
582 Expect(string(debug.CmdArgs.StdinData)).To(ContainSubstring("\"prevResult\":"))
583 Expect(string(debug.CmdArgs.StdinData)).NotTo(ContainSubstring("\"config\":"))
584 Expect(string(debug.CmdArgs.StdinData)).NotTo(ContainSubstring("\"kind\":"))
585 })
586 })
587
588 Context("equal to 0.4.0", func() {
589 It("passes a prevResult to the plugin", func() {
590 ipResult := `{
591 "cniVersion": "0.4.0",
592 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
593 "dns": {}
594 }`
595
596 var err error
597 netConfig, err = libcni.ConfFromBytes([]byte(`{
598 "type": "noop",
599 "name": "apitest",
600 "cniVersion": "0.4.0",
601 "capabilities": {
602 "portMappings": true,
603 "somethingElse": true,
604 "noCapability": false
605 }
606 }`))
607 Expect(err).NotTo(HaveOccurred())
608
609 err = os.WriteFile(cacheFile, []byte(ipResult), 0o600)
610 Expect(err).NotTo(HaveOccurred())
611
612 debug.ReportResult = ipResult
613 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
614
615 err = cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
616 Expect(err).NotTo(HaveOccurred())
617 debug, err := noop_debug.ReadDebug(debugFilePath)
618 Expect(err).NotTo(HaveOccurred())
619 Expect(string(debug.CmdArgs.StdinData)).To(ContainSubstring("\"prevResult\":"))
620 })
621 })
622 })
623
624 Context("when the cached result", func() {
625 var cacheFile string
626
627 BeforeEach(func() {
628 cacheFile = resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
629 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
630 Expect(err).NotTo(HaveOccurred())
631 })
632
633 Context("is invalid JSON", func() {
634 It("returns an error", func() {
635 err := os.WriteFile(cacheFile, []byte("adfadsfasdfasfdsafaf"), 0o600)
636 Expect(err).NotTo(HaveOccurred())
637
638 err = cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
639 Expect(err).To(MatchError("failed to get network \"apitest\" cached result: decoding version from network config: invalid character 'a' looking for beginning of value"))
640 })
641 })
642
643 Context("version doesn't match the config version", func() {
644 It("succeeds when the cached result can be converted", func() {
645 err := os.WriteFile(cacheFile, []byte(`{
646 "cniVersion": "0.3.1",
647 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
648 "dns": {}
649 }`), 0o600)
650 Expect(err).NotTo(HaveOccurred())
651
652 err = cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
653 Expect(err).NotTo(HaveOccurred())
654 })
655
656 It("returns an error when the cached result cannot be converted", func() {
657 err := os.WriteFile(cacheFile, []byte(`{
658 "cniVersion": "0.4567.0",
659 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
660 "dns": {}
661 }`), 0o600)
662 Expect(err).NotTo(HaveOccurred())
663
664 err = cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
665 Expect(err).To(MatchError("failed to get network \"apitest\" cached result: unsupported CNI result version \"0.4567.0\""))
666 })
667 })
668 })
669 })
670
671 Describe("DelNetwork", func() {
672 It("executes the plugin with command DEL", func() {
673 cacheFile := resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
674 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
675 Expect(err).NotTo(HaveOccurred())
676 cachedJson := `{
677 "cniVersion": "` + version.Current() + `",
678 "ips": [{"address": "10.1.2.3/24"}]
679 }`
680 err = os.WriteFile(cacheFile, []byte(cachedJson), 0o600)
681 Expect(err).NotTo(HaveOccurred())
682
683 err = cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
684 Expect(err).NotTo(HaveOccurred())
685
686 debug, err := noop_debug.ReadDebug(debugFilePath)
687 Expect(err).NotTo(HaveOccurred())
688 Expect(debug.Command).To(Equal("DEL"))
689 Expect(string(debug.CmdArgs.StdinData)).To(ContainSubstring("\"portMappings\":"))
690
691 // Explicitly match stdin data as json after
692 // inserting the expected prevResult
693 var data, data2 map[string]interface{}
694 err = json.Unmarshal(expectedCmdArgs.StdinData, &data)
695 Expect(err).NotTo(HaveOccurred())
696 err = json.Unmarshal([]byte(cachedJson), &data2)
697 Expect(err).NotTo(HaveOccurred())
698 data["prevResult"] = data2
699 expectedStdinJson, err := json.Marshal(data)
700 Expect(err).NotTo(HaveOccurred())
701 Expect(debug.CmdArgs.StdinData).To(MatchJSON(expectedStdinJson))
702
703 debug.CmdArgs.StdinData = nil
704 expectedCmdArgs.StdinData = nil
705 Expect(debug.CmdArgs).To(Equal(expectedCmdArgs))
706
707 // Ensure the cached result no longer exists
708 cachedResult, err := cniConfig.GetNetworkCachedResult(netConfig, runtimeConfig)
709 Expect(err).NotTo(HaveOccurred())
710 Expect(cachedResult).To(BeNil())
711
712 // Ensure the cached config no longer exists
713 cachedConfig, newRt, err := cniConfig.GetNetworkCachedConfig(netConfig, runtimeConfig)
714 Expect(err).NotTo(HaveOccurred())
715 Expect(cachedConfig).To(BeNil())
716 Expect(newRt).To(BeNil())
717
718 // Ensure the cached attachments no longer exist
719 for _, containerID := range []string{"", runtimeConfig.ContainerID} {
720 attachments, err := cniConfig.GetCachedAttachments(containerID)
721 Expect(err).NotTo(HaveOccurred())
722 Expect(attachments).To(BeEmpty())
723 }
724 })
725
726 Context("when finding the plugin fails", func() {
727 BeforeEach(func() {
728 netConfig.Network.Type = "does-not-exist"
729 })
730
731 It("returns the error", func() {
732 err := cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
733 Expect(err).To(MatchError(ContainSubstring(`failed to find plugin "does-not-exist"`)))
734 })
735 })
736
737 Context("when the plugin errors", func() {
738 BeforeEach(func() {
739 debug.ReportError = "plugin error: banana"
740 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
741 })
742 It("unmarshals and returns the error", func() {
743 err := cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
744 Expect(err).To(MatchError("plugin error: banana"))
745 })
746 })
747
748 Context("when DEL is called twice", func() {
749 var resultCacheFile string
750
751 BeforeEach(func() {
752 resultCacheFile = resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
753 err := os.MkdirAll(filepath.Dir(resultCacheFile), 0o700)
754 Expect(err).NotTo(HaveOccurred())
755 })
756
757 It("deletes the cached result and config after the first DEL", func() {
758 err := os.WriteFile(resultCacheFile, []byte(`{
759 "cniVersion": "0.4.0",
760 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
761 "dns": {}
762 }`), 0o600)
763 Expect(err).NotTo(HaveOccurred())
764
765 err = cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
766 Expect(err).NotTo(HaveOccurred())
767 _, err = os.ReadFile(resultCacheFile)
768 Expect(err).To(HaveOccurred())
769
770 err = cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
771 Expect(err).NotTo(HaveOccurred())
772 })
773 })
774
775 Context("when DEL is called with a configuration version", func() {
776 var cacheFile string
777
778 BeforeEach(func() {
779 cacheFile = resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
780 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
781 Expect(err).NotTo(HaveOccurred())
782 })
783
784 Context("less than 0.4.0", func() {
785 It("does not pass a prevResult to the plugin", func() {
786 err := os.WriteFile(cacheFile, []byte(`{
787 "cniVersion": "0.3.1",
788 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
789 "dns": {}
790 }`), 0o600)
791 Expect(err).NotTo(HaveOccurred())
792
793 // Generate plugin config with older version
794 netConfig, err = libcni.ConfFromBytes([]byte(`{
795 "type": "noop",
796 "name": "apitest",
797 "cniVersion": "0.3.1"
798 }`))
799 Expect(err).NotTo(HaveOccurred())
800 err = cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
801 Expect(err).NotTo(HaveOccurred())
802
803 debug, err := noop_debug.ReadDebug(debugFilePath)
804 Expect(err).NotTo(HaveOccurred())
805 Expect(debug.Command).To(Equal("DEL"))
806 Expect(string(debug.CmdArgs.StdinData)).NotTo(ContainSubstring("\"prevResult\":"))
807 })
808 })
809
810 Context("equal to 0.4.0", func() {
811 It("passes a prevResult to the plugin", func() {
812 err := os.WriteFile(cacheFile, []byte(`{
813 "cniVersion": "0.4.0",
814 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
815 "dns": {}
816 }`), 0o600)
817 Expect(err).NotTo(HaveOccurred())
818
819 err = cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
820 Expect(err).NotTo(HaveOccurred())
821
822 debug, err := noop_debug.ReadDebug(debugFilePath)
823 Expect(err).NotTo(HaveOccurred())
824 Expect(debug.Command).To(Equal("DEL"))
825 Expect(string(debug.CmdArgs.StdinData)).To(ContainSubstring("\"prevResult\":"))
826 })
827 })
828 })
829
830 Context("when the cached", func() {
831 var cacheFile string
832
833 BeforeEach(func() {
834 cacheFile = resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
835 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
836 Expect(err).NotTo(HaveOccurred())
837 })
838
839 Context("result is invalid JSON", func() {
840 It("returns an error", func() {
841 err := os.WriteFile(cacheFile, []byte("adfadsfasdfasfdsafaf"), 0o600)
842 Expect(err).NotTo(HaveOccurred())
843
844 err = cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
845 Expect(err).To(MatchError("failed to get network \"apitest\" cached result: decoding version from network config: invalid character 'a' looking for beginning of value"))
846 })
847 })
848
849 Context("result version doesn't match the config version", func() {
850 It("succeeds when the cached result can be converted", func() {
851 err := os.WriteFile(cacheFile, []byte(`{
852 "cniVersion": "0.3.1",
853 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
854 "dns": {}
855 }`), 0o600)
856 Expect(err).NotTo(HaveOccurred())
857
858 err = cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
859 Expect(err).NotTo(HaveOccurred())
860 })
861
862 It("returns an error when the cached result cannot be converted", func() {
863 err := os.WriteFile(cacheFile, []byte(`{
864 "cniVersion": "0.4567.0",
865 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
866 "dns": {}
867 }`), 0o600)
868 Expect(err).NotTo(HaveOccurred())
869
870 err = cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
871 Expect(err).To(MatchError("failed to get network \"apitest\" cached result: unsupported CNI result version \"0.4567.0\""))
872 })
873 })
874 })
875 })
876
877 Describe("GetVersionInfo", func() {
878 It("executes the plugin with the command VERSION", func() {
879 versionInfo, err := cniConfig.GetVersionInfo(ctx, "noop")
880 Expect(err).NotTo(HaveOccurred())
881
882 Expect(versionInfo).NotTo(BeNil())
883 Expect(versionInfo.SupportedVersions()).To(Equal([]string{
884 "0.-42.0", "0.1.0", "0.2.0", "0.3.0", "0.3.1", "0.4.0", "1.0.0", "1.1.0",
885 }))
886 })
887
888 Context("when finding the plugin fails", func() {
889 It("returns the error", func() {
890 _, err := cniConfig.GetVersionInfo(ctx, "does-not-exist")
891 Expect(err).To(MatchError(ContainSubstring(`failed to find plugin "does-not-exist"`)))
892 })
893 })
894 })
895
896 Describe("ValidateNetwork", func() {
897 It("validates a good configuration", func() {
898 _, err := cniConfig.ValidateNetwork(ctx, netConfig)
899 Expect(err).NotTo(HaveOccurred())
900 })
901
902 It("catches non-existent plugins", func() {
903 netConfig.Network.Type = "nope"
904 _, err := cniConfig.ValidateNetwork(ctx, netConfig)
905 Expect(err).To(MatchError("failed to find plugin \"nope\" in path [" + cniConfig.Path[0] + "]"))
906 })
907
908 It("catches unsupported versions", func() {
909 netConfig.Network.CNIVersion = "broken"
910 _, err := cniConfig.ValidateNetwork(ctx, netConfig)
911 Expect(err).To(MatchError("plugin noop does not support config version \"broken\""))
912 })
913 It("allows version to be omitted", func() {
914 netConfig.Network.CNIVersion = ""
915 _, err := cniConfig.ValidateNetwork(ctx, netConfig)
916 Expect(err).NotTo(HaveOccurred())
917 })
918 })
919 })
920
921 Describe("Invoking a plugin list", func() {
922 var (
923 plugins []pluginInfo
924 cniBinPath string
925 cniConfig *libcni.CNIConfig
926 netConfigList *libcni.NetworkConfigList
927 runtimeConfig *libcni.RuntimeConf
928 rcMap map[string]interface{}
929 ctx context.Context
930 ipResult string
931
932 expectedCmdArgs skel.CmdArgs
933 )
934
935 BeforeEach(func() {
936 capabilityArgs := map[string]interface{}{
937 "portMappings": []portMapping{
938 {HostPort: 8080, ContainerPort: 80, Protocol: "tcp"},
939 },
940 "otherCapability": 33,
941 }
942
943 cniBinPath = filepath.Dir(pluginPaths["noop"])
944 cniConfig = libcni.NewCNIConfigWithCacheDir([]string{cniBinPath}, cacheDirPath, nil)
945 runtimeConfig = &libcni.RuntimeConf{
946 ContainerID: "some-container-id",
947 NetNS: "/some/netns/path",
948 IfName: "some-eth0",
949 Args: [][2]string{{"FOO", "BAR"}},
950 CapabilityArgs: capabilityArgs,
951 }
952
953 expectedCmdArgs = skel.CmdArgs{
954 ContainerID: runtimeConfig.ContainerID,
955 Netns: runtimeConfig.NetNS,
956 IfName: runtimeConfig.IfName,
957 Args: "FOO=BAR",
958 Path: cniBinPath,
959 }
960
961 rcMap = map[string]interface{}{
962 "containerId": runtimeConfig.ContainerID,
963 "netNs": runtimeConfig.NetNS,
964 "ifName": runtimeConfig.IfName,
965 "args": map[string]string{
966 "FOO": "BAR",
967 },
968 "portMappings": capabilityArgs["portMappings"],
969 "otherCapability": capabilityArgs["otherCapability"],
970 }
971
972 ipResult = fmt.Sprintf(`{"cniVersion": "%s", "ips":[{"address": "10.1.2.3/24"}]}`, version.Current())
973 netConfigList, plugins = makePluginList(version.Current(), ipResult, rcMap)
974
975 ctx = context.TODO()
976 })
977
978 AfterEach(func() {
979 for _, p := range plugins {
980 Expect(os.RemoveAll(p.debugFilePath)).To(Succeed())
981 }
982 })
983
984 Describe("AddNetworkList", func() {
985 It("executes all plugins with command ADD and returns an intermediate result", func() {
986 r, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
987 Expect(err).NotTo(HaveOccurred())
988
989 result, err := current.GetResult(r)
990 Expect(err).NotTo(HaveOccurred())
991
992 Expect(result).To(Equal(&current.Result{
993 CNIVersion: current.ImplementedSpecVersion,
994 // IP4 added by first plugin
995 IPs: []*current.IPConfig{
996 {
997 Address: net.IPNet{
998 IP: net.ParseIP("10.1.2.3"),
999 Mask: net.IPv4Mask(255, 255, 255, 0),
1000 },
1001 },
1002 },
1003 // DNS injected by last plugin
1004 DNS: types.DNS{
1005 Nameservers: []string{"1.2.3.4"},
1006 },
1007 }))
1008
1009 for i := 0; i < len(plugins); i++ {
1010 debug, err := noop_debug.ReadDebug(plugins[i].debugFilePath)
1011 Expect(err).NotTo(HaveOccurred())
1012 Expect(debug.Command).To(Equal("ADD"))
1013
1014 // Must explicitly match JSON due to dict element ordering
1015 Expect(debug.CmdArgs.StdinData).To(MatchJSON(plugins[i].stdinData))
1016 debug.CmdArgs.StdinData = nil
1017 Expect(debug.CmdArgs).To(Equal(expectedCmdArgs))
1018 }
1019 })
1020
1021 It("writes the correct cached result", func() {
1022 r, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1023 Expect(err).NotTo(HaveOccurred())
1024
1025 result, err := current.GetResult(r)
1026 Expect(err).NotTo(HaveOccurred())
1027
1028 // Ensure the cached result matches the returned one
1029 cachedResult, err := cniConfig.GetNetworkListCachedResult(netConfigList, runtimeConfig)
1030 Expect(err).NotTo(HaveOccurred())
1031 result2, err := current.GetResult(cachedResult)
1032 Expect(err).NotTo(HaveOccurred())
1033 cachedJson, err := json.Marshal(result2)
1034 Expect(err).NotTo(HaveOccurred())
1035 returnedJson, err := json.Marshal(result)
1036 Expect(err).NotTo(HaveOccurred())
1037 Expect(cachedJson).To(MatchJSON(returnedJson))
1038 })
1039
1040 It("writes the correct cached config", func() {
1041 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1042 Expect(err).NotTo(HaveOccurred())
1043
1044 // Ensure the cached config matches the returned one
1045 cachedConfig, newRt, err := cniConfig.GetNetworkListCachedConfig(netConfigList, runtimeConfig)
1046 Expect(err).NotTo(HaveOccurred())
1047 Expect(bytes.Equal(cachedConfig, netConfigList.Bytes)).To(BeTrue())
1048 Expect(reflect.DeepEqual(newRt.Args, runtimeConfig.Args)).To(BeTrue())
1049 // CapabilityArgs are freeform, so we have to match their JSON not
1050 // the Go structs (which could be unmarshalled differently than the
1051 // struct that was marshalled).
1052 expectedCABytes, err := json.Marshal(runtimeConfig.CapabilityArgs)
1053 Expect(err).NotTo(HaveOccurred())
1054 foundCABytes, err := json.Marshal(newRt.CapabilityArgs)
1055 Expect(err).NotTo(HaveOccurred())
1056 Expect(foundCABytes).To(MatchJSON(expectedCABytes))
1057 })
1058
1059 Context("when finding the plugin fails", func() {
1060 BeforeEach(func() {
1061 netConfigList.Plugins[1].Network.Type = "does-not-exist"
1062 })
1063
1064 It("returns the error", func() {
1065 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1066 Expect(err).To(MatchError(ContainSubstring(`failed to find plugin "does-not-exist"`)))
1067 })
1068 })
1069
1070 Context("when there is an invalid containerID", func() {
1071 BeforeEach(func() {
1072 runtimeConfig.ContainerID = "some-%%container-id"
1073 })
1074
1075 It("returns the error", func() {
1076 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1077 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1078 Code: types.ErrInvalidEnvironmentVariables,
1079 Msg: "invalid characters in containerID",
1080 Details: "some-%%container-id",
1081 }))
1082 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (add):"))
1083 })
1084 })
1085
1086 Context("when there is an invalid networkName", func() {
1087 BeforeEach(func() {
1088 netConfigList.Name = "invalid-%%-name"
1089 })
1090
1091 It("returns the error", func() {
1092 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1093 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1094 Code: types.ErrInvalidNetworkConfig,
1095 Msg: "invalid characters found in network name",
1096 Details: "invalid-%%-name",
1097 }))
1098 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (add):"))
1099 })
1100 })
1101
1102 Context("return errors when interface name is invalid", func() {
1103 It("interface name is empty", func() {
1104 runtimeConfig.IfName = ""
1105
1106 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1107 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1108 Code: types.ErrInvalidEnvironmentVariables,
1109 Msg: "interface name is empty",
1110 Details: "",
1111 }))
1112 })
1113
1114 It("interface name is too long", func() {
1115 runtimeConfig.IfName = "1234567890123456"
1116
1117 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1118 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1119 Code: types.ErrInvalidEnvironmentVariables,
1120 Msg: "interface name is too long",
1121 Details: "interface name should be less than 16 characters",
1122 }))
1123 })
1124
1125 It("interface name is .", func() {
1126 runtimeConfig.IfName = "."
1127
1128 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1129 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1130 Code: types.ErrInvalidEnvironmentVariables,
1131 Msg: "interface name is . or ..",
1132 Details: "",
1133 }))
1134 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (add):"))
1135 })
1136
1137 It("interface name is ..", func() {
1138 runtimeConfig.IfName = ".."
1139
1140 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1141 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1142 Code: types.ErrInvalidEnvironmentVariables,
1143 Msg: "interface name is . or ..",
1144 Details: "",
1145 }))
1146 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (add):"))
1147 })
1148
1149 It("interface name contains invalid characters /", func() {
1150 runtimeConfig.IfName = "test/test"
1151
1152 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1153 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1154 Code: types.ErrInvalidEnvironmentVariables,
1155 Msg: "interface name contains / or : or whitespace characters",
1156 Details: "",
1157 }))
1158 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (add):"))
1159 })
1160
1161 It("interface name contains invalid characters :", func() {
1162 runtimeConfig.IfName = "test:test"
1163
1164 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1165 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1166 Code: types.ErrInvalidEnvironmentVariables,
1167 Msg: "interface name contains / or : or whitespace characters",
1168 Details: "",
1169 }))
1170 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (add):"))
1171 })
1172
1173 It("interface name contains invalid characters whitespace", func() {
1174 runtimeConfig.IfName = "test test"
1175
1176 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1177 Expect(errors.Unwrap(err)).To(Equal(&types.Error{
1178 Code: types.ErrInvalidEnvironmentVariables,
1179 Msg: "interface name contains / or : or whitespace characters",
1180 Details: "",
1181 }))
1182 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (add):"))
1183 })
1184 })
1185
1186 Context("when the second plugin errors", func() {
1187 BeforeEach(func() {
1188 plugins[1].debug.ReportError = "plugin error: banana"
1189 Expect(plugins[1].debug.WriteDebug(plugins[1].debugFilePath)).To(Succeed())
1190 })
1191 It("unmarshals and returns the error", func() {
1192 result, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1193 Expect(result).To(BeNil())
1194 Expect(errors.Unwrap(err)).To(MatchError("plugin error: banana"))
1195 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (add):"))
1196 })
1197 It("should not have written cache files", func() {
1198 resultCacheFile := resultCacheFilePath(cacheDirPath, netConfigList.Name, runtimeConfig)
1199 _, err := os.ReadFile(resultCacheFile)
1200 Expect(err).To(HaveOccurred())
1201 })
1202 })
1203
1204 Context("when the cache directory cannot be accessed", func() {
1205 It("returns an error when the results cache file cannot be written", func() {
1206 // Make the results directory inaccessible by making it a
1207 // file instead of a directory
1208 tmpPath := filepath.Join(cacheDirPath, "results")
1209 err := os.WriteFile(tmpPath, []byte("afdsasdfasdf"), 0o600)
1210 Expect(err).NotTo(HaveOccurred())
1211
1212 result, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1213 Expect(result).To(BeNil())
1214 Expect(err).To(HaveOccurred())
1215 })
1216 })
1217 })
1218
1219 Describe("CheckNetworkList", func() {
1220 It("executes all plugins with command CHECK", func() {
1221 cacheFile := resultCacheFilePath(cacheDirPath, netConfigList.Name, runtimeConfig)
1222 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
1223 Expect(err).NotTo(HaveOccurred())
1224 err = os.WriteFile(cacheFile, []byte(ipResult), 0o600)
1225 Expect(err).NotTo(HaveOccurred())
1226
1227 err = cniConfig.CheckNetworkList(ctx, netConfigList, runtimeConfig)
1228 Expect(err).NotTo(HaveOccurred())
1229
1230 for i := 0; i < len(plugins); i++ {
1231 debug, err := noop_debug.ReadDebug(plugins[i].debugFilePath)
1232 Expect(err).NotTo(HaveOccurred())
1233 Expect(debug.Command).To(Equal("CHECK"))
1234
1235 // Ensure each plugin gets the prevResult from the cache
1236 asMap := make(map[string]interface{})
1237 err = json.Unmarshal(debug.CmdArgs.StdinData, &asMap)
1238 Expect(err).NotTo(HaveOccurred())
1239 Expect(asMap["prevResult"]).NotTo(BeNil())
1240 foo, err := json.Marshal(asMap["prevResult"])
1241 Expect(err).NotTo(HaveOccurred())
1242 Expect(foo).To(MatchJSON(ipResult))
1243
1244 debug.CmdArgs.StdinData = nil
1245 Expect(debug.CmdArgs).To(Equal(expectedCmdArgs))
1246 }
1247 })
1248
1249 It("does not executes plugins with command CHECK when disableCheck is true", func() {
1250 netConfigList.DisableCheck = true
1251 err := cniConfig.CheckNetworkList(ctx, netConfigList, runtimeConfig)
1252 Expect(err).NotTo(HaveOccurred())
1253
1254 for i := 0; i < len(plugins); i++ {
1255 debug, err := noop_debug.ReadDebug(plugins[i].debugFilePath)
1256 Expect(err).NotTo(HaveOccurred())
1257 Expect(debug.Command).To(Equal(""))
1258 }
1259 })
1260
1261 Context("when the configuration version", func() {
1262 var cacheFile string
1263
1264 BeforeEach(func() {
1265 cacheFile = resultCacheFilePath(cacheDirPath, netConfigList.Name, runtimeConfig)
1266 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
1267 Expect(err).NotTo(HaveOccurred())
1268 })
1269
1270 Context("is 0.4.0", func() {
1271 It("passes a cached result to the first plugin", func() {
1272 ipResult = `{
1273 "cniVersion": "0.4.0",
1274 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
1275 "dns": {}
1276 }`
1277 err := os.WriteFile(cacheFile, []byte(ipResult), 0o600)
1278 Expect(err).NotTo(HaveOccurred())
1279
1280 netConfigList, plugins = makePluginList("0.4.0", ipResult, rcMap)
1281 for _, p := range plugins {
1282 p.debug.ReportResult = ipResult
1283 Expect(p.debug.WriteDebug(p.debugFilePath)).To(Succeed())
1284 }
1285
1286 err = cniConfig.CheckNetworkList(ctx, netConfigList, runtimeConfig)
1287 Expect(err).NotTo(HaveOccurred())
1288
1289 // Match the first plugin's stdin config to the cached result JSON
1290 debug, err := noop_debug.ReadDebug(plugins[0].debugFilePath)
1291 Expect(err).NotTo(HaveOccurred())
1292
1293 var data map[string]interface{}
1294 err = json.Unmarshal(debug.CmdArgs.StdinData, &data)
1295 Expect(err).NotTo(HaveOccurred())
1296 stdinPrevResult, err := json.Marshal(data["prevResult"])
1297 Expect(err).NotTo(HaveOccurred())
1298 Expect(stdinPrevResult).To(MatchJSON(ipResult))
1299 })
1300 })
1301
1302 Context("is less than 0.4.0", func() {
1303 It("fails as CHECK is not supported before 0.4.0", func() {
1304 // Set an older CNI version
1305 confList := make(map[string]interface{})
1306 err := json.Unmarshal(netConfigList.Bytes, &confList)
1307 Expect(err).NotTo(HaveOccurred())
1308 confList["cniVersion"] = "0.3.1"
1309 newBytes, err := json.Marshal(confList)
1310 Expect(err).NotTo(HaveOccurred())
1311
1312 netConfigList, err = libcni.ConfListFromBytes(newBytes)
1313 Expect(err).NotTo(HaveOccurred())
1314 err = cniConfig.CheckNetworkList(ctx, netConfigList, runtimeConfig)
1315 Expect(err).To(MatchError("configuration version \"0.3.1\" does not support the CHECK command"))
1316 Expect(errors.Is(err, libcni.ErrorCheckNotSupp)).To(BeTrue())
1317 })
1318 })
1319 })
1320
1321 Context("when finding the plugin fails", func() {
1322 BeforeEach(func() {
1323 netConfigList.Plugins[1].Network.Type = "does-not-exist"
1324 })
1325
1326 It("returns the error", func() {
1327 err := cniConfig.CheckNetworkList(ctx, netConfigList, runtimeConfig)
1328 Expect(err).To(MatchError(ContainSubstring(`failed to find plugin "does-not-exist"`)))
1329 })
1330 })
1331
1332 Context("when the second plugin errors", func() {
1333 BeforeEach(func() {
1334 plugins[1].debug.ReportError = "plugin error: banana"
1335 Expect(plugins[1].debug.WriteDebug(plugins[1].debugFilePath)).To(Succeed())
1336 })
1337 It("unmarshals and returns the error", func() {
1338 err := cniConfig.CheckNetworkList(ctx, netConfigList, runtimeConfig)
1339 Expect(err).To(MatchError("plugin error: banana"))
1340 })
1341 })
1342
1343 Context("when the cached result is invalid", func() {
1344 It("returns an error", func() {
1345 cacheFile := resultCacheFilePath(cacheDirPath, netConfigList.Name, runtimeConfig)
1346 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
1347 Expect(err).NotTo(HaveOccurred())
1348 err = os.WriteFile(cacheFile, []byte("adfadsfasdfasfdsafaf"), 0o600)
1349 Expect(err).NotTo(HaveOccurred())
1350
1351 err = cniConfig.CheckNetworkList(ctx, netConfigList, runtimeConfig)
1352 Expect(err).To(MatchError("failed to get network \"some-list\" cached result: decoding version from network config: invalid character 'a' looking for beginning of value"))
1353 })
1354 })
1355 })
1356
1357 Describe("DelNetworkList", func() {
1358 It("executes all the plugins in reverse order with command DEL", func() {
1359 err := cniConfig.DelNetworkList(ctx, netConfigList, runtimeConfig)
1360 Expect(err).NotTo(HaveOccurred())
1361
1362 for i := 0; i < len(plugins); i++ {
1363 debug, err := noop_debug.ReadDebug(plugins[i].debugFilePath)
1364 Expect(err).NotTo(HaveOccurred())
1365 Expect(debug.Command).To(Equal("DEL"))
1366
1367 // Must explicitly match JSON due to dict element ordering
1368 Expect(debug.CmdArgs.StdinData).To(MatchJSON(plugins[i].stdinData))
1369 debug.CmdArgs.StdinData = nil
1370 Expect(debug.CmdArgs).To(Equal(expectedCmdArgs))
1371 }
1372
1373 // Ensure the cached result no longer exists
1374 cachedResult, err := cniConfig.GetNetworkListCachedResult(netConfigList, runtimeConfig)
1375 Expect(err).NotTo(HaveOccurred())
1376 Expect(cachedResult).To(BeNil())
1377
1378 // Ensure the cached config no longer exists
1379 cachedConfig, newRt, err := cniConfig.GetNetworkListCachedConfig(netConfigList, runtimeConfig)
1380 Expect(err).NotTo(HaveOccurred())
1381 Expect(cachedConfig).To(BeNil())
1382 Expect(newRt).To(BeNil())
1383 })
1384
1385 Context("when the configuration version", func() {
1386 var cacheFile string
1387
1388 BeforeEach(func() {
1389 cacheFile = resultCacheFilePath(cacheDirPath, netConfigList.Name, runtimeConfig)
1390 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
1391 Expect(err).NotTo(HaveOccurred())
1392 })
1393
1394 Context("is 0.4.0", func() {
1395 It("passes a cached result to the first plugin", func() {
1396 ipResult = `{
1397 "cniVersion": "0.4.0",
1398 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
1399 "dns": {}
1400 }`
1401 err := os.WriteFile(cacheFile, []byte(ipResult), 0o600)
1402 Expect(err).NotTo(HaveOccurred())
1403
1404 netConfigList, plugins = makePluginList("0.4.0", ipResult, rcMap)
1405 for _, p := range plugins {
1406 p.debug.ReportResult = ipResult
1407 Expect(p.debug.WriteDebug(p.debugFilePath)).To(Succeed())
1408 }
1409
1410 err = cniConfig.DelNetworkList(ctx, netConfigList, runtimeConfig)
1411 Expect(err).NotTo(HaveOccurred())
1412
1413 // Match the first plugin's stdin config to the cached result JSON
1414 debug, err := noop_debug.ReadDebug(plugins[0].debugFilePath)
1415 Expect(err).NotTo(HaveOccurred())
1416
1417 var data map[string]interface{}
1418 err = json.Unmarshal(debug.CmdArgs.StdinData, &data)
1419 Expect(err).NotTo(HaveOccurred())
1420 stdinPrevResult, err := json.Marshal(data["prevResult"])
1421 Expect(err).NotTo(HaveOccurred())
1422 Expect(stdinPrevResult).To(MatchJSON(ipResult))
1423 })
1424 })
1425
1426 Context("is less than 0.4.0", func() {
1427 It("does not pass a cached result to the first plugin", func() {
1428 ipResult = `{
1429 "cniVersion": "0.3.1",
1430 "ips": [{"version": "4", "address": "10.1.2.3/24"}],
1431 "dns": {}
1432 }`
1433 err := os.WriteFile(cacheFile, []byte(ipResult), 0o600)
1434 Expect(err).NotTo(HaveOccurred())
1435
1436 netConfigList, plugins = makePluginList("0.3.1", ipResult, rcMap)
1437 for _, p := range plugins {
1438 p.debug.ReportResult = ipResult
1439 Expect(p.debug.WriteDebug(p.debugFilePath)).To(Succeed())
1440 }
1441
1442 err = cniConfig.DelNetworkList(ctx, netConfigList, runtimeConfig)
1443 Expect(err).NotTo(HaveOccurred())
1444
1445 // Make sure first plugin does not receive a prevResult
1446 debug, err := noop_debug.ReadDebug(plugins[0].debugFilePath)
1447 Expect(err).NotTo(HaveOccurred())
1448 Expect(string(debug.CmdArgs.StdinData)).NotTo(ContainSubstring("\"prevResult\":"))
1449 })
1450 })
1451 })
1452
1453 Context("when finding the plugin fails", func() {
1454 BeforeEach(func() {
1455 netConfigList.Plugins[1].Network.Type = "does-not-exist"
1456 })
1457
1458 It("returns the error", func() {
1459 err := cniConfig.DelNetworkList(ctx, netConfigList, runtimeConfig)
1460 Expect(err).To(MatchError(ContainSubstring(`failed to find plugin "does-not-exist"`)))
1461 })
1462 })
1463
1464 Context("when the plugin errors", func() {
1465 BeforeEach(func() {
1466 plugins[1].debug.ReportError = "plugin error: banana"
1467 Expect(plugins[1].debug.WriteDebug(plugins[1].debugFilePath)).To(Succeed())
1468 })
1469 It("unmarshals and returns the error", func() {
1470 err := cniConfig.DelNetworkList(ctx, netConfigList, runtimeConfig)
1471 Expect(errors.Unwrap(err)).To(MatchError("plugin error: banana"))
1472 Expect(err.Error()).To(HavePrefix("plugin type=\"noop\" failed (delete):"))
1473 })
1474 })
1475
1476 Context("when the cached result is invalid", func() {
1477 It("tolerates the error", func() {
1478 cacheFile := resultCacheFilePath(cacheDirPath, netConfigList.Name, runtimeConfig)
1479 err := os.MkdirAll(filepath.Dir(cacheFile), 0o700)
1480 Expect(err).NotTo(HaveOccurred())
1481 err = os.WriteFile(cacheFile, []byte("adfadsfasdfasfdsafaf"), 0o600)
1482 Expect(err).NotTo(HaveOccurred())
1483
1484 err = cniConfig.DelNetworkList(ctx, netConfigList, runtimeConfig)
1485 Expect(err).NotTo(HaveOccurred())
1486 })
1487 })
1488 })
1489 Describe("ValidateNetworkList", func() {
1490 It("Checks that all plugins exist", func() {
1491 caps, err := cniConfig.ValidateNetworkList(ctx, netConfigList)
1492 Expect(err).NotTo(HaveOccurred())
1493 Expect(caps).To(ConsistOf("portMappings", "otherCapability"))
1494
1495 netConfigList.Plugins[1].Network.Type = "nope"
1496 _, err = cniConfig.ValidateNetworkList(ctx, netConfigList)
1497 Expect(err).To(MatchError("[failed to find plugin \"nope\" in path [" + cniConfig.Path[0] + "]]"))
1498 })
1499
1500 It("Checks that the plugins support the needed version", func() {
1501 netConfigList.CNIVersion = "broken"
1502 _, err := cniConfig.ValidateNetworkList(ctx, netConfigList)
1503
1504 // The config list is just noop 3 times, so we get 3 errors
1505 Expect(err).To(MatchError("[plugin noop does not support config version \"broken\" plugin noop does not support config version \"broken\" plugin noop does not support config version \"broken\"]"))
1506 })
1507 })
1508 Describe("GCNetworkList", func() {
1509 It("issues a DEL and GC as necessary", func() {
1510 By("doing a CNI ADD")
1511 _, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1512 Expect(err).NotTo(HaveOccurred())
1513
1514 By("Issuing a GC with disableGC=true")
1515 netConfigList.DisableGC = true
1516 gcargs := &libcni.GCArgs{}
1517 err = cniConfig.GCNetworkList(ctx, netConfigList, gcargs)
1518 Expect(err).NotTo(HaveOccurred())
1519
1520 commands, err := noop_debug.ReadCommandLog(plugins[0].commandFilePath)
1521 Expect(err).NotTo(HaveOccurred())
1522 Expect(commands).To(HaveLen(1)) // ADD
1523
1524 By("Issuing a GC with valid networks")
1525 netConfigList.DisableGC = false
1526 gcargs = &libcni.GCArgs{
1527 ValidAttachments: []types.GCAttachment{{
1528 ContainerID: runtimeConfig.ContainerID,
1529 IfName: runtimeConfig.IfName,
1530 }},
1531 }
1532 err = cniConfig.GCNetworkList(ctx, netConfigList, gcargs)
1533 Expect(err).NotTo(HaveOccurred())
1534
1535 By("Issuing a GC with no valid networks")
1536 gcargs.ValidAttachments = nil
1537 err = cniConfig.GCNetworkList(ctx, netConfigList, gcargs)
1538 Expect(err).NotTo(HaveOccurred())
1539
1540 commands, err = noop_debug.ReadCommandLog(plugins[0].commandFilePath)
1541 Expect(err).NotTo(HaveOccurred())
1542 Expect(commands).To(HaveLen(4))
1543
1544 validations := []struct {
1545 name string
1546 fn func(entry noop_debug.CmdLogEntry)
1547 }{
1548 {
1549 name: "ADD",
1550 fn: func(entry noop_debug.CmdLogEntry) {
1551 Expect(entry.CmdArgs.ContainerID).To(Equal(runtimeConfig.ContainerID))
1552 Expect(entry.CmdArgs.IfName).To(Equal(runtimeConfig.IfName))
1553 },
1554 },
1555 {
1556 name: "GC",
1557 fn: func(entry noop_debug.CmdLogEntry) {
1558 var conf struct {
1559 Attachments []map[string]string `json:"cni.dev/valid-attachments"`
1560 }
1561 err = json.Unmarshal(entry.CmdArgs.StdinData, &conf)
1562 Expect(err).NotTo(HaveOccurred())
1563 Expect(conf.Attachments).To(HaveLen(1))
1564 Expect(conf.Attachments[0]).To(Equal(map[string]string{"containerID": runtimeConfig.ContainerID, "ifname": runtimeConfig.IfName}))
1565 },
1566 },
1567 {
1568 name: "DEL",
1569 fn: func(entry noop_debug.CmdLogEntry) {
1570 Expect(entry.CmdArgs.ContainerID).To(Equal(runtimeConfig.ContainerID))
1571 Expect(entry.CmdArgs.IfName).To(Equal(runtimeConfig.IfName))
1572 },
1573 },
1574 {
1575 name: "GC",
1576 fn: func(entry noop_debug.CmdLogEntry) {
1577 var conf struct {
1578 Attachments []map[string]string `json:"cni.dev/valid-attachments"`
1579 }
1580 err = json.Unmarshal(entry.CmdArgs.StdinData, &conf)
1581 Expect(err).NotTo(HaveOccurred())
1582 Expect(conf.Attachments).To(BeEmpty())
1583 },
1584 },
1585 }
1586 for i, c := range validations {
1587 Expect(commands[i].Command).To(Equal(c.name))
1588 c.fn(commands[i])
1589 }
1590 })
1591 })
1592 Describe("GetStatusNetworkList", func() {
1593 It("issues a STATUS request", func() {
1594 netConfigList, plugins = makePluginList("1.1.0", ipResult, rcMap)
1595
1596 err := cniConfig.GetStatusNetworkList(ctx, netConfigList)
1597 Expect(err).NotTo(HaveOccurred())
1598
1599 debug, err := noop_debug.ReadDebug(plugins[0].debugFilePath)
1600 Expect(err).NotTo(HaveOccurred())
1601 Expect(debug.Command).To(Equal("STATUS"))
1602 })
1603
1604 It("correctly reports an error", func() {
1605 netConfigList, plugins = makePluginList("1.1.0", ipResult, rcMap)
1606
1607 plugins[1].debug.ReportError = "plugin error: banana"
1608 plugins[1].debug.ReportErrorCode = 50
1609 Expect(plugins[1].debug.WriteDebug(plugins[1].debugFilePath)).To(Succeed())
1610
1611 err := cniConfig.GetStatusNetworkList(ctx, netConfigList)
1612 Expect(err).To(HaveOccurred())
1613 var eerr *types.Error
1614 Expect(errors.As(err, &eerr)).To(BeTrue())
1615 Expect(eerr.Code).To(Equal(uint(50)))
1616
1617 debug, err := noop_debug.ReadDebug(plugins[0].debugFilePath)
1618 Expect(err).NotTo(HaveOccurred())
1619 Expect(debug.Command).To(Equal("STATUS"))
1620
1621 debug, err = noop_debug.ReadDebug(plugins[1].debugFilePath)
1622 Expect(err).NotTo(HaveOccurred())
1623 Expect(debug.Command).To(Equal("STATUS"))
1624
1625 debug, err = noop_debug.ReadDebug(plugins[2].debugFilePath)
1626 Expect(err).NotTo(HaveOccurred())
1627 Expect(debug.Command).To(Equal(""))
1628 })
1629 })
1630 })
1631
1632 Describe("Invoking a sleep plugin", func() {
1633 var (
1634 debugFilePath string
1635 debug *noop_debug.Debug
1636 cniBinPath string
1637 pluginConfig string
1638 cniConfig *libcni.CNIConfig
1639 netConfig *libcni.PluginConfig
1640 runtimeConfig *libcni.RuntimeConf
1641 netConfigList *libcni.NetworkConfigList
1642 )
1643
1644 BeforeEach(func() {
1645 debugFile, err := os.CreateTemp("", "cni_debug")
1646 Expect(err).NotTo(HaveOccurred())
1647 Expect(debugFile.Close()).To(Succeed())
1648 debugFilePath = debugFile.Name()
1649
1650 debug = &noop_debug.Debug{
1651 ReportResult: `{ "ips": [{ "version": "4", "address": "10.1.2.3/24" }], "dns": {} }`,
1652 }
1653 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
1654
1655 portMappings := []portMapping{
1656 {HostPort: 8080, ContainerPort: 80, Protocol: "tcp"},
1657 }
1658
1659 pluginConfig = fmt.Sprintf(`{
1660 "type": "sleep",
1661 "name": "apitest",
1662 "some-key": "some-value",
1663 "cniVersion": "%s",
1664 "capabilities": { "portMappings": true }
1665 }`, version.Current())
1666
1667 cniBinPath = filepath.Dir(pluginPaths["sleep"])
1668 cniConfig = libcni.NewCNIConfig([]string{cniBinPath}, nil)
1669 netConfig, err = libcni.ConfFromBytes([]byte(pluginConfig))
1670 Expect(err).NotTo(HaveOccurred())
1671 runtimeConfig = &libcni.RuntimeConf{
1672 ContainerID: "some-container-id",
1673 NetNS: "/some/netns/path",
1674 IfName: "some-eth0",
1675 Args: [][2]string{{"DEBUG", debugFilePath}},
1676 }
1677
1678 // inject runtime args into the expected plugin config
1679 conf := make(map[string]interface{})
1680 err = json.Unmarshal([]byte(pluginConfig), &conf)
1681 Expect(err).NotTo(HaveOccurred())
1682 conf["runtimeConfig"] = map[string]interface{}{
1683 "portMappings": portMappings,
1684 }
1685
1686 configList := []byte(fmt.Sprintf(`{
1687 "name": "some-list",
1688 "cniVersion": "%s",
1689 "plugins": [
1690 %s
1691 ]
1692 }`, version.Current(), pluginConfig))
1693
1694 netConfigList, err = libcni.ConfListFromBytes(configList)
1695 Expect(err).NotTo(HaveOccurred())
1696 })
1697
1698 AfterEach(func() {
1699 Expect(os.RemoveAll(debugFilePath)).To(Succeed())
1700 })
1701
1702 Describe("AddNetwork", func() {
1703 Context("when the plugin timeout", func() {
1704 It("returns the timeout error", func() {
1705 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1706 result, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
1707 cancel()
1708 Expect(result).To(BeNil())
1709 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1710 })
1711 })
1712 })
1713
1714 Describe("DelNetwork", func() {
1715 Context("when the plugin timeout", func() {
1716 It("returns the timeout error", func() {
1717 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1718 err := cniConfig.DelNetwork(ctx, netConfig, runtimeConfig)
1719 cancel()
1720 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1721 })
1722 })
1723 })
1724
1725 Describe("CheckNetwork", func() {
1726 Context("when the plugin timeout", func() {
1727 It("returns the timeout error", func() {
1728 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1729 err := cniConfig.CheckNetwork(ctx, netConfig, runtimeConfig)
1730 cancel()
1731 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1732 })
1733 })
1734 })
1735
1736 Describe("GetVersionInfo", func() {
1737 Context("when the plugin timeout", func() {
1738 It("returns the timeout error", func() {
1739 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1740 result, err := cniConfig.GetVersionInfo(ctx, "sleep")
1741 cancel()
1742 Expect(result).To(BeNil())
1743 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1744 })
1745 })
1746 })
1747
1748 Describe("ValidateNetwork", func() {
1749 Context("when the plugin timeout", func() {
1750 It("returns the timeout error", func() {
1751 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1752 _, err := cniConfig.ValidateNetwork(ctx, netConfig)
1753 cancel()
1754 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1755 })
1756 })
1757 })
1758
1759 Describe("AddNetworkList", func() {
1760 Context("when the plugin timeout", func() {
1761 It("returns the timeout error", func() {
1762 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1763 result, err := cniConfig.AddNetworkList(ctx, netConfigList, runtimeConfig)
1764 cancel()
1765 Expect(result).To(BeNil())
1766 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1767 })
1768 })
1769 })
1770
1771 Describe("DelNetworkList", func() {
1772 Context("when the plugin timeout", func() {
1773 It("returns the timeout error", func() {
1774 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1775 err := cniConfig.DelNetworkList(ctx, netConfigList, runtimeConfig)
1776 cancel()
1777 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1778 })
1779 })
1780 })
1781
1782 Describe("CheckNetworkList", func() {
1783 Context("when the plugin timeout", func() {
1784 It("returns the timeout error", func() {
1785 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1786 err := cniConfig.CheckNetworkList(ctx, netConfigList, runtimeConfig)
1787 cancel()
1788 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1789 })
1790 })
1791 })
1792
1793 Describe("ValidateNetworkList", func() {
1794 Context("when the plugin timeout", func() {
1795 It("returns the timeout error", func() {
1796 ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
1797 _, err := cniConfig.ValidateNetworkList(ctx, netConfigList)
1798 cancel()
1799 Expect(err).To(MatchError(ContainSubstring("netplugin failed with no error message")))
1800 })
1801 })
1802 })
1803 })
1804
1805 Describe("Cache operations", func() {
1806 var (
1807 debugFilePath string
1808 debug *noop_debug.Debug
1809 cniBinPath string
1810 pluginConfig string
1811 cniConfig *libcni.CNIConfig
1812 netConfig *libcni.PluginConfig
1813 runtimeConfig *libcni.RuntimeConf
1814
1815 ctx context.Context
1816 )
1817 firstIP := "10.1.2.3/24"
1818 firstIfname := "eth0"
1819 secondIP := "10.1.2.5/24"
1820 secondIfname := "eth1"
1821 containerID := "some-container-id"
1822 netName := "cachetest"
1823 netNS := "/some/netns/path"
1824
1825 BeforeEach(func() {
1826 debugFile, err := os.CreateTemp("", "cni_debug")
1827 Expect(err).NotTo(HaveOccurred())
1828 Expect(debugFile.Close()).To(Succeed())
1829 debugFilePath = debugFile.Name()
1830
1831 debug = &noop_debug.Debug{
1832 ReportResult: fmt.Sprintf(`{
1833 "cniVersion": "%s",
1834 "ips": [{"version": "4", "address": "%s"}]
1835 }`, version.Current(), firstIP),
1836 }
1837 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
1838
1839 cniBinPath = filepath.Dir(pluginPaths["noop"])
1840 pluginConfig = fmt.Sprintf(`{
1841 "type": "noop",
1842 "name": "%s",
1843 "cniVersion": "%s"
1844 }`, netName, version.Current())
1845 cniConfig = libcni.NewCNIConfigWithCacheDir([]string{cniBinPath}, cacheDirPath, nil)
1846 netConfig, err = libcni.ConfFromBytes([]byte(pluginConfig))
1847 Expect(err).NotTo(HaveOccurred())
1848 runtimeConfig = &libcni.RuntimeConf{
1849 ContainerID: containerID,
1850 NetNS: netNS,
1851 IfName: firstIfname,
1852 Args: [][2]string{{"DEBUG", debugFilePath}},
1853 }
1854 ctx = context.TODO()
1855 })
1856
1857 AfterEach(func() {
1858 Expect(os.RemoveAll(debugFilePath)).To(Succeed())
1859 })
1860
1861 It("creates separate result cache files for multiple attachments to the same network", func() {
1862 _, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
1863 Expect(err).NotTo(HaveOccurred())
1864
1865 debug.ReportResult = fmt.Sprintf(`{
1866 "cniVersion": "%s",
1867 "ips": [{"version": "4", "address": "%s"}]
1868 }`, version.Current(), secondIP)
1869 Expect(debug.WriteDebug(debugFilePath)).To(Succeed())
1870 runtimeConfig.IfName = secondIfname
1871 _, err = cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
1872 Expect(err).NotTo(HaveOccurred())
1873
1874 resultsDir := filepath.Join(cacheDirPath, "results")
1875 files, err := os.ReadDir(resultsDir)
1876 Expect(err).NotTo(HaveOccurred())
1877 Expect(files).To(HaveLen(2))
1878 var foundFirst, foundSecond bool
1879 for _, f := range files {
1880 type cachedConfig struct {
1881 Kind string `json:"kind"`
1882 IfName string `json:"ifName"`
1883 ContainerID string `json:"containerId"`
1884 NetworkName string `json:"networkName"`
1885 }
1886
1887 data, err := os.ReadFile(filepath.Join(resultsDir, f.Name()))
1888 Expect(err).NotTo(HaveOccurred())
1889 cc := &cachedConfig{}
1890 err = json.Unmarshal(data, cc)
1891 Expect(err).NotTo(HaveOccurred())
1892 Expect(cc.Kind).To(Equal("cniCacheV1"))
1893 Expect(cc.ContainerID).To(Equal(containerID))
1894 Expect(cc.NetworkName).To(Equal(netName))
1895 if strings.HasSuffix(f.Name(), firstIfname) {
1896 foundFirst = true
1897 Expect(strings.Contains(string(data), firstIP)).To(BeTrue())
1898 Expect(cc.IfName).To(Equal(firstIfname))
1899 } else if strings.HasSuffix(f.Name(), secondIfname) {
1900 foundSecond = true
1901 Expect(strings.Contains(string(data), secondIP)).To(BeTrue())
1902 Expect(cc.IfName).To(Equal(secondIfname))
1903 }
1904 }
1905 Expect(foundFirst).To(BeTrue())
1906 Expect(foundSecond).To(BeTrue())
1907 })
1908
1909 It("returns an updated copy of RuntimeConf filled with cached info", func() {
1910 _, err := cniConfig.AddNetwork(ctx, netConfig, runtimeConfig)
1911 Expect(err).NotTo(HaveOccurred())
1912
1913 // Ensure the cached config matches the sent one
1914 rt := &libcni.RuntimeConf{
1915 ContainerID: containerID,
1916 NetNS: netNS,
1917 IfName: firstIfname,
1918 }
1919 _, newRt, err := cniConfig.GetNetworkListCachedConfig(&libcni.NetworkConfigList{Name: netName}, rt)
1920 Expect(err).NotTo(HaveOccurred())
1921 Expect(newRt.IfName).To(Equal(runtimeConfig.IfName))
1922 Expect(newRt.ContainerID).To(Equal(runtimeConfig.ContainerID))
1923 Expect(reflect.DeepEqual(newRt.Args, runtimeConfig.Args)).To(BeTrue())
1924 expectedCABytes, err := json.Marshal(runtimeConfig.CapabilityArgs)
1925 Expect(err).NotTo(HaveOccurred())
1926 foundCABytes, err := json.Marshal(newRt.CapabilityArgs)
1927 Expect(err).NotTo(HaveOccurred())
1928 Expect(foundCABytes).To(MatchJSON(expectedCABytes))
1929 })
1930
1931 Context("when the RuntimeConf is incomplete", func() {
1932 var (
1933 testRt *libcni.RuntimeConf
1934 testNetConf *libcni.PluginConfig
1935 testNetConfList *libcni.NetworkConfigList
1936 )
1937
1938 BeforeEach(func() {
1939 testRt = &libcni.RuntimeConf{}
1940 testNetConf = &libcni.PluginConfig{
1941 Network: &types.PluginConf{},
1942 }
1943 testNetConfList = &libcni.NetworkConfigList{}
1944 })
1945
1946 It("returns an error on missing network name", func() {
1947 testRt.ContainerID = containerID
1948 testRt.IfName = firstIfname
1949 cachedConfig, newRt, err := cniConfig.GetNetworkCachedConfig(testNetConf, testRt)
1950 Expect(err).To(MatchError("cache file path requires network name (\"\"), container ID (\"some-container-id\"), and interface name (\"eth0\")"))
1951 Expect(cachedConfig).To(BeNil())
1952 Expect(newRt).To(BeNil())
1953
1954 cachedConfig, newRt, err = cniConfig.GetNetworkListCachedConfig(testNetConfList, testRt)
1955 Expect(err).To(MatchError("cache file path requires network name (\"\"), container ID (\"some-container-id\"), and interface name (\"eth0\")"))
1956 Expect(cachedConfig).To(BeNil())
1957 Expect(newRt).To(BeNil())
1958 })
1959
1960 It("returns an error on missing container ID", func() {
1961 testNetConf.Network.Name = "foobar"
1962 testNetConfList.Name = "foobar"
1963 testRt.IfName = firstIfname
1964
1965 cachedConfig, newRt, err := cniConfig.GetNetworkCachedConfig(testNetConf, testRt)
1966 Expect(err).To(MatchError("cache file path requires network name (\"foobar\"), container ID (\"\"), and interface name (\"eth0\")"))
1967 Expect(cachedConfig).To(BeNil())
1968 Expect(newRt).To(BeNil())
1969
1970 cachedConfig, newRt, err = cniConfig.GetNetworkListCachedConfig(testNetConfList, testRt)
1971 Expect(err).To(MatchError("cache file path requires network name (\"foobar\"), container ID (\"\"), and interface name (\"eth0\")"))
1972 Expect(cachedConfig).To(BeNil())
1973 Expect(newRt).To(BeNil())
1974 })
1975
1976 It("returns an error on missing interface name", func() {
1977 testNetConf.Network.Name = "foobar"
1978 testNetConfList.Name = "foobar"
1979 testRt.ContainerID = containerID
1980
1981 cachedConfig, newRt, err := cniConfig.GetNetworkCachedConfig(testNetConf, testRt)
1982 Expect(err).To(MatchError("cache file path requires network name (\"foobar\"), container ID (\"some-container-id\"), and interface name (\"\")"))
1983 Expect(cachedConfig).To(BeNil())
1984 Expect(newRt).To(BeNil())
1985
1986 cachedConfig, newRt, err = cniConfig.GetNetworkListCachedConfig(testNetConfList, testRt)
1987 Expect(err).To(MatchError("cache file path requires network name (\"foobar\"), container ID (\"some-container-id\"), and interface name (\"\")"))
1988 Expect(cachedConfig).To(BeNil())
1989 Expect(newRt).To(BeNil())
1990 })
1991 })
1992
1993 Context("when the cached config", func() {
1994 Context("is invalid JSON", func() {
1995 It("returns an error", func() {
1996 resultCacheFile := resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
1997 err := os.MkdirAll(filepath.Dir(resultCacheFile), 0o700)
1998 Expect(err).NotTo(HaveOccurred())
1999
2000 err = os.WriteFile(resultCacheFile, []byte("adfadsfasdfasfdsafaf"), 0o600)
2001 Expect(err).NotTo(HaveOccurred())
2002
2003 cachedConfig, newRt, err := cniConfig.GetNetworkCachedConfig(netConfig, runtimeConfig)
2004 Expect(err).To(MatchError("failed to unmarshal cached network \"cachetest\" config: invalid character 'a' looking for beginning of value"))
2005 Expect(cachedConfig).To(BeNil())
2006 Expect(newRt).To(BeNil())
2007 })
2008 })
2009 Context("is missing", func() {
2010 It("returns no error", func() {
2011 resultCacheFile := resultCacheFilePath(cacheDirPath, netConfig.Network.Name, runtimeConfig)
2012 err := os.MkdirAll(filepath.Dir(resultCacheFile), 0o700)
2013 Expect(err).NotTo(HaveOccurred())
2014
2015 cachedConfig, newRt, err := cniConfig.GetNetworkCachedConfig(netConfig, runtimeConfig)
2016 Expect(err).NotTo(HaveOccurred())
2017 Expect(cachedConfig).To(BeNil())
2018 Expect(newRt).To(BeNil())
2019 })
2020 })
2021 })
2022 })
2023 })