cni.go 4.5 KB

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