This repository has been archived by the owner on Oct 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
statefulset_rollout_reconciler.go
265 lines (237 loc) · 9.98 KB
/
statefulset_rollout_reconciler.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package statefulset
import (
"context"
"fmt"
"strconv"
"time"
"github.com/pkg/errors"
appsv1 "k8s.io/api/apps/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
crc "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"code.cloudfoundry.org/quarks-statefulset/pkg/kube/apis"
"code.cloudfoundry.org/quarks-utils/pkg/config"
"code.cloudfoundry.org/quarks-utils/pkg/ctxlog"
"code.cloudfoundry.org/quarks-utils/pkg/meltdown"
"code.cloudfoundry.org/quarks-utils/pkg/pointers"
)
const (
rolloutStatePending = "Pending"
rolloutStateCanary = "Canary"
rolloutStateRollout = "Rollout"
rolloutStateDone = "Done"
rolloutStateFailed = "Failed"
rolloutStateCanaryUpscale = "CanaryUpscale"
)
var (
// AnnotationCanaryRolloutEnabled if set to "true" canary behaviour is desired
AnnotationCanaryRolloutEnabled = fmt.Sprintf("%s/canary-rollout-enabled", apis.GroupName)
// AnnotationCanaryRollout is the state of the canary rollout of the stateful set
AnnotationCanaryRollout = fmt.Sprintf("%s/canary-rollout", apis.GroupName)
// AnnotationCanaryWatchTime is the max time for the canary update
AnnotationCanaryWatchTime = fmt.Sprintf("%s/canary-watch-time-ms", apis.GroupName)
// AnnotationUpdateWatchTime is the max time for the complete update
AnnotationUpdateWatchTime = fmt.Sprintf("%s/update-watch-time-ms", apis.GroupName)
// AnnotationUpdateStartTime is the timestamp when the update started
AnnotationUpdateStartTime = fmt.Sprintf("%s/update-start-time", apis.GroupName)
)
// NewStatefulSetRolloutReconciler returns a new reconcile.Reconciler
func NewStatefulSetRolloutReconciler(ctx context.Context, config *config.Config, mgr manager.Manager) reconcile.Reconciler {
return &ReconcileStatefulSetRollout{
ctx: ctx,
config: config,
client: mgr.GetClient(),
scheme: mgr.GetScheme(),
}
}
// ReconcileStatefulSetRollout reconciles an QuarksStatefulSet object when references changes
type ReconcileStatefulSetRollout struct {
ctx context.Context
client crc.Client
scheme *runtime.Scheme
config *config.Config
}
// Reconcile cleans up old versions and volumeManagement statefulSet of the QuarksStatefulSet
func (r *ReconcileStatefulSetRollout) Reconcile(request reconcile.Request) (reconcile.Result, error) {
// Set the ctx to be Background, as the top-level context for incoming requests.
ctx, cancel := context.WithTimeout(r.ctx, r.config.CtxTimeOut)
defer cancel()
ctxlog.Debug(ctx, "Reconciling StatefulSet ", request.NamespacedName)
statefulSet := appsv1.StatefulSet{}
err := r.client.Get(ctx, request.NamespacedName, &statefulSet)
if err != nil {
ctxlog.Error(ctx, "StatefulSet not found ", request.NamespacedName)
return reconcile.Result{}, err
}
if meltdown.NewAnnotationWindow(r.config.MeltdownDuration, statefulSet.Annotations).Contains(time.Now()) {
ctxlog.WithEvent(&statefulSet, "Meltdown").Debugf(ctx, "Resource '%s/%s' is in meltdown, requeue reconcile after %s", statefulSet.Namespace, statefulSet.Name, r.config.MeltdownRequeueAfter)
return reconcile.Result{RequeueAfter: r.config.MeltdownRequeueAfter}, nil
}
var status = statefulSet.Annotations[AnnotationCanaryRollout]
if status == rolloutStateFailed || status == rolloutStateDone {
return reconcile.Result{}, nil
}
var newStatus = status
dirty := false
var oldPartition int32
if statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition == nil {
oldPartition = -1
ctxlog.Error(ctx, "StatefulSet with unexpected partition = nil found (webhook should prevent this)", request.NamespacedName)
} else {
oldPartition = *statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition
}
if timedOut, err := r.failIfTimedOut(ctx, statefulSet, AnnotationUpdateWatchTime); timedOut || err != nil {
ctxlog.Errorf(ctx, "Error updating StatefulSet '%s' after timeout: %s", request.NamespacedName, err)
return reconcile.Result{}, err
}
var resultWithRetrigger reconcile.Result
resultWithRetrigger.RequeueAfter = getTimeOut(ctx, statefulSet, AnnotationUpdateWatchTime)
switch status {
case rolloutStateCanaryUpscale:
if statefulSet.Status.Replicas == *statefulSet.Spec.Replicas && statefulSet.Status.ReadyReplicas == *statefulSet.Spec.Replicas {
if *statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition == 0 {
newStatus = rolloutStateDone
} else {
(*statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition)--
newStatus = rolloutStateRollout
}
}
case rolloutStateCanary:
if getTimeOut(ctx, statefulSet, AnnotationCanaryWatchTime) < 0 {
newStatus = rolloutStateFailed
break
}
fallthrough
case rolloutStateRollout:
if resultWithRetrigger.RequeueAfter > time.Minute {
resultWithRetrigger.RequeueAfter = time.Minute
}
ready, err := partitionPodIsReadyAndUpdated(ctx, r.client, &statefulSet)
if err != nil {
return reconcile.Result{}, err
}
if *statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition == 0 {
if ready {
newStatus = rolloutStateDone
}
break
}
if !ready {
break
}
(*statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition)--
resultWithRetrigger.Requeue = true
dirty = true
newStatus = rolloutStateRollout
ctxlog.Debugf(ctx, "Statefulset rollout for '%s/%s' has partition %d, will reconcile in %d ms", statefulSet.Namespace, statefulSet.Name, *statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition, resultWithRetrigger.RequeueAfter*time.Millisecond)
case rolloutStatePending:
if statefulSet.Status.Replicas < *statefulSet.Spec.Replicas {
if *statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition > 0 {
(*statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition)--
}
newStatus = rolloutStateCanaryUpscale
resultWithRetrigger.RequeueAfter = getTimeOut(ctx, statefulSet, AnnotationUpdateWatchTime)
} else {
resultWithRetrigger.RequeueAfter = getTimeOut(ctx, statefulSet, AnnotationCanaryWatchTime)
newStatus = rolloutStateCanary
(*statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition)--
dirty = true
}
}
statusChanged := newStatus != statefulSet.Annotations[AnnotationCanaryRollout]
ctxlog.Debugf(ctx, "Statefulset rollout for '%s/%s' is in status %s", statefulSet.Namespace, statefulSet.Name, newStatus)
if statusChanged {
statefulSet.Annotations[AnnotationCanaryRollout] = newStatus
dirty = true
}
if dirty {
if err = r.updateWithPartitionMove(ctx, statefulSet, oldPartition); err != nil {
ctxlog.Errorf(ctx, "Error updating StatefulSet '%s' with partition move: %s", request.NamespacedName, err)
return reconcile.Result{}, err
}
}
return resultWithRetrigger, nil
}
func (r *ReconcileStatefulSetRollout) failIfTimedOut(ctx context.Context, statefulSet appsv1.StatefulSet, timeout string) (bool, error) {
if getTimeOut(ctx, statefulSet, timeout) < 0 {
statefulSet.Annotations[AnnotationCanaryRollout] = rolloutStateFailed
if err := r.updateStatefulSet(ctx, &statefulSet); err != nil {
return true, err
}
return true, nil
}
return false, nil
}
func (r *ReconcileStatefulSetRollout) updateWithPartitionMove(ctx context.Context, statefulset appsv1.StatefulSet, oldPartition int32) error {
err := r.updateStatefulSet(ctx, &statefulset)
if err != nil {
return err
}
if oldPartition != *statefulset.Spec.UpdateStrategy.RollingUpdate.Partition {
err = CleanupNonReadyPod(ctx, r.client, &statefulset, *statefulset.Spec.UpdateStrategy.RollingUpdate.Partition)
if err != nil {
return err
}
}
return nil
}
func getTimeOut(ctx context.Context, statefulSet appsv1.StatefulSet, watchTimeAnnotation string) time.Duration {
watchTimeStr, ok := statefulSet.Annotations[watchTimeAnnotation]
if !ok || watchTimeStr == "" {
return 0 // never timeout
}
watchTime, err := strconv.Atoi(watchTimeStr)
if err != nil {
ctxlog.Errorf(ctx, "Invalid annotation '%s' on '%s/%s': %s", watchTimeAnnotation, statefulSet.Namespace, statefulSet.Name, statefulSet.Annotations[watchTimeAnnotation])
return -1
}
updateStartTimeUnix, err := strconv.ParseInt(statefulSet.Annotations[AnnotationUpdateStartTime], 10, 64)
if err != nil {
ctxlog.Errorf(ctx, "Invalid annotation '%s' on '%s/%s': %s", AnnotationUpdateStartTime, statefulSet.Namespace, statefulSet.Name, statefulSet.Annotations[AnnotationUpdateStartTime])
return -1
}
updateStartTime := time.Unix(updateStartTimeUnix, 0)
timeLeft := time.Until(updateStartTime.Add(time.Millisecond * time.Duration(watchTime)))
if timeLeft == 0 { //differ from 'never timeout'
timeLeft = -1
}
return timeLeft
}
func (r *ReconcileStatefulSetRollout) updateStatefulSet(ctx context.Context, statefulSet *appsv1.StatefulSet) error {
meltdown.SetLastReconcile(&statefulSet.ObjectMeta, time.Now())
partition := *statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition
state := statefulSet.Annotations[AnnotationCanaryRollout]
_, err := controllerutil.CreateOrUpdate(ctx, r.client, statefulSet, func() error {
statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition = pointers.Int32(partition)
statefulSet.Annotations[AnnotationCanaryRollout] = state
return nil
})
if err != nil {
statusError, ok := err.(*apierrors.StatusError)
if ok && statusError.Status().Code == 409 {
return errors.Wrap(err, "Conflict while updating stateful set")
}
return err
}
ctxlog.Debugf(ctx, "StatefulSet state %s/%s updated", statefulSet.Namespace, statefulSet.Name)
return nil
}
func partitionPodIsReadyAndUpdated(ctx context.Context, client crc.Client, statefulSet *appsv1.StatefulSet) (bool, error) {
ready := false
updated := false
if statefulSet.Spec.UpdateStrategy.RollingUpdate != nil {
pod, podReady, err := getPodWithIndex(ctx, client, statefulSet, *statefulSet.Spec.UpdateStrategy.RollingUpdate.Partition)
if err != nil {
ctxlog.Debug(ctx, "Error calling GetNoneReadyPod ", statefulSet.Namespace, "/", statefulSet.Name, err)
return false, err
}
if podReady {
ready = true
updated = pod.Labels[appsv1.StatefulSetRevisionLabel] == statefulSet.Status.UpdateRevision
}
}
return ready && updated, nil
}