cni.go 4.5 KB

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