range_allocator.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package ipam
  14. import (
  15. "fmt"
  16. "net"
  17. "sync"
  18. "k8s.io/api/core/v1"
  19. "k8s.io/klog"
  20. apierrors "k8s.io/apimachinery/pkg/api/errors"
  21. "k8s.io/apimachinery/pkg/types"
  22. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  23. "k8s.io/apimachinery/pkg/util/sets"
  24. informers "k8s.io/client-go/informers/core/v1"
  25. clientset "k8s.io/client-go/kubernetes"
  26. "k8s.io/client-go/kubernetes/scheme"
  27. v1core "k8s.io/client-go/kubernetes/typed/core/v1"
  28. corelisters "k8s.io/client-go/listers/core/v1"
  29. "k8s.io/client-go/tools/cache"
  30. "k8s.io/client-go/tools/record"
  31. "k8s.io/kubernetes/pkg/controller/nodeipam/ipam/cidrset"
  32. nodeutil "k8s.io/kubernetes/pkg/controller/util/node"
  33. utilnode "k8s.io/kubernetes/pkg/util/node"
  34. )
  35. // cidrs are reserved, then node resource is patched with them
  36. // this type holds the reservation info for a node
  37. type nodeReservedCIDRs struct {
  38. allocatedCIDRs []*net.IPNet
  39. nodeName string
  40. }
  41. type rangeAllocator struct {
  42. client clientset.Interface
  43. // cluster cidrs as passed in during controller creation
  44. clusterCIDRs []*net.IPNet
  45. // for each entry in clusterCIDRs we maintain a list of what is used and what is not
  46. cidrSets []*cidrset.CidrSet
  47. // nodeLister is able to list/get nodes and is populated by the shared informer passed to controller
  48. nodeLister corelisters.NodeLister
  49. // nodesSynced returns true if the node shared informer has been synced at least once.
  50. nodesSynced cache.InformerSynced
  51. // Channel that is used to pass updating Nodes and their reserved CIDRs to the background
  52. // This increases a throughput of CIDR assignment by not blocking on long operations.
  53. nodeCIDRUpdateChannel chan nodeReservedCIDRs
  54. recorder record.EventRecorder
  55. // Keep a set of nodes that are currently being processed to avoid races in CIDR allocation
  56. lock sync.Mutex
  57. nodesInProcessing sets.String
  58. }
  59. // NewCIDRRangeAllocator returns a CIDRAllocator to allocate CIDRs for node (one from each of clusterCIDRs)
  60. // Caller must ensure subNetMaskSize is not less than cluster CIDR mask size.
  61. // Caller must always pass in a list of existing nodes so the new allocator.
  62. // Caller must ensure that ClusterCIDRs are semantically correct e.g (1 for non DualStack, 2 for DualStack etc..)
  63. // can initialize its CIDR map. NodeList is only nil in testing.
  64. func NewCIDRRangeAllocator(client clientset.Interface, nodeInformer informers.NodeInformer, allocatorParams CIDRAllocatorParams, nodeList *v1.NodeList) (CIDRAllocator, error) {
  65. if client == nil {
  66. klog.Fatalf("kubeClient is nil when starting NodeController")
  67. }
  68. eventBroadcaster := record.NewBroadcaster()
  69. recorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "cidrAllocator"})
  70. eventBroadcaster.StartLogging(klog.Infof)
  71. klog.V(0).Infof("Sending events to api server.")
  72. eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: client.CoreV1().Events("")})
  73. // create a cidrSet for each cidr we operate on
  74. // cidrSet are mapped to clusterCIDR by index
  75. cidrSets := make([]*cidrset.CidrSet, len(allocatorParams.ClusterCIDRs))
  76. for idx, cidr := range allocatorParams.ClusterCIDRs {
  77. cidrSet, err := cidrset.NewCIDRSet(cidr, allocatorParams.NodeCIDRMaskSizes[idx])
  78. if err != nil {
  79. return nil, err
  80. }
  81. cidrSets[idx] = cidrSet
  82. }
  83. ra := &rangeAllocator{
  84. client: client,
  85. clusterCIDRs: allocatorParams.ClusterCIDRs,
  86. cidrSets: cidrSets,
  87. nodeLister: nodeInformer.Lister(),
  88. nodesSynced: nodeInformer.Informer().HasSynced,
  89. nodeCIDRUpdateChannel: make(chan nodeReservedCIDRs, cidrUpdateQueueSize),
  90. recorder: recorder,
  91. nodesInProcessing: sets.NewString(),
  92. }
  93. if allocatorParams.ServiceCIDR != nil {
  94. ra.filterOutServiceRange(allocatorParams.ServiceCIDR)
  95. } else {
  96. klog.V(0).Info("No Service CIDR provided. Skipping filtering out service addresses.")
  97. }
  98. if allocatorParams.SecondaryServiceCIDR != nil {
  99. ra.filterOutServiceRange(allocatorParams.SecondaryServiceCIDR)
  100. } else {
  101. klog.V(0).Info("No Secondary Service CIDR provided. Skipping filtering out secondary service addresses.")
  102. }
  103. if nodeList != nil {
  104. for _, node := range nodeList.Items {
  105. if len(node.Spec.PodCIDRs) == 0 {
  106. klog.V(4).Infof("Node %v has no CIDR, ignoring", node.Name)
  107. continue
  108. }
  109. klog.V(4).Infof("Node %v has CIDR %s, occupying it in CIDR map", node.Name, node.Spec.PodCIDR)
  110. if err := ra.occupyCIDRs(&node); err != nil {
  111. // This will happen if:
  112. // 1. We find garbage in the podCIDRs field. Retrying is useless.
  113. // 2. CIDR out of range: This means a node CIDR has changed.
  114. // This error will keep crashing controller-manager.
  115. return nil, err
  116. }
  117. }
  118. }
  119. nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
  120. AddFunc: nodeutil.CreateAddNodeHandler(ra.AllocateOrOccupyCIDR),
  121. UpdateFunc: nodeutil.CreateUpdateNodeHandler(func(_, newNode *v1.Node) error {
  122. // If the PodCIDRs list is not empty we either:
  123. // - already processed a Node that already had CIDRs after NC restarted
  124. // (cidr is marked as used),
  125. // - already processed a Node successfully and allocated CIDRs for it
  126. // (cidr is marked as used),
  127. // - already processed a Node but we did saw a "timeout" response and
  128. // request eventually got through in this case we haven't released
  129. // the allocated CIDRs (cidr is still marked as used).
  130. // There's a possible error here:
  131. // - NC sees a new Node and assigns CIDRs X,Y.. to it,
  132. // - Update Node call fails with a timeout,
  133. // - Node is updated by some other component, NC sees an update and
  134. // assigns CIDRs A,B.. to the Node,
  135. // - Both CIDR X,Y.. and CIDR A,B.. are marked as used in the local cache,
  136. // even though Node sees only CIDR A,B..
  137. // The problem here is that in in-memory cache we see CIDR X,Y.. as marked,
  138. // which prevents it from being assigned to any new node. The cluster
  139. // state is correct.
  140. // Restart of NC fixes the issue.
  141. if len(newNode.Spec.PodCIDRs) == 0 {
  142. return ra.AllocateOrOccupyCIDR(newNode)
  143. }
  144. return nil
  145. }),
  146. DeleteFunc: nodeutil.CreateDeleteNodeHandler(ra.ReleaseCIDR),
  147. })
  148. return ra, nil
  149. }
  150. func (r *rangeAllocator) Run(stopCh <-chan struct{}) {
  151. defer utilruntime.HandleCrash()
  152. klog.Infof("Starting range CIDR allocator")
  153. defer klog.Infof("Shutting down range CIDR allocator")
  154. if !cache.WaitForNamedCacheSync("cidrallocator", stopCh, r.nodesSynced) {
  155. return
  156. }
  157. for i := 0; i < cidrUpdateWorkers; i++ {
  158. go r.worker(stopCh)
  159. }
  160. <-stopCh
  161. }
  162. func (r *rangeAllocator) worker(stopChan <-chan struct{}) {
  163. for {
  164. select {
  165. case workItem, ok := <-r.nodeCIDRUpdateChannel:
  166. if !ok {
  167. klog.Warning("Channel nodeCIDRUpdateChannel was unexpectedly closed")
  168. return
  169. }
  170. if err := r.updateCIDRsAllocation(workItem); err != nil {
  171. // Requeue the failed node for update again.
  172. r.nodeCIDRUpdateChannel <- workItem
  173. }
  174. case <-stopChan:
  175. return
  176. }
  177. }
  178. }
  179. func (r *rangeAllocator) insertNodeToProcessing(nodeName string) bool {
  180. r.lock.Lock()
  181. defer r.lock.Unlock()
  182. if r.nodesInProcessing.Has(nodeName) {
  183. return false
  184. }
  185. r.nodesInProcessing.Insert(nodeName)
  186. return true
  187. }
  188. func (r *rangeAllocator) removeNodeFromProcessing(nodeName string) {
  189. r.lock.Lock()
  190. defer r.lock.Unlock()
  191. r.nodesInProcessing.Delete(nodeName)
  192. }
  193. // marks node.PodCIDRs[...] as used in allocator's tracked cidrSet
  194. func (r *rangeAllocator) occupyCIDRs(node *v1.Node) error {
  195. defer r.removeNodeFromProcessing(node.Name)
  196. if len(node.Spec.PodCIDRs) == 0 {
  197. return nil
  198. }
  199. for idx, cidr := range node.Spec.PodCIDRs {
  200. _, podCIDR, err := net.ParseCIDR(cidr)
  201. if err != nil {
  202. return fmt.Errorf("failed to parse node %s, CIDR %s", node.Name, node.Spec.PodCIDR)
  203. }
  204. // If node has a pre allocate cidr that does not exist in our cidrs.
  205. // This will happen if cluster went from dualstack(multi cidrs) to non-dualstack
  206. // then we have now way of locking it
  207. if idx >= len(r.cidrSets) {
  208. return fmt.Errorf("node:%s has an allocated cidr: %v at index:%v that does not exist in cluster cidrs configuration", node.Name, cidr, idx)
  209. }
  210. if err := r.cidrSets[idx].Occupy(podCIDR); err != nil {
  211. return fmt.Errorf("failed to mark cidr[%v] at idx [%v] as occupied for node: %v: %v", podCIDR, idx, node.Name, err)
  212. }
  213. }
  214. return nil
  215. }
  216. // WARNING: If you're adding any return calls or defer any more work from this
  217. // function you have to make sure to update nodesInProcessing properly with the
  218. // disposition of the node when the work is done.
  219. func (r *rangeAllocator) AllocateOrOccupyCIDR(node *v1.Node) error {
  220. if node == nil {
  221. return nil
  222. }
  223. if !r.insertNodeToProcessing(node.Name) {
  224. klog.V(2).Infof("Node %v is already in a process of CIDR assignment.", node.Name)
  225. return nil
  226. }
  227. if len(node.Spec.PodCIDRs) > 0 {
  228. return r.occupyCIDRs(node)
  229. }
  230. // allocate and queue the assignment
  231. allocated := nodeReservedCIDRs{
  232. nodeName: node.Name,
  233. allocatedCIDRs: make([]*net.IPNet, len(r.cidrSets)),
  234. }
  235. for idx := range r.cidrSets {
  236. podCIDR, err := r.cidrSets[idx].AllocateNext()
  237. if err != nil {
  238. r.removeNodeFromProcessing(node.Name)
  239. nodeutil.RecordNodeStatusChange(r.recorder, node, "CIDRNotAvailable")
  240. return fmt.Errorf("failed to allocate cidr from cluster cidr at idx:%v: %v", idx, err)
  241. }
  242. allocated.allocatedCIDRs[idx] = podCIDR
  243. }
  244. //queue the assignement
  245. klog.V(4).Infof("Putting node %s with CIDR %v into the work queue", node.Name, allocated.allocatedCIDRs)
  246. r.nodeCIDRUpdateChannel <- allocated
  247. return nil
  248. }
  249. // ReleaseCIDR marks node.podCIDRs[...] as unused in our tracked cidrSets
  250. func (r *rangeAllocator) ReleaseCIDR(node *v1.Node) error {
  251. if node == nil || len(node.Spec.PodCIDRs) == 0 {
  252. return nil
  253. }
  254. for idx, cidr := range node.Spec.PodCIDRs {
  255. _, podCIDR, err := net.ParseCIDR(cidr)
  256. if err != nil {
  257. return fmt.Errorf("failed to parse CIDR %s on Node %v: %v", cidr, node.Name, err)
  258. }
  259. // If node has a pre allocate cidr that does not exist in our cidrs.
  260. // This will happen if cluster went from dualstack(multi cidrs) to non-dualstack
  261. // then we have now way of locking it
  262. if idx >= len(r.cidrSets) {
  263. return fmt.Errorf("node:%s has an allocated cidr: %v at index:%v that does not exist in cluster cidrs configuration", node.Name, cidr, idx)
  264. }
  265. klog.V(4).Infof("release CIDR %s for node:%v", cidr, node.Name)
  266. if err = r.cidrSets[idx].Release(podCIDR); err != nil {
  267. return fmt.Errorf("error when releasing CIDR %v: %v", cidr, err)
  268. }
  269. }
  270. return nil
  271. }
  272. // Marks all CIDRs with subNetMaskSize that belongs to serviceCIDR as used across all cidrs
  273. // so that they won't be assignable.
  274. func (r *rangeAllocator) filterOutServiceRange(serviceCIDR *net.IPNet) {
  275. // Checks if service CIDR has a nonempty intersection with cluster
  276. // CIDR. It is the case if either clusterCIDR contains serviceCIDR with
  277. // clusterCIDR's Mask applied (this means that clusterCIDR contains
  278. // serviceCIDR) or vice versa (which means that serviceCIDR contains
  279. // clusterCIDR).
  280. for idx, cidr := range r.clusterCIDRs {
  281. // if they don't overlap then ignore the filtering
  282. if !cidr.Contains(serviceCIDR.IP.Mask(cidr.Mask)) && !serviceCIDR.Contains(cidr.IP.Mask(serviceCIDR.Mask)) {
  283. continue
  284. }
  285. // at this point, len(cidrSet) == len(clusterCidr)
  286. if err := r.cidrSets[idx].Occupy(serviceCIDR); err != nil {
  287. klog.Errorf("Error filtering out service cidr out cluster cidr:%v (index:%v) %v: %v", cidr, idx, serviceCIDR, err)
  288. }
  289. }
  290. }
  291. // updateCIDRsAllocation assigns CIDR to Node and sends an update to the API server.
  292. func (r *rangeAllocator) updateCIDRsAllocation(data nodeReservedCIDRs) error {
  293. var err error
  294. var node *v1.Node
  295. defer r.removeNodeFromProcessing(data.nodeName)
  296. cidrsString := cidrsAsString(data.allocatedCIDRs)
  297. node, err = r.nodeLister.Get(data.nodeName)
  298. if err != nil {
  299. klog.Errorf("Failed while getting node %v for updating Node.Spec.PodCIDRs: %v", data.nodeName, err)
  300. return err
  301. }
  302. // if cidr list matches the proposed.
  303. // then we possibly updated this node
  304. // and just failed to ack the success.
  305. if len(node.Spec.PodCIDRs) == len(data.allocatedCIDRs) {
  306. match := true
  307. for idx, cidr := range cidrsString {
  308. if node.Spec.PodCIDRs[idx] != cidr {
  309. match = false
  310. break
  311. }
  312. }
  313. if match {
  314. klog.V(4).Infof("Node %v already has allocated CIDR %v. It matches the proposed one.", node.Name, data.allocatedCIDRs)
  315. return nil
  316. }
  317. }
  318. // node has cidrs, release the reserved
  319. if len(node.Spec.PodCIDRs) != 0 {
  320. klog.Errorf("Node %v already has a CIDR allocated %v. Releasing the new one.", node.Name, node.Spec.PodCIDRs)
  321. for idx, cidr := range data.allocatedCIDRs {
  322. if releaseErr := r.cidrSets[idx].Release(cidr); releaseErr != nil {
  323. klog.Errorf("Error when releasing CIDR idx:%v value: %v err:%v", idx, cidr, releaseErr)
  324. }
  325. }
  326. return nil
  327. }
  328. // If we reached here, it means that the node has no CIDR currently assigned. So we set it.
  329. for i := 0; i < cidrUpdateRetries; i++ {
  330. if err = utilnode.PatchNodeCIDRs(r.client, types.NodeName(node.Name), cidrsString); err == nil {
  331. klog.Infof("Set node %v PodCIDR to %v", node.Name, cidrsString)
  332. return nil
  333. }
  334. }
  335. // failed release back to the pool
  336. klog.Errorf("Failed to update node %v PodCIDR to %v after multiple attempts: %v", node.Name, cidrsString, err)
  337. nodeutil.RecordNodeStatusChange(r.recorder, node, "CIDRAssignmentFailed")
  338. // We accept the fact that we may leak CIDRs here. This is safer than releasing
  339. // them in case when we don't know if request went through.
  340. // NodeController restart will return all falsely allocated CIDRs to the pool.
  341. if !apierrors.IsServerTimeout(err) {
  342. klog.Errorf("CIDR assignment for node %v failed: %v. Releasing allocated CIDR", node.Name, err)
  343. for idx, cidr := range data.allocatedCIDRs {
  344. if releaseErr := r.cidrSets[idx].Release(cidr); releaseErr != nil {
  345. klog.Errorf("Error releasing allocated CIDR for node %v: %v", node.Name, releaseErr)
  346. }
  347. }
  348. }
  349. return err
  350. }
  351. // converts a slice of cidrs into <c-1>,<c-2>,<c-n>
  352. func cidrsAsString(inCIDRs []*net.IPNet) []string {
  353. outCIDRs := make([]string, len(inCIDRs))
  354. for idx, inCIDR := range inCIDRs {
  355. outCIDRs[idx] = inCIDR.String()
  356. }
  357. return outCIDRs
  358. }