|
| 1 | +/* |
| 2 | +Copyright 2023 The Karmada 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 | + |
| 14 | +package cronfederatedhpa |
| 15 | + |
| 16 | +import ( |
| 17 | + "context" |
| 18 | + |
| 19 | + corev1 "k8s.io/api/core/v1" |
| 20 | + "k8s.io/apimachinery/pkg/api/equality" |
| 21 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 22 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 23 | + "k8s.io/apimachinery/pkg/util/sets" |
| 24 | + "k8s.io/client-go/tools/record" |
| 25 | + "k8s.io/klog/v2" |
| 26 | + controllerruntime "sigs.k8s.io/controller-runtime" |
| 27 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 28 | + "sigs.k8s.io/controller-runtime/pkg/controller" |
| 29 | + |
| 30 | + autoscalingv1alpha1 "github.com/karmada-io/karmada/pkg/apis/autoscaling/v1alpha1" |
| 31 | + "github.com/karmada-io/karmada/pkg/sharedcli/ratelimiterflag" |
| 32 | + "github.com/karmada-io/karmada/pkg/util/helper" |
| 33 | +) |
| 34 | + |
| 35 | +const ( |
| 36 | + // ControllerName is the controller name that will be used when reporting events. |
| 37 | + ControllerName = "cronfederatedhpa-controller" |
| 38 | +) |
| 39 | + |
| 40 | +// CronFHPAController is used to operate CronFederatedHPA. |
| 41 | +type CronFHPAController struct { |
| 42 | + client.Client // used to operate Cron resources. |
| 43 | + EventRecorder record.EventRecorder |
| 44 | + |
| 45 | + RateLimiterOptions ratelimiterflag.Options |
| 46 | + CronHandler *CronHandler |
| 47 | +} |
| 48 | + |
| 49 | +// Reconcile performs a full reconciliation for the object referred to by the Request. |
| 50 | +// The Controller will requeue the Request to be processed again if an error is non-nil or |
| 51 | +// Result.Requeue is true, otherwise upon completion it will remove the work from the queue. |
| 52 | +func (c *CronFHPAController) Reconcile(ctx context.Context, req controllerruntime.Request) (controllerruntime.Result, error) { |
| 53 | + klog.V(4).Infof("Reconciling CronFederatedHPA %s", req.NamespacedName) |
| 54 | + |
| 55 | + cronFHPA := &autoscalingv1alpha1.CronFederatedHPA{} |
| 56 | + if err := c.Client.Get(ctx, req.NamespacedName, cronFHPA); err != nil { |
| 57 | + if apierrors.IsNotFound(err) { |
| 58 | + klog.V(4).Infof("Begin to cleanup the cron jobs for CronFederatedHPA:%s", req.NamespacedName) |
| 59 | + c.CronHandler.StopCronFHPAExecutor(req.NamespacedName.String()) |
| 60 | + return controllerruntime.Result{}, nil |
| 61 | + } |
| 62 | + |
| 63 | + klog.Errorf("Fail to get CronFederatedHPA(%s):%v", req.NamespacedName, err) |
| 64 | + return controllerruntime.Result{Requeue: true}, err |
| 65 | + } |
| 66 | + |
| 67 | + // If this CronFederatedHPA is deleting, stop all related cron executors |
| 68 | + if !cronFHPA.DeletionTimestamp.IsZero() { |
| 69 | + c.CronHandler.StopCronFHPAExecutor(req.NamespacedName.String()) |
| 70 | + return controllerruntime.Result{}, nil |
| 71 | + } |
| 72 | + |
| 73 | + origRuleSets := sets.New[string]() |
| 74 | + for _, history := range cronFHPA.Status.ExecutionHistories { |
| 75 | + origRuleSets.Insert(history.RuleName) |
| 76 | + } |
| 77 | + |
| 78 | + // If scale target is updated, stop all the rule executors, and next steps will create the new executors |
| 79 | + if c.CronHandler.CronFHPAScaleTargetRefUpdates(req.NamespacedName.String(), cronFHPA.Spec.ScaleTargetRef) { |
| 80 | + c.CronHandler.StopCronFHPAExecutor(req.NamespacedName.String()) |
| 81 | + } |
| 82 | + |
| 83 | + c.CronHandler.AddCronExecutorIfNotExist(req.NamespacedName.String()) |
| 84 | + |
| 85 | + newRuleSets := sets.New[string]() |
| 86 | + for _, rule := range cronFHPA.Spec.Rules { |
| 87 | + if err := c.processCronRule(cronFHPA, rule); err != nil { |
| 88 | + return controllerruntime.Result{Requeue: true}, err |
| 89 | + } |
| 90 | + newRuleSets.Insert(rule.Name) |
| 91 | + } |
| 92 | + |
| 93 | + // If rule is deleted, remove the rule executor from the handler |
| 94 | + for name := range origRuleSets { |
| 95 | + if newRuleSets.Has(name) { |
| 96 | + continue |
| 97 | + } |
| 98 | + c.CronHandler.StopRuleExecutor(req.NamespacedName.String(), name) |
| 99 | + if err := c.removeCronFHPAHistory(cronFHPA, name); err != nil { |
| 100 | + return controllerruntime.Result{Requeue: true}, err |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + return controllerruntime.Result{}, nil |
| 105 | +} |
| 106 | + |
| 107 | +// SetupWithManager creates a controller and register to controller manager. |
| 108 | +func (c *CronFHPAController) SetupWithManager(mgr controllerruntime.Manager) error { |
| 109 | + c.CronHandler = NewCronHandler(mgr.GetClient(), mgr.GetEventRecorderFor(ControllerName)) |
| 110 | + return controllerruntime.NewControllerManagedBy(mgr). |
| 111 | + For(&autoscalingv1alpha1.CronFederatedHPA{}). |
| 112 | + WithOptions(controller.Options{RateLimiter: ratelimiterflag.DefaultControllerRateLimiter(c.RateLimiterOptions)}). |
| 113 | + Complete(c) |
| 114 | +} |
| 115 | + |
| 116 | +// processCronRule processes the cron rule |
| 117 | +func (c *CronFHPAController) processCronRule(cronFHPA *autoscalingv1alpha1.CronFederatedHPA, rule autoscalingv1alpha1.CronFederatedHPARule) error { |
| 118 | + cronFHPAKey := helper.GetCronFederatedHPAKey(cronFHPA) |
| 119 | + if ruleOld, exists := c.CronHandler.RuleCronExecutorExists(cronFHPAKey, rule.Name); exists { |
| 120 | + if equality.Semantic.DeepEqual(ruleOld, rule) { |
| 121 | + return nil |
| 122 | + } |
| 123 | + c.CronHandler.StopRuleExecutor(cronFHPAKey, rule.Name) |
| 124 | + } |
| 125 | + |
| 126 | + if !helper.IsCronFederatedHPARuleSuspend(rule) { |
| 127 | + if err := c.CronHandler.CreateCronJobForExecutor(cronFHPA, rule); err != nil { |
| 128 | + c.EventRecorder.Event(cronFHPA, corev1.EventTypeWarning, "StartRuleFailed", err.Error()) |
| 129 | + klog.Errorf("Fail to start cron for CronFederatedHPA(%s) rule(%s):%v", cronFHPAKey, rule.Name, err) |
| 130 | + return err |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + if err := c.updateRuleHistory(cronFHPA, rule); err != nil { |
| 135 | + c.EventRecorder.Event(cronFHPA, corev1.EventTypeWarning, "UpdateCronFederatedHPAFailed", err.Error()) |
| 136 | + return err |
| 137 | + } |
| 138 | + return nil |
| 139 | +} |
| 140 | + |
| 141 | +// updateRuleHistory updates the rule history |
| 142 | +func (c *CronFHPAController) updateRuleHistory(cronFHPA *autoscalingv1alpha1.CronFederatedHPA, rule autoscalingv1alpha1.CronFederatedHPARule) error { |
| 143 | + var nextExecutionTime *metav1.Time |
| 144 | + if !helper.IsCronFederatedHPARuleSuspend(rule) { |
| 145 | + // If rule is not suspended, we should set the nextExecutionTime filed, or the nextExecutionTime will be nil |
| 146 | + next, err := c.CronHandler.GetRuleNextExecuteTime(cronFHPA, rule.Name) |
| 147 | + if err != nil { |
| 148 | + klog.Errorf("Fail to get next execution time for CronFederatedHPA(%s/%s) rule(%s):%v", |
| 149 | + cronFHPA.Namespace, cronFHPA.Name, rule.Name, err) |
| 150 | + return err |
| 151 | + } |
| 152 | + nextExecutionTime = &metav1.Time{Time: next} |
| 153 | + } |
| 154 | + |
| 155 | + exists := false |
| 156 | + for index, history := range cronFHPA.Status.ExecutionHistories { |
| 157 | + if history.RuleName != rule.Name { |
| 158 | + continue |
| 159 | + } |
| 160 | + exists = true |
| 161 | + cronFHPA.Status.ExecutionHistories[index].NextExecutionTime = nextExecutionTime |
| 162 | + break |
| 163 | + } |
| 164 | + |
| 165 | + if !exists { |
| 166 | + ruleHistory := autoscalingv1alpha1.ExecutionHistory{ |
| 167 | + RuleName: rule.Name, |
| 168 | + NextExecutionTime: nextExecutionTime, |
| 169 | + } |
| 170 | + cronFHPA.Status.ExecutionHistories = append(cronFHPA.Status.ExecutionHistories, ruleHistory) |
| 171 | + } |
| 172 | + |
| 173 | + if err := c.Client.Status().Update(context.Background(), cronFHPA); err != nil { |
| 174 | + klog.Errorf("Fail to update CronFederatedHPA(%s/%s) rule(%s)'s next execution time:%v", |
| 175 | + cronFHPA.Namespace, cronFHPA.Name, err) |
| 176 | + return err |
| 177 | + } |
| 178 | + |
| 179 | + return nil |
| 180 | +} |
| 181 | + |
| 182 | +// removeCronFHPAHistory removes the rule history in status |
| 183 | +func (c *CronFHPAController) removeCronFHPAHistory(cronFHPA *autoscalingv1alpha1.CronFederatedHPA, ruleName string) error { |
| 184 | + exists := false |
| 185 | + for index, history := range cronFHPA.Status.ExecutionHistories { |
| 186 | + if history.RuleName != ruleName { |
| 187 | + continue |
| 188 | + } |
| 189 | + cronFHPA.Status.ExecutionHistories = append(cronFHPA.Status.ExecutionHistories[:index], cronFHPA.Status.ExecutionHistories[index+1:]...) |
| 190 | + exists = true |
| 191 | + break |
| 192 | + } |
| 193 | + |
| 194 | + if !exists { |
| 195 | + return nil |
| 196 | + } |
| 197 | + if err := c.Client.Status().Update(context.Background(), cronFHPA); err != nil { |
| 198 | + c.EventRecorder.Event(cronFHPA, corev1.EventTypeWarning, "UpdateCronFederatedHPAFailed", err.Error()) |
| 199 | + klog.Errorf("Fail to remove CronFederatedHPA(%s/%s) rule(%s) history:%v", cronFHPA.Namespace, cronFHPA.Name, ruleName, err) |
| 200 | + return err |
| 201 | + } |
| 202 | + |
| 203 | + return nil |
| 204 | +} |
0 commit comments