-
Notifications
You must be signed in to change notification settings - Fork 231
/
status_manager.go
596 lines (525 loc) · 19.5 KB
/
status_manager.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
package statusmanager
import (
"context"
"fmt"
"log"
"os"
"reflect"
"strings"
"sync"
"github.com/ghodss/yaml"
"github.com/openshift/cluster-network-operator/pkg/hypershift"
configv1 "github.com/openshift/api/config/v1"
operv1 "github.com/openshift/api/operator/v1"
"github.com/openshift/cluster-network-operator/pkg/apply"
cnoclient "github.com/openshift/cluster-network-operator/pkg/client"
"github.com/openshift/cluster-network-operator/pkg/names"
cohelpers "github.com/openshift/library-go/pkg/config/clusteroperator/v1helpers"
operstatus "github.com/openshift/library-go/pkg/operator/status"
"github.com/openshift/library-go/pkg/operator/v1helpers"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
uns "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
crclient "sigs.k8s.io/controller-runtime/pkg/client"
)
type StatusLevel int
const (
PanicLevel StatusLevel = iota // Special StatusLevel used when recovering from a panic
ClusterConfig
OperatorConfig
OperatorRender
ProxyConfig
InjectorConfig
PodDeployment
PKIConfig
EgressRouterConfig
RolloutHung
CertificateSigner
InfrastructureConfig
DashboardConfig
maxStatusLevel
)
const (
ClusteredNameSeparator = '/'
)
type ClusteredName struct {
ClusterName string
Namespace string
Name string
}
func NewClusteredName(obj crclient.Object) ClusteredName {
return ClusteredName{
Namespace: obj.GetNamespace(),
Name: obj.GetName(),
ClusterName: apply.GetClusterName(obj),
}
}
func (c ClusteredName) String() string {
return c.ClusterName + string(ClusteredNameSeparator) + c.Namespace + string(ClusteredNameSeparator) + c.Name
}
// StatusManager coordinates changes to ClusterOperator.Status
type StatusManager struct {
sync.Mutex
client cnoclient.Client
name string
hyperShiftConfig *hypershift.HyperShiftConfig
failing [maxStatusLevel]*operv1.OperatorCondition
installComplete bool
// All our informers and listers
dsInformers map[string]cache.SharedIndexInformer
dsListers map[string]DaemonSetLister
depInformers map[string]cache.SharedIndexInformer
depListers map[string]DeploymentLister
ssInformers map[string]cache.SharedIndexInformer
ssListers map[string]StatefulSetLister
labelSelector labels.Selector
relatedObjects []configv1.ObjectReference
// used only for upgrades from <=4.13 to 4.14 with ovn-kubernetes
// TODO: remove in 4.15
isOVNKubernetes *bool
}
func New(client cnoclient.Client, name, cluster string) *StatusManager {
status := &StatusManager{
client: client,
name: name,
hyperShiftConfig: hypershift.NewHyperShiftConfig(),
dsInformers: map[string]cache.SharedIndexInformer{},
dsListers: map[string]DaemonSetLister{},
depInformers: map[string]cache.SharedIndexInformer{},
depListers: map[string]DeploymentLister{},
ssInformers: map[string]cache.SharedIndexInformer{},
ssListers: map[string]StatefulSetLister{},
}
var err error
status.labelSelector, err = labels.Parse(fmt.Sprintf("%s==%s", names.GenerateStatusLabel, cluster))
if err != nil {
panic(err) // selector is guaranteed valid, unreachable
}
return status
}
// setClusterOperAnnotation sets an annotation on the clusterOperator network object
func (status *StatusManager) setClusterOperAnnotation(obj *configv1.ClusterOperator) error {
value := []string{}
for _, obj := range status.hyperShiftConfig.RelatedObjects {
value = append(value, fmt.Sprintf("%s/%s/%s/%s/%s", obj.ClusterName, obj.Group, obj.Resource, obj.Namespace, obj.Name))
}
anno := strings.Join(value, ",")
return status.setAnnotation(context.TODO(), obj, names.RelatedClusterObjectsAnnotation, &anno)
}
// getClusterOperAnnotation gets an annotation from the clusterOperator network object
func (status *StatusManager) getClusterOperAnnotation(obj *configv1.ClusterOperator) ([]hypershift.RelatedObject, error) {
new := obj.DeepCopy()
anno := new.GetAnnotations()
objs := []hypershift.RelatedObject{}
value, set := anno[names.RelatedClusterObjectsAnnotation]
if !set || value == "" {
return objs, nil
}
items := strings.Split(value, ",")
if len(items) == 0 {
return objs, nil
}
for _, res := range items {
parts := strings.Split(res, "/")
if len(parts) != 5 {
return objs, fmt.Errorf("'%s' annotation is invalid, expected: ClusterName/Group/Resource/Namespace/Name, got: %s",
names.RelatedClusterObjectsAnnotation, res)
}
objs = append(objs, hypershift.RelatedObject{
ClusterName: parts[0],
ObjectReference: configv1.ObjectReference{
Group: parts[1],
Resource: parts[2],
Namespace: parts[3],
Name: parts[4],
},
})
}
return objs, nil
}
// deleteRelatedObjects checks for related objects attached to ClusterOperator and deletes
// whatever is not being rendered from manifests. This is a mechanism to cleanup objects
// that are no longer needed and are probably present from a previous version
func (status *StatusManager) deleteRelatedObjectsNotRendered(co *configv1.ClusterOperator) {
if status.relatedObjects == nil && status.hyperShiftConfig.RelatedObjects == nil {
return
}
for _, currentObj := range co.Status.RelatedObjects {
var found bool = false
for _, renderedObj := range status.relatedObjects {
found = reflect.DeepEqual(currentObj, renderedObj)
if found {
break
}
}
if !found {
gvr := schema.GroupVersionResource{
Group: currentObj.Group,
Resource: currentObj.Resource,
}
gvk, err := status.client.ClientFor("").RESTMapper().KindFor(gvr)
if err != nil {
log.Printf("Error getting GVK of object for deletion: %v", err)
status.relatedObjects = append(status.relatedObjects, currentObj)
continue
}
if gvk.Kind == "Namespace" && gvk.Group == "" {
// BZ 1820472: During SDN migration, deleting a namespace object may get stuck in 'Terminating' forever if the cluster network doesn't working as expected.
// We choose to not delete the namespace here but to ask user do it manually after the cluster is back to normal state.
log.Printf("Object Kind is Namespace, skip")
continue
}
// @aconstan: remove this after having the PR implementing this change, integrated.
if gvk.Kind == "Network" && gvk.Group == "operator.openshift.io" {
log.Printf("Object Kind is network.operator.openshift.io, skip")
continue
}
// @npinaeva objects without a name shouldn't be listed as relatedObjects in the first place,
// and we should never try to delete them
if currentObj.Name == "" {
log.Printf("Object without a name GVK %+v, skip", gvk)
continue
}
// Do not remove old rbac definitions before upgrade completes to avoid disruptions
if !status.installComplete && gvk.Group == "rbac.authorization.k8s.io" {
klog.Infof("Upgrade in progress, skipping removal of (%s) %s/%s for now", gvk, currentObj.Namespace, currentObj.Name)
status.relatedObjects = append(status.relatedObjects, currentObj)
continue
}
log.Printf("Detected related object with GVK %+v, namespace %v and name %v not rendered by manifests, deleting...", gvk, currentObj.Namespace, currentObj.Name)
objToDelete := &uns.Unstructured{}
objToDelete.SetName(currentObj.Name)
objToDelete.SetNamespace(currentObj.Namespace)
objToDelete.SetGroupVersionKind(gvk)
err = status.client.ClientFor("").CRClient().Delete(context.TODO(), objToDelete, crclient.PropagationPolicy("Background"))
if err != nil {
log.Printf("Error deleting related object: %v", err)
if !errors.IsNotFound(err) {
status.relatedObjects = append(status.relatedObjects, currentObj)
}
continue
}
}
}
currentObjs, err := status.getClusterOperAnnotation(co)
if err != nil {
log.Printf("Error parsing related cluster objects: %v", err)
}
for _, currentObj := range currentObjs {
var found bool = false
for _, renderedObj := range status.hyperShiftConfig.RelatedObjects {
found = reflect.DeepEqual(currentObj, renderedObj)
if found {
break
}
}
if !found {
gvr := schema.GroupVersionResource{
Group: currentObj.Group,
Resource: currentObj.Resource,
}
gvk, err := status.client.ClientFor(currentObj.ClusterName).RESTMapper().KindFor(gvr)
if err != nil {
log.Printf("Error getting GVK of object for deletion: %v", err)
status.hyperShiftConfig.RelatedObjects = append(status.hyperShiftConfig.RelatedObjects, currentObj)
continue
}
log.Printf("Detected related cluster object with GVK %+v, namespace %v and name %v not rendered by manifests, deleting...", gvk, currentObj.Namespace, currentObj.Name)
objToDelete := &uns.Unstructured{}
objToDelete.SetName(currentObj.Name)
objToDelete.SetNamespace(currentObj.Namespace)
objToDelete.SetGroupVersionKind(gvk)
err = status.client.ClientFor(currentObj.ClusterName).CRClient().Delete(context.TODO(), objToDelete, crclient.PropagationPolicy("Background"))
if err != nil {
log.Printf("Error deleting related cluser object: %v", err)
if !errors.IsNotFound(err) {
status.hyperShiftConfig.RelatedObjects = append(status.hyperShiftConfig.RelatedObjects, currentObj)
}
continue
}
}
}
}
// WriteHypershiftStatus mirrors network.operator status to HostedControlPlane status
func (status *StatusManager) writeHypershiftStatus(operStatus *operv1.NetworkStatus) {
if !status.hyperShiftConfig.Enabled {
return
}
err := retry.RetryOnConflict(retry.DefaultBackoff, func() error {
hcp := &uns.Unstructured{}
hcp.SetGroupVersionKind(hypershift.HostedControlPlaneGVK)
err := status.client.ClientFor(names.ManagementClusterName).CRClient().Get(context.TODO(), types.NamespacedName{Namespace: status.hyperShiftConfig.Namespace, Name: status.hyperShiftConfig.Name}, hcp)
if err != nil {
return err
}
updatedConditions, err := hypershift.SetHostedControlPlaneConditions(hcp, operStatus)
if err != nil {
return fmt.Errorf("failed to set HostedControlPlane conditions: %v", err)
}
if len(updatedConditions) == 0 {
// nothing changed, return
return nil
}
if err := status.client.ClientFor(names.ManagementClusterName).CRClient().Status().Update(context.TODO(), hcp); err != nil {
return err
}
log.Printf("Set HostedControlPlane conditions:\n%v", updatedConditions)
return nil
})
if err != nil {
log.Printf("Failed to set HostedControlPlane: %v", err)
}
}
// Set updates the operator and clusteroperator statuses with the provided conditions.
func (status *StatusManager) set(reachedAvailableLevel bool, conditions ...operv1.OperatorCondition) {
var operStatus *operv1.NetworkStatus
// Set status on the network.operator object
err := retry.RetryOnConflict(retry.DefaultBackoff, func() error {
oc := &operv1.Network{ObjectMeta: metav1.ObjectMeta{Name: names.OPERATOR_CONFIG}}
err := status.client.ClientFor("").CRClient().Get(context.TODO(), types.NamespacedName{Name: names.OPERATOR_CONFIG}, oc)
if err != nil {
// Should never happen outside of unit tests
return err
}
oldStatus := oc.Status.DeepCopy()
oc.Status.Version = os.Getenv("RELEASE_VERSION")
// If there is no Available condition on the operator config then copy the
// conditions from the ClusterOperator (which will either also be empty if
// this is a new install, or will contain the pre-4.7 conditions if this is
// a 4.6->4.7 upgrade).
if v1helpers.FindOperatorCondition(oc.Status.Conditions, operv1.OperatorStatusTypeAvailable) == nil {
co := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: status.name}}
err := status.client.ClientFor("").CRClient().Get(context.TODO(), types.NamespacedName{Name: status.name}, co)
if err != nil {
log.Printf("failed to retrieve ClusterOperator object: %v - continuing", err)
}
for _, condition := range co.Status.Conditions {
v1helpers.SetOperatorCondition(&oc.Status.Conditions, operv1.OperatorCondition{
Type: string(condition.Type),
Status: operv1.ConditionStatus(condition.Status),
LastTransitionTime: condition.LastTransitionTime,
Reason: condition.Reason,
Message: condition.Message,
})
}
}
for _, condition := range conditions {
v1helpers.SetOperatorCondition(&oc.Status.Conditions, condition)
}
progressingCondition := v1helpers.FindOperatorCondition(oc.Status.Conditions, operv1.OperatorStatusTypeProgressing)
availableCondition := v1helpers.FindOperatorCondition(oc.Status.Conditions, operv1.OperatorStatusTypeAvailable)
if availableCondition == nil && progressingCondition != nil && progressingCondition.Status == operv1.ConditionTrue {
v1helpers.SetOperatorCondition(&oc.Status.Conditions,
operv1.OperatorCondition{
Type: operv1.OperatorStatusTypeAvailable,
Status: operv1.ConditionFalse,
Reason: "Startup",
Message: "The network is starting up",
},
)
}
if oc.Spec.DefaultNetwork.Type == operv1.NetworkTypeOpenShiftSDN {
// OpenShiftSDN is removed in 4.17, so block the upgrade if we have OpenShiftSDN in the spec.
v1helpers.SetOperatorCondition(&oc.Status.Conditions,
operv1.OperatorCondition{
Type: operv1.OperatorStatusTypeUpgradeable,
Status: operv1.ConditionFalse,
Reason: "OpenShiftSDNConfigured",
Message: "Cluster is configured with OpenShiftSDN, which is not supported in the next version. Please " +
"follow the documented steps to migrate from OpenShiftSDN to OVN-Kubernetes in order to be able to upgrade. " +
"https://docs.openshift.com/container-platform/4.16/networking/ovn_kubernetes_network_provider/migrate-from-openshift-sdn.html",
},
)
} else {
v1helpers.SetOperatorCondition(&oc.Status.Conditions,
operv1.OperatorCondition{
Type: operv1.OperatorStatusTypeUpgradeable,
Status: operv1.ConditionTrue,
},
)
}
operStatus = &oc.Status
if equality.Semantic.DeepEqual(&oc.Status, oldStatus) {
return nil
}
buf, err := yaml.Marshal(oc.Status.Conditions)
if err != nil {
buf = []byte(fmt.Sprintf("(failed to convert to YAML: %s)", err))
}
if err := status.client.ClientFor("").CRClient().Update(context.TODO(), oc); err != nil {
return err
}
log.Printf("Network operator config updated with conditions:\n%s", buf)
return nil
})
if err != nil {
log.Printf("Failed to set operator status: %v", err)
}
// Set status conditions on the network clusteroperator object.
// TODO: enable the library-go ClusterOperatorStatusController, which will
// do this for us. We can't use that yet, because it doesn't allow dynamic RelatedObjects[].
err = retry.RetryOnConflict(retry.DefaultBackoff, func() error {
co := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: status.name}}
err := status.client.ClientFor("").CRClient().Get(context.TODO(), types.NamespacedName{Name: status.name}, co)
isNotFound := errors.IsNotFound(err)
if err != nil && !isNotFound {
return err
}
oldStatus := co.Status.DeepCopy()
status.deleteRelatedObjectsNotRendered(co)
if status.relatedObjects != nil {
co.Status.RelatedObjects = status.relatedObjects
}
if status.hyperShiftConfig.RelatedObjects != nil {
err := status.setClusterOperAnnotation(co)
if err != nil {
return err
}
}
if operStatus == nil {
cohelpers.SetStatusCondition(&co.Status.Conditions, configv1.ClusterOperatorStatusCondition{
Type: configv1.OperatorDegraded,
Status: configv1.ConditionTrue,
Reason: "NoOperConfig",
Message: "No networks.operator.openshift.io cluster found",
})
} else {
if reachedAvailableLevel {
co.Status.Versions = []configv1.OperandVersion{
{Name: "operator", Version: operStatus.Version},
}
}
for _, cond := range operStatus.Conditions {
cohelpers.SetStatusCondition(&co.Status.Conditions, operstatus.OperatorConditionToClusterOperatorCondition(cond))
}
}
if reflect.DeepEqual(*oldStatus, co.Status) {
return nil
}
buf, err := yaml.Marshal(co.Status.Conditions)
if err != nil {
buf = []byte(fmt.Sprintf("(failed to convert to YAML: %s)", err))
}
if isNotFound {
if err := status.client.ClientFor("").CRClient().Create(context.TODO(), co); err != nil {
return err
}
log.Printf("ClusterOperator config: %s created with conditions:\n%s", co.Name, buf)
return nil
}
if err := status.client.ClientFor("").CRClient().Status().Update(context.TODO(), co); err != nil {
return err
}
log.Printf("ClusterOperator config status updated with conditions:\n%s", buf)
return nil
})
if err != nil {
log.Printf("Failed to set ClusterOperator: %v", err)
}
status.writeHypershiftStatus(operStatus)
}
// syncDegraded syncs the current Degraded status
func (status *StatusManager) syncDegraded() {
for _, c := range status.failing {
if c != nil && c.Type == operv1.OperatorStatusTypeDegraded {
status.set(false, *c)
return
}
}
status.set(
false,
operv1.OperatorCondition{
Type: operv1.OperatorStatusTypeDegraded,
Status: operv1.ConditionFalse,
},
)
}
func (status *StatusManager) setDegraded(statusLevel StatusLevel, reason, message string) {
status.failing[statusLevel] = &operv1.OperatorCondition{
Type: operv1.OperatorStatusTypeDegraded,
Status: operv1.ConditionTrue,
Reason: reason,
Message: message,
}
status.syncDegraded()
}
func (status *StatusManager) setNotDegraded(statusLevel StatusLevel) {
if status.failing[statusLevel] != nil {
status.failing[statusLevel] = nil
}
status.syncDegraded()
}
func (status *StatusManager) SetDegraded(statusLevel StatusLevel, reason, message string) {
status.Lock()
defer status.Unlock()
status.setDegraded(statusLevel, reason, message)
}
func (status *StatusManager) SetDegradedOnPanicAndCrash(panicVal interface{}) {
status.Lock()
defer status.Unlock()
status.setDegraded(PanicLevel, "ReconcileError", fmt.Sprintf("Panic detected: %v", panicVal))
panic(panicVal)
}
func (status *StatusManager) SetNotDegraded(statusLevel StatusLevel) {
status.Lock()
defer status.Unlock()
status.setNotDegraded(statusLevel)
}
// syncProgressing syncs the current Progressing status
func (status *StatusManager) syncProgressing() {
for _, c := range status.failing {
if c != nil && c.Type == operv1.OperatorStatusTypeProgressing {
status.set(false, *c)
return
}
}
status.set(
false,
operv1.OperatorCondition{
Type: operv1.OperatorStatusTypeProgressing,
Status: operv1.ConditionFalse,
},
)
}
func (status *StatusManager) setProgressing(statusLevel StatusLevel, reason, message string) {
status.failing[statusLevel] = &operv1.OperatorCondition{
Type: operv1.OperatorStatusTypeProgressing,
Status: operv1.ConditionTrue,
Reason: reason,
Message: message,
}
status.syncProgressing()
}
func (status *StatusManager) unsetProgressing(statusLevel StatusLevel) {
if status.failing[statusLevel] != nil {
status.failing[statusLevel] = nil
}
status.syncProgressing()
}
func (status *StatusManager) SetProgressing(statusLevel StatusLevel, reason, message string) {
status.Lock()
defer status.Unlock()
status.setProgressing(statusLevel, reason, message)
}
func (status *StatusManager) UnsetProgressing(statusLevel StatusLevel) {
status.Lock()
defer status.Unlock()
status.unsetProgressing(statusLevel)
}
func (status *StatusManager) SetRelatedObjects(relatedObjects []configv1.ObjectReference) {
status.Lock()
defer status.Unlock()
status.relatedObjects = relatedObjects
}
func (status *StatusManager) SetRelatedClusterObjects(relatedObjects []hypershift.RelatedObject) {
status.Lock()
defer status.Unlock()
status.hyperShiftConfig.RelatedObjects = relatedObjects
}