-
Notifications
You must be signed in to change notification settings - Fork 103
Add flex CIDR allocator controller #535
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
253 changes: 253 additions & 0 deletions
253
pkg/cloudprovider/providers/oci/flex_cidr_controller.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,253 @@ | ||
| // Copyright 2026 Oracle and/or its affiliates. All rights reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package oci | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/oracle/oci-cloud-controller-manager/pkg/flexcidr" | ||
| "github.com/oracle/oci-cloud-controller-manager/pkg/oci/client" | ||
| "github.com/oracle/oci-go-sdk/v65/core" | ||
| "github.com/pkg/errors" | ||
| "go.uber.org/zap" | ||
| v1 "k8s.io/api/core/v1" | ||
| "k8s.io/apimachinery/pkg/types" | ||
| utilruntime "k8s.io/apimachinery/pkg/util/runtime" | ||
| "k8s.io/apimachinery/pkg/util/wait" | ||
| coreinformers "k8s.io/client-go/informers/core/v1" | ||
| clientset "k8s.io/client-go/kubernetes" | ||
| "k8s.io/client-go/tools/cache" | ||
| "k8s.io/client-go/util/workqueue" | ||
| ) | ||
|
|
||
| const flexCIDRRetryDelay = time.Minute | ||
|
|
||
| type FlexCIDRController struct { | ||
| nodeInformer coreinformers.NodeInformer | ||
| serviceInformer coreinformers.ServiceInformer | ||
| kubeClient clientset.Interface | ||
| cloud *CloudProvider | ||
| queue workqueue.RateLimitingInterface | ||
| logger *zap.SugaredLogger | ||
| ociClient client.Interface | ||
| expectedPodCIDRsMu sync.RWMutex | ||
| expectedPodCIDRsByNode map[string][]string | ||
| } | ||
|
|
||
| func NewFlexCIDRController( | ||
| nodeInformer coreinformers.NodeInformer, | ||
| serviceInformer coreinformers.ServiceInformer, | ||
| kubeClient clientset.Interface, | ||
| cloud *CloudProvider, | ||
| logger *zap.SugaredLogger, | ||
| ociClient client.Interface) *FlexCIDRController { | ||
|
|
||
| controller := &FlexCIDRController{ | ||
| nodeInformer: nodeInformer, | ||
| serviceInformer: serviceInformer, | ||
| kubeClient: kubeClient, | ||
| cloud: cloud, | ||
| queue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), | ||
| logger: logger, | ||
| ociClient: ociClient, | ||
| expectedPodCIDRsByNode: make(map[string][]string), | ||
| } | ||
|
|
||
| controller.nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ | ||
| AddFunc: func(obj interface{}) { | ||
| node := obj.(*v1.Node) | ||
| controller.queue.Add(node.Name) | ||
| }, | ||
| UpdateFunc: func(_, newObj interface{}) { | ||
| node := newObj.(*v1.Node) | ||
| controller.queue.Add(node.Name) | ||
| }, | ||
| DeleteFunc: func(obj interface{}) { | ||
| key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) | ||
| if err != nil { | ||
| controller.logger.With(zap.Error(err)).Debug("failed to determine deleted node cache key") | ||
| return | ||
| } | ||
| controller.deleteExpectedPodCIDRs(key) | ||
| }, | ||
| }) | ||
|
|
||
| return controller | ||
| } | ||
|
|
||
| func (fcc *FlexCIDRController) Run(stopCh <-chan struct{}) { | ||
| defer utilruntime.HandleCrash() | ||
| defer fcc.queue.ShutDown() | ||
|
|
||
| fcc.logger.Info("Starting flex CIDR controller") | ||
|
|
||
| if !cache.WaitForCacheSync(stopCh, fcc.nodeInformer.Informer().HasSynced, fcc.serviceInformer.Informer().HasSynced) { | ||
| utilruntime.HandleError(fmt.Errorf("timed out waiting for flex CIDR controller caches to sync")) | ||
| return | ||
| } | ||
|
|
||
| wait.Until(fcc.runWorker, time.Second, stopCh) | ||
| } | ||
|
|
||
| func (fcc *FlexCIDRController) runWorker() { | ||
| for fcc.processNextItem() { | ||
| } | ||
| } | ||
|
|
||
| func (fcc *FlexCIDRController) processNextItem() bool { | ||
| key, quit := fcc.queue.Get() | ||
| if quit { | ||
| return false | ||
| } | ||
| defer fcc.queue.Done(key) | ||
|
|
||
| if err := fcc.processItem(key.(string)); err != nil { | ||
| fcc.logger.Errorf("Error processing flex CIDR for node %s (will retry): %v", key, err) | ||
| fcc.queue.AddRateLimited(key) | ||
| } else { | ||
| fcc.queue.Forget(key) | ||
| } | ||
|
|
||
| return true | ||
| } | ||
|
|
||
| func (fcc *FlexCIDRController) processItem(key string) error { | ||
| logger := fcc.logger.With("node", key) | ||
|
|
||
| node, err := fcc.nodeInformer.Lister().Get(key) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if len(node.Spec.PodCIDRs) > 0 && len(node.Spec.ProviderID) == 0 { | ||
| logger.Debug("node already has podCIDRs but providerID is empty, skipping") | ||
| return nil | ||
| } | ||
|
|
||
| if expectedPodCIDRs, ok := fcc.getExpectedPodCIDRs(node.Name); ok && flexcidr.StringSlicesEqualIgnoreOrder(node.Spec.PodCIDRs, expectedPodCIDRs) { | ||
| logger.Debugf("node already has cached expected podCIDRs %v", expectedPodCIDRs) | ||
| return nil | ||
| } | ||
|
|
||
| instance, instanceID, err := fcc.getInstanceByNode(node, logger) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if instance == nil { | ||
| return nil | ||
| } | ||
|
|
||
| if instance.LifecycleState != core.InstanceLifecycleStateRunning { | ||
| logger.Infof("instance %s not running yet, requeueing", instanceID) | ||
| fcc.queue.AddAfter(key, flexCIDRRetryDelay) | ||
| return nil | ||
| } | ||
|
|
||
| config, hasConfig := flexcidr.ParsePrimaryVnicConfig(instance) | ||
| if !hasConfig { | ||
| logger.Debug("instance metadata does not include flex CIDR configuration, skipping") | ||
| return nil | ||
| } | ||
|
|
||
| clusterIPFamily, err := flexcidr.GetClusterIpFamily(context.Background(), fcc.serviceInformer.Lister()) | ||
| if err != nil { | ||
| logger.With(zap.Error(err)).Info("cluster IP family not ready yet, requeueing") | ||
| fcc.queue.AddAfter(key, flexCIDRRetryDelay) | ||
| return nil | ||
| } | ||
|
|
||
| primaryVNIC, err := fcc.ociClient.Compute().GetPrimaryVNICForInstance(context.Background(), *instance.CompartmentId, instanceID) | ||
| if err != nil { | ||
| return errors.Wrap(err, "GetPrimaryVNICForInstance") | ||
| } | ||
|
|
||
| flexCIDRManager := &flexcidr.FlexCIDR{ | ||
| Logger: logger, | ||
| PrimaryVnicConfig: config, | ||
| ClusterIpFamily: clusterIPFamily, | ||
| OciCoreClient: fcc.ociClient.Networking(nil), | ||
| } | ||
|
|
||
| flexCIDRs, err := flexCIDRManager.GetOrCreateFlexCidrList(*primaryVNIC.Id) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if !flexCIDRManager.ValidateFlexCidrList(flexCIDRs) { | ||
| return fmt.Errorf("computed flex CIDRs %v are invalid", flexCIDRs) | ||
| } | ||
| fcc.setExpectedPodCIDRs(node.Name, flexCIDRs) | ||
| if flexcidr.StringSlicesEqualIgnoreOrder(node.Spec.PodCIDRs, flexCIDRs) { | ||
| logger.Debugf("node already has expected podCIDRs %v", flexCIDRs) | ||
| return nil | ||
| } | ||
|
|
||
| return flexcidr.PatchNodePodCIDRs(context.Background(), fcc.kubeClient, node.Name, flexCIDRs, logger) | ||
| } | ||
|
|
||
| func (fcc *FlexCIDRController) getExpectedPodCIDRs(nodeName string) ([]string, bool) { | ||
| fcc.expectedPodCIDRsMu.RLock() | ||
| defer fcc.expectedPodCIDRsMu.RUnlock() | ||
|
|
||
| podCIDRs, ok := fcc.expectedPodCIDRsByNode[nodeName] | ||
| if !ok { | ||
| return nil, false | ||
| } | ||
| return append([]string(nil), podCIDRs...), true | ||
| } | ||
|
|
||
| func (fcc *FlexCIDRController) setExpectedPodCIDRs(nodeName string, podCIDRs []string) { | ||
| fcc.expectedPodCIDRsMu.Lock() | ||
| defer fcc.expectedPodCIDRsMu.Unlock() | ||
|
|
||
| fcc.expectedPodCIDRsByNode[nodeName] = append([]string(nil), podCIDRs...) | ||
| } | ||
|
|
||
| func (fcc *FlexCIDRController) deleteExpectedPodCIDRs(nodeName string) { | ||
| fcc.expectedPodCIDRsMu.Lock() | ||
| defer fcc.expectedPodCIDRsMu.Unlock() | ||
|
|
||
| delete(fcc.expectedPodCIDRsByNode, nodeName) | ||
| } | ||
|
|
||
| func (fcc *FlexCIDRController) getInstanceByNode(node *v1.Node, logger *zap.SugaredLogger) (*core.Instance, string, error) { | ||
| ctx, cancel := context.WithTimeout(context.Background(), timeout) | ||
| defer cancel() | ||
|
|
||
| providerID := node.Spec.ProviderID | ||
| var err error | ||
| if providerID == "" { | ||
| providerID, err = fcc.cloud.InstanceID(ctx, types.NodeName(node.Name)) | ||
| if err != nil { | ||
| return nil, "", err | ||
| } | ||
| } | ||
|
|
||
| instanceID, err := MapProviderIDToResourceID(providerID) | ||
| if err != nil { | ||
| logger.With(zap.Error(err)).Error("failed to map providerID to instanceID") | ||
| return nil, "", err | ||
| } | ||
|
|
||
| instance, err := fcc.ociClient.Compute().GetInstance(ctx, instanceID) | ||
| if err != nil { | ||
| logger.With(zap.Error(err)).Error("failed to fetch instance") | ||
| return nil, "", err | ||
| } | ||
|
|
||
| return instance, instanceID, nil | ||
| } | ||
66 changes: 66 additions & 0 deletions
66
pkg/cloudprovider/providers/oci/flex_cidr_controller_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| // Copyright 2026 Oracle and/or its affiliates. All rights reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package oci | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "go.uber.org/zap" | ||
| corev1 "k8s.io/api/core/v1" | ||
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
| "k8s.io/client-go/informers" | ||
| "k8s.io/client-go/kubernetes/fake" | ||
| ) | ||
|
|
||
| func TestProcessItemSkipsOCILookupsWhenNodeAlreadyHasCachedExpectedPodCIDRs(t *testing.T) { | ||
| kubeClient := fake.NewSimpleClientset() | ||
| factory := informers.NewSharedInformerFactory(kubeClient, 0) | ||
| nodeInformer := factory.Core().V1().Nodes() | ||
|
|
||
| node := &corev1.Node{ | ||
| ObjectMeta: metav1.ObjectMeta{Name: "worker-node-3"}, | ||
| Spec: corev1.NodeSpec{ | ||
| ProviderID: "oci://instance", | ||
| PodCIDRs: []string{"10.0.0.0/24", "2001:db8::/80"}, | ||
| }, | ||
| } | ||
| if err := nodeInformer.Informer().GetStore().Add(node); err != nil { | ||
| t.Fatalf("adding node to informer store: %v", err) | ||
| } | ||
|
|
||
| controller := &FlexCIDRController{ | ||
| nodeInformer: nodeInformer, | ||
| logger: zap.NewNop().Sugar(), | ||
| expectedPodCIDRsByNode: make(map[string][]string), | ||
| } | ||
| controller.setExpectedPodCIDRs(node.Name, []string{"10.0.0.0/24", "2001:db8::/80"}) | ||
|
|
||
| if err := controller.processItem(node.Name); err != nil { | ||
| t.Fatalf("processItem() error = %v, want nil", err) | ||
| } | ||
| } | ||
|
|
||
| func TestDeleteExpectedPodCIDRsRemovesCachedValue(t *testing.T) { | ||
| controller := &FlexCIDRController{ | ||
| expectedPodCIDRsByNode: make(map[string][]string), | ||
| } | ||
|
|
||
| controller.setExpectedPodCIDRs("worker-node-3", []string{"10.0.0.0/24"}) | ||
| controller.deleteExpectedPodCIDRs("worker-node-3") | ||
|
|
||
| if _, ok := controller.getExpectedPodCIDRs("worker-node-3"); ok { | ||
| t.Fatal("expected cached podCIDRs to be removed") | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this skip condition is currently inverted from what is is intended to be. The log message sounds like an
ORbut the test condition is anAND, meaning that we'll most likely never enter this block.Also, there is currently no early exit for the "already has the expected PodCIDRs" case. This means that every node update event will trigger
GetInstance,GetPrimaryVNICandListPrivateIpsAPI calls. There's already such an early exit pattern in the node info controller here:oci-cloud-controller-manager/pkg/cloudprovider/providers/oci/node_info_controller.go
Line 164 in 3d019ab
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
len(node.Spec.PodCIDRs) > 0=> node already has podCIDRs&&=> butlen(node.Spec.ProviderID) == 0=> providerID is emptythe if block looks good to me.
I agree an early exit for already processed node is desirable.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good point, you're right, the if block is good 👍
On the early exit, the new
expectedPodCIDRsCacheworks, but I think it can be improved even further:map[string][]stringguarded by a mutex (or sync.Map), populated on successful reconcile and cleared from the existing DeleteFunc, would give zero API traffic in steady state without the TTL churn. The node informer's DeleteFunc is already wired up, so there's no leak risk.if fcc.expectedPodCIDRsCache == nilguards insetExpectedPodCIDRs/deleteExpectedPodCIDRsare unreachable,NewFlexCIDRControlleralways constructs the store.expectedPodCIDRsEntrystruct +expectedPodCIDRsCacheKeyFnexist only to satisfycache.Store's interface, they disappear if you switch to a plain map.Anyway, none of that is blocking, just minor suggestions ;)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Made the changes now and also made the controller optional and can be enabled via envvars