File: integration_linux_test.go

package info (click to toggle)
golang-github-containernetworking-plugins 0.9.1%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,512 kB
  • sloc: sh: 124; makefile: 18
file content (269 lines) | stat: -rw-r--r-- 8,711 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// Copyright 2018 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package integration_test

import (
	"fmt"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"

	"bytes"
	"io"
	"net"
	"regexp"
	"strconv"
	"strings"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
)

var _ = Describe("Basic PTP using cnitool", func() {
	var (
		cnitoolBin string
		cniPath    string
	)

	BeforeEach(func() {
		var err error
		cniPath, err = filepath.Abs("../bin")
		Expect(err).NotTo(HaveOccurred())
		cnitoolBin, err = exec.LookPath("cnitool")
		Expect(err).NotTo(HaveOccurred(), "expected to find cnitool in your PATH")
	})

	Context("basic cases", func() {
		var (
			env    TestEnv
			hostNS Namespace
			contNS Namespace
		)

		BeforeEach(func() {
			var err error

			netConfPath, err := filepath.Abs("./testdata")
			Expect(err).NotTo(HaveOccurred())

			env = TestEnv([]string{
				"CNI_PATH=" + cniPath,
				"NETCONFPATH=" + netConfPath,
				"PATH=" + os.Getenv("PATH"),
			})

			hostNS = Namespace(fmt.Sprintf("cni-test-host-%x", rand.Int31()))
			hostNS.Add()

			contNS = Namespace(fmt.Sprintf("cni-test-cont-%x", rand.Int31()))
			contNS.Add()
		})

		AfterEach(func() {
			contNS.Del()
			hostNS.Del()
		})

		basicAssertion := func(netName, expectedIPPrefix string) {
			env.runInNS(hostNS, cnitoolBin, "add", netName, contNS.LongName())

			addrOutput := env.runInNS(contNS, "ip", "addr")
			Expect(addrOutput).To(ContainSubstring(expectedIPPrefix))

			env.runInNS(hostNS, cnitoolBin, "del", netName, contNS.LongName())
		}

		It("supports basic network add and del operations", func() {
			basicAssertion("basic-ptp", "10.1.2.")
		})

		It("supports add and del with ptp + bandwidth", func() {
			basicAssertion("chained-ptp-bandwidth", "10.9.2.")
		})
	})

	Context("when the bandwidth plugin is chained with a plugin that returns multiple adapters", func() {
		var (
			hostNS                                            Namespace
			contNS1                                           Namespace
			contNS2                                           Namespace
			basicBridgeEnv                                    TestEnv
			chainedBridgeBandwidthEnv                         TestEnv
			chainedBridgeBandwidthSession, basicBridgeSession *gexec.Session
		)

		BeforeEach(func() {
			hostNS = Namespace(fmt.Sprintf("cni-test-host-%x", rand.Int31()))
			hostNS.Add()

			contNS1 = Namespace(fmt.Sprintf("cni-test-cont1-%x", rand.Int31()))
			contNS1.Add()

			contNS2 = Namespace(fmt.Sprintf("cni-test-cont2-%x", rand.Int31()))
			contNS2.Add()

			basicBridgeNetConfPath, err := filepath.Abs("./testdata/basic-bridge")
			Expect(err).NotTo(HaveOccurred())

			basicBridgeEnv = TestEnv([]string{
				"CNI_PATH=" + cniPath,
				"NETCONFPATH=" + basicBridgeNetConfPath,
				"PATH=" + os.Getenv("PATH"),
			})

			chainedBridgeBandwidthNetConfPath, err := filepath.Abs("./testdata/chained-bridge-bandwidth")
			Expect(err).NotTo(HaveOccurred())

			chainedBridgeBandwidthEnv = TestEnv([]string{
				"CNI_PATH=" + cniPath,
				"NETCONFPATH=" + chainedBridgeBandwidthNetConfPath,
				"PATH=" + os.Getenv("PATH"),
			})
		})

		AfterEach(func() {
			if chainedBridgeBandwidthSession != nil {
				chainedBridgeBandwidthSession.Kill()
			}
			if basicBridgeSession != nil {
				basicBridgeSession.Kill()
			}

			chainedBridgeBandwidthEnv.runInNS(hostNS, cnitoolBin, "del", "network-chain-test", contNS1.LongName())
			basicBridgeEnv.runInNS(hostNS, cnitoolBin, "del", "network-chain-test", contNS2.LongName())
		})

		Measure("limits traffic only on the restricted bandwith veth device", func(b Benchmarker) {
			ipRegexp := regexp.MustCompile("10\\.1[12]\\.2\\.\\d{1,3}")

			By(fmt.Sprintf("adding %s to %s\n\n", "chained-bridge-bandwidth", contNS1.ShortName()))
			chainedBridgeBandwidthEnv.runInNS(hostNS, cnitoolBin, "add", "network-chain-test", contNS1.LongName())
			chainedBridgeIP := ipRegexp.FindString(chainedBridgeBandwidthEnv.runInNS(contNS1, "ip", "addr"))
			Expect(chainedBridgeIP).To(ContainSubstring("10.12.2."))

			By(fmt.Sprintf("adding %s to %s\n\n", "basic-bridge", contNS2.ShortName()))
			basicBridgeEnv.runInNS(hostNS, cnitoolBin, "add", "network-chain-test", contNS2.LongName())
			basicBridgeIP := ipRegexp.FindString(basicBridgeEnv.runInNS(contNS2, "ip", "addr"))
			Expect(basicBridgeIP).To(ContainSubstring("10.11.2."))

			var chainedBridgeBandwidthPort, basicBridgePort int
			var err error

			By(fmt.Sprintf("starting echo server in %s\n\n", contNS1.ShortName()))
			chainedBridgeBandwidthPort, chainedBridgeBandwidthSession, err = startEchoServerInNamespace(contNS1)
			Expect(err).ToNot(HaveOccurred())

			By(fmt.Sprintf("starting echo server in %s\n\n", contNS2.ShortName()))
			basicBridgePort, basicBridgeSession, err = startEchoServerInNamespace(contNS2)
			Expect(err).ToNot(HaveOccurred())

			packetInBytes := 20000 // The shaper needs to 'warm'. Send enough to cause it to throttle,
			// balanced by run time.

			By(fmt.Sprintf("sending tcp traffic to the chained, bridged, traffic shaped container on ip address '%s:%d'\n\n", chainedBridgeIP, chainedBridgeBandwidthPort))
			runtimeWithLimit := b.Time("with chained bridge and bandwidth plugins", func() {
				makeTcpClientInNS(hostNS.ShortName(), chainedBridgeIP, chainedBridgeBandwidthPort, packetInBytes)
			})

			By(fmt.Sprintf("sending tcp traffic to the basic bridged container on ip address '%s:%d'\n\n", basicBridgeIP, basicBridgePort))
			runtimeWithoutLimit := b.Time("with basic bridged plugin", func() {
				makeTcpClientInNS(hostNS.ShortName(), basicBridgeIP, basicBridgePort, packetInBytes)
			})

			Expect(runtimeWithLimit).To(BeNumerically(">", runtimeWithoutLimit+1000*time.Millisecond))
		}, 1)
	})
})

