|
| 1 | +/* |
| 2 | +Copyright 2022 The Kubernetes-CSI-Addons Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package controllers |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "reflect" |
| 23 | + "time" |
| 24 | + |
| 25 | + csiaddonsv1alpha1 "github.com/csi-addons/kubernetes-csi-addons/api/v1alpha1" |
| 26 | + |
| 27 | + "github.com/go-logr/logr" |
| 28 | + "github.com/robfig/cron/v3" |
| 29 | + corev1 "k8s.io/api/core/v1" |
| 30 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 31 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 32 | + "k8s.io/apimachinery/pkg/runtime" |
| 33 | + "k8s.io/apimachinery/pkg/types" |
| 34 | + ctrl "sigs.k8s.io/controller-runtime" |
| 35 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 36 | + "sigs.k8s.io/controller-runtime/pkg/event" |
| 37 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 38 | + "sigs.k8s.io/controller-runtime/pkg/predicate" |
| 39 | + "sigs.k8s.io/controller-runtime/pkg/reconcile" |
| 40 | +) |
| 41 | + |
| 42 | +// PersistentVolumeClaimReconciler reconciles a PersistentVolumeClaim object |
| 43 | +type PersistentVolumeClaimReconciler struct { |
| 44 | + client.Client |
| 45 | + Scheme *runtime.Scheme |
| 46 | +} |
| 47 | + |
| 48 | +var ( |
| 49 | + rsCronJobScheduleTimeAnnotation = "reclaimspace." + csiaddonsv1alpha1.GroupVersion.Group + "/schedule" |
| 50 | + rsCronJobNameAnnotation = "reclaimspace." + csiaddonsv1alpha1.GroupVersion.Group + "/cronjob" |
| 51 | +) |
| 52 | + |
| 53 | +const ( |
| 54 | + defaultSchedule = "@weekly" |
| 55 | +) |
| 56 | + |
| 57 | +//+kubebuilder:rbac:groups=core,resources=persistentvolumeclaims,verbs=get;list;watch;patch |
| 58 | +//+kubebuilder:rbac:groups=csiaddons.openshift.io,resources=reclaimspacecronjobs,verbs=get;list;watch;create;delete;update |
| 59 | + |
| 60 | +// Reconcile is part of the main kubernetes reconciliation loop which aims to |
| 61 | +// move the current state of the cluster closer to the desired state. |
| 62 | +// This is triggered when `reclaimspace.csiaddons.openshift/schedule` annotation |
| 63 | +// is found on newly created PVC or if there is a change in value of the annotation. |
| 64 | +// It is also triggered by any changes to the child cronjob. |
| 65 | +func (r *PersistentVolumeClaimReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { |
| 66 | + logger := log.FromContext(ctx) |
| 67 | + |
| 68 | + // Fetch PersistentVolumeClaim instance |
| 69 | + pvc := &corev1.PersistentVolumeClaim{} |
| 70 | + err := r.Client.Get(ctx, req.NamespacedName, pvc) |
| 71 | + if err != nil { |
| 72 | + if apierrors.IsNotFound(err) { |
| 73 | + // Request object not found, could have been deleted after reconcile request. |
| 74 | + logger.Info("PersistentVolumeClaim resource not found") |
| 75 | + |
| 76 | + return ctrl.Result{}, nil |
| 77 | + } |
| 78 | + |
| 79 | + return ctrl.Result{}, err |
| 80 | + } |
| 81 | + |
| 82 | + rsCronJob, err := r.findChildCronJob(ctx, &logger, &req) |
| 83 | + if err != nil { |
| 84 | + return ctrl.Result{}, err |
| 85 | + } |
| 86 | + if rsCronJob != nil { |
| 87 | + logger = logger.WithValues("ReclaimSpaceCronJobName", rsCronJob.Name) |
| 88 | + } |
| 89 | + |
| 90 | + annotations := pvc.GetAnnotations() |
| 91 | + schedule, scheduleFound := getScheduleFromAnnotation(&logger, annotations) |
| 92 | + if !scheduleFound { |
| 93 | + // if schedule is not found, |
| 94 | + // delete cron job. |
| 95 | + if rsCronJob != nil { |
| 96 | + err = r.deleteChildCronJob(ctx, &logger, rsCronJob) |
| 97 | + if err != nil { |
| 98 | + return ctrl.Result{}, err |
| 99 | + } |
| 100 | + } |
| 101 | + // delete name from annotation. |
| 102 | + _, nameFound := annotations[rsCronJobNameAnnotation] |
| 103 | + if nameFound { |
| 104 | + // remove name annotation by patching it to null. |
| 105 | + patch := []byte(fmt.Sprintf(`{"metadata":{"annotations":{%q: null}}}`, rsCronJobNameAnnotation)) |
| 106 | + err = r.Client.Patch(ctx, pvc, client.RawPatch(types.StrategicMergePatchType, patch)) |
| 107 | + if err != nil { |
| 108 | + logger.Error(err, "Failed to remove annotation") |
| 109 | + |
| 110 | + return ctrl.Result{}, err |
| 111 | + } |
| 112 | + } |
| 113 | + logger.Info("Annotation not set, exiting reconcile") |
| 114 | + // no schedule annotation set, just dequeue. |
| 115 | + return ctrl.Result{}, nil |
| 116 | + } |
| 117 | + logger = logger.WithValues("Schedule", schedule) |
| 118 | + |
| 119 | + if rsCronJob != nil { |
| 120 | + newRSCronJob := constructRSCronJob(rsCronJob.Name, req.Namespace, schedule, pvc.Name) |
| 121 | + if reflect.DeepEqual(newRSCronJob.Spec, rsCronJob.Spec) { |
| 122 | + logger.Info("No change in reclaimSpaceCronJob.Spec, exiting reconcile") |
| 123 | + |
| 124 | + return ctrl.Result{}, nil |
| 125 | + } |
| 126 | + // update rsCronJob spec |
| 127 | + rsCronJob.Spec = newRSCronJob.Spec |
| 128 | + err = r.Client.Update(ctx, rsCronJob) |
| 129 | + if err != nil { |
| 130 | + logger.Error(err, "Failed to update reclaimSpaceCronJob") |
| 131 | + |
| 132 | + return ctrl.Result{}, err |
| 133 | + } |
| 134 | + logger.Info("Successfully updated reclaimSpaceCronJob") |
| 135 | + |
| 136 | + return ctrl.Result{}, nil |
| 137 | + } |
| 138 | + |
| 139 | + rsCronJobName := generateCronJobName(req.Name) |
| 140 | + logger = logger.WithValues("ReclaimSpaceCronJobName", rsCronJobName) |
| 141 | + // add cronjob name in annotations. |
| 142 | + patch := []byte(fmt.Sprintf(`{"metadata":{"annotations":{%q:%q}}}`, rsCronJobNameAnnotation, rsCronJobName)) |
| 143 | + err = r.Client.Patch(ctx, pvc, client.RawPatch(types.StrategicMergePatchType, patch)) |
| 144 | + if err != nil { |
| 145 | + logger.Error(err, "Failed to update annotation") |
| 146 | + |
| 147 | + return ctrl.Result{}, err |
| 148 | + } |
| 149 | + |
| 150 | + rsCronJob = constructRSCronJob(rsCronJobName, req.Namespace, schedule, pvc.Name) |
| 151 | + err = ctrl.SetControllerReference(pvc, rsCronJob, r.Scheme) |
| 152 | + if err != nil { |
| 153 | + logger.Error(err, "Failed to set controllerReference") |
| 154 | + |
| 155 | + return ctrl.Result{}, err |
| 156 | + } |
| 157 | + |
| 158 | + err = r.Client.Create(ctx, rsCronJob) |
| 159 | + if err != nil { |
| 160 | + logger.Error(err, "Failed to create reclaimSpaceCronJob") |
| 161 | + |
| 162 | + return ctrl.Result{}, err |
| 163 | + } |
| 164 | + logger.Info("Successfully created reclaimSpaceCronJob") |
| 165 | + |
| 166 | + return ctrl.Result{}, nil |
| 167 | +} |
| 168 | + |
| 169 | +// SetupWithManager sets up the controller with the Manager. |
| 170 | +func (r *PersistentVolumeClaimReconciler) SetupWithManager(mgr ctrl.Manager) error { |
| 171 | + err := mgr.GetFieldIndexer().IndexField( |
| 172 | + context.Background(), |
| 173 | + &csiaddonsv1alpha1.ReclaimSpaceCronJob{}, |
| 174 | + jobOwnerKey, |
| 175 | + extractOwnerNameFromPVCObj) |
| 176 | + if err != nil { |
| 177 | + return err |
| 178 | + } |
| 179 | + |
| 180 | + pred := predicate.Funcs{ |
| 181 | + CreateFunc: func(e event.CreateEvent) bool { |
| 182 | + if e.Object == nil { |
| 183 | + return false |
| 184 | + } |
| 185 | + // reconcile only if schedule annotation is found. |
| 186 | + _, ok := e.Object.GetAnnotations()[rsCronJobScheduleTimeAnnotation] |
| 187 | + |
| 188 | + return ok |
| 189 | + }, |
| 190 | + UpdateFunc: func(e event.UpdateEvent) bool { |
| 191 | + if e.ObjectNew == nil || e.ObjectOld == nil { |
| 192 | + return false |
| 193 | + } |
| 194 | + // reconcile only if schedule annotation between old and new objects have changed. |
| 195 | + oldSchdeule, oldOk := e.ObjectOld.GetAnnotations()[rsCronJobScheduleTimeAnnotation] |
| 196 | + newSchdeule, newOk := e.ObjectNew.GetAnnotations()[rsCronJobScheduleTimeAnnotation] |
| 197 | + |
| 198 | + return oldOk != newOk || oldSchdeule != newSchdeule |
| 199 | + }, |
| 200 | + } |
| 201 | + |
| 202 | + return ctrl.NewControllerManagedBy(mgr). |
| 203 | + For(&corev1.PersistentVolumeClaim{}). |
| 204 | + Owns(&csiaddonsv1alpha1.ReclaimSpaceCronJob{}). |
| 205 | + WithEventFilter(pred). |
| 206 | + Complete(r) |
| 207 | +} |
| 208 | + |
| 209 | +// findChildCronJob lists child cronjobs, returns the first cronjob and |
| 210 | +// deletes the rest if there are more than one cronjob. |
| 211 | +func (r *PersistentVolumeClaimReconciler) findChildCronJob( |
| 212 | + ctx context.Context, |
| 213 | + logger *logr.Logger, |
| 214 | + req *reconcile.Request) (*csiaddonsv1alpha1.ReclaimSpaceCronJob, error) { |
| 215 | + var childJobs csiaddonsv1alpha1.ReclaimSpaceCronJobList |
| 216 | + var activeJob *csiaddonsv1alpha1.ReclaimSpaceCronJob |
| 217 | + err := r.List(ctx, |
| 218 | + &childJobs, |
| 219 | + client.InNamespace(req.Namespace), |
| 220 | + client.MatchingFields{jobOwnerKey: req.Name}) |
| 221 | + if err != nil { |
| 222 | + logger.Error(err, "Failed to list child reclaimSpaceCronJobs") |
| 223 | + |
| 224 | + return activeJob, fmt.Errorf("Failed to list child reclaimSpaceCronJob: %v", err) |
| 225 | + } |
| 226 | + |
| 227 | + for i, job := range childJobs.Items { |
| 228 | + if i == 0 { |
| 229 | + activeJob = &job |
| 230 | + continue |
| 231 | + } |
| 232 | + // there should be only one child cronjob, delete rest if they |
| 233 | + // exist |
| 234 | + err = r.deleteChildCronJob(ctx, logger, &job) |
| 235 | + if err != nil { |
| 236 | + return nil, err |
| 237 | + } |
| 238 | + } |
| 239 | + |
| 240 | + return activeJob, nil |
| 241 | +} |
| 242 | + |
| 243 | +// deleteChildCronJob deletes child cron job, ignoring not found error. |
| 244 | +func (r *PersistentVolumeClaimReconciler) deleteChildCronJob( |
| 245 | + ctx context.Context, |
| 246 | + logger *logr.Logger, |
| 247 | + job *csiaddonsv1alpha1.ReclaimSpaceCronJob) error { |
| 248 | + err := r.Delete(ctx, job) |
| 249 | + if client.IgnoreNotFound(err) != nil { |
| 250 | + logger.Error(err, "Failed to delete child reclaimSpaceCronJob", |
| 251 | + "ReclaimSpaceCronJobName", job.Name) |
| 252 | + |
| 253 | + return fmt.Errorf("Failed to delete child reclaimSpaceCronJob %q: %w", |
| 254 | + job.Name, err) |
| 255 | + } |
| 256 | + |
| 257 | + return nil |
| 258 | +} |
| 259 | + |
| 260 | +// getScheduleFromAnnotation parses schedule and returns it. |
| 261 | +// A error is logged and default schedule is returned if it |
| 262 | +// is not in cron format. |
| 263 | +func getScheduleFromAnnotation( |
| 264 | + logger *logr.Logger, |
| 265 | + annotations map[string]string) (string, bool) { |
| 266 | + schedule, ok := annotations[rsCronJobScheduleTimeAnnotation] |
| 267 | + if !ok { |
| 268 | + return "", false |
| 269 | + } |
| 270 | + _, err := cron.ParseStandard(schedule) |
| 271 | + if err != nil { |
| 272 | + logger.Info(fmt.Sprintf("Parsing given schedule %q failed, using default schedule %q", |
| 273 | + schedule, |
| 274 | + defaultSchedule), |
| 275 | + "error", |
| 276 | + err) |
| 277 | + |
| 278 | + return defaultSchedule, true |
| 279 | + } |
| 280 | + |
| 281 | + return schedule, true |
| 282 | +} |
| 283 | + |
| 284 | +// constructRSCronJob constructs and returns ReclaimSpaceCronJob. |
| 285 | +func constructRSCronJob(name, namespace, schedule, pvcName string) *csiaddonsv1alpha1.ReclaimSpaceCronJob { |
| 286 | + failedJobsHistoryLimit := defaultFailedJobsHistoryLimit |
| 287 | + successfulJobsHistoryLimit := defaultSuccessfulJobsHistoryLimit |
| 288 | + return &csiaddonsv1alpha1.ReclaimSpaceCronJob{ |
| 289 | + ObjectMeta: metav1.ObjectMeta{ |
| 290 | + Name: name, |
| 291 | + Namespace: namespace, |
| 292 | + }, |
| 293 | + Spec: csiaddonsv1alpha1.ReclaimSpaceCronJobSpec{ |
| 294 | + Schedule: schedule, |
| 295 | + JobSpec: csiaddonsv1alpha1.ReclaimSpaceJobTemplateSpec{ |
| 296 | + Spec: csiaddonsv1alpha1.ReclaimSpaceJobSpec{ |
| 297 | + Target: csiaddonsv1alpha1.TargetSpec{PersistentVolumeClaim: pvcName}, |
| 298 | + BackoffLimit: defaultBackoffLimit, |
| 299 | + RetryDeadlineSeconds: defaultRetryDeadlineSeconds, |
| 300 | + }, |
| 301 | + }, |
| 302 | + FailedJobsHistoryLimit: &failedJobsHistoryLimit, |
| 303 | + SuccessfulJobsHistoryLimit: &successfulJobsHistoryLimit, |
| 304 | + }, |
| 305 | + } |
| 306 | +} |
| 307 | + |
| 308 | +// extractOwnerNameFromPVCObj extracts owner.Name from the object if it is |
| 309 | +// of type ReclaimSpaceCronJob and has a PVC as its owner. |
| 310 | +func extractOwnerNameFromPVCObj(rawObj client.Object) []string { |
| 311 | + // extract the owner from job object. |
| 312 | + job, ok := rawObj.(*csiaddonsv1alpha1.ReclaimSpaceCronJob) |
| 313 | + if !ok { |
| 314 | + return nil |
| 315 | + } |
| 316 | + owner := metav1.GetControllerOf(job) |
| 317 | + if owner == nil { |
| 318 | + return nil |
| 319 | + } |
| 320 | + if owner.APIVersion != "v1" || owner.Kind != "PersistentVolumeClaim" { |
| 321 | + return nil |
| 322 | + } |
| 323 | + |
| 324 | + return []string{owner.Name} |
| 325 | +} |
| 326 | + |
| 327 | +// generateCronJobName returns unique name by suffixing parent name |
| 328 | +// with time hash. |
| 329 | +func generateCronJobName(parentName string) string { |
| 330 | + return fmt.Sprintf("%s-%d", parentName, time.Now().Unix()) |
| 331 | +} |
0 commit comments