File: sbr_linux_test.go

package info (click to toggle)
golang-github-containernetworking-plugins 0.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,448 kB
  • sloc: sh: 124; makefile: 13
file content (430 lines) | stat: -rw-r--r-- 10,703 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Copyright 2017 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 main

import (
	"fmt"
	"log"
	"net"

	"github.com/containernetworking/cni/pkg/skel"
	"github.com/containernetworking/plugins/pkg/ns"
	"github.com/containernetworking/plugins/pkg/testutils"

	"github.com/vishvananda/netlink"
	"golang.org/x/sys/unix"

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

// Structures specifying state at start.
type Device struct {
	Name   string
	Addrs  []net.IPNet
	Routes []netlink.Route
}

type Rule struct {
	Src   string
	Table int
}

type netStatus struct {
	Devices []Device
	Rules   []netlink.Rule
}

// Create a link, shove some IP addresses on it, and push it into the network
// namespace.
func setup(targetNs ns.NetNS, status netStatus) error {
	// Get the status right
	err := targetNs.Do(func(_ ns.NetNS) error {
		for _, dev := range status.Devices {
			log.Printf("Adding dev %s\n", dev.Name)
			link := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: dev.Name}}
			err := netlink.LinkAdd(link)
			if err != nil {
				return err
			}

			err = netlink.LinkSetUp(link)
			if err != nil {
				return err
			}

			for _, addr := range dev.Addrs {
				log.Printf("Adding address %v to device %s\n", addr, dev.Name)
				err = netlink.AddrAdd(link, &netlink.Addr{IPNet: &addr})
				if err != nil {
					return err
				}
			}

			for _, route := range dev.Routes {
				log.Printf("Adding route %v to device %s\n", route, dev.Name)
				route.LinkIndex = link.Attrs().Index
				err = netlink.RouteAdd(&route)
				if err != nil {
					return err
				}
			}
		}
		return nil
	})

	return err
}

// Readback the routes and rules.
func readback(targetNs ns.NetNS, devNames []string) (netStatus, error) {
	// Get the status right.
	var retVal netStatus

	err := targetNs.Do(func(_ ns.NetNS) error {
		retVal.Devices = make([]Device, 2)

		for i, name := range devNames {
			log.Printf("Checking device %s", name)
			retVal.Devices[i].Name = name

			link, err := netlink.LinkByName(name)
			if err != nil {
				return err
			}

			// Need to read all tables, so cannot use RouteList
			routeFilter := &netlink.Route{
				LinkIndex: link.Attrs().Index,
				Table:     unix.RT_TABLE_UNSPEC,
			}

			routes, err := netlink.RouteListFiltered(netlink.FAMILY_ALL,
				routeFilter,
				netlink.RT_FILTER_OIF|netlink.RT_FILTER_TABLE)

			if err != nil {
				return err
			}

			for _, route := range routes {
				log.Printf("Got %s route %v", name, route)
			}

			retVal.Devices[i].Routes = routes
		}

		rules, err := netlink.RuleList(netlink.FAMILY_ALL)
		if err != nil {
			return err
		}

		retVal.Rules = make([]netlink.Rule, 0, len(rules))

		for _, rule := range rules {
			// Rules over 250 are the kernel defaults, that we ignore.
			if rule.Table < 250 {
				log.Printf("Got interesting rule %v", rule)
				retVal.Rules = append(retVal.Rules, rule)
			}
		}

		return nil
	})

	return retVal, err
}

func equalRoutes(expected, actual []netlink.Route) bool {
	// Compare two sets of routes, comparing only destination, gateway and
	// table. Return true if equal.
	match := true

	// Map used to make comparisons easy
	expMap := make(map[string]bool)

	for _, route := range expected {
		expMap[route.String()] = true
	}

	for _, route := range actual {
		routeString := route.String()
		if expMap[routeString] {
			log.Printf("Route %s expected and found", routeString)
			delete(expMap, routeString)
		} else {
			log.Printf("Route %s found, not expected", routeString)
			match = false
		}
	}

	for expRoute := range expMap {
		log.Printf("Route %s expected, not found", expRoute)
		match = false
	}

	return match
}

