Debian Codegraph @

plugins/meta/portmap/portmap_integ_test.go

raw symbols SCIP
1 // Copyright 2017 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 "bytes"
19 "context"
20 "fmt"
21 "math/rand"
22 "net"
23 "os"
24 "os/exec"
25 "path/filepath"
26
27 "github.com/coreos/go-iptables/iptables"
28 . "github.com/onsi/ginkgo/v2"
29 . "github.com/onsi/gomega"
30 "github.com/onsi/gomega/gexec"
31 "github.com/vishvananda/netlink"
32
33 "github.com/containernetworking/cni/libcni"
34 types100 "github.com/containernetworking/cni/pkg/types/100"
35 "github.com/containernetworking/plugins/pkg/netlinksafe"
36 "github.com/containernetworking/plugins/pkg/ns"
37 "github.com/containernetworking/plugins/pkg/testutils"
38 )
39
40 func makeConfig(ver string) *libcni.NetworkConfigList {
41 configList, err := libcni.ConfListFromBytes([]byte(fmt.Sprintf(`{
42 "cniVersion": "%s",
43 "name": "cni-portmap-unit-test",
44 "plugins": [
45 {
46 "type": "ptp",
47 "ipMasq": true,
48 "ipam": {
49 "type": "host-local",
50 "subnet": "172.16.31.0/24",
51 "routes": [
52 {"dst": "0.0.0.0/0"}
53 ]
54 }
55 },
56 {
57 "type": "portmap",
58 "capabilities": {
59 "portMappings": true
60 }
61 }
62 ]
63 }`, ver)))
64 Expect(err).NotTo(HaveOccurred())
65 return configList
66 }
67
68 var _ = Describe("portmap integration tests", func() {
69 var (
70 cniConf *libcni.CNIConfig
71 targetNS ns.NetNS
72 containerPort int
73 session *gexec.Session
74 )
75
76 BeforeEach(func() {
77 // turn PATH in to CNI_PATH
78 dirs := filepath.SplitList(os.Getenv("PATH"))
79 cniConf = &libcni.CNIConfig{Path: dirs}
80
81 var err error
82 targetNS, err = testutils.NewNS()
83 Expect(err).NotTo(HaveOccurred())
84 fmt.Fprintln(GinkgoWriter, "namespace:", targetNS.Path())
85
86 // Start an echo server and get the port
87 containerPort, session = StartEchoServerInNamespace(targetNS)
88 })
89
90 AfterEach(func() {
91 session.Terminate().Wait()
92 targetNS.Close()
93 testutils.UnmountNS(targetNS)
94 })
95
96 for _, ver := range []string{"0.3.0", "0.3.1", "0.4.0", "1.0.0"} {
97 // Redefine ver inside for scope so real value is picked up by each dynamically defined It()
98 // See Gingkgo's "Patterns for dynamically generating tests" documentation.
99 ver := ver
100
101 Describe("Creating an interface in a namespace with the ptp plugin", func() {
102 // This needs to be done using Ginkgo's asynchronous testing mode.
103 It(fmt.Sprintf("[%s] forwards a TCP port on ipv4", ver), func(done Done) {
104 var err error
105 hostPort := rand.Intn(10000) + 1025
106 runtimeConfig := libcni.RuntimeConf{
107 ContainerID: fmt.Sprintf("unit-test-%d", hostPort),
108 NetNS: targetNS.Path(),
109 IfName: "eth0",
110 CapabilityArgs: map[string]interface{}{
111 "portMappings": []map[string]interface{}{
112 {
113 "hostPort": hostPort,
114 "containerPort": containerPort,
115 "protocol": "tcp",
116 },
117 },
118 },
119 }
120 configList := makeConfig(ver)
121
122 // Make delete idempotent, so we can clean up on failure
123 netDeleted := false
124 deleteNetwork := func() error {
125 if netDeleted {
126 return nil
127 }
128 netDeleted = true
129 return cniConf.DelNetworkList(context.TODO(), configList, &runtimeConfig)
130 }
131
132 // we'll also manually check the iptables chains
133 ipt, err := iptables.NewWithProtocol(iptables.ProtocolIPv4)
134 Expect(err).NotTo(HaveOccurred())
135 dnatChainName := genDnatChain("cni-portmap-unit-test", runtimeConfig.ContainerID).name
136
137 // Create the network
138 resI, err := cniConf.AddNetworkList(context.TODO(), configList, &runtimeConfig)
139 Expect(err).NotTo(HaveOccurred())
140 defer deleteNetwork()
141
142 // Undo Docker's forwarding policy
143 cmd := exec.Command("iptables", "-t", "filter",
144 "-P", "FORWARD", "ACCEPT")
145 cmd.Stderr = GinkgoWriter
146 err = cmd.Run()
147 Expect(err).NotTo(HaveOccurred())
148
149 // Check the chain exists
150 _, err = ipt.List("nat", dnatChainName)
151 Expect(err).NotTo(HaveOccurred())
152
153 result, err := types100.GetResult(resI)
154 Expect(err).NotTo(HaveOccurred())
155 var contIP net.IP
156
157 for _, ip := range result.IPs {
158 intfIndex := *ip.Interface
159 if result.Interfaces[intfIndex].Sandbox == "" {
160 continue
161 }
162 contIP = ip.Address.IP
163 }
164 if contIP == nil {
165 Fail("could not determine container IP")
166 }
167
168 hostIP := getLocalIP()
169 fmt.Fprintf(GinkgoWriter, "hostIP: %s:%d, contIP: %s:%d\n",
170 hostIP, hostPort, contIP, containerPort)
171
172 // dump iptables-save output for debugging
173 cmd = exec.Command("iptables-save")
174 cmd.Stderr = GinkgoWriter
175 cmd.Stdout = GinkgoWriter
176 Expect(cmd.Run()).To(Succeed())
177
178 // dump ip routes output for debugging
179 cmd = exec.Command("ip", "route")
180 cmd.Stderr = GinkgoWriter
181 cmd.Stdout = GinkgoWriter
182 Expect(cmd.Run()).To(Succeed())
183
184 // dump ip addresses output for debugging
185 cmd = exec.Command("ip", "addr")
186 cmd.Stderr = GinkgoWriter
187 cmd.Stdout = GinkgoWriter
188 Expect(cmd.Run()).To(Succeed())
189
190 // Sanity check: verify that the container is reachable directly
191 contOK := testEchoServer(contIP.String(), "tcp", containerPort, "")
192
193 // Verify that a connection to the forwarded port works
194 dnatOK := testEchoServer(hostIP, "tcp", hostPort, "")
195
196 // Verify that a connection to localhost works
197 snatOK := testEchoServer("127.0.0.1", "tcp", hostPort, "")
198
199 // verify that hairpin works
200 hairpinOK := testEchoServer(hostIP, "tcp", hostPort, targetNS.Path())
201
202 // Cleanup
203 session.Terminate()
204 err = deleteNetwork()
205 Expect(err).NotTo(HaveOccurred())
206
207 // Verify iptables rules are gone
208 _, err = ipt.List("nat", dnatChainName)
209 Expect(err).To(HaveOccurred())
210
211 // Check that everything succeeded *after* we clean up the network
212 if !contOK {
213 Fail("connection direct to " + contIP.String() + " failed")
214 }
215 if !dnatOK {
216 Fail("Connection to " + hostIP + " was not forwarded")
217 }
218 if !snatOK {
219 Fail("connection to 127.0.0.1 was not forwarded")
220 }
221 if !hairpinOK {
222 Fail("Hairpin connection failed")
223 }
224
225 close(done)
226 })
227
228 It(fmt.Sprintf("[%s] forwards a UDP port on ipv4 and keep working after creating a second container with the same HostPort", ver), func(done Done) {
229 var err error
230 hostPort := rand.Intn(10000) + 1025
231 runtimeConfig := libcni.RuntimeConf{
232 ContainerID: fmt.Sprintf("unit-test-%d", hostPort),
233 NetNS: targetNS.Path(),
234 IfName: "eth0",
235 CapabilityArgs: map[string]interface{}{
236 "portMappings": []map[string]interface{}{
237 {
238 "hostPort": hostPort,
239 "containerPort": containerPort,
240 "protocol": "udp",
241 },
242 },
243 },
244 }
245 configList := makeConfig(ver)
246
247 // Make delete idempotent, so we can clean up on failure
248 netDeleted := false
249 deleteNetwork := func() error {
250 if netDeleted {
251 return nil
252 }
253 netDeleted = true
254 return cniConf.DelNetworkList(context.TODO(), configList, &runtimeConfig)
255 }
256
257 // Create the network
258 resI, err := cniConf.AddNetworkList(context.TODO(), configList, &runtimeConfig)
259 Expect(err).NotTo(HaveOccurred())
260 defer deleteNetwork()
261
262 // Undo Docker's forwarding policy
263 cmd := exec.Command("iptables", "-t", "filter",
264 "-P", "FORWARD", "ACCEPT")
265 cmd.Stderr = GinkgoWriter
266 err = cmd.Run()
267 Expect(err).NotTo(HaveOccurred())
268
269 result, err := types100.GetResult(resI)
270 Expect(err).NotTo(HaveOccurred())
271 var contIP net.IP
272
273 for _, ip := range result.IPs {
274 intfIndex := *ip.Interface
275 if result.Interfaces[intfIndex].Sandbox == "" {
276 continue
277 }
278 contIP = ip.Address.IP
279 }
280 if contIP == nil {
281 Fail("could not determine container IP")
282 }
283
284 hostIP := getLocalIP()
285 fmt.Fprintf(GinkgoWriter, "First container hostIP: %s:%d, contIP: %s:%d\n",
286 hostIP, hostPort, contIP, containerPort)
287
288 // dump iptables-save output for debugging
289 cmd = exec.Command("iptables-save")
290 cmd.Stderr = GinkgoWriter
291 cmd.Stdout = GinkgoWriter
292 Expect(cmd.Run()).To(Succeed())
293
294 // dump ip routes output for debugging
295 cmd = exec.Command("ip", "route")
296 cmd.Stderr = GinkgoWriter
297 cmd.Stdout = GinkgoWriter
298 Expect(cmd.Run()).To(Succeed())
299
300 // dump ip addresses output for debugging
301 cmd = exec.Command("ip", "addr")
302 cmd.Stderr = GinkgoWriter
303 cmd.Stdout = GinkgoWriter
304 Expect(cmd.Run()).To(Succeed())
305
306 // Sanity check: verify that the container is reachable directly
307 fmt.Fprintln(GinkgoWriter, "Connect to container:", contIP.String(), containerPort)
308 contOK := testEchoServer(contIP.String(), "udp", containerPort, "")
309
310 // Verify that a connection to the forwarded port works
311 fmt.Fprintln(GinkgoWriter, "Connect to host:", hostIP, hostPort)
312 dnatOK := testEchoServer(hostIP, "udp", hostPort, "")
313
314 // Cleanup
315 session.Terminate()
316 err = deleteNetwork()
317 Expect(err).NotTo(HaveOccurred())
318
319 // Check that everything succeeded *after* we clean up the network
320 if !contOK {
321 Fail("connection direct to " + contIP.String() + " failed")
322 }
323 if !dnatOK {
324 Fail("Connection to " + hostIP + " was not forwarded")
325 }
326 // Create a second container
327 targetNS2, err := testutils.NewNS()
328 Expect(err).NotTo(HaveOccurred())
329 fmt.Fprintln(GinkgoWriter, "namespace:", targetNS2.Path())
330
331 // Start an echo server and get the port
332 containerPort, session2 := StartEchoServerInNamespace(targetNS2)
333
334 runtimeConfig2 := libcni.RuntimeConf{
335 ContainerID: fmt.Sprintf("unit-test2-%d", hostPort),
336 NetNS: targetNS2.Path(),
337 IfName: "eth0",
338 CapabilityArgs: map[string]interface{}{
339 "portMappings": []map[string]interface{}{
340 {
341 "hostPort": hostPort,
342 "containerPort": containerPort,
343 "protocol": "udp",
344 },
345 },
346 },
347 }
348
349 // Make delete idempotent, so we can clean up on failure
350 net2Deleted := false
351 deleteNetwork2 := func() error {
352 if net2Deleted {
353 return nil
354 }
355 net2Deleted = true
356 return cniConf.DelNetworkList(context.TODO(), configList, &runtimeConfig2)
357 }
358
359 // Create the network
360 resI2, err := cniConf.AddNetworkList(context.TODO(), configList, &runtimeConfig2)
361 Expect(err).NotTo(HaveOccurred())
362 defer deleteNetwork2()
363
364 result2, err := types100.GetResult(resI2)
365 Expect(err).NotTo(HaveOccurred())
366 var contIP2 net.IP
367
368 for _, ip := range result2.IPs {
369 intfIndex := *ip.Interface
370 if result2.Interfaces[intfIndex].Sandbox == "" {
371 continue
372 }
373 contIP2 = ip.Address.IP
374 }
375 if contIP2 == nil {
376 Fail("could not determine container IP")
377 }
378
379 fmt.Fprintf(GinkgoWriter, "Second container: hostIP: %s:%d, contIP: %s:%d\n",
380 hostIP, hostPort, contIP2, containerPort)
381
382 // dump iptables-save output for debugging
383 cmd = exec.Command("iptables-save")
384 cmd.Stderr = GinkgoWriter
385 cmd.Stdout = GinkgoWriter
386 Expect(cmd.Run()).To(Succeed())
387
388 // dump ip routes output for debugging
389 cmd = exec.Command("ip", "route")
390 cmd.Stderr = GinkgoWriter
391 cmd.Stdout = GinkgoWriter
392 Expect(cmd.Run()).To(Succeed())
393
394 // dump ip addresses output for debugging
395 cmd = exec.Command("ip", "addr")
396 cmd.Stderr = GinkgoWriter
397 cmd.Stdout = GinkgoWriter
398 Expect(cmd.Run()).To(Succeed())
399
400 // Sanity check: verify that the container is reachable directly
401 fmt.Fprintln(GinkgoWriter, "Connect to container:", contIP2.String(), containerPort)
402 cont2OK := testEchoServer(contIP2.String(), "udp", containerPort, "")
403
404 // Verify that a connection to the forwarded port works
405 fmt.Fprintln(GinkgoWriter, "Connect to host:", hostIP, hostPort)
406 dnat2OK := testEchoServer(hostIP, "udp", hostPort, "")
407
408 // Cleanup
409 session2.Terminate()
410 err = deleteNetwork2()
411 Expect(err).NotTo(HaveOccurred())
412
413 // Check that everything succeeded *after* we clean up the network
414 if !cont2OK {
415 Fail("connection direct to " + contIP2.String() + " failed")
416 }
417 if !dnat2OK {
418 Fail("Connection to " + hostIP + " was not forwarded")
419 }
420
421 close(done)
422 })
423 })
424 }
425 })
426
427 // testEchoServer returns true if we found an echo server on the port
428 func testEchoServer(address, protocol string, port int, netns string) bool {
429 message := "'Aliquid melius quam pessimum optimum non est.'"
430
431 var cmd *exec.Cmd
432 if netns != "" {
433 netns = filepath.Base(netns)
434 cmd = exec.Command("ip", "netns", "exec", netns, echoClientBinaryPath, "--target", fmt.Sprintf("%s:%d", address, port), "--message", message, "--protocol", protocol)
435 } else {
436 cmd = exec.Command(echoClientBinaryPath, "--target", fmt.Sprintf("%s:%d", address, port), "--message", message, "--protocol", protocol)
437 }
438 cmd.Stdin = bytes.NewBufferString(message)
439 cmd.Stderr = GinkgoWriter
440 out, err := cmd.Output()
441 if err != nil {
442 fmt.Fprintln(GinkgoWriter, "got non-zero exit from ", cmd.Args)
443 return false
444 }
445
446 if string(out) != message {
447 fmt.Fprintln(GinkgoWriter, "returned message didn't match?")
448 fmt.Fprintln(GinkgoWriter, string(out))
449 return false
450 }
451
452 return true
453 }
454
455 func getLocalIP() string {
456 addrs, err := netlinksafe.AddrList(nil, netlink.FAMILY_V4)
457 Expect(err).NotTo(HaveOccurred())
458
459 for _, addr := range addrs {
460 if !addr.IP.IsGlobalUnicast() {
461 continue
462 }
463 return addr.IP.String()
464 }
465 Fail("no live addresses")
466 return ""
467 }