File: cni_setup_teardown_linux_test.go

package info (click to toggle)
golang-github-containerd-go-cni 1.1.9-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 220 kB
  • sloc: makefile: 21; sh: 18
file content (395 lines) | stat: -rw-r--r-- 10,712 bytes parent folder | download
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
/*
   Copyright The containerd 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.
*/

// 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

import (
	"context"
	"crypto/rand"
	"fmt"
	"os"
	"path"
	"runtime"
	"sync"
	"syscall"
	"testing"

	"github.com/containerd/continuity/fs"
	"github.com/containerd/continuity/testutil"
	"github.com/containerd/go-cni"
	"github.com/stretchr/testify/assert"
)

var (
	baseNetNSDir = "/var/run/netns/"

	defaultCNIPluginDir = "/opt/cni/bin/"

	cniBridgePluginCfg = `
{
  "cniVersion": "1.0.0",
  "name": "gocni-test",
  "plugins": [
    {
      "type":"bridge",
      "bridge":"gocni-test0",
      "isGateway":true,
      "ipMasq":true,
      "promiscMode":true,
      "ipam":{
        "type":"host-local",
        "ranges":[
          [{
            "subnet":"10.88.0.0/16"
          }],
          [{
            "subnet":"2001:4860:4860::/64"
          }]
        ],
        "routes":[
          {"dst":"0.0.0.0/0"},
          {"dst":"::/0"}
        ]
       }
    },
    {
      "type":"portmap",
      "capabilities":{
        "portMappings":true
      }
    }
  ]
}
`

	cniBridgePluginCfgWithoutVersion = `
{
  "name": "gocni-test",
  "plugins": [
    {
      "type":"bridge",
      "bridge":"gocni-test0",
      "isGateway":true,
      "ipMasq":true,
      "promiscMode":true,
      "ipam":{
        "type":"host-local",
        "ranges":[
          [{
            "subnet":"10.88.0.0/16"
          }],
          [{
            "subnet":"2001:4860:4860::/64"
          }]
        ],
        "routes":[
          {"dst":"0.0.0.0/0"},
          {"dst":"::/0"}
        ]
       }
    },
    {
      "type":"portmap",
      "capabilities":{
        "portMappings":true
      }
    }
  ]
}
`
)

// TestBasicSetupAndRemove tests the cni.Setup/Remove with real bridge and
// loopback CNI plugins.
//
// NOTE:
//
// 1. It required that the both bridge and loopback CNI plugins are installed
// in /opt/cni/bin.
//
// 2. Since #76 enables parallel mode, we should enable -race option for this.
func TestBasicSetupAndRemove(t *testing.T) {
	testutil.RequiresRoot(t)

	// setup config dir
	tmpPluginConfDir, err := os.MkdirTemp("", t.Name()+"-conf")
	assert.NoError(t, err, "create temp dir for plugin conf dir")
	defer os.RemoveAll(tmpPluginConfDir)

	assert.NoError(t,
		os.WriteFile(
			path.Join(tmpPluginConfDir, "10-gocni-test-net.conflist"),
			[]byte(cniBridgePluginCfg),
			0600,
		),
		"init cni config",
	)

	// copy plugins from /opt/cni/bin
	tmpPluginDir, err := os.MkdirTemp("", t.Name()+"-bin")
	assert.NoError(t, err, "create temp dir for plugin bin dir")
	defer os.RemoveAll(tmpPluginDir)

	assert.NoError(t,
		fs.CopyDir(tmpPluginDir, defaultCNIPluginDir),
		"copy %v into %v", defaultCNIPluginDir, tmpPluginDir)

	nsPath, done, err := createNetNS()
	assert.NoError(t, err, "create temp netns")
	defer func() {
		assert.NoError(t, done(), "cleanup temp netns")
	}()

	defaultIfName := "eth0"
	ctx := context.Background()
	id := t.Name()

	for idx, opts := range [][]cni.Opt{
		// Use default plugin dir
		{
			cni.WithMinNetworkCount(2),
			cni.WithPluginConfDir(tmpPluginConfDir),
		},
		// Use customize plugin dir
		{
			cni.WithMinNetworkCount(2),
			cni.WithPluginConfDir(tmpPluginConfDir),
			cni.WithPluginDir([]string{
				tmpPluginDir,
			}),
		},
	} {
		l, err := cni.New(opts...)
		assert.NoError(t, err, "[%v] initialize cni library", idx)

		assert.NoError(t,
			l.Load(cni.WithLoNetwork, cni.WithDefaultConf),
			"[%v] load cni configuration", idx,
		)

		// Setup network
		result, err := l.Setup(ctx, id, nsPath)
		assert.NoError(t, err, "[%v] setup network interfaces for namespace in parallel %v", idx, nsPath)

		ip := result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
		t.Logf("[%v] ip is %v", idx, ip)

		assert.NoError(t,
			l.Remove(ctx, id, nsPath),
			"[%v] teardown network interfaces for namespace %v", idx, nsPath,
		)

		// Setup network serially
		result, err = l.SetupSerially(ctx, id, nsPath)
		assert.NoError(t, err, "[%v] setup network interfaces for namespace serially%v", idx, nsPath)

		ip = result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
		t.Logf("[%v] ip is %v", idx, ip)

		assert.NoError(t,
			l.Remove(ctx, id, nsPath),
			"[%v] teardown network interfaces for namespace %v", idx, nsPath,
		)
	}
}

