cni.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // Copyright 2019 the Kilo 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. // +build linux
  15. package mesh
  16. import (
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "io/ioutil"
  21. "net"
  22. "github.com/containernetworking/cni/libcni"
  23. "github.com/containernetworking/cni/pkg/types"
  24. ipamallocator "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
  25. "github.com/go-kit/kit/log/level"
  26. "github.com/vishvananda/netlink"
  27. )
  28. const cniDeviceName = "kube-bridge"
  29. // Try to get the CNI device index.
  30. // Return 0 if not found and any error encountered.
  31. func cniDeviceIndex() (int, error) {
  32. i, err := netlink.LinkByName(cniDeviceName)
  33. if _, ok := err.(netlink.LinkNotFoundError); ok {
  34. return 0, nil
  35. }
  36. if err != nil {
  37. return 0, err
  38. }
  39. return i.Attrs().Index, nil
  40. }
  41. // updateCNIConfig will try to update the local node's CNI config.
  42. func (m *Mesh) updateCNIConfig() {
  43. m.mu.Lock()
  44. n := m.nodes[m.hostname]
  45. m.mu.Unlock()
  46. if n == nil || n.Subnet == nil {
  47. level.Debug(m.logger).Log("msg", "local node does not have a valid subnet assigned")
  48. return
  49. }
  50. cidr, err := getCIDRFromCNI(m.cniPath)
  51. if err != nil {
  52. level.Warn(m.logger).Log("msg", "failed to get CIDR from CNI file; overwriting it", "err", err.Error())
  53. }
  54. if ipNetsEqual(cidr, n.Subnet) {
  55. return
  56. }
  57. if cidr == nil {
  58. level.Info(m.logger).Log("msg", "CIDR in CNI file is empty")
  59. } else {
  60. level.Info(m.logger).Log("msg", "CIDR in CNI file is not empty; overwriting", "old", cidr.String(), "new", n.Subnet.String())
  61. }
  62. level.Info(m.logger).Log("msg", "setting CIDR in CNI file", "CIDR", n.Subnet.String())
  63. if err := setCIDRInCNI(m.cniPath, n.Subnet); err != nil {
  64. level.Warn(m.logger).Log("msg", "failed to set CIDR in CNI file", "err", err.Error())
  65. }
  66. }
  67. // getCIDRFromCNI finds the CIDR for the node from the CNI configuration file.
  68. func getCIDRFromCNI(path string) (*net.IPNet, error) {
  69. var cidr net.IPNet
  70. var ic *ipamallocator.IPAMConfig
  71. cl, err := libcni.ConfListFromFile(path)
  72. if err != nil {
  73. return nil, fmt.Errorf("failed to read CNI config list file: %v", err)
  74. }
  75. for _, conf := range cl.Plugins {
  76. if conf.Network.IPAM.Type != "" {
  77. ic, _, err = ipamallocator.LoadIPAMConfig(conf.Bytes, "")
  78. if err != nil {
  79. return nil, fmt.Errorf("failed to read IPAM config from CNI config list file: %v", err)
  80. }
  81. for _, set := range ic.Ranges {
  82. for _, r := range set {
  83. cidr = net.IPNet(r.Subnet)
  84. if (&cidr).String() == "" {
  85. continue
  86. }
  87. // Return the first subnet we find.
  88. return &cidr, nil
  89. }
  90. }
  91. }
  92. }
  93. return nil, nil
  94. }
  95. // setCIDRInCNI sets the CIDR allocated to the node in the CNI configuration file.
  96. func setCIDRInCNI(path string, cidr *net.IPNet) error {
  97. f, err := ioutil.ReadFile(path)
  98. if err != nil {
  99. return fmt.Errorf("failed to read CNI config list file: %v", err)
  100. }
  101. raw := make(map[string]interface{})
  102. if err := json.Unmarshal(f, &raw); err != nil {
  103. return fmt.Errorf("failed to parse CNI config file: %v", err)
  104. }
  105. if _, ok := raw["plugins"]; !ok {
  106. return errors.New("failed to find plugins in CNI config file")
  107. }
  108. plugins, ok := raw["plugins"].([]interface{})
  109. if !ok {
  110. return errors.New("failed to parse plugins in CNI config file")
  111. }
  112. var found bool
  113. for i := range plugins {
  114. p, ok := plugins[i].(map[string]interface{})
  115. if !ok {
  116. return fmt.Errorf("failed to parse plugin %d in CNI config file", i)
  117. }
  118. if _, ok := p["ipam"]; !ok {
  119. continue
  120. }
  121. ipam, ok := p["ipam"].(map[string]interface{})
  122. if !ok {
  123. return errors.New("failed to parse IPAM configuration in CNI config file")
  124. }
  125. ipam["ranges"] = []ipamallocator.RangeSet{
  126. {
  127. {
  128. Subnet: types.IPNet(*cidr),
  129. },
  130. },
  131. }
  132. found = true
  133. }
  134. if !found {
  135. return errors.New("failed to set subnet CIDR in CNI config file; file appears invalid")
  136. }
  137. buf, err := json.Marshal(raw)
  138. if err != nil {
  139. return fmt.Errorf("failed to marshal CNI config: %v", err)
  140. }
  141. if err := ioutil.WriteFile(path, buf, 0644); err != nil {
  142. return fmt.Errorf("failed to write CNI config file to disk: %v", err)
  143. }
  144. return nil
  145. }