Debian Codegraph @

plugins/main/ptp/ptp_test.go

raw symbols SCIP
1 // Copyright 2015 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 main
16
17 import (
18 "encoding/json"
19 "fmt"
20 "os"
21 "strings"
22
23 . "github.com/onsi/ginkgo/v2"
24 . "github.com/onsi/gomega"
25
26 "github.com/containernetworking/cni/pkg/skel"
27 "github.com/containernetworking/cni/pkg/types"
28 types020 "github.com/containernetworking/cni/pkg/types/020"
29 types040 "github.com/containernetworking/cni/pkg/types/040"
30 types100 "github.com/containernetworking/cni/pkg/types/100"
31 "github.com/containernetworking/plugins/pkg/netlinksafe"
32 "github.com/containernetworking/plugins/pkg/ns"
33 "github.com/containernetworking/plugins/pkg/testutils"
34 "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
35 )
36
37 type Net struct {
38 Name string `json:"name"`
39 CNIVersion string `json:"cniVersion"`
40 Type string `json:"type,omitempty"`
41 IPMasq bool `json:"ipMasq"`
42 IPMasqBackend *string `json:"ipMasqBackend,omitempty"`
43 MTU int `json:"mtu"`
44 IPAM *allocator.IPAMConfig `json:"ipam"`
45 DNS types.DNS `json:"dns"`
46 RawPrevResult map[string]interface{} `json:"prevResult,omitempty"`
47 PrevResult types100.Result `json:"-"`
48 }
49
50 func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult types.Result) (*Net, error) {
51 var err error
52
53 inject := map[string]interface{}{
54 "name": netName,
55 "cniVersion": cniVersion,
56 }
57 // Add previous plugin result
58 if prevResult != nil {
59 inject["prevResult"] = prevResult
60 }
61
62 // Ensure every config uses the same name and version
63 config := make(map[string]interface{})
64
65 confBytes, err := json.Marshal(orig)
66 if err != nil {
67 return nil, err
68 }
69
70 err = json.Unmarshal(confBytes, &config)
71 if err != nil {
72 return nil, fmt.Errorf("unmarshal existing network bytes: %s", err)
73 }
74
75 for key, value := range inject {
76 config[key] = value
77 }
78
79 newBytes, err := json.Marshal(config)
80 if err != nil {
81 return nil, err
82 }
83
84 conf := &Net{}
85 if err := json.Unmarshal(newBytes, &conf); err != nil {
86 return nil, fmt.Errorf("error parsing configuration: %s", err)
87 }
88
89 return conf, nil
90 }
91
92 type tester interface {
93 // verifyResult minimally verifies the Result and returns the interface's IP addresses and MAC address
94 verifyResult(result types.Result, expectedIfName, expectedSandbox string, expectedDNS types.DNS) ([]resultIP, string)
95 }
96
97 type testerBase struct{}
98
99 type (
100 testerV10x testerBase
101 testerV04x testerBase
102 testerV03x testerBase
103 testerV01xOr02x testerBase
104 )
105
106 func newTesterByVersion(version string) tester {
107 switch {
108 case strings.HasPrefix(version, "1."):
109 return &testerV10x{}
110 case strings.HasPrefix(version, "0.4."):
111 return &testerV04x{}
112 case strings.HasPrefix(version, "0.3."):
113 return &testerV03x{}
114 default:
115 return &testerV01xOr02x{}
116 }
117 }
118
119 type resultIP struct {
120 ip string
121 gw string
122 }
123
124 // verifyResult minimally verifies the Result and returns the interface's IP addresses and MAC address
125 func (t *testerV10x) verifyResult(result types.Result, expectedIfName, expectedSandbox string, expectedDNS types.DNS) ([]resultIP, string) {
126 r, err := types100.GetResult(result)
127 Expect(err).NotTo(HaveOccurred())
128
129 Expect(r.Interfaces).To(HaveLen(2))
130 Expect(r.Interfaces[0].Name).To(HavePrefix("veth"))
131 Expect(r.Interfaces[0].Mac).To(HaveLen(17))
132 Expect(r.Interfaces[0].Sandbox).To(BeEmpty())
133 Expect(r.Interfaces[1].Name).To(Equal(expectedIfName))
134 Expect(r.Interfaces[1].Sandbox).To(Equal(expectedSandbox))
135
136 Expect(r.DNS).To(Equal(expectedDNS))
137
138 // Grab IPs from container interface
139 ips := []resultIP{}
140 for _, ipc := range r.IPs {
141 if *ipc.Interface == 1 {
142 ips = append(ips, resultIP{
143 ip: ipc.Address.IP.String(),
144 gw: ipc.Gateway.String(),
145 })
146 }
147 }
148
149 return ips, r.Interfaces[1].Mac
150 }
151
152 func verify0403(result types.Result, expectedIfName, expectedSandbox string, expectedDNS types.DNS) ([]resultIP, string) {
153 r, err := types040.GetResult(result)
154 Expect(err).NotTo(HaveOccurred())
155
156 Expect(r.Interfaces).To(HaveLen(2))
157 Expect(r.Interfaces[0].Name).To(HavePrefix("veth"))
158 Expect(r.Interfaces[0].Mac).To(HaveLen(17))
159 Expect(r.Interfaces[0].Sandbox).To(BeEmpty())
160 Expect(r.Interfaces[1].Name).To(Equal(expectedIfName))
161 Expect(r.Interfaces[1].Sandbox).To(Equal(expectedSandbox))
162
163 Expect(r.DNS).To(Equal(expectedDNS))
164
165 // Grab IPs from container interface
166 ips := []resultIP{}
167 for _, ipc := range r.IPs {
168 if *ipc.Interface == 1 {
169 ips = append(ips, resultIP{
170 ip: ipc.Address.IP.String(),
171 gw: ipc.Gateway.String(),
172 })
173 }
174 }
175
176 return ips, r.Interfaces[1].Mac
177 }
178
179 // verifyResult minimally verifies the Result and returns the interface's IP addresses and MAC address
180 func (t *testerV04x) verifyResult(result types.Result, expectedIfName, expectedSandbox string, expectedDNS types.DNS) ([]resultIP, string) {
181 return verify0403(result, expectedIfName, expectedSandbox, expectedDNS)
182 }
183
184 // verifyResult minimally verifies the Result and returns the interface's IP addresses and MAC address
185 func (t *testerV03x) verifyResult(result types.Result, expectedIfName, expectedSandbox string, expectedDNS types.DNS) ([]resultIP, string) {
186 return verify0403(result, expectedIfName, expectedSandbox, expectedDNS)
187 }
188
189 // verifyResult minimally verifies the Result and returns the interface's IP addresses and MAC address
190 func (t *testerV01xOr02x) verifyResult(result types.Result, _, _ string, _ types.DNS) ([]resultIP, string) {
191 r, err := types020.GetResult(result)
192 Expect(err).NotTo(HaveOccurred())
193
194 ips := []resultIP{}
195 if r.IP4 != nil && r.IP4.IP.IP != nil {
196 ips = append(ips, resultIP{
197 ip: r.IP4.IP.IP.String(),
198 gw: r.IP4.Gateway.String(),
199 })
200 }
201 if r.IP6 != nil && r.IP6.IP.IP != nil {
202 ips = append(ips, resultIP{
203 ip: r.IP6.IP.IP.String(),
204 gw: r.IP6.Gateway.String(),
205 })
206 }
207
208 // 0.2 and earlier don't return MAC address
209 return ips, ""
210 }
211
212 var _ = Describe("ptp Operations", func() {
213 var originalNS, targetNS ns.NetNS
214 var dataDir string
215
216 BeforeEach(func() {
217 // Create a new NetNS so we don't modify the host
218 var err error
219 originalNS, err = testutils.NewNS()
220 Expect(err).NotTo(HaveOccurred())
221 targetNS, err = testutils.NewNS()
222 Expect(err).NotTo(HaveOccurred())
223
224 dataDir, err = os.MkdirTemp("", "ptp_test")
225 Expect(err).NotTo(HaveOccurred())
226 })
227
228 AfterEach(func() {
229 Expect(os.RemoveAll(dataDir)).To(Succeed())
230 Expect(originalNS.Close()).To(Succeed())
231 Expect(testutils.UnmountNS(originalNS)).To(Succeed())
232 Expect(targetNS.Close()).To(Succeed())
233 Expect(testutils.UnmountNS(targetNS)).To(Succeed())
234 })
235
236 doTest := func(conf, cniVersion string, numIPs int, expectedDNSConf types.DNS, targetNS ns.NetNS) {
237 const IFNAME = "ptp0"
238
239 args := &skel.CmdArgs{
240 ContainerID: "dummy",
241 Netns: targetNS.Path(),
242 IfName: IFNAME,
243 StdinData: []byte(conf),
244 }
245
246 var result types.Result
247
248 // Execute the plugin with the ADD command, creating the veth endpoints
249 err := originalNS.Do(func(ns.NetNS) error {
250 defer GinkgoRecover()
251
252 var err error
253 if testutils.SpecVersionHasSTATUS(cniVersion) {
254 By("Doing a cni STATUS")
255 err = testutils.CmdStatus(func() error {
256 return cmdStatus(args)
257 })
258 Expect(err).NotTo(HaveOccurred())
259 }
260
261 result, _, err = testutils.CmdAddWithArgs(args, func() error {
262 return cmdAdd(args)
263 })
264 Expect(err).NotTo(HaveOccurred())
265 return nil
266 })
267 Expect(err).NotTo(HaveOccurred())
268
269 t := newTesterByVersion(cniVersion)
270 ips, mac := t.verifyResult(result, IFNAME, targetNS.Path(), expectedDNSConf)
271 Expect(ips).To(HaveLen(numIPs))
272
273 // Make sure ptp link exists in the target namespace
274 // Then, ping the gateway
275 err = targetNS.Do(func(ns.NetNS) error {
276 defer GinkgoRecover()
277
278 link, err := netlinksafe.LinkByName(IFNAME)
279 Expect(err).NotTo(HaveOccurred())
280 if mac != "" {
281 Expect(mac).To(Equal(link.Attrs().HardwareAddr.String()))
282 }
283
284 for _, ipc := range ips {
285 fmt.Fprintln(GinkgoWriter, "ping", ipc.ip, "->", ipc.gw)
286 if err := testutils.Ping(ipc.ip, ipc.gw, 30); err != nil {
287 return fmt.Errorf("ping %s -> %s failed: %s", ipc.ip, ipc.gw, err)
288 }
289 }
290
291 return nil
292 })
293 Expect(err).NotTo(HaveOccurred())
294
295 // call CmdCheck
296 n := &Net{}
297 err = json.Unmarshal([]byte(conf), &n)
298 Expect(err).NotTo(HaveOccurred())
299
300 n.IPAM, _, err = allocator.LoadIPAMConfig([]byte(conf), "")
301 Expect(err).NotTo(HaveOccurred())
302
303 newConf, err := buildOneConfig(n.Name, cniVersion, n, result)
304 Expect(err).NotTo(HaveOccurred())
305
306 confString, err := json.Marshal(newConf)
307 Expect(err).NotTo(HaveOccurred())
308
309 args.StdinData = confString
310
311 // CNI Check host-device in the target namespace
312 err = originalNS.Do(func(ns.NetNS) error {
313 defer GinkgoRecover()
314 return testutils.CmdCheckWithArgs(args, func() error { return cmdCheck(args) })
315 })
316 if testutils.SpecVersionHasCHECK(cniVersion) {
317 Expect(err).NotTo(HaveOccurred())
318 } else {
319 Expect(err).To(MatchError("config version does not allow CHECK"))
320 }
321
322 args.StdinData = []byte(conf)
323
324 // Call the plugins with the DEL command, deleting the veth endpoints
325 err = originalNS.Do(func(ns.NetNS) error {
326 defer GinkgoRecover()
327
328 err := testutils.CmdDelWithArgs(args, func() error {
329 return cmdDel(args)
330 })
331 Expect(err).NotTo(HaveOccurred())
332 return nil
333 })
334 Expect(err).NotTo(HaveOccurred())
335
336 // Make sure ptp link has been deleted
337 err = targetNS.Do(func(ns.NetNS) error {
338 defer GinkgoRecover()
339
340 link, err := netlinksafe.LinkByName(IFNAME)
341 Expect(err).To(HaveOccurred())
342 Expect(link).To(BeNil())
343 return nil
344 })
345 Expect(err).NotTo(HaveOccurred())
346 }
347
348 for _, ver := range testutils.AllSpecVersions {
349 // Redefine ver inside for scope so real value is picked up by each dynamically defined It()
350 // See Gingkgo's "Patterns for dynamically generating tests" documentation.
351 ver := ver
352
353 It(fmt.Sprintf("[%s] configures and deconfigures a ptp link with ADD/DEL", ver), func() {
354 dnsConf := types.DNS{
355 Nameservers: []string{"10.1.2.123"},
356 Domain: "some.domain.test",
357 Search: []string{"search.test"},
358 Options: []string{"option1:foo"},
359 }
360 dnsConfBytes, err := json.Marshal(dnsConf)
361 Expect(err).NotTo(HaveOccurred())
362
363 conf := fmt.Sprintf(`{
364 "cniVersion": "%s",
365 "name": "mynet",
366 "type": "ptp",
367 "ipMasq": true,
368 "mtu": 5000,
369 "ipam": {
370 "type": "host-local",
371 "subnet": "10.1.2.0/24",
372 "dataDir": "%s"
373 },
374 "dns": %s
375 }`, ver, dataDir, string(dnsConfBytes))
376
377 doTest(conf, ver, 1, dnsConf, targetNS)
378 })
379
380 It(fmt.Sprintf("[%s] configures and deconfigures a ptp link when specifying ipMasqBackend: iptables", ver), func() {
381 dnsConf := types.DNS{
382 Nameservers: []string{"10.1.2.123"},
383 Domain: "some.domain.test",
384 Search: []string{"search.test"},
385 Options: []string{"option1:foo"},
386 }
387 dnsConfBytes, err := json.Marshal(dnsConf)
388 Expect(err).NotTo(HaveOccurred())
389
390 conf := fmt.Sprintf(`{
391 "cniVersion": "%s",
392 "name": "mynet",
393 "type": "ptp",
394 "ipMasq": true,
395 "ipMasqBackend": "iptables",
396 "mtu": 5000,
397 "ipam": {
398 "type": "host-local",
399 "subnet": "10.1.2.0/24",
400 "dataDir": "%s"
401 },
402 "dns": %s
403 }`, ver, dataDir, string(dnsConfBytes))
404
405 doTest(conf, ver, 1, dnsConf, targetNS)
406 })
407
408 It(fmt.Sprintf("[%s] configures and deconfigures a ptp link when specifying ipMasqBackend: nftables", ver), func() {
409 dnsConf := types.DNS{
410 Nameservers: []string{"10.1.2.123"},
411 Domain: "some.domain.test",
412 Search: []string{"search.test"},
413 Options: []string{"option1:foo"},
414 }
415 dnsConfBytes, err := json.Marshal(dnsConf)
416 Expect(err).NotTo(HaveOccurred())
417
418 conf := fmt.Sprintf(`{
419 "cniVersion": "%s",
420 "name": "mynet",
421 "type": "ptp",
422 "ipMasq": true,
423 "ipMasqBackend": "nftables",
424 "mtu": 5000,
425 "ipam": {
426 "type": "host-local",
427 "subnet": "10.1.2.0/24",
428 "dataDir": "%s"
429 },
430 "dns": %s
431 }`, ver, dataDir, string(dnsConfBytes))
432
433 doTest(conf, ver, 1, dnsConf, targetNS)
434 })
435
436 It(fmt.Sprintf("[%s] configures and deconfigures a dual-stack ptp link + routes with ADD/DEL", ver), func() {
437 conf := fmt.Sprintf(`{
438 "cniVersion": "%s",
439 "name": "mynet",
440 "type": "ptp",
441 "ipMasq": true,
442 "mtu": 5000,
443 "ipam": {
444 "type": "host-local",
445 "ranges": [
446 [{ "subnet": "10.1.2.0/24"}],
447 [{ "subnet": "2001:db8:1::0/66"}]
448 ],
449 "routes": [
450 { "dst": "0.0.0.0/0" },
451 { "dst": "192.168.0.0/16" },
452 { "dst": "1.2.3.4/32" }
453 ],
454 "dataDir": "%s"
455 }
456 }`, ver, dataDir)
457
458 doTest(conf, ver, 2, types.DNS{}, targetNS)
459 })
460
461 It(fmt.Sprintf("[%s] does not override IPAM DNS settings if no DNS settings provided", ver), func() {
462 ipamDNSConf := types.DNS{
463 Nameservers: []string{"10.1.2.123"},
464 Domain: "some.domain.test",
465 Search: []string{"search.test"},
466 Options: []string{"option1:foo"},
467 }
468 resolvConfPath, err := testutils.TmpResolvConf(ipamDNSConf)
469 Expect(err).NotTo(HaveOccurred())
470 defer os.RemoveAll(resolvConfPath)
471
472 conf := fmt.Sprintf(`{
473 "cniVersion": "%s",
474 "name": "mynet",
475 "type": "ptp",
476 "ipMasq": true,
477 "mtu": 5000,
478 "ipam": {
479 "type": "host-local",
480 "subnet": "10.1.2.0/24",
481 "resolvConf": "%s",
482 "dataDir": "%s"
483 }
484 }`, ver, resolvConfPath, dataDir)
485
486 doTest(conf, ver, 1, ipamDNSConf, targetNS)
487 })
488
489 It(fmt.Sprintf("[%s] overrides IPAM DNS settings if any DNS settings provided", ver), func() {
490 ipamDNSConf := types.DNS{
491 Nameservers: []string{"10.1.2.123"},
492 Domain: "some.domain.test",
493 Search: []string{"search.test"},
494 Options: []string{"option1:foo"},
495 }
496 resolvConfPath, err := testutils.TmpResolvConf(ipamDNSConf)
497 Expect(err).NotTo(HaveOccurred())
498 defer os.RemoveAll(resolvConfPath)
499
500 for _, ptpDNSConf := range []types.DNS{
501 {
502 Nameservers: []string{"10.1.2.234"},
503 },
504 {
505 Domain: "someother.domain.test",
506 },
507 {
508 Search: []string{"search.elsewhere.test"},
509 },
510 {
511 Options: []string{"option2:bar"},
512 },
513 } {
514 dnsConfBytes, err := json.Marshal(ptpDNSConf)
515 Expect(err).NotTo(HaveOccurred())
516
517 conf := fmt.Sprintf(`{
518 "cniVersion": "%s",
519 "name": "mynet",
520 "type": "ptp",
521 "ipMasq": true,
522 "mtu": 5000,
523 "ipam": {
524 "type": "host-local",
525 "subnet": "10.1.2.0/24",
526 "resolvConf": "%s",
527 "dataDir": "%s"
528 },
529 "dns": %s
530 }`, ver, resolvConfPath, dataDir, string(dnsConfBytes))
531
532 doTest(conf, ver, 1, ptpDNSConf, targetNS)
533 }
534 })
535
536 It(fmt.Sprintf("[%s] overrides IPAM DNS settings if any empty list DNS settings provided", ver), func() {
537 ipamDNSConf := types.DNS{
538 Nameservers: []string{"10.1.2.123"},
539 Domain: "some.domain.test",
540 Search: []string{"search.test"},
541 Options: []string{"option1:foo"},
542 }
543 resolvConfPath, err := testutils.TmpResolvConf(ipamDNSConf)
544 Expect(err).NotTo(HaveOccurred())
545 defer os.RemoveAll(resolvConfPath)
546
547 conf := fmt.Sprintf(`{
548 "cniVersion": "%s",
549 "name": "mynet",
550 "type": "ptp",
551 "ipMasq": true,
552 "mtu": 5000,
553 "ipam": {
554 "type": "host-local",
555 "subnet": "10.1.2.0/24",
556 "dataDir": "%s",
557 "resolvConf": "%s"
558 },
559 "dns": {
560 "nameservers": [],
561 "search": [],
562 "options": []
563 }
564 }`, ver, dataDir, resolvConfPath)
565
566 doTest(conf, ver, 1, types.DNS{}, targetNS)
567 })
568
569 It(fmt.Sprintf("[%s] deconfigures an unconfigured ptp link with DEL", ver), func() {
570 const IFNAME = "ptp0"
571
572 conf := fmt.Sprintf(`{
573 "cniVersion": "%s",
574 "name": "mynet",
575 "type": "ptp",
576 "ipMasq": true,
577 "mtu": 5000,
578 "ipam": {
579 "type": "host-local",
580 "dataDir": "%s",
581 "subnet": "10.1.2.0/24"
582 }
583 }`, ver, dataDir)
584
585 args := &skel.CmdArgs{
586 ContainerID: "dummy",
587 Netns: targetNS.Path(),
588 IfName: IFNAME,
589 StdinData: []byte(conf),
590 }
591
592 // Call the plugins with the DEL command. It should not error even though the veth doesn't exist.
593 err := originalNS.Do(func(ns.NetNS) error {
594 defer GinkgoRecover()
595
596 err := testutils.CmdDelWithArgs(args, func() error {
597 return cmdDel(args)
598 })
599 Expect(err).NotTo(HaveOccurred())
600 return nil
601 })
602 Expect(err).NotTo(HaveOccurred())
603 })
604 }
605 })