-
Notifications
You must be signed in to change notification settings - Fork 123
/
upgradebackupcontroller.go
326 lines (294 loc) · 12.7 KB
/
upgradebackupcontroller.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package upgradebackupcontroller
import (
"context"
"fmt"
"strings"
"time"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
configv1client "github.com/openshift/client-go/config/clientset/versioned/typed/config/v1"
configv1informers "github.com/openshift/client-go/config/informers/externalversions/config/v1"
configv1listers "github.com/openshift/client-go/config/listers/config/v1"
"github.com/openshift/cluster-etcd-operator/pkg/etcdcli"
"github.com/openshift/cluster-etcd-operator/pkg/operator/etcd_assets"
"github.com/openshift/cluster-etcd-operator/pkg/operator/operatorclient"
configv1helpers "github.com/openshift/library-go/pkg/config/clusteroperator/v1helpers"
"github.com/openshift/library-go/pkg/controller/factory"
"github.com/openshift/library-go/pkg/operator/events"
"github.com/openshift/library-go/pkg/operator/resource/resourceapply"
"github.com/openshift/library-go/pkg/operator/resource/resourceread"
"github.com/openshift/library-go/pkg/operator/v1helpers"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/kubernetes"
coreclientv1 "k8s.io/client-go/kubernetes/typed/core/v1"
corev1listers "k8s.io/client-go/listers/core/v1"
"k8s.io/klog/v2"
)
// UpgradeBackupController responds to an upgrade request to 4.9 by attempting
// to ensure the cluster is backed up. The CVO is expected to wait on a ceo
// condition indicating successful backup before responding to the upgrade
// request. This is intended to ensure that an upgrade from 4.8 to 4.9 does not
// proceed without a recent backup to restore a cluster that is not healthy after
// upgrade to 4.9.
const (
backupConditionType = "RecentBackup"
backupSuccess = "UpgradeBackupSuccessful"
clusterBackupPodName = "cluster-backup"
recentBackupPath = "/etc/kubernetes/cluster-backup"
failedPodBackoffDuration = 30 * time.Second
backupDirEnvName = "CLUSTER_BACKUP_PATH"
)
type UpgradeBackupController struct {
operatorClient v1helpers.OperatorClient
clusterOperatorClient configv1client.ClusterOperatorsGetter
kubeClient kubernetes.Interface
etcdClient etcdcli.EtcdClient
podLister corev1listers.PodLister
clusterVersionLister configv1listers.ClusterVersionLister
clusterOperatorLister configv1listers.ClusterOperatorLister
targetImagePullSpec string
operatorImagePullSpec string
}
func NewUpgradeBackupController(
operatorClient v1helpers.OperatorClient,
clusterOperatorClient configv1client.ClusterOperatorsGetter,
kubeClient kubernetes.Interface,
etcdClient etcdcli.EtcdClient,
kubeInformers v1helpers.KubeInformersForNamespaces,
clusterVersionInformer configv1informers.ClusterVersionInformer,
clusterOperatorInformer configv1informers.ClusterOperatorInformer,
eventRecorder events.Recorder,
targetImagePullSpec string,
operatorImagePullSpec string,
) factory.Controller {
c := &UpgradeBackupController{
operatorClient: operatorClient,
clusterOperatorClient: clusterOperatorClient,
clusterOperatorLister: clusterOperatorInformer.Lister(),
kubeClient: kubeClient,
etcdClient: etcdClient,
podLister: kubeInformers.InformersFor(operatorclient.TargetNamespace).Core().V1().Pods().Lister(),
clusterVersionLister: clusterVersionInformer.Lister(),
targetImagePullSpec: targetImagePullSpec,
operatorImagePullSpec: operatorImagePullSpec,
}
return factory.New().ResyncEvery(1*time.Minute).WithInformers(
kubeInformers.InformersFor(operatorclient.TargetNamespace).Core().V1().Pods().Informer(),
operatorClient.Informer(),
clusterVersionInformer.Informer(),
clusterOperatorInformer.Informer(),
).WithSync(c.sync).ToController("ClusterBackupController", eventRecorder.WithComponentSuffix("cluster-backup-controller"))
}
func (c *UpgradeBackupController) sync(ctx context.Context, syncCtx factory.SyncContext) error {
originalClusterOperatorObj, err := c.clusterOperatorLister.Get("etcd")
if err != nil && !apierrors.IsNotFound(err) {
syncCtx.Recorder().Warningf("StatusFailed", "Unable to get current operator status for clusteroperator/etcd: %v", err)
return err
}
if err != nil {
return err
}
clusterOperatorObj := originalClusterOperatorObj.DeepCopy()
if !isBackupConditionExist(originalClusterOperatorObj.Status.Conditions) {
configv1helpers.SetStatusCondition(&clusterOperatorObj.Status.Conditions, configv1.ClusterOperatorStatusCondition{
Type: "RecentBackup",
Status: configv1.ConditionUnknown,
Reason: "ControllerStarted",
})
if _, err := c.clusterOperatorClient.ClusterOperators().UpdateStatus(ctx, clusterOperatorObj, metav1.UpdateOptions{}); err != nil {
syncCtx.Recorder().Warning("ClusterBackupControllerUpdatingStatus", err.Error())
return err
}
}
recentBackupCondition, err := c.ensureRecentBackup(ctx, &clusterOperatorObj.Status, syncCtx.Recorder())
if err != nil {
_, _, updateErr := v1helpers.UpdateStatus(ctx, c.operatorClient, v1helpers.UpdateConditionFn(operatorv1.OperatorCondition{
Type: "UpgradeBackupControllerDegraded",
Status: operatorv1.ConditionTrue,
Reason: "Error",
Message: err.Error(),
}))
if updateErr != nil {
syncCtx.Recorder().Warning("ClusterBackupControllerUpdatingStatus", updateErr.Error())
}
return err
}
_, _, updateErr := v1helpers.UpdateStatus(ctx, c.operatorClient, v1helpers.UpdateConditionFn(operatorv1.OperatorCondition{
Type: "UpgradeBackupControllerDegraded",
Status: operatorv1.ConditionFalse,
Reason: "AsExpected",
}))
if updateErr != nil {
syncCtx.Recorder().Warning("ClusterBackupControllerUpdatingStatus", updateErr.Error())
return updateErr
}
// If recentBackupCondition is nil work is done and no need to update status.
if recentBackupCondition == nil {
return nil
}
configv1helpers.SetStatusCondition(&clusterOperatorObj.Status.Conditions, *recentBackupCondition)
if _, err := c.clusterOperatorClient.ClusterOperators().UpdateStatus(ctx, clusterOperatorObj, metav1.UpdateOptions{}); err != nil {
syncCtx.Recorder().Warning("ClusterBackupControllerUpdatingStatus", err.Error())
return err
}
return nil
}
// ensureRecentBackup ensures that a new backup pod is created if one does not exist, returns the appropriate RecentBackup condition.
func (c *UpgradeBackupController) ensureRecentBackup(ctx context.Context, clusterOperatorStatus *configv1.ClusterOperatorStatus, recorder events.Recorder) (*configv1.ClusterOperatorStatusCondition, error) {
clusterVersion, err := c.clusterVersionLister.Get("version")
if err != nil {
return nil, err
}
// Check cluster version status for backup condition.
if !isRequireRecentBackup(clusterVersion) {
return nil, nil
}
backupPod, err := c.podLister.Pods(operatorclient.TargetNamespace).Get(clusterBackupPodName)
// No backup found, attempt to create one.
if err != nil && apierrors.IsNotFound(err) {
// Check nodes for backup preconditions
backupNodeName, err := c.getBackupNodeName(ctx)
if err != nil {
return nil, err
}
recentBackupName := fmt.Sprintf("upgrade-backup-%s", time.Now().Format("2006-01-02_150405"))
if err := createBackupPod(ctx, backupNodeName, recentBackupName, c.operatorImagePullSpec, c.targetImagePullSpec, c.kubeClient.CoreV1(), recorder); err != nil {
return nil, fmt.Errorf("pod/%s: %v", clusterBackupPodName, err)
}
return &configv1.ClusterOperatorStatusCondition{
Status: configv1.ConditionUnknown,
Type: backupConditionType,
Reason: "UpgradeBackupInProgress",
Message: fmt.Sprintf("Upgrade backup pod created on node %s", backupNodeName),
}, nil
}
if err != nil {
return nil, err
}
// Check the existing Pod Status, reconcile pod and update condition respectively.
// PodSucceeded => ConditionTrue
// PodFailed => ConditionFalse
// everything else ConditionUnknown
switch {
case backupPod.Status.Phase == corev1.PodSucceeded:
backupCondition := configv1helpers.FindStatusCondition(clusterOperatorStatus.Conditions, backupConditionType)
if backupCondition.Reason != backupSuccess {
// Read the backup directory name from the backup pod's env
backupDirName := ""
for _, env := range backupPod.Spec.Containers[0].Env {
if env.Name == backupDirEnvName {
backupDirName = env.Value
}
}
if backupDirName == "" {
klog.Warningf("failed to get backup directory name from backup pod: %s/%s", backupPod.Namespace, backupPod.Name)
}
return &configv1.ClusterOperatorStatusCondition{
Status: configv1.ConditionTrue,
Type: backupConditionType,
Reason: backupSuccess,
Message: fmt.Sprintf("UpgradeBackup pre 4.9 located at path %s on node %q", backupDirName, backupPod.Spec.NodeName),
}, nil
}
return nil, nil
case backupPod.Status.Phase == corev1.PodFailed && !isBackoffDuration(backupPod.CreationTimestamp.Time, failedPodBackoffDuration):
// Pod must be older than retry duration before any delete action is taken.
return operatorStatusBackupPodFailed("pod failed within retry duration: delete skipped"), nil
case backupPod.Status.Phase == corev1.PodFailed:
// Delete pod
err := c.kubeClient.CoreV1().Pods(operatorclient.TargetNamespace).Delete(ctx, backupPod.Name, metav1.DeleteOptions{})
if err != nil {
return operatorStatusBackupPodFailed(fmt.Sprintf("failed to delete pod openshift-etcd/%s: %v", clusterBackupPodName, err)), nil
}
podDeletedMessage := fmt.Sprintf("Successful deletion of failed pod openshift-etcd/%s", clusterBackupPodName)
recorder.Event("UpgradeBackupFailed", podDeletedMessage)
return operatorStatusBackupPodFailed(podDeletedMessage), nil
}
return &configv1.ClusterOperatorStatusCondition{
Status: configv1.ConditionUnknown,
Type: backupConditionType,
Reason: "UpgradeBackupInProgress",
Message: fmt.Sprintf("Backup pod phase: %q", backupPod.Status.Phase),
}, nil
}
// getBackupNodeName checks all etcd pods and verifies the etcd member on that
// pod is healthy if yes returns the node name it is scheduled on and errors if
// no healthy members exist.
func (c *UpgradeBackupController) getBackupNodeName(ctx context.Context) (string, error) {
pods, err := c.podLister.List(labels.Set{"app": "etcd"}.AsSelector())
if err != nil {
return "", err
}
var errs []error
for _, pod := range pods {
if !strings.HasPrefix(pod.Name, "etcd-") {
continue
}
member, err := c.etcdClient.GetMember(ctx, pod.Spec.NodeName)
if err != nil {
errs = append(errs, err)
continue
}
isHealthy, err := c.etcdClient.IsMemberHealthy(ctx, member)
if err != nil {
errs = append(errs, err)
continue
}
if isHealthy {
return pod.Spec.NodeName, nil
}
klog.V(4).Infof("etcd member failed health check: %s", pod.Spec.NodeName)
}
if len(errs) > 0 {
return "", utilerrors.NewAggregate(errs)
}
return "", fmt.Errorf("no valid node found to schedule backup pod")
}
func createBackupPod(ctx context.Context, nodeName, recentBackupName, operatorImagePullSpec, targetImagePullSpec string, client coreclientv1.PodsGetter, recorder events.Recorder) error {
pod := resourceread.ReadPodV1OrDie(etcd_assets.MustAsset("etcd/cluster-backup-pod.yaml"))
pod.Spec.NodeName = nodeName
pod.Spec.InitContainers[0].Image = operatorImagePullSpec
pod.Spec.Containers[0].Image = targetImagePullSpec
pod.Spec.Containers[0].Env = []corev1.EnvVar{
{Name: backupDirEnvName, Value: fmt.Sprintf("%s/%s", recentBackupPath, recentBackupName)},
}
_, _, err := resourceapply.ApplyPod(ctx, client, recorder, pod)
if err != nil {
return err
}
return nil
}
// isRequireRecentBackup checks the conditions of ClusterVersion to verify if a backup is required.
func isRequireRecentBackup(config *configv1.ClusterVersion) bool {
for _, condition := range config.Status.Conditions {
// Check if ReleaseAccepted is false and Message field containers the string RecentBackup.
if condition.Type == "ReleaseAccepted" && condition.Status == configv1.ConditionFalse {
return strings.Contains(condition.Message, "RecentBackup")
}
}
return false
}
// isBackoffDuration returns true if the pod is older than backoff duration.
func isBackoffDuration(createdTimeStamp time.Time, duration time.Duration) bool {
return metav1.Now().Add(-duration).After(createdTimeStamp)
}
func operatorStatusBackupPodFailed(message string) *configv1.ClusterOperatorStatusCondition {
return &configv1.ClusterOperatorStatusCondition{
Status: configv1.ConditionFalse,
Type: backupConditionType,
Reason: "UpgradeBackupFailed",
Message: message,
}
}
func isBackupConditionExist(conditions []configv1.ClusterOperatorStatusCondition) bool {
for _, condition := range conditions {
if condition.Type == backupConditionType {
return true
}
}
return false
}