| 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 | "net" |
| 22 | "runtime" |
| 23 | |
| 24 | "github.com/vishvananda/netlink" |
| 25 | |
| 26 | "github.com/containernetworking/cni/pkg/skel" |
| 27 | "github.com/containernetworking/cni/pkg/types" |
| 28 | current "github.com/containernetworking/cni/pkg/types/100" |
| 29 | "github.com/containernetworking/cni/pkg/version" |
| 30 | "github.com/containernetworking/plugins/pkg/ip" |
| 31 | "github.com/containernetworking/plugins/pkg/ipam" |
| 32 | "github.com/containernetworking/plugins/pkg/netlinksafe" |
| 33 | "github.com/containernetworking/plugins/pkg/ns" |
| 34 | bv "github.com/containernetworking/plugins/pkg/utils/buildversion" |
| 35 | "github.com/containernetworking/plugins/pkg/utils/sysctl" |
| 36 | ) |
| 37 | |
| 38 | type NetConf struct { |
| 39 | types.NetConf |
| 40 | Master string `json:"master"` |
| 41 | Mode string `json:"mode"` |
| 42 | MTU int `json:"mtu"` |
| 43 | Mac string `json:"mac,omitempty"` |
| 44 | LinkContNs bool `json:"linkInContainer,omitempty"` |
| 45 | BcQueueLen uint32 `json:"bcqueuelen,omitempty"` |
| 46 | |
| 47 | RuntimeConfig struct { |
| 48 | Mac string `json:"mac,omitempty"` |
| 49 | } `json:"runtimeConfig,omitempty"` |
| 50 | } |
| 51 | |
| 52 | // MacEnvArgs represents CNI_ARG |
| 53 | type MacEnvArgs struct { |
| 54 | types.CommonArgs |
| 55 | MAC types.UnmarshallableString `json:"mac,omitempty"` |
| 56 | } |
| 57 | |
| 58 | func init() { |
| 59 | // this ensures that main runs only on main thread (thread group leader). |
| 60 | // since namespace ops (unshare, setns) are done for a single thread, we |
| 61 | // must ensure that the goroutine does not jump from OS thread to thread |
| 62 | runtime.LockOSThread() |
| 63 | } |
| 64 | |
| 65 | func getDefaultRouteInterfaceName() (string, error) { |
| 66 | routeToDstIP, err := netlinksafe.RouteList(nil, netlink.FAMILY_ALL) |
| 67 | if err != nil { |
| 68 | return "", err |
| 69 | } |
| 70 | |
| 71 | for _, v := range routeToDstIP { |
| 72 | if ip.IsIPNetZero(v.Dst) { |
| 73 | l, err := netlink.LinkByIndex(v.LinkIndex) |
| 74 | if err != nil { |
| 75 | return "", err |
| 76 | } |
| 77 | return l.Attrs().Name, nil |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | return "", fmt.Errorf("no default route interface found") |
| 82 | } |
| 83 | |
| 84 | func getNamespacedDefaultRouteInterfaceName(namespace string, inContainer bool) (string, error) { |
| 85 | if !inContainer { |
| 86 | return getDefaultRouteInterfaceName() |
| 87 | } |
| 88 | netns, err := ns.GetNS(namespace) |
| 89 | if err != nil { |
| 90 | return "", fmt.Errorf("failed to open netns %q: %v", netns, err) |
| 91 | } |
| 92 | defer netns.Close() |
| 93 | var defaultRouteInterface string |
| 94 | err = netns.Do(func(_ ns.NetNS) error { |
| 95 | defaultRouteInterface, err = getDefaultRouteInterfaceName() |
| 96 | if err != nil { |
| 97 | return err |
| 98 | } |
| 99 | return nil |
| 100 | }) |
| 101 | if err != nil { |
| 102 | return "", err |
| 103 | } |
| 104 | return defaultRouteInterface, nil |
| 105 | } |
| 106 | |
| 107 | func loadConf(args *skel.CmdArgs, envArgs string) (*NetConf, string, error) { |
| 108 | n := &NetConf{} |
| 109 | if err := json.Unmarshal(args.StdinData, n); err != nil { |
| 110 | return nil, "", fmt.Errorf("failed to load netconf: %v", err) |
| 111 | } |
| 112 | if n.Master == "" { |
| 113 | defaultRouteInterface, err := getNamespacedDefaultRouteInterfaceName(args.Netns, n.LinkContNs) |
| 114 | if err != nil { |
| 115 | return nil, "", err |
| 116 | } |
| 117 | n.Master = defaultRouteInterface |
| 118 | } |
| 119 | |
| 120 | // check existing and MTU of master interface |
| 121 | masterMTU, err := getMTUByName(n.Master, args.Netns, n.LinkContNs) |
| 122 | if err != nil { |
| 123 | return nil, "", err |
| 124 | } |
| 125 | if n.MTU < 0 || n.MTU > masterMTU { |
| 126 | return nil, "", fmt.Errorf("invalid MTU %d, must be [0, master MTU(%d)]", n.MTU, masterMTU) |
| 127 | } |
| 128 | |
| 129 | if envArgs != "" { |
| 130 | e := MacEnvArgs{} |
| 131 | err := types.LoadArgs(envArgs, &e) |
| 132 | if err != nil { |
| 133 | return nil, "", err |
| 134 | } |
| 135 | |
| 136 | if e.MAC != "" { |
| 137 | n.Mac = string(e.MAC) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | if n.RuntimeConfig.Mac != "" { |
| 142 | n.Mac = n.RuntimeConfig.Mac |
| 143 | } |
| 144 | |
| 145 | return n, n.CNIVersion, nil |
| 146 | } |
| 147 | |
| 148 | func getMTUByName(ifName string, namespace string, inContainer bool) (int, error) { |
| 149 | var link netlink.Link |
| 150 | var err error |
| 151 | if inContainer { |
| 152 | var netns ns.NetNS |
| 153 | netns, err = ns.GetNS(namespace) |
| 154 | if err != nil { |
| 155 | return 0, fmt.Errorf("failed to open netns %q: %v", netns, err) |
| 156 | } |
| 157 | defer netns.Close() |
| 158 | |
| 159 | err = netns.Do(func(_ ns.NetNS) error { |
| 160 | link, err = netlinksafe.LinkByName(ifName) |
| 161 | return err |
| 162 | }) |
| 163 | } else { |
| 164 | link, err = netlinksafe.LinkByName(ifName) |
| 165 | } |
| 166 | if err != nil { |
| 167 | return 0, err |
| 168 | } |
| 169 | return link.Attrs().MTU, nil |
| 170 | } |
| 171 | |
| 172 | func modeFromString(s string) (netlink.MacvlanMode, error) { |
| 173 | switch s { |
| 174 | case "", "bridge": |
| 175 | return netlink.MACVLAN_MODE_BRIDGE, nil |
| 176 | case "private": |
| 177 | return netlink.MACVLAN_MODE_PRIVATE, nil |
| 178 | case "vepa": |
| 179 | return netlink.MACVLAN_MODE_VEPA, nil |
| 180 | case "passthru": |
| 181 | return netlink.MACVLAN_MODE_PASSTHRU, nil |
| 182 | default: |
| 183 | return 0, fmt.Errorf("unknown macvlan mode: %q", s) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | func modeToString(mode netlink.MacvlanMode) (string, error) { |
| 188 | switch mode { |
| 189 | case netlink.MACVLAN_MODE_BRIDGE: |
| 190 | return "bridge", nil |
| 191 | case netlink.MACVLAN_MODE_PRIVATE: |
| 192 | return "private", nil |
| 193 | case netlink.MACVLAN_MODE_VEPA: |
| 194 | return "vepa", nil |
| 195 | case netlink.MACVLAN_MODE_PASSTHRU: |
| 196 | return "passthru", nil |
| 197 | default: |
| 198 | return "", fmt.Errorf("unknown macvlan mode: %q", mode) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | func createMacvlan(conf *NetConf, ifName string, netns ns.NetNS) (*current.Interface, error) { |
| 203 | macvlan := ¤t.Interface{} |
| 204 | |
| 205 | mode, err := modeFromString(conf.Mode) |
| 206 | if err != nil { |
| 207 | return nil, err |
| 208 | } |
| 209 | |
| 210 | var m netlink.Link |
| 211 | if conf.LinkContNs { |
| 212 | err = netns.Do(func(_ ns.NetNS) error { |
| 213 | m, err = netlinksafe.LinkByName(conf.Master) |
| 214 | return err |
| 215 | }) |
| 216 | } else { |
| 217 | m, err = netlinksafe.LinkByName(conf.Master) |
| 218 | } |
| 219 | if err != nil { |
| 220 | return nil, fmt.Errorf("failed to lookup master %q: %v", conf.Master, err) |
| 221 | } |
| 222 | |
| 223 | // due to kernel bug we have to create with tmpName or it might |
| 224 | // collide with the name on the host and error out |
| 225 | tmpName, err := ip.RandomVethName() |
| 226 | if err != nil { |
| 227 | return nil, err |
| 228 | } |
| 229 | |
| 230 | linkAttrs := netlink.NewLinkAttrs() |
| 231 | linkAttrs.MTU = conf.MTU |
| 232 | linkAttrs.Name = tmpName |
| 233 | linkAttrs.ParentIndex = m.Attrs().Index |
| 234 | linkAttrs.Namespace = netlink.NsFd(int(netns.Fd())) |
| 235 | |
| 236 | if conf.Mac != "" { |
| 237 | addr, err := net.ParseMAC(conf.Mac) |
| 238 | if err != nil { |
| 239 | return nil, fmt.Errorf("invalid args %v for MAC addr: %v", conf.Mac, err) |
| 240 | } |
| 241 | linkAttrs.HardwareAddr = addr |
| 242 | } |
| 243 | |
| 244 | mv := &netlink.Macvlan{ |
| 245 | LinkAttrs: linkAttrs, |
| 246 | Mode: mode, |
| 247 | } |
| 248 | |
| 249 | mv.BCQueueLen = conf.BcQueueLen |
| 250 | |
| 251 | if conf.LinkContNs { |
| 252 | err = netns.Do(func(_ ns.NetNS) error { |
| 253 | return netlink.LinkAdd(mv) |
| 254 | }) |
| 255 | } else { |
| 256 | if err = netlink.LinkAdd(mv); err != nil { |
| 257 | return nil, fmt.Errorf("failed to create macvlan: %v", err) |
| 258 | } |
| 259 | } |
| 260 | if err != nil { |
| 261 | return nil, fmt.Errorf("failed to create macvlan: %v", err) |
| 262 | } |
| 263 | |
| 264 | err = netns.Do(func(_ ns.NetNS) error { |
| 265 | err := ip.RenameLink(tmpName, ifName) |
| 266 | if err != nil { |
| 267 | _ = netlink.LinkDel(mv) |
| 268 | return fmt.Errorf("failed to rename macvlan to %q: %v", ifName, err) |
| 269 | } |
| 270 | macvlan.Name = ifName |
| 271 | |
| 272 | // Re-fetch macvlan to get all properties/attributes |
| 273 | contMacvlan, err := netlinksafe.LinkByName(ifName) |
| 274 | if err != nil { |
| 275 | return fmt.Errorf("failed to refetch macvlan %q: %v", ifName, err) |
| 276 | } |
| 277 | macvlan.Mac = contMacvlan.Attrs().HardwareAddr.String() |
| 278 | macvlan.Sandbox = netns.Path() |
| 279 | |
| 280 | return nil |
| 281 | }) |
| 282 | if err != nil { |
| 283 | return nil, err |
| 284 | } |
| 285 | |
| 286 | return macvlan, nil |
| 287 | } |
| 288 | |
| 289 | func cmdAdd(args *skel.CmdArgs) error { |
| 290 | n, cniVersion, err := loadConf(args, args.Args) |
| 291 | if err != nil { |
| 292 | return err |
| 293 | } |
| 294 | |
| 295 | isLayer3 := n.IPAM.Type != "" |
| 296 | |
| 297 | netns, err := ns.GetNS(args.Netns) |
| 298 | if err != nil { |
| 299 | return fmt.Errorf("failed to open netns %q: %v", netns, err) |
| 300 | } |
| 301 | defer netns.Close() |
| 302 | |
| 303 | macvlanInterface, err := createMacvlan(n, args.IfName, netns) |
| 304 | if err != nil { |
| 305 | return err |
| 306 | } |
| 307 | |
| 308 | // Delete link if err to avoid link leak in this ns |
| 309 | defer func() { |
| 310 | if err != nil { |
| 311 | netns.Do(func(_ ns.NetNS) error { |
| 312 | return ip.DelLinkByName(args.IfName) |
| 313 | }) |
| 314 | } |
| 315 | }() |
| 316 | |
| 317 | // Assume L2 interface only |
| 318 | result := ¤t.Result{ |
| 319 | CNIVersion: current.ImplementedSpecVersion, |
| 320 | Interfaces: []*current.Interface{macvlanInterface}, |
| 321 | } |
| 322 | |
| 323 | if isLayer3 { |
| 324 | // run the IPAM plugin and get back the config to apply |
| 325 | r, err := ipam.ExecAdd(n.IPAM.Type, args.StdinData) |
| 326 | if err != nil { |
| 327 | return err |
| 328 | } |
| 329 | |
| 330 | // Invoke ipam del if err to avoid ip leak |
| 331 | defer func() { |
| 332 | if err != nil { |
| 333 | ipam.ExecDel(n.IPAM.Type, args.StdinData) |
| 334 | } |
| 335 | }() |
| 336 | |
| 337 | // Convert whatever the IPAM result was into the current Result type |
| 338 | ipamResult, err := current.NewResultFromResult(r) |
| 339 | if err != nil { |
| 340 | return err |
| 341 | } |
| 342 | |
| 343 | if len(ipamResult.IPs) == 0 { |
| 344 | return errors.New("IPAM plugin returned missing IP config") |
| 345 | } |
| 346 | |
| 347 | result.IPs = ipamResult.IPs |
| 348 | result.Routes = ipamResult.Routes |
| 349 | |
| 350 | for _, ipc := range result.IPs { |
| 351 | // All addresses apply to the container macvlan interface |
| 352 | ipc.Interface = current.Int(0) |
| 353 | } |
| 354 | |
| 355 | err = netns.Do(func(_ ns.NetNS) error { |
| 356 | _, _ = sysctl.Sysctl(fmt.Sprintf("net/ipv4/conf/%s/arp_notify", args.IfName), "1") |
| 357 | _, _ = sysctl.Sysctl(fmt.Sprintf("net/ipv6/conf/%s/ndisc_notify", args.IfName), "1") |
| 358 | |
| 359 | return ipam.ConfigureIface(args.IfName, result) |
| 360 | }) |
| 361 | if err != nil { |
| 362 | return err |
| 363 | } |
| 364 | } else { |
| 365 | // For L2 just change interface status to up |
| 366 | err = netns.Do(func(_ ns.NetNS) error { |
| 367 | macvlanInterfaceLink, err := netlinksafe.LinkByName(args.IfName) |
| 368 | if err != nil { |
| 369 | return fmt.Errorf("failed to find interface name %q: %v", macvlanInterface.Name, err) |
| 370 | } |
| 371 | |
| 372 | if err := netlink.LinkSetUp(macvlanInterfaceLink); err != nil { |
| 373 | return fmt.Errorf("failed to set %q UP: %v", args.IfName, err) |
| 374 | } |
| 375 | |
| 376 | return nil |
| 377 | }) |
| 378 | if err != nil { |
| 379 | return err |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | result.DNS = n.DNS |
| 384 | |
| 385 | return types.PrintResult(result, cniVersion) |
| 386 | } |
| 387 | |
| 388 | func cmdDel(args *skel.CmdArgs) error { |
| 389 | var n NetConf |
| 390 | err := json.Unmarshal(args.StdinData, &n) |
| 391 | if err != nil { |
| 392 | return fmt.Errorf("failed to load netConf: %v", err) |
| 393 | } |
| 394 | |
| 395 | isLayer3 := n.IPAM.Type != "" |
| 396 | if isLayer3 { |
| 397 | err = ipam.ExecDel(n.IPAM.Type, args.StdinData) |
| 398 | if err != nil { |
| 399 | return err |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | if args.Netns == "" { |
| 404 | return nil |
| 405 | } |
| 406 | |
| 407 | // There is a netns so try to clean up. Delete can be called multiple times |
| 408 | // so don't return an error if the device is already removed. |
| 409 | err = ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error { |
| 410 | if err := ip.DelLinkByName(args.IfName); err != nil { |
| 411 | if err != ip.ErrLinkNotFound { |
| 412 | return err |
| 413 | } |
| 414 | } |
| 415 | return nil |
| 416 | }) |
| 417 | if err != nil { |
| 418 | // if NetNs is passed down by the Cloud Orchestration Engine, or if it called multiple times |
| 419 | // so don't return an error if the device is already removed. |
| 420 | // https://github.com/kubernetes/kubernetes/issues/43014#issuecomment-287164444 |
| 421 | _, ok := err.(ns.NSPathNotExistErr) |
| 422 | if ok { |
| 423 | return nil |
| 424 | } |
| 425 | return err |
| 426 | } |
| 427 | |
| 428 | return err |
| 429 | } |
| 430 | |
| 431 | func main() { |
| 432 | skel.PluginMainFuncs(skel.CNIFuncs{ |
| 433 | Add: cmdAdd, |
| 434 | Check: cmdCheck, |
| 435 | Del: cmdDel, |
| 436 | Status: cmdStatus, |
| 437 | /* FIXME GC */ |
| 438 | }, version.All, bv.BuildString("macvlan")) |
| 439 | } |
| 440 | |
| 441 | func cmdCheck(args *skel.CmdArgs) error { |
| 442 | n, _, err := loadConf(args, args.Args) |
| 443 | if err != nil { |
| 444 | return err |
| 445 | } |
| 446 | isLayer3 := n.IPAM.Type != "" |
| 447 | |
| 448 | netns, err := ns.GetNS(args.Netns) |
| 449 | if err != nil { |
| 450 | return fmt.Errorf("failed to open netns %q: %v", args.Netns, err) |
| 451 | } |
| 452 | defer netns.Close() |
| 453 | |
| 454 | if isLayer3 { |
| 455 | // run the IPAM plugin and get back the config to apply |
| 456 | err = ipam.ExecCheck(n.IPAM.Type, args.StdinData) |
| 457 | if err != nil { |
| 458 | return err |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | // Parse previous result. |
| 463 | if n.NetConf.RawPrevResult == nil { |
| 464 | return fmt.Errorf("required prevResult missing") |
| 465 | } |
| 466 | |
| 467 | if err := version.ParsePrevResult(&n.NetConf); err != nil { |
| 468 | return err |
| 469 | } |
| 470 | |
| 471 | result, err := current.NewResultFromResult(n.PrevResult) |
| 472 | if err != nil { |
| 473 | return err |
| 474 | } |
| 475 | |
| 476 | var contMap current.Interface |
| 477 | // Find interfaces for names whe know, macvlan device name inside container |
| 478 | for _, intf := range result.Interfaces { |
| 479 | if args.IfName == intf.Name { |
| 480 | if args.Netns == intf.Sandbox { |
| 481 | contMap = *intf |
| 482 | continue |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | // The namespace must be the same as what was configured |
| 488 | if args.Netns != contMap.Sandbox { |
| 489 | return fmt.Errorf("sandbox in prevResult %s doesn't match configured netns: %s", |
| 490 | contMap.Sandbox, args.Netns) |
| 491 | } |
| 492 | |
| 493 | if n.LinkContNs { |
| 494 | err = netns.Do(func(_ ns.NetNS) error { |
| 495 | _, err = netlinksafe.LinkByName(n.Master) |
| 496 | return err |
| 497 | }) |
| 498 | } else { |
| 499 | _, err = netlinksafe.LinkByName(n.Master) |
| 500 | } |
| 501 | if err != nil { |
| 502 | return fmt.Errorf("failed to lookup master %q: %v", n.Master, err) |
| 503 | } |
| 504 | |
| 505 | // Check prevResults for ips, routes and dns against values found in the container |
| 506 | if err := netns.Do(func(_ ns.NetNS) error { |
| 507 | // Check interface against values found in the container |
| 508 | err := validateCniContainerInterface(contMap, n.Mode) |
| 509 | if err != nil { |
| 510 | return err |
| 511 | } |
| 512 | |
| 513 | err = ip.ValidateExpectedInterfaceIPs(args.IfName, result.IPs) |
| 514 | if err != nil { |
| 515 | return err |
| 516 | } |
| 517 | |
| 518 | err = ip.ValidateExpectedRoute(result.Routes) |
| 519 | if err != nil { |
| 520 | return err |
| 521 | } |
| 522 | return nil |
| 523 | }); err != nil { |
| 524 | return err |
| 525 | } |
| 526 | |
| 527 | return nil |
| 528 | } |
| 529 | |
| 530 | func validateCniContainerInterface(intf current.Interface, modeExpected string) error { |
| 531 | var link netlink.Link |
| 532 | var err error |
| 533 | |
| 534 | if intf.Name == "" { |
| 535 | return fmt.Errorf("container interface name missing in prevResult: %v", intf.Name) |
| 536 | } |
| 537 | link, err = netlinksafe.LinkByName(intf.Name) |
| 538 | if err != nil { |
| 539 | return fmt.Errorf("container Interface name in prevResult: %s not found", intf.Name) |
| 540 | } |
| 541 | if intf.Sandbox == "" { |
| 542 | return fmt.Errorf("error: Container interface %s should not be in host namespace", link.Attrs().Name) |
| 543 | } |
| 544 | |
| 545 | macv, isMacvlan := link.(*netlink.Macvlan) |
| 546 | if !isMacvlan { |
| 547 | return fmt.Errorf("error: Container interface %s not of type macvlan", link.Attrs().Name) |
| 548 | } |
| 549 | |
| 550 | mode, err := modeFromString(modeExpected) |
| 551 | if err != nil { |
| 552 | return err |
| 553 | } |
| 554 | if macv.Mode != mode { |
| 555 | currString, err := modeToString(macv.Mode) |
| 556 | if err != nil { |
| 557 | return err |
| 558 | } |
| 559 | confString, err := modeToString(mode) |
| 560 | if err != nil { |
| 561 | return err |
| 562 | } |
| 563 | return fmt.Errorf("container macvlan mode %s does not match expected value: %s", currString, confString) |
| 564 | } |
| 565 | |
| 566 | if intf.Mac != "" { |
| 567 | if intf.Mac != link.Attrs().HardwareAddr.String() { |
| 568 | return fmt.Errorf("interface %s Mac %s doesn't match container Mac: %s", intf.Name, intf.Mac, link.Attrs().HardwareAddr) |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | return nil |
| 573 | } |
| 574 | |
| 575 | func cmdStatus(args *skel.CmdArgs) error { |
| 576 | conf := NetConf{} |
| 577 | if err := json.Unmarshal(args.StdinData, &conf); err != nil { |
| 578 | return fmt.Errorf("failed to load netconf: %w", err) |
| 579 | } |
| 580 | |
| 581 | if conf.IPAM.Type != "" { |
| 582 | if err := ipam.ExecStatus(conf.IPAM.Type, args.StdinData); err != nil { |
| 583 | return err |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | // TODO: Check if master interface exists. |
| 588 | |
| 589 | return nil |
| 590 | } |