-
Notifications
You must be signed in to change notification settings - Fork 72
/
medusabackupschedule_controller.go
185 lines (151 loc) · 6.42 KB
/
medusabackupschedule_controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/*
Copyright 2021.
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 medusa
import (
"context"
"fmt"
"time"
batchv1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
cassdcapi "github.com/k8ssandra/cass-operator/apis/cassandra/v1beta1"
medusav1alpha1 "github.com/k8ssandra/k8ssandra-operator/apis/medusa/v1alpha1"
cron "github.com/robfig/cron/v3"
)
type Clock interface {
Now() time.Time
}
// MedusaBackupScheduleReconciler reconciles a MedusaBackupSchedule object
type MedusaBackupScheduleReconciler struct {
client.Client
Scheme *runtime.Scheme
Clock Clock
}
type RealClock struct{}
func (r *RealClock) Now() time.Time {
return time.Now()
}
//+kubebuilder:rbac:groups=medusa.k8ssandra.io,namespace="k8ssandra",resources=medusabackupschedules,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=medusa.k8ssandra.io,namespace="k8ssandra",resources=medusabackupschedules/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=medusa.k8ssandra.io,namespace="k8ssandra",resources=medusabackupschedules/finalizers,verbs=update
//+kubebuilder:rbac:groups=medusa.k8ssandra.io,namespace="k8ssandra",resources=medusabackupjobs,verbs=get;list;watch;create
func (r *MedusaBackupScheduleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx).WithValues("medusabackupscheduler", req.NamespacedName)
backupSchedule := &medusav1alpha1.MedusaBackupSchedule{}
err := r.Get(ctx, req.NamespacedName, backupSchedule)
if err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
sched, err := cron.ParseStandard(backupSchedule.Spec.CronSchedule)
if err != nil {
// The schedule is in incorrect format
return ctrl.Result{}, err
}
dcKey := types.NamespacedName{Namespace: backupSchedule.Namespace, Name: backupSchedule.Spec.BackupSpec.CassandraDatacenter}
dc := &cassdcapi.CassandraDatacenter{}
if err := r.Get(ctx, dcKey, dc); err != nil {
logger.Error(err, "failed to get cassandradatacenter", "CassandraDatacenter", dcKey)
return ctrl.Result{}, err
}
defaults(backupSchedule)
previousExecution, err := getPreviousExecutionTime(ctx, backupSchedule)
if err != nil {
return ctrl.Result{}, err
}
now := r.Clock.Now().UTC()
// Calculate the next execution time
nextExecution := sched.Next(previousExecution).UTC()
createBackup := false
if nextExecution.Before(now) {
if backupSchedule.Spec.ConcurrencyPolicy == batchv1.ForbidConcurrent {
if activeTasks, err := r.activeTasks(backupSchedule, dc); err != nil {
logger.V(1).Info("failed to get activeTasks", "error", err)
return ctrl.Result{}, err
} else {
if len(activeTasks) > 0 {
logger.V(1).Info("Postponing backup schedule due to existing active backups", "MedusaBackupSchedule", req.NamespacedName)
return ctrl.Result{RequeueAfter: 1 * time.Minute}, nil
}
}
}
nextExecution = sched.Next(now)
previousExecution = now
createBackup = true && !backupSchedule.Spec.Disabled
}
// Update the status if there are modifications
if backupSchedule.Status.LastExecution.Time.Before(previousExecution) ||
backupSchedule.Status.NextSchedule.Time.Before(nextExecution) {
backupSchedule.Status.NextSchedule = metav1.NewTime(nextExecution)
backupSchedule.Status.LastExecution = metav1.NewTime(previousExecution)
if err := r.Client.Status().Update(ctx, backupSchedule); err != nil {
return ctrl.Result{}, err
}
}
if createBackup {
logger.V(1).Info("Scheduled time has been reached, creating a backup job", "MedusaBackupSchedule", req.NamespacedName)
generatedName := fmt.Sprintf("%s-%d", backupSchedule.Name, now.Unix())
backupJob := &medusav1alpha1.MedusaBackupJob{
ObjectMeta: metav1.ObjectMeta{
Name: generatedName,
Namespace: backupSchedule.Namespace,
Labels: dc.GetDatacenterLabels(),
},
Spec: backupSchedule.Spec.BackupSpec,
}
if err := r.Client.Create(ctx, backupJob); err != nil {
// We've already updated the Status times.. we'll miss this job now?
return ctrl.Result{}, err
}
}
nextRunTime := nextExecution.Sub(now)
logger.V(1).Info("Requeing for next scheduled event", "nextRuntime", nextRunTime.String())
return ctrl.Result{RequeueAfter: nextRunTime}, nil
}
func getPreviousExecutionTime(ctx context.Context, backupSchedule *medusav1alpha1.MedusaBackupSchedule) (time.Time, error) {
previousExecution := backupSchedule.Status.LastExecution
if previousExecution.IsZero() {
// This job has never been executed, we use creationTimestamp
previousExecution = backupSchedule.CreationTimestamp
}
return previousExecution.Time.UTC(), nil
}
func defaults(backupSchedule *medusav1alpha1.MedusaBackupSchedule) {
if backupSchedule.Spec.ConcurrencyPolicy == "" {
backupSchedule.Spec.ConcurrencyPolicy = batchv1.ForbidConcurrent
}
}
func (r *MedusaBackupScheduleReconciler) activeTasks(backupSchedule *medusav1alpha1.MedusaBackupSchedule, dc *cassdcapi.CassandraDatacenter) ([]medusav1alpha1.MedusaBackupJob, error) {
backupJobs := &medusav1alpha1.MedusaBackupJobList{}
if err := r.Client.List(context.Background(), backupJobs, client.InNamespace(backupSchedule.Namespace), client.MatchingLabels(dc.GetDatacenterLabels())); err != nil {
return nil, err
}
activeJobs := make([]medusav1alpha1.MedusaBackupJob, 0)
for _, job := range backupJobs.Items {
if job.Status.FinishTime.IsZero() {
activeJobs = append(activeJobs, job)
}
}
return activeJobs, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *MedusaBackupScheduleReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&medusav1alpha1.MedusaBackupSchedule{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})).
Complete(r)
}