Skip to content

Commit 744f7e5

Browse files
authored
feat: add ClusterStagedUpdateRun controller and handle deletion (#951)
add ClusterStagedUpdateRun controller and handle deletion
1 parent 85ab438 commit 744f7e5

File tree

8 files changed

+694
-25
lines changed

8 files changed

+694
-25
lines changed

apis/placement/v1alpha1/common.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,23 @@ const (
1414

1515
// ResourceOverrideSnapshotKind is the kind of the ResourceOverrideSnapshotKind.
1616
ResourceOverrideSnapshotKind = "ResourceOverrideSnapshot"
17+
18+
// ClusterStagedUpdateRunFinalizer is used by the ClusterStagedUpdateRun controller to make sure that the ClusterStagedUpdateRun
19+
// object is not deleted until all its dependent resources are deleted.
20+
ClusterStagedUpdateRunFinalizer = fleetPrefix + "stagedupdaterun-finalizer"
21+
22+
// TargetUpdateRunLabel indicates the target update run on a staged run related object.
23+
TargetUpdateRunLabel = fleetPrefix + "targetupdaterun"
24+
25+
// UpdateRunDeleteStageName is the name of delete stage in the staged update run.
26+
UpdateRunDeleteStageName = fleetPrefix + "deleteStage"
27+
28+
// IsLatestUpdateRunApprovalLabel indicates if the approval is the latest approval on a staged run.
29+
IsLatestUpdateRunApprovalLabel = fleetPrefix + "isLatestUpdateRunApproval"
30+
31+
// TargetUpdatingStageNameLabel indicates the updating stage name on a staged run related object.
32+
TargetUpdatingStageNameLabel = fleetPrefix + "targetUpdatingStage"
33+
34+
// ApprovalTaskNameFmt is the format of the approval task name.
35+
ApprovalTaskNameFmt = "%s-%s"
1736
)

apis/placement/v1beta1/commons.go

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,25 @@ Licensed under the MIT license.
66
package v1beta1
77

88
const (
9-
ClusterResourcePlacementKind = "ClusterResourcePlacement"
10-
ClusterResourcePlacementResource = "clusterresourceplacements"
11-
ClusterResourceBindingKind = "ClusterResourceBinding"
12-
ClusterResourceSnapshotKind = "ClusterResourceSnapshot"
9+
// ClusterResourcePlacementKind represents the kind of ClusterResourcePlacement.
10+
ClusterResourcePlacementKind = "ClusterResourcePlacement"
11+
// ClusterResourcePlacementResource represents the resource name for ClusterResourcePlacement.
12+
ClusterResourcePlacementResource = "clusterresourceplacements"
13+
// ClusterResourceBindingKind represents the kind of ClusterResourceBinding.
14+
ClusterResourceBindingKind = "ClusterResourceBinding"
15+
// ClusterResourceSnapshotKind represents the kind of ClusterResourceSnapshot.
16+
ClusterResourceSnapshotKind = "ClusterResourceSnapshot"
17+
// ClusterSchedulingPolicySnapshotKind represents the kind of ClusterSchedulingPolicySnapshot.
1318
ClusterSchedulingPolicySnapshotKind = "ClusterSchedulingPolicySnapshot"
14-
WorkKind = "Work"
15-
AppliedWorkKind = "AppliedWork"
19+
// WorkKind represents the kind of Work.
20+
WorkKind = "Work"
21+
// AppliedWorkKind represents the kind of AppliedWork.
22+
AppliedWorkKind = "AppliedWork"
1623
)
1724

1825
const (
26+
// fleetPrefix is the prefix used for official fleet labels/annotations.
1927
// Unprefixed labels/annotations are reserved for end-users
20-
// we will add a kubernetes-fleet.io to designate these labels/annotations as official fleet labels/annotations.
2128
// See https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#label-selector-and-annotation-conventions
2229
fleetPrefix = "kubernetes-fleet.io/"
2330

@@ -29,25 +36,25 @@ const (
2936
// cluster.
3037
WorkFinalizer = fleetPrefix + "work-cleanup"
3138

32-
// CRPTrackingLabel is the label that points to the cluster resource policy that creates a resource binding.
39+
// CRPTrackingLabel points to the cluster resource placement that creates this resource binding.
3340
CRPTrackingLabel = fleetPrefix + "parent-CRP"
3441

35-
// IsLatestSnapshotLabel tells if the snapshot is the latest one.
42+
// IsLatestSnapshotLabel indicates if the snapshot is the latest one.
3643
IsLatestSnapshotLabel = fleetPrefix + "is-latest-snapshot"
3744

38-
// FleetResourceLabelKey is that label that indicates the resource is a fleet resource.
45+
// FleetResourceLabelKey indicates that the resource is a fleet resource.
3946
FleetResourceLabelKey = fleetPrefix + "is-fleet-resource"
4047

41-
// FirstWorkNameFmt is the format of the name of the work generated with first resource snapshot .
48+
// FirstWorkNameFmt is the format of the name of the work generated with the first resource snapshot.
4249
// The name of the first work is {crpName}-work.
4350
FirstWorkNameFmt = "%s-work"
4451

45-
// WorkNameWithSubindexFmt is the format of the name of a work generated with resource snapshot with subindex.
52+
// WorkNameWithSubindexFmt is the format of the name of a work generated with a resource snapshot with a subindex.
4653
// The name of the first work is {crpName}-{subindex}.
4754
WorkNameWithSubindexFmt = "%s-%d"
4855

49-
// WorkNameWithConfigEnvelopeFmt is the format of the name of a work generated with config envelop.
50-
// The format is {workPrefix}-configMap-uuid
56+
// WorkNameWithConfigEnvelopeFmt is the format of the name of a work generated with a config envelope.
57+
// The format is {workPrefix}-configMap-uuid.
5158
WorkNameWithConfigEnvelopeFmt = "%s-configmap-%s"
5259

5360
// ParentClusterResourceOverrideSnapshotHashAnnotation is the annotation to work that contains the hash of the parent cluster resource override snapshot list.
@@ -65,25 +72,23 @@ const (
6572
// ParentBindingLabel is the label applied to work that contains the name of the binding that generates the work.
6673
ParentBindingLabel = fleetPrefix + "parent-resource-binding"
6774

68-
// CRPGenerationAnnotation is the annotation that indicates the generation of the CRP from
69-
// which an object is derived or last updated.
75+
// CRPGenerationAnnotation indicates the generation of the CRP from which an object is derived or last updated.
7076
CRPGenerationAnnotation = fleetPrefix + "CRP-generation"
7177

72-
// EnvelopeConfigMapAnnotation is the annotation that indicates the configmap is an envelope configmap that contains resources
73-
// we need to apply to the member cluster instead of the configMap itself.
78+
// EnvelopeConfigMapAnnotation indicates the configmap is an envelope configmap containing resources we need to apply to the member cluster instead of the configMap itself.
7479
EnvelopeConfigMapAnnotation = fleetPrefix + "envelope-configmap"
7580

76-
// EnvelopeTypeLabel is the label that marks the work object as generated from an envelope object.
81+
// EnvelopeTypeLabel marks the work object as generated from an envelope object.
7782
// The value of the annotation is the type of the envelope object.
7883
EnvelopeTypeLabel = fleetPrefix + "envelope-work"
7984

80-
// EnvelopeNamespaceLabel is the label that contains the namespace of the envelope object that the work is generated from.
85+
// EnvelopeNamespaceLabel contains the namespace of the envelope object that the work is generated from.
8186
EnvelopeNamespaceLabel = fleetPrefix + "envelope-namespace"
8287

83-
// EnvelopeNameLabel is the label that contains the name of the envelope object that the work is generated from.
88+
// EnvelopeNameLabel contains the name of the envelope object that the work is generated from.
8489
EnvelopeNameLabel = fleetPrefix + "envelope-name"
8590

86-
// PreviousBindingStateAnnotation is the annotation that records the previous state of a binding.
91+
// PreviousBindingStateAnnotation records the previous state of a binding.
8792
// This is used to remember if an "unscheduled" binding was moved from a "bound" state or a "scheduled" state.
8893
PreviousBindingStateAnnotation = fleetPrefix + "previous-binding-state"
8994
)
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/*
2+
Copyright (c) Microsoft Corporation.
3+
Licensed under the MIT license.
4+
*/
5+
6+
// Package updaterun features a controller to reconcile the clusterStagedUpdateRun objects.
7+
package updaterun
8+
9+
import (
10+
"context"
11+
"fmt"
12+
"time"
13+
14+
"go.goms.io/fleet/pkg/utils"
15+
"go.goms.io/fleet/pkg/utils/controller"
16+
"k8s.io/apimachinery/pkg/types"
17+
"k8s.io/client-go/tools/record"
18+
"k8s.io/client-go/util/workqueue"
19+
"k8s.io/klog/v2"
20+
runtime "sigs.k8s.io/controller-runtime"
21+
"sigs.k8s.io/controller-runtime/pkg/builder"
22+
"sigs.k8s.io/controller-runtime/pkg/client"
23+
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
24+
"sigs.k8s.io/controller-runtime/pkg/event"
25+
"sigs.k8s.io/controller-runtime/pkg/handler"
26+
"sigs.k8s.io/controller-runtime/pkg/predicate"
27+
"sigs.k8s.io/controller-runtime/pkg/reconcile"
28+
29+
placementv1alpha1 "go.goms.io/fleet/apis/placement/v1alpha1"
30+
)
31+
32+
// Reconciler reconciles a ClusterStagedUpdateRun object.
33+
type Reconciler struct {
34+
client.Client
35+
recorder record.EventRecorder
36+
}
37+
38+
func (r *Reconciler) Reconcile(ctx context.Context, req runtime.Request) (runtime.Result, error) {
39+
startTime := time.Now()
40+
klog.V(2).InfoS("ClusterStagedUpdateRun reconciliation starts", "clusterStagedUpdateRun", req.NamespacedName)
41+
defer func() {
42+
latency := time.Since(startTime).Milliseconds()
43+
klog.V(2).InfoS("ClusterStagedUpdateRun reconciliation ends", "clusterStagedUpdateRun", req.NamespacedName, "latency", latency)
44+
}()
45+
46+
var updateRun placementv1alpha1.ClusterStagedUpdateRun
47+
if err := r.Client.Get(ctx, req.NamespacedName, &updateRun); err != nil {
48+
klog.ErrorS(err, "Failed to get clusterStagedUpdateRun object", "clusterStagedUpdateRun", req.Name)
49+
return runtime.Result{}, client.IgnoreNotFound(err)
50+
}
51+
runObjRef := klog.KObj(&updateRun)
52+
53+
// Handle the deletion of the clusterStagedUpdateRun.
54+
if !updateRun.DeletionTimestamp.IsZero() {
55+
klog.V(2).InfoS("The clusterStagedUpdateRun is being deleted", "clusterStagedUpdateRun", runObjRef)
56+
deleted, waitTime, err := r.handleDelete(ctx, updateRun.DeepCopy())
57+
if err != nil {
58+
return runtime.Result{}, err
59+
}
60+
if deleted {
61+
return runtime.Result{}, nil
62+
}
63+
return runtime.Result{RequeueAfter: waitTime}, nil
64+
}
65+
66+
// Add the finalizer to the clusterStagedUpdateRun.
67+
if err := r.ensureFinalizer(ctx, &updateRun); err != nil {
68+
klog.ErrorS(err, "Failed to add the finalizer to the clusterStagedUpdateRun", "clusterStagedUpdateRun", runObjRef)
69+
return runtime.Result{}, err
70+
}
71+
72+
// TODO(wantjian): reconcile the clusterStagedUpdateRun.
73+
return runtime.Result{}, nil
74+
}
75+
76+
// handleDelete handles the deletion of the clusterStagedUpdateRun object.
77+
// We delete all the dependent resources, including approvalRequest objects, of the clusterStagedUpdateRun object.
78+
func (r *Reconciler) handleDelete(ctx context.Context, updateRun *placementv1alpha1.ClusterStagedUpdateRun) (bool, time.Duration, error) {
79+
runObjRef := klog.KObj(updateRun)
80+
// delete all the associated approvalRequests.
81+
approvalRequest := &placementv1alpha1.ClusterApprovalRequest{}
82+
if err := r.Client.DeleteAllOf(ctx, approvalRequest, client.MatchingLabels{placementv1alpha1.TargetUpdateRunLabel: updateRun.GetName()}); err != nil {
83+
klog.ErrorS(err, "Failed to delete all associated approvalRequests", "clusterStagedUpdateRun", runObjRef)
84+
return false, 0, controller.NewAPIServerError(false, err)
85+
}
86+
klog.V(2).InfoS("Deleted all approvalRequests associated with the clusterStagedUpdateRun", "clusterStagedUpdateRun", runObjRef)
87+
controllerutil.RemoveFinalizer(updateRun, placementv1alpha1.ClusterStagedUpdateRunFinalizer)
88+
if err := r.Client.Update(ctx, updateRun); err != nil {
89+
klog.ErrorS(err, "Failed to remove updateRun finalizer", "clusterStagedUpdateRun", runObjRef)
90+
return false, 0, controller.NewUpdateIgnoreConflictError(err)
91+
}
92+
return true, 0, nil
93+
}
94+
95+
// ensureFinalizer makes sure that the ClusterStagedUpdateRun CR has a finalizer on it.
96+
func (r *Reconciler) ensureFinalizer(ctx context.Context, updateRun *placementv1alpha1.ClusterStagedUpdateRun) error {
97+
if controllerutil.ContainsFinalizer(updateRun, placementv1alpha1.ClusterStagedUpdateRunFinalizer) {
98+
return nil
99+
}
100+
klog.InfoS("Added the staged update run finalizer", "stagedUpdateRun", klog.KObj(updateRun))
101+
controllerutil.AddFinalizer(updateRun, placementv1alpha1.ClusterStagedUpdateRunFinalizer)
102+
return r.Update(ctx, updateRun, client.FieldOwner(utils.UpdateRunControllerFieldManagerName))
103+
}
104+
105+
// SetupWithManager sets up the controller with the Manager.
106+
func (r *Reconciler) SetupWithManager(mgr runtime.Manager) error {
107+
r.recorder = mgr.GetEventRecorderFor("clusterresource-stagedupdaterun-controller")
108+
return runtime.NewControllerManagedBy(mgr).
109+
Named("clusterresource-stagedupdaterun-controller").
110+
For(&placementv1alpha1.ClusterStagedUpdateRun{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})).
111+
Watches(&placementv1alpha1.ClusterApprovalRequest{}, &handler.Funcs{
112+
// We only care about when an approval request is approved.
113+
UpdateFunc: func(ctx context.Context, e event.UpdateEvent, q workqueue.RateLimitingInterface) {
114+
klog.V(2).InfoS("Handling a clusterApprovalRequest update event", "clusterApprovalRequest", klog.KObj(e.ObjectNew))
115+
handleClusterApprovalRequest(e.ObjectNew, q)
116+
},
117+
GenericFunc: func(ctx context.Context, e event.GenericEvent, q workqueue.RateLimitingInterface) {
118+
klog.V(2).InfoS("Handling a clusterApprovalRequest generic event", "clusterApprovalRequest", klog.KObj(e.Object))
119+
handleClusterApprovalRequest(e.Object, q)
120+
},
121+
}).Complete(r)
122+
}
123+
124+
// handleClusterApprovalRequest finds the ClusterStagedUpdateRun creating the ClusterApprovalRequest,
125+
// and enqueues it to the ClusterStagedUpdateRun controller queue.
126+
func handleClusterApprovalRequest(obj client.Object, q workqueue.RateLimitingInterface) {
127+
approvalRequest, ok := obj.(*placementv1alpha1.ClusterApprovalRequest)
128+
if !ok {
129+
klog.V(2).ErrorS(controller.NewUnexpectedBehaviorError(fmt.Errorf("cannot cast runtime object to ClusterApprovalRequest")),
130+
"Invalid object type", "object", klog.KObj(obj))
131+
return
132+
}
133+
updateRun := approvalRequest.Spec.TargetUpdateRun
134+
if len(updateRun) == 0 {
135+
klog.V(2).ErrorS(controller.NewUnexpectedBehaviorError(fmt.Errorf("TargetUpdateRun field in ClusterApprovalRequest is empty")),
136+
"Invalid clusterApprovalRequest", "clusterApprovalRequest", klog.KObj(approvalRequest))
137+
return
138+
}
139+
// enqueue to the updaterun controller queue.
140+
q.Add(reconcile.Request{
141+
NamespacedName: types.NamespacedName{Name: updateRun},
142+
})
143+
}

0 commit comments

Comments
 (0)