func TestBasicSetupAndRemovePluginWithoutVersion(t *testing.T) {
	testutil.RequiresRoot(t)

	// setup config dir
	tmpPluginConfDir, err := os.MkdirTemp("", t.Name()+"-conf")
	assert.NoError(t, err, "create temp dir for plugin conf dir")
	defer os.RemoveAll(tmpPluginConfDir)

	assert.NoError(t,
		os.WriteFile(
			path.Join(tmpPluginConfDir, "10-gocni-test-net.conflist"),
			[]byte(cniBridgePluginCfgWithoutVersion),
			0600,
		),
		"init cni config",
	)

	// copy plugins from /opt/cni/bin
	tmpPluginDir, err := os.MkdirTemp("", t.Name()+"-bin")
	assert.NoError(t, err, "create temp dir for plugin bin dir")
	defer os.RemoveAll(tmpPluginDir)

	assert.NoError(t,
		fs.CopyDir(tmpPluginDir, defaultCNIPluginDir),
		"copy %v into %v", defaultCNIPluginDir, tmpPluginDir)

	nsPath, done, err := createNetNS()
	assert.NoError(t, err, "create temp netns")
	defer func() {
		assert.NoError(t, done(), "cleanup temp netns")
	}()

	defaultIfName := "eth0"
	ctx := context.Background()
	id := t.Name()

	for idx, opts := range [][]cni.Opt{
		// Use default plugin dir
		{
			cni.WithMinNetworkCount(2),
			cni.WithPluginConfDir(tmpPluginConfDir),
		},
		// Use customize plugin dir
		{
			cni.WithMinNetworkCount(2),
			cni.WithPluginConfDir(tmpPluginConfDir),
			cni.WithPluginDir([]string{
				tmpPluginDir,
			}),
		},
	} {
		l, err := cni.New(opts...)
		assert.NoError(t, err, "[%v] initialize cni library", idx)

		assert.NoError(t,
			l.Load(cni.WithLoNetwork, cni.WithDefaultConf),
			"[%v] load cni configuration", idx,
		)

		// Setup network
		result, err := l.Setup(ctx, id, nsPath)
		assert.NoError(t, err, "[%v] setup network interfaces for namespace in parallel %v", idx, nsPath)

		ip := result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
		t.Logf("[%v] ip is %v", idx, ip)

		assert.NoError(t,
			l.Remove(ctx, id, nsPath),
			"[%v] teardown network interfaces for namespace %v", idx, nsPath,
		)

		// Setup network serially
		result, err = l.SetupSerially(ctx, id, nsPath)
		assert.NoError(t, err, "[%v] setup network interfaces for namespace serially%v", idx, nsPath)

		ip = result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
		t.Logf("[%v] ip is %v", idx, ip)

		assert.NoError(t,
			l.Remove(ctx, id, nsPath),
			"[%v] teardown network interfaces for namespace %v", idx, nsPath,
		)
	}
}

// createNetNS returns temp netns path.
//
// NOTE: It is based on https://github.com/containernetworking/plugins/blob/v1.0.1/pkg/testutils/netns_linux.go.
// That can prevent from introducing unnessary dependencies in go.mod.
func createNetNS() (_ string, _ func() error, retErr error) {
	b := make([]byte, 16)
	if _, err := rand.Reader.Read(b); err != nil {
		return "", nil, fmt.Errorf("failed to generate random netns name: %w", err)
	}

	// Create the directory for mounting network namespaces
	// This needs to be a shared mountpoint in case it is mounted in to
	// other namespaces (containers)
	if err := os.MkdirAll(baseNetNSDir, 0755); err != nil {
		return "", nil, fmt.Errorf("failed to init base netns dir %s: %v", baseNetNSDir, err)
	}

	// create an empty file at the mount point
	nsName := fmt.Sprintf("gocni-test-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
	nsPath := path.Join(baseNetNSDir, nsName)
	mountPointFd, err := os.Create(nsPath)
	if err != nil {
		return "", nil, fmt.Errorf("failed to create temp nspath %s: %v", nsPath, err)
	}
	mountPointFd.Close()

	defer func() {
		if retErr != nil {
			_ = os.RemoveAll(nsPath)
		}
	}()

	var wg sync.WaitGroup
	wg.Add(1)

	// do namespace work in a dedicated goroutine, so that we can safely
	// Lock/Unlock OSThread without upsetting the lock/unlock state of
	// the caller of this function
	go (func() {
		defer wg.Done()

		// Don't unlock. By not unlocking, golang will kill the OS thread
		// when the goroutine is done (>= go1.10). Since <= go1.10 has
		// been deprecated, we don't need to get current net ns and
		// reset.
		runtime.LockOSThread()

		// create a new netns on the current thread
		if err = syscall.Unshare(syscall.CLONE_NEWNET); err != nil {
			return
		}

		// bind mount the netns from the current thread (from /proc) onto the
		// mount point. This causes the namespace to persist, even when there
		// are no threads in the ns.
		err = syscall.Mount(getCurrentThreadNetNSPath(), nsPath, "none", syscall.MS_BIND, "")
		if err != nil {
			err = fmt.Errorf("failed to bind mount ns at %s: %w", nsPath, err)
		}
	})()
	wg.Wait()

	if err != nil {
		return "", nil, fmt.Errorf("failed to create net namespace: %w", err)
	}

	return nsPath, func() error {
		if err := syscall.Unmount(nsPath, 0); err != nil {
			return fmt.Errorf("failed to unmount netns: at %s: %v", nsPath, err)
		}

		if err := os.Remove(nsPath); err != nil {
			return fmt.Errorf("failed to remove nspath %s: %v", nsPath, err)
		}
		return nil
	}, nil
}

// getCurrentThreadNetNSPath copied from pkg/ns
//
// NOTE: It is from https://github.com/containernetworking/plugins/blob/v1.0.1/pkg/testutils/netns_linux.go.
func getCurrentThreadNetNSPath() string {
	// /proc/self/ns/net returns the namespace of the main thread, not
	// of whatever thread this goroutine is running on.  Make sure we
	// use the thread's net namespace since the thread is switching around
	return fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), syscall.Gettid())
}