ipam.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. package ipam
  15. import (
  16. "fmt"
  17. "os"
  18. "github.com/containernetworking/cni/pkg/invoke"
  19. "github.com/containernetworking/cni/pkg/ip"
  20. "github.com/containernetworking/cni/pkg/types"
  21. "github.com/vishvananda/netlink"
  22. )
  23. func ExecAdd(plugin string, netconf []byte) (*types.Result, error) {
  24. return invoke.DelegateAdd(plugin, netconf)
  25. }
  26. func ExecDel(plugin string, netconf []byte) error {
  27. return invoke.DelegateDel(plugin, netconf)
  28. }
  29. // ConfigureIface takes the result of IPAM plugin and
  30. // applies to the ifName interface
  31. func ConfigureIface(ifName string, res *types.Result) error {
  32. link, err := netlink.LinkByName(ifName)
  33. if err != nil {
  34. return fmt.Errorf("failed to lookup %q: %v", ifName, err)
  35. }
  36. if err := netlink.LinkSetUp(link); err != nil {
  37. return fmt.Errorf("failed to set %q UP: %v", ifName, err)
  38. }
  39. // TODO(eyakubovich): IPv6
  40. addr := &netlink.Addr{IPNet: &res.IP4.IP, Label: ""}
  41. if err = netlink.AddrAdd(link, addr); err != nil {
  42. return fmt.Errorf("failed to add IP addr to %q: %v", ifName, err)
  43. }
  44. for _, r := range res.IP4.Routes {
  45. gw := r.GW
  46. if gw == nil {
  47. gw = res.IP4.Gateway
  48. }
  49. if err = ip.AddRoute(&r.Dst, gw, link); err != nil {
  50. // we skip over duplicate routes as we assume the first one wins
  51. if !os.IsExist(err) {
  52. return fmt.Errorf("failed to add route '%v via %v dev %v': %v", r.Dst, gw, ifName, err)
  53. }
  54. }
  55. }
  56. return nil
  57. }