Debian Codegraph @

plugins/main/vlan/vlan.go

raw symbols SCIP
1 // Copyright 2015 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 "encoding/json"
19 "errors"
20 "fmt"
21 "runtime"
22
23 "github.com/vishvananda/netlink"
24
25 "github.com/containernetworking/cni/pkg/skel"
26 "github.com/containernetworking/cni/pkg/types"
27 current "github.com/containernetworking/cni/pkg/types/100"
28 "github.com/containernetworking/cni/pkg/version"
29 "github.com/containernetworking/plugins/pkg/ip"
30 "github.com/containernetworking/plugins/pkg/ipam"
31 "github.com/containernetworking/plugins/pkg/netlinksafe"
32 "github.com/containernetworking/plugins/pkg/ns"
33 bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
34 )
35
36 type NetConf struct {
37 types.NetConf
38 Master string `json:"master"`
39 VlanID int `json:"vlanId"`
40 MTU int `json:"mtu,omitempty"`
41 LinkContNs bool `json:"linkInContainer,omitempty"`
42 }
43
44 func init() {
45 // this ensures that main runs only on main thread (thread group leader).
46 // since namespace ops (unshare, setns) are done for a single thread, we
47 // must ensure that the goroutine does not jump from OS thread to thread
48 runtime.LockOSThread()
49 }
50
51 func loadConf(args *skel.CmdArgs) (*NetConf, string, error) {
52 n := &NetConf{}
53 if err := json.Unmarshal(args.StdinData, n); err != nil {
54 return nil, "", fmt.Errorf("failed to load netconf: %v", err)
55 }
56 if n.Master == "" {
57 return nil, "", fmt.Errorf("\"master\" field is required. It specifies the host interface name to create the VLAN for")
58 }
59 if n.VlanID < 0 || n.VlanID > 4094 {
60 return nil, "", fmt.Errorf("invalid VLAN ID %d (must be between 0 and 4095 inclusive)", n.VlanID)
61 }
62
63 // check existing and MTU of master interface
64 masterMTU, err := getMTUByName(n.Master, args.Netns, n.LinkContNs)
65 if err != nil {
66 return nil, "", err
67 }
68 if n.MTU < 0 || n.MTU > masterMTU {
69 return nil, "", fmt.Errorf("invalid MTU %d, must be [0, master MTU(%d)]", n.MTU, masterMTU)
70 }
71 return n, n.CNIVersion, nil
72 }
73
74 func getMTUByName(ifName string, namespace string, inContainer bool) (int, error) {
75 var link netlink.Link
76 var err error
77 if inContainer {
78 var netns ns.NetNS
79 netns, err = ns.GetNS(namespace)
80 if err != nil {
81 return 0, fmt.Errorf("failed to open netns %q: %v", netns, err)
82 }
83 defer netns.Close()
84
85 err = netns.Do(func(_ ns.NetNS) error {
86 link, err = netlinksafe.LinkByName(ifName)
87 return err
88 })
89 } else {
90 link, err = netlinksafe.LinkByName(ifName)
91 }
92 if err != nil {
93 return 0, err
94 }
95 return link.Attrs().MTU, nil
96 }
97
98 func createVlan(conf *NetConf, ifName string, netns ns.NetNS) (*current.Interface, error) {
99 vlan := &current.Interface{}
100
101 var m netlink.Link
102 var err error
103 if conf.LinkContNs {
104 err = netns.Do(func(_ ns.NetNS) error {
105 m, err = netlinksafe.LinkByName(conf.Master)
106 return err
107 })
108 } else {
109 m, err = netlinksafe.LinkByName(conf.Master)
110 }
111
112 if err != nil {
113 return nil, fmt.Errorf("failed to lookup master %q: %v", conf.Master, err)
114 }
115
116 // due to kernel bug we have to create with tmpname or it might
117 // collide with the name on the host and error out
118 tmpName, err := ip.RandomVethName()
119 if err != nil {
120 return nil, err
121 }
122
123 linkAttrs := netlink.NewLinkAttrs()
124 linkAttrs.MTU = conf.MTU
125 linkAttrs.Name = tmpName
126 linkAttrs.ParentIndex = m.Attrs().Index
127 linkAttrs.Namespace = netlink.NsFd(int(netns.Fd()))
128
129 v := &netlink.Vlan{
130 LinkAttrs: linkAttrs,
131 VlanId: conf.VlanID,
132 }
133
134 if conf.LinkContNs {
135 err = netns.Do(func(_ ns.NetNS) error {
136 return netlink.LinkAdd(v)
137 })
138 } else {
139 err = netlink.LinkAdd(v)
140 }
141 if err != nil {
142 return nil, fmt.Errorf("failed to create vlan: %v", err)
143 }
144
145 err = netns.Do(func(_ ns.NetNS) error {
146 err := ip.RenameLink(tmpName, ifName)
147 if err != nil {
148 return fmt.Errorf("failed to rename vlan to %q: %v", ifName, err)
149 }
150 vlan.Name = ifName
151
152 // Re-fetch interface to get all properties/attributes
153 contVlan, err := netlinksafe.LinkByName(vlan.Name)
154 if err != nil {
155 return fmt.Errorf("failed to refetch vlan %q: %v", vlan.Name, err)
156 }
157 vlan.Mac = contVlan.Attrs().HardwareAddr.String()
158 vlan.Sandbox = netns.Path()
159
160 return nil
161 })
162 if err != nil {
163 return nil, err
164 }
165
166 return vlan, nil
167 }
168
169 func cmdAdd(args *skel.CmdArgs) error {
170 n, cniVersion, err := loadConf(args)
171 if err != nil {
172 return err
173 }
174
175 netns, err := ns.GetNS(args.Netns)
176 if err != nil {
177 return fmt.Errorf("failed to open netns %q: %v", args.Netns, err)
178 }
179 defer netns.Close()
180
181 vlanInterface, err := createVlan(n, args.IfName, netns)
182 if err != nil {
183 return err
184 }
185
186 // run the IPAM plugin and get back the config to apply
187 r, err := ipam.ExecAdd(n.IPAM.Type, args.StdinData)
188 if err != nil {
189 return fmt.Errorf("failed to execute IPAM delegate: %v", err)
190 }
191
192 // Invoke ipam del if err to avoid ip leak
193 defer func() {
194 if err != nil {
195 ipam.ExecDel(n.IPAM.Type, args.StdinData)
196 }
197 }()
198
199 // Convert whatever the IPAM result was into the current Result type
200 result, err := current.NewResultFromResult(r)
201 if err != nil {
202 return err
203 }
204
205 if len(result.IPs) == 0 {
206 return errors.New("IPAM plugin returned missing IP config")
207 }
208 for _, ipc := range result.IPs {
209 // All addresses belong to the vlan interface
210 ipc.Interface = current.Int(0)
211 }
212
213 result.Interfaces = []*current.Interface{vlanInterface}
214
215 err = netns.Do(func(_ ns.NetNS) error {
216 return ipam.ConfigureIface(args.IfName, result)
217 })
218 if err != nil {
219 return err
220 }
221
222 result.DNS = n.DNS
223
224 return types.PrintResult(result, cniVersion)
225 }
226
227 func cmdDel(args *skel.CmdArgs) error {
228 n, _, err := loadConf(args)
229 if err != nil {
230 return err
231 }
232
233 err = ipam.ExecDel(n.IPAM.Type, args.StdinData)
234 if err != nil {
235 return err
236 }
237
238 if args.Netns == "" {
239 return nil
240 }
241
242 err = ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error {
243 err = ip.DelLinkByName(args.IfName)
244 if err != nil && err == ip.ErrLinkNotFound {
245 return nil
246 }
247 return err
248 })
249 if err != nil {
250 // if NetNs is passed down by the Cloud Orchestration Engine, or if it called multiple times
251 // so don't return an error if the device is already removed.
252 // https://github.com/kubernetes/kubernetes/issues/43014#issuecomment-287164444
253 _, ok := err.(ns.NSPathNotExistErr)
254 if ok {
255 return nil
256 }
257 return err
258 }
259
260 return err
261 }
262
263 func main() {
264 skel.PluginMainFuncs(skel.CNIFuncs{
265 Add: cmdAdd,
266 Check: cmdCheck,
267 Del: cmdDel,
268 Status: cmdStatus,
269 /* FIXME GC */
270 }, version.All, bv.BuildString("vlan"))
271 }
272
273 func cmdCheck(args *skel.CmdArgs) error {
274 conf := NetConf{}
275 if err := json.Unmarshal(args.StdinData, &conf); err != nil {
276 return fmt.Errorf("failed to load netconf: %v", err)
277 }
278
279 netns, err := ns.GetNS(args.Netns)
280 if err != nil {
281 return fmt.Errorf("failed to open netns %q: %v", args.Netns, err)
282 }
283 defer netns.Close()
284
285 // run the IPAM plugin and get back the config to apply
286 err = ipam.ExecCheck(conf.IPAM.Type, args.StdinData)
287 if err != nil {
288 return err
289 }
290 if conf.NetConf.RawPrevResult == nil {
291 return fmt.Errorf("vlan: Required prevResult missing")
292 }
293 if err := version.ParsePrevResult(&conf.NetConf); err != nil {
294 return err
295 }
296 // Convert whatever the IPAM result was into the current Result type
297 result, err := current.NewResultFromResult(conf.PrevResult)
298 if err != nil {
299 return err
300 }
301
302 var contMap current.Interface
303 // Find interfaces for name whe know, that of host-device inside container
304 for _, intf := range result.Interfaces {
305 if args.IfName == intf.Name {
306 if args.Netns == intf.Sandbox {
307 contMap = *intf
308 continue
309 }
310 }
311 }
312
313 // The namespace must be the same as what was configured
314 if args.Netns != contMap.Sandbox {
315 return fmt.Errorf("Sandbox in prevResult %s doesn't match configured netns: %s",
316 contMap.Sandbox, args.Netns)
317 }
318
319 if conf.LinkContNs {
320 err = netns.Do(func(_ ns.NetNS) error {
321 _, err = netlinksafe.LinkByName(conf.Master)
322 return err
323 })
324 } else {
325 _, err = netlinksafe.LinkByName(conf.Master)
326 }
327
328 if err != nil {
329 return fmt.Errorf("failed to lookup master %q: %v", conf.Master, err)
330 }
331
332 //
333 // Check prevResults for ips, routes and dns against values found in the container
334 if err := netns.Do(func(_ ns.NetNS) error {
335 // Check interface against values found in the container
336 err := validateCniContainerInterface(contMap, conf.VlanID, conf.MTU)
337 if err != nil {
338 return err
339 }
340
341 err = ip.ValidateExpectedInterfaceIPs(args.IfName, result.IPs)
342 if err != nil {
343 return err
344 }
345
346 err = ip.ValidateExpectedRoute(result.Routes)
347 if err != nil {
348 return err
349 }
350 return nil
351 }); err != nil {
352 return err
353 }
354
355 return nil
356 }
357
358 func validateCniContainerInterface(intf current.Interface, vlanID int, mtu int) error {
359 var link netlink.Link
360 var err error
361
362 if intf.Name == "" {
363 return fmt.Errorf("Container interface name missing in prevResult: %v", intf.Name)
364 }
365 link, err = netlinksafe.LinkByName(intf.Name)
366 if err != nil {
367 return fmt.Errorf("vlan: Container Interface name in prevResult: %s not found", intf.Name)
368 }
369 if intf.Sandbox == "" {
370 return fmt.Errorf("vlan: Error: Container interface %s should not be in host namespace", link.Attrs().Name)
371 }
372
373 vlan, isVlan := link.(*netlink.Vlan)
374 if !isVlan {
375 return fmt.Errorf("Error: Container interface %s not of type vlan", link.Attrs().Name)
376 }
377
378 // TODO This works when unit testing via cnitool; fails with ./test.sh
379 // if masterIndex != vlan.Attrs().ParentIndex {
380 // return fmt.Errorf("Container vlan Master %d does not match expected value: %d", vlan.Attrs().ParentIndex, masterIndex)
381 //}
382
383 if intf.Mac != "" {
384 if intf.Mac != link.Attrs().HardwareAddr.String() {
385 return fmt.Errorf("vlan: Interface %s Mac %s doesn't match container Mac: %s", intf.Name, intf.Mac, link.Attrs().HardwareAddr)
386 }
387 }
388
389 if vlanID != vlan.VlanId {
390 return fmt.Errorf("Error: Tuning link %s configured promisc is %v, current value is %d",
391 intf.Name, vlanID, vlan.VlanId)
392 }
393
394 if mtu != 0 {
395 if mtu != link.Attrs().MTU {
396 return fmt.Errorf("Error: Tuning configured MTU of %s is %d, current value is %d",
397 intf.Name, mtu, link.Attrs().MTU)
398 }
399 }
400
401 return nil
402 }
403
404 func cmdStatus(args *skel.CmdArgs) error {
405 conf := NetConf{}
406 if err := json.Unmarshal(args.StdinData, &conf); err != nil {
407 return fmt.Errorf("failed to load netconf: %w", err)
408 }
409
410 if err := ipam.ExecStatus(conf.IPAM.Type, args.StdinData); err != nil {
411 return err
412 }
413
414 // TODO: Check if master interface exists.
415
416 return nil
417 }