type TestEnv []string

func (e TestEnv) run(bin string, args ...string) string {
	cmd := exec.Command(bin, args...)
	cmd.Env = e
	session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
	Expect(err).NotTo(HaveOccurred())
	Eventually(session, "5s").Should(gexec.Exit(0))
	return string(session.Out.Contents())
}

func (e TestEnv) runInNS(nsShortName Namespace, bin string, args ...string) string {
	a := append([]string{"netns", "exec", string(nsShortName), bin}, args...)
	return e.run("ip", a...)
}

type Namespace string

func (n Namespace) LongName() string {
	return fmt.Sprintf("/var/run/netns/%s", n)
}

func (n Namespace) ShortName() string {
	return string(n)
}

func (n Namespace) Add() {
	(TestEnv{}).run("ip", "netns", "add", string(n))
}

func (n Namespace) Del() {
	(TestEnv{}).run("ip", "netns", "del", string(n))
}

func makeTcpClientInNS(netns string, address string, port int, numBytes int) {
	payload := bytes.Repeat([]byte{'a'}, numBytes)
	message := string(payload)

	var cmd *exec.Cmd
	if netns != "" {
		netns = filepath.Base(netns)
		cmd = exec.Command("ip", "netns", "exec", netns, echoClientBinaryPath, "--target", fmt.Sprintf("%s:%d", address, port), "--message", message)
	} else {
		cmd = exec.Command(echoClientBinaryPath, "--target", fmt.Sprintf("%s:%d", address, port), "--message", message)
	}
	cmd.Stdin = bytes.NewBuffer([]byte(message))
	cmd.Stderr = GinkgoWriter
	out, err := cmd.Output()

	Expect(err).NotTo(HaveOccurred())
	Expect(string(out)).To(Equal(message))
}

func startEchoServerInNamespace(netNS Namespace) (int, *gexec.Session, error) {
	session, err := startInNetNS(echoServerBinaryPath, netNS)
	Expect(err).NotTo(HaveOccurred())

	// wait for it to print it's address on stdout
	Eventually(session.Out).Should(gbytes.Say("\n"))
	_, portString, err := net.SplitHostPort(strings.TrimSpace(string(session.Out.Contents())))
	Expect(err).NotTo(HaveOccurred())

	port, err := strconv.Atoi(portString)
	Expect(err).NotTo(HaveOccurred())

	go func() {
		// print out echoserver output to ginkgo to capture any errors that might be occurring.
		io.Copy(GinkgoWriter, io.MultiReader(session.Out, session.Err))
	}()

	return port, session, nil
}

func startInNetNS(binPath string, namespace Namespace) (*gexec.Session, error) {
	cmd := exec.Command("ip", "netns", "exec", namespace.ShortName(), binPath)
	return gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
}