File: network-device-injector.go

package info (click to toggle)
golang-github-containerd-nri 0.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,980 kB
  • sloc: makefile: 117; sh: 45
file content (306 lines) | stat: -rw-r--r-- 7,028 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
/*
   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.
*/

package main

import (
	"context"
	"flag"
	"fmt"
	"net"
	"os"
	"runtime"
	"strings"

	"github.com/containernetworking/plugins/pkg/ns"
	"github.com/sirupsen/logrus"
	"github.com/vishvananda/netlink"
	"sigs.k8s.io/yaml"

	"github.com/containerd/nri/pkg/api"
	"github.com/containerd/nri/pkg/stub"
)

const (
	// Prefix of the key used for network device annotations.
	netdeviceKey = "netdevices.nri.containerd.io"
)

var (
	log     *logrus.Logger
	verbose bool
)

// an annotated netdevice
// https://man7.org/linux/man-pages/man7/netdevice.7.html
type netdevice struct {
	Name    string `json:"name"`     // name in the runtime namespace
	NewName string `json:"new_name"` // name inside the pod namespace
	Address string `json:"address"`
	Prefix  int    `json:"prefix"`
	MTU     int    `json:"mtu"`
}

func (n *netdevice) inject(nsPath string) error {
	// Lock the OS Thread so we don't accidentally switch namespaces
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	containerNs, err := ns.GetNS(nsPath)
	if err != nil {
		return err
	}
	defer containerNs.Close()

	hostDev, err := netlink.LinkByName(n.Name)
	if err != nil {
		return err
	}

	_, err = moveLinkIn(hostDev, containerNs, n.NewName)
	if err != nil {
		return fmt.Errorf("failed to move link %v", err)
	}
	return nil
}

// remove the network device from the Pod namespace and recover its name
// Leaves the interface in down state to avoid issues with the root network.
func (n *netdevice) release(nsPath string) error {
	// Lock the OS Thread so we don't accidentally switch namespaces
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	containerNs, err := ns.GetNS(nsPath)
	if err != nil {
		return err
	}
	defer containerNs.Close()

	err = moveLinkOut(containerNs, n.NewName)
	if err != nil {
		return err
	}

	return nil
}

// our injector plugin
type plugin struct {
	stub stub.Stub
}

func (p *plugin) RunPodSandbox(_ context.Context, pod *api.PodSandbox) error {
	log.WithField("namespace", pod.GetNamespace()).WithField("name", pod.GetName).Debug("Started pod...")
	if verbose {
		dump("RunPodSandbox", "pod", pod)
	}

	// inject associated netdevices (based on received pod annotations) into the pod
	// network namespace that will be attached to the pod's containers
	netdevices, err := parseNetdevices(pod.Annotations)
	if err != nil {
		return err
	}

	if len(netdevices) == 0 {
		return nil
	}

	// get the pod network namespace
	var ns string
	for _, namespace := range pod.Linux.GetNamespaces() {
		if namespace.Type == "network" {
			ns = namespace.Path
			break
		}
	}

	// Pods running on the host network namespace has this value empty
	if ns == "" {
		log.WithField("namespace", pod.GetNamespace()).WithField("name", pod.GetName).Info("Pod using host namespace, skipping ...")
		return fmt.Errorf("trying to inject network device on host network Pod")
	}

	// attach the network devices to the pod namespace
	for _, n := range netdevices {
		err = n.inject(ns)
		if err != nil {
			return nil
		}
	}
	return nil
}

func (p *plugin) StopPodSandbox(_ context.Context, pod *api.PodSandbox) error {
	log.WithField("namespace", pod.GetNamespace()).WithField("name", pod.GetName).Debug("Stopped pod...")
	if verbose {
		dump("StopPodSandbox", "pod", pod)
	}
	// release associated devices of the netdevice to the Pod
	netdevices, err := parseNetdevices(pod.Annotations)
	if err != nil {
		return err
	}

	if len(netdevices) == 0 {
		return nil
	}

	// get the pod network namespace
	var ns string
	for _, namespace := range pod.Linux.GetNamespaces() {
		if namespace.Type == "network" {
			ns = namespace.Path
			break
		}
	}
	// TODO check host network namespace
	if ns == "" {
		return nil
	}

	// release the network devices from the pod namespace
	for _, n := range netdevices {
		err = n.release(ns)
		if err != nil {
			return nil
		}
	}

	return nil
}

func parseNetdevices(annotations map[string]string) ([]netdevice, error) {
	var (
		key        string
		annotation []byte
		netdevices []netdevice
	)

	// look up effective device annotation and unmarshal devices
	for _, key = range []string{
		netdeviceKey + "/pod",
		netdeviceKey,
	} {
		if value, ok := annotations[key]; ok {
			annotation = []byte(value)
			break
		}
	}

	if annotation == nil {
		return nil, nil
	}

	if err := yaml.Unmarshal(annotation, &netdevices); err != nil {
		return nil, fmt.Errorf("invalid device annotation %q: %w", key, err)
	}

	// validate and default
	for _, n := range netdevices {
		if n.NewName == "" {
			n.NewName = n.Name
		}
		if n.Address != "" {
			ip := net.ParseIP(n.Address)
			if ip == nil {
				return nil, fmt.Errorf("error parsing address %s", n.Address)
			}

			if n.Prefix == 0 {
				if ip.To4() == nil {
					n.Prefix = 128
				} else {
					n.Prefix = 32
				}
			}
		}

	}
	return netdevices, nil
}

// Dump one or more objects, with an optional global prefix and per-object tags.
func dump(args ...interface{}) {
	var (
		prefix string
		idx    int
	)

	if len(args) == 1 {
		prefix = args[0].(string)
		idx++
	}

	for ; idx < len(args)-1; idx += 2 {
		tag, obj := args[idx], args[idx+1]
		msg, err := yaml.Marshal(obj)
		if err != nil {
			log.Infof("%s: %s: failed to dump object: %v", prefix, tag, err)
			continue
		}

		if prefix != "" {
			log.Infof("%s: %s:", prefix, tag)
			for _, line := range strings.Split(strings.TrimSpace(string(msg)), "\n") {
				log.Infof("%s:    %s", prefix, line)
			}
		} else {
			log.Infof("%s:", tag)
			for _, line := range strings.Split(strings.TrimSpace(string(msg)), "\n") {
				log.Infof("  %s", line)
			}
		}
	}
}

func main() {
	var (
		pluginName string
		pluginIdx  string
		opts       []stub.Option
		err        error
	)

	log = logrus.StandardLogger()
	log.SetFormatter(&logrus.TextFormatter{
		PadLevelText: true,
	})

	flag.StringVar(&pluginName, "name", "", "plugin name to register to NRI")
	flag.StringVar(&pluginIdx, "idx", "", "plugin index to register to NRI")
	flag.BoolVar(&verbose, "verbose", false, "enable (more) verbose logging")
	flag.Parse()

	if pluginName != "" {
		opts = append(opts, stub.WithPluginName(pluginName))
	}
	if pluginIdx != "" {
		opts = append(opts, stub.WithPluginIdx(pluginIdx))
	}

	p := &plugin{}
	if p.stub, err = stub.New(p, opts...); err != nil {
		log.Fatalf("failed to create plugin stub: %v", err)
	}

	err = p.stub.Run(context.Background())
	if err != nil {
		log.Errorf("plugin exited with error %v", err)
		os.Exit(1)
	}
}