func createDefaultStatus() netStatus {
	// Useful default status.
	devs := make([]Device, 2)
	rules := make([]netlink.Rule, 0)

	devs[0] = Device{Name: "eth0"}
	devs[0].Addrs = make([]net.IPNet, 1)
	devs[0].Addrs[0] = net.IPNet{
		IP:   net.IPv4(10, 0, 0, 2),
		Mask: net.IPv4Mask(255, 255, 255, 0),
	}
	devs[0].Routes = make([]netlink.Route, 2)
	devs[0].Routes[0] = netlink.Route{
		Dst: &net.IPNet{
			IP:   net.IPv4(10, 2, 0, 0),
			Mask: net.IPv4Mask(255, 255, 255, 0),
		},
		Gw: net.IPv4(10, 0, 0, 5),
	}
	devs[0].Routes[1] = netlink.Route{
		Gw: net.IPv4(10, 0, 0, 1),
	}

	devs[1] = Device{Name: "net1"}
	devs[1].Addrs = make([]net.IPNet, 1)
	devs[1].Addrs[0] = net.IPNet{
		IP:   net.IPv4(192, 168, 1, 209),
		Mask: net.IPv4Mask(255, 255, 255, 0),
	}
	devs[1].Routes = make([]netlink.Route, 1)
	devs[1].Routes[0] = netlink.Route{
		Dst: &net.IPNet{
			IP:   net.IPv4(192, 168, 2, 0),
			Mask: net.IPv4Mask(255, 255, 255, 0),
		},
		Gw: net.IPv4(192, 168, 1, 2),
	}

	return netStatus{
		Devices: devs,
		Rules:   rules}
}

var _ = Describe("sbr test", func() {
	var targetNs ns.NetNS

	BeforeEach(func() {
		var err error
		targetNs, err = testutils.NewNS()
		Expect(err).NotTo(HaveOccurred())
	})

	AfterEach(func() {
		targetNs.Close()
	})

	It("Works with a 0.3.0 config", func() {
		ifname := "net1"
		conf := `{
	"cniVersion": "0.3.0",
	"name": "cni-plugin-sbr-test",
	"type": "sbr",
	"prevResult": {
		"interfaces": [
			{
				"name": "%s",
				"sandbox": "%s"
			}
		],
		"ips": [
			{
				"version": "4",
				"address": "192.168.1.209/24",
				"gateway": "192.168.1.1",
				"interface": 0
			}
		],
		"routes": []
	}
}`
		conf = fmt.Sprintf(conf, ifname, targetNs.Path())
		args := &skel.CmdArgs{
			ContainerID: "dummy",
			Netns:       targetNs.Path(),
			IfName:      ifname,
			StdinData:   []byte(conf),
		}

		err := setup(targetNs, createDefaultStatus())
		Expect(err).NotTo(HaveOccurred())

		oldStatus, err := readback(targetNs, []string{"net1", "eth0"})
		Expect(err).NotTo(HaveOccurred())

		_, _, err = testutils.CmdAddWithArgs(args, func() error { return cmdAdd(args) })
		Expect(err).NotTo(HaveOccurred())

		newStatus, err := readback(targetNs, []string{"net1", "eth0"})
		Expect(err).NotTo(HaveOccurred())

		// Check results. We expect all the routes on net1 to have moved to
		// table 100 except for local routes (table 255); a new default gateway
		// route to have been created; and a single rule to exist.
		expNet1 := oldStatus.Devices[0]
		expEth0 := oldStatus.Devices[1]
		for i := range expNet1.Routes {
			if expNet1.Routes[i].Table != 255 {
				expNet1.Routes[i].Table = 100
			}
		}
		expNet1.Routes = append(expNet1.Routes,
			netlink.Route{
				Gw:        net.IPv4(192, 168, 1, 1),
				Table:     100,
				LinkIndex: expNet1.Routes[0].LinkIndex})

		Expect(len(newStatus.Rules)).To(Equal(1))
		Expect(newStatus.Rules[0].Table).To(Equal(100))
		Expect(newStatus.Rules[0].Src.String()).To(Equal("192.168.1.209/32"))
		devNet1 := newStatus.Devices[0]
		devEth0 := newStatus.Devices[1]
		Expect(equalRoutes(expNet1.Routes, devNet1.Routes)).To(BeTrue())
		Expect(equalRoutes(expEth0.Routes, devEth0.Routes)).To(BeTrue())

		conf = `{
	"cniVersion": "0.3.0",
	"name": "cni-plugin-sbr-test",
	"type": "sbr"
}`

		// And now check that we can back it all out.
		args = &skel.CmdArgs{
			ContainerID: "dummy",
			Netns:       targetNs.Path(),
			IfName:      ifname,
			StdinData:   []byte(conf),
		}
		err = testutils.CmdDelWithArgs(args, func() error { return cmdDel(args) })
		Expect(err).NotTo(HaveOccurred())

		retVal, err := readback(targetNs, []string{"net1", "eth0"})
		Expect(err).NotTo(HaveOccurred())

		// Check results. We expect the rule to have been removed.
		Expect(len(retVal.Rules)).To(Equal(0))
	})

	It("Works with a default route already set", func() {
		ifname := "net1"
		conf := `{
	"cniVersion": "0.3.0",
	"name": "cni-plugin-sbr-test",
	"type": "sbr",
	"prevResult": {
		"interfaces": [
			{
				"name": "%s",
				"sandbox": "%s"
			}
		],
		"ips": [
			{
				"version": "4",
				"address": "192.168.1.209/24",
				"gateway": "192.168.1.1",
				"interface": 0
			}
		],
		"routes": []
	}
}`
		conf = fmt.Sprintf(conf, ifname, targetNs.Path())
		args := &skel.CmdArgs{
			ContainerID: "dummy",
			Netns:       targetNs.Path(),
			IfName:      ifname,
			StdinData:   []byte(conf),
		}

		preStatus := createDefaultStatus()
		// Remove final (default) route from eth0, then add another default
		// route to net1
		preStatus.Devices[0].Routes = preStatus.Devices[0].Routes[:0]
		routes := preStatus.Devices[1].Routes
		preStatus.Devices[1].Routes = append(preStatus.Devices[1].Routes,
			netlink.Route{
				Gw:        net.IPv4(192, 168, 1, 1),
				LinkIndex: routes[0].LinkIndex})

		err := setup(targetNs, preStatus)
		Expect(err).NotTo(HaveOccurred())

		oldStatus, err := readback(targetNs, []string{"net1", "eth0"})
		Expect(err).NotTo(HaveOccurred())

		_, _, err = testutils.CmdAddWithArgs(args, func() error { return cmdAdd(args) })
		Expect(err).NotTo(HaveOccurred())

		newStatus, err := readback(targetNs, []string{"net1", "eth0"})
		Expect(err).NotTo(HaveOccurred())

		// Check results. We expect all the routes on net1 to have moved to
		// table 100 except for local routes (table 255); a new default gateway
		// route to have been created; and a single rule to exist.
		expNet1 := oldStatus.Devices[0]
		expEth0 := oldStatus.Devices[1]
		for i := range expNet1.Routes {
			if expNet1.Routes[i].Table != 255 {
				expNet1.Routes[i].Table = 100
			}
		}

		Expect(len(newStatus.Rules)).To(Equal(1))
		Expect(newStatus.Rules[0].Table).To(Equal(100))
		Expect(newStatus.Rules[0].Src.String()).To(Equal("192.168.1.209/32"))
		devNet1 := newStatus.Devices[0]
		devEth0 := newStatus.Devices[1]
		Expect(equalRoutes(expEth0.Routes, devEth0.Routes)).To(BeTrue())
		Expect(equalRoutes(expNet1.Routes, devNet1.Routes)).To(BeTrue())
	})

	It("works with a 0.2.0 config", func() {
		conf := `{
	"cniVersion": "0.2.0",
	"name": "cni-plugin-sbr-test",
	"type": "sbr",
	"anotherAwesomeArg": "foo",
	"prevResult": {
		"ip4": {
        	"ip": "192.168.1.209/24",
		    "gateway": "192.168.1.1",
			"routes": []
		}
	}
}`

		args := &skel.CmdArgs{
			ContainerID: "dummy",
			Netns:       targetNs.Path(),
			IfName:      "net1",
			StdinData:   []byte(conf),
		}
		err := setup(targetNs, createDefaultStatus())
		Expect(err).NotTo(HaveOccurred())

		_, _, err = testutils.CmdAddWithArgs(args, func() error { return cmdAdd(args) })
		Expect(err).NotTo(HaveOccurred())
	})

})