diff --git a/.github/.copilot/breadcrumbs/2026-10-28-0840-staticcheck-go1.26.md b/.github/.copilot/breadcrumbs/2026-10-28-0840-staticcheck-go1.26.md new file mode 100644 index 000000000..555f77ace --- /dev/null +++ b/.github/.copilot/breadcrumbs/2026-10-28-0840-staticcheck-go1.26.md @@ -0,0 +1,31 @@ +# Go 1.26 Staticcheck Prerequisite + +**Date**: October 28, 2026 +**Task**: Upgrade Staticcheck and resolve warnings before stacking the Go-fix PR. +**Status**: Implemented and validated; ready for the prerequisite PR. + +## Plan and Decisions + +1. Upgrade standalone Staticcheck from v0.6.1 to v0.8.2, which supports Go 1.26. +2. Resolve the 22 warnings exposed on the unchanged baseline. +3. Use `RequeueAfter` instead of deprecated `Requeue`, retaining positive wait + times and using a one-second fallback otherwise. The user approved this + explicit change from rate-limited retries to fixed-delay retries. +4. Correct the two embedded RawExtension JSON tags without changing their + existing JSON representation. +5. Keep intentional SelfLink sanitization fixtures with narrow documented + deprecation exceptions. +6. Validate, sign off the commit, and open the prerequisite PR against `main`. +7. Stack the automated Go-fix PR on this branch. + +## Progress + +- Confirmed all 22 warnings on a clean worktree based on `origin/main`. +- Kept this work separate from the automated Go-fix changes. +- Updated all affected retry assertions and added focused tests for zero, + negative, and positive waits, plus normal error retry behavior. +- `make reviewable` passed with the pinned tools shared from the Go-fix worktree. +- Race-enabled unit tests passed for the seven affected controller/helper + packages; the member-cluster integration suite also passed. +- `make manifests` produced no CRD changes after correcting the JSON tags. +- Excluded unrelated generated import-alias normalization from the commit. diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 4bafc0a80..f94f440d8 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden Runner - uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 13e1a7526..9692630b9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -87,7 +87,7 @@ jobs: ref: ${{ needs.setup.outputs.tag }} - name: Login to ghcr.io - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -187,7 +187,7 @@ jobs: ref: ${{ needs.setup.outputs.tag }} - name: Login to GitHub Container Registry - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -252,7 +252,7 @@ jobs: # follow-up issue). Auditing egress at least records what it reaches out # to until that action is replaced. - name: Harden Runner - uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit diff --git a/.github/workflows/trivy.yml b/.github/workflows/trivy.yml index cb897bfc3..26aa4b05f 100644 --- a/.github/workflows/trivy.yml +++ b/.github/workflows/trivy.yml @@ -50,7 +50,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Login to ${{ env.REGISTRY }} - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} diff --git a/.github/workflows/workflow-lint.yml b/.github/workflows/workflow-lint.yml index 6224c65cd..829a63667 100644 --- a/.github/workflows/workflow-lint.yml +++ b/.github/workflows/workflow-lint.yml @@ -24,7 +24,7 @@ jobs: timeout-minutes: 10 steps: - name: Harden Runner - uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit diff --git a/Makefile b/Makefile index 6f51cef71..3c946aa0b 100644 --- a/Makefile +++ b/Makefile @@ -69,7 +69,7 @@ CONTROLLER_GEN_VER := v0.20.0 CONTROLLER_GEN_BIN := controller-gen CONTROLLER_GEN := $(abspath $(TOOLS_BIN_DIR)/$(CONTROLLER_GEN_BIN)-$(CONTROLLER_GEN_VER)) -STATICCHECK_VER := v0.6.1 +STATICCHECK_VER := v0.8.2 STATICCHECK_BIN := staticcheck STATICCHECK := $(abspath $(TOOLS_BIN_DIR)/$(STATICCHECK_BIN)-$(STATICCHECK_VER)) diff --git a/apis/cluster/v1beta1/zz_generated.deepcopy.go b/apis/cluster/v1beta1/zz_generated.deepcopy.go index a51641c3f..cec52aa39 100644 --- a/apis/cluster/v1beta1/zz_generated.deepcopy.go +++ b/apis/cluster/v1beta1/zz_generated.deepcopy.go @@ -21,7 +21,7 @@ limitations under the License. package v1beta1 import ( - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) diff --git a/apis/kubefleet.dev/placement/v1alpha1/zz_generated.deepcopy.go b/apis/kubefleet.dev/placement/v1alpha1/zz_generated.deepcopy.go index 708652d46..eebe65e22 100644 --- a/apis/kubefleet.dev/placement/v1alpha1/zz_generated.deepcopy.go +++ b/apis/kubefleet.dev/placement/v1alpha1/zz_generated.deepcopy.go @@ -21,7 +21,7 @@ limitations under the License. package v1alpha1 import ( - "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" ) diff --git a/apis/kubefleet.dev/rollout/v1alpha1/zz_generated.deepcopy.go b/apis/kubefleet.dev/rollout/v1alpha1/zz_generated.deepcopy.go index 6d24d80f6..c159aaede 100644 --- a/apis/kubefleet.dev/rollout/v1alpha1/zz_generated.deepcopy.go +++ b/apis/kubefleet.dev/rollout/v1alpha1/zz_generated.deepcopy.go @@ -21,7 +21,7 @@ limitations under the License. package v1alpha1 import ( - "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" ) diff --git a/apis/placement/v1/resourcesnapshot_types.go b/apis/placement/v1/resourcesnapshot_types.go index 3a625cc94..bb61a8096 100644 --- a/apis/placement/v1/resourcesnapshot_types.go +++ b/apis/placement/v1/resourcesnapshot_types.go @@ -80,7 +80,7 @@ type ResourceSnapshotSpec struct { type ResourceContent struct { // +kubebuilder:validation:EmbeddedResource // +kubebuilder:pruning:PreserveUnknownFields - runtime.RawExtension `json:"-,inline"` + runtime.RawExtension `json:",inline"` } type ResourceSnapshotStatus struct { diff --git a/apis/placement/v1alpha1/zz_generated.deepcopy.go b/apis/placement/v1alpha1/zz_generated.deepcopy.go index 086e1ff64..ec4b45d86 100644 --- a/apis/placement/v1alpha1/zz_generated.deepcopy.go +++ b/apis/placement/v1alpha1/zz_generated.deepcopy.go @@ -21,10 +21,11 @@ limitations under the License. package v1alpha1 import ( - "go.goms.io/fleet/apis/placement/v1beta1" - "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" + + "go.goms.io/fleet/apis/placement/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. diff --git a/apis/placement/v1beta1/resourcesnapshot_types.go b/apis/placement/v1beta1/resourcesnapshot_types.go index c5d616eb6..5d64b6d0e 100644 --- a/apis/placement/v1beta1/resourcesnapshot_types.go +++ b/apis/placement/v1beta1/resourcesnapshot_types.go @@ -151,7 +151,7 @@ type ResourceSnapshotSpec struct { type ResourceContent struct { // +kubebuilder:validation:EmbeddedResource // +kubebuilder:pruning:PreserveUnknownFields - runtime.RawExtension `json:"-,inline"` + runtime.RawExtension `json:",inline"` } type ResourceSnapshotStatus struct { diff --git a/apis/placement/v1beta1/zz_generated.deepcopy.go b/apis/placement/v1beta1/zz_generated.deepcopy.go index 3561518d1..ae74b5326 100644 --- a/apis/placement/v1beta1/zz_generated.deepcopy.go +++ b/apis/placement/v1beta1/zz_generated.deepcopy.go @@ -21,7 +21,7 @@ limitations under the License. package v1beta1 import ( - "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" ) diff --git a/apis/protos/azure/compute/v1/vmsizerecommender.pb.go b/apis/protos/azure/compute/v1/vmsizerecommender.pb.go index 543b75155..243b11763 100644 --- a/apis/protos/azure/compute/v1/vmsizerecommender.pb.go +++ b/apis/protos/azure/compute/v1/vmsizerecommender.pb.go @@ -11,11 +11,12 @@ package v1 import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" + + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) const ( diff --git a/apis/protos/azure/compute/v1/vmsizerecommender_grpc.pb.go b/apis/protos/azure/compute/v1/vmsizerecommender_grpc.pb.go index 9d00f1924..b3205246b 100644 --- a/apis/protos/azure/compute/v1/vmsizerecommender_grpc.pb.go +++ b/apis/protos/azure/compute/v1/vmsizerecommender_grpc.pb.go @@ -12,6 +12,7 @@ package v1 import ( context "context" + grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" diff --git a/charts/member-agent/templates/deployment.yaml b/charts/member-agent/templates/deployment.yaml index c6d43051a..b268e703a 100644 --- a/charts/member-agent/templates/deployment.yaml +++ b/charts/member-agent/templates/deployment.yaml @@ -15,6 +15,7 @@ metadata: labels: {{- include "member-agent.labels" . | nindent 4 }} spec: + replicas: {{ .Values.replicaCount }} selector: matchLabels: {{- include "member-agent.selectorLabels" . | nindent 6 }} diff --git a/pkg/admissionpolicymanager/manager_integration_test.go b/pkg/admissionpolicymanager/manager_integration_test.go index d0a8acab2..153df4fb0 100644 --- a/pkg/admissionpolicymanager/manager_integration_test.go +++ b/pkg/admissionpolicymanager/manager_integration_test.go @@ -167,7 +167,7 @@ var _ = Describe("Policies, Policy Bindings and their Effects", Ordered, func() Validations: []admissionregistrationv1.Validation{ { Expression: `(!((request.namespace.startsWith("fleet-")) || (request.namespace.startsWith("kube-")))) || ((request.userInfo.username == "system:kube-scheduler") || (request.userInfo.username == "system:kube-controller-manager") || ("system:nodes" in request.userInfo.groups) || ("system:masters" in request.userInfo.groups) || ("kubeadm:cluster-admins" in request.userInfo.groups) || ("system:serviceaccounts" in request.userInfo.groups) || (request.userInfo.username == "whitelisted-user") || ("whitelisted-group" in request.userInfo.groups))`, - Message: "writing service accounts in reserved namespaces or requesting tokens from such service accounts is disallowed", + Message: wantSvcAccountsAndTokenRequestsDenialMsg, Reason: ptr.To(metav1.StatusReasonForbidden), }, }, diff --git a/pkg/controllers/bindingwatcher/suite_test.go b/pkg/controllers/bindingwatcher/suite_test.go index 95afb27db..3aebbc393 100644 --- a/pkg/controllers/bindingwatcher/suite_test.go +++ b/pkg/controllers/bindingwatcher/suite_test.go @@ -18,6 +18,7 @@ package bindingwatcher import ( "context" "flag" + "fmt" "path/filepath" "testing" "time" @@ -37,6 +38,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/metrics/server" fleetv1beta1 "go.goms.io/fleet/apis/placement/v1beta1" + utilcontroller "go.goms.io/fleet/pkg/utils/controller" "go.goms.io/fleet/test/utils/controller" ) @@ -92,9 +94,6 @@ var _ = BeforeSuite(func() { Expect(k8sClient.Create(ctx, &ns)).Should(Succeed(), "failed to create namespace") By("starting the controller manager") - klog.InitFlags(flag.CommandLine) - flag.Parse() - mgr, err = ctrl.NewManager(cfg, ctrl.Options{ Scheme: scheme.Scheme, Metrics: server.Options{ @@ -120,19 +119,51 @@ var _ = BeforeSuite(func() { go func() { defer GinkgoRecover() - err = mgr.Start(ctx) - Expect(err).Should(Succeed(), "failed to run manager") + Expect(mgr.Start(ctx)).Should(Succeed(), "failed to run manager") }() - // Note (chenyu1): for the binding watcher integration tests, must wait for the cache to sync - // before moving onto the test stage, otherwise some Update events might not be caught properly. - // - // This is wrapped in an Eventually block as the manager might not have started yet. - Eventually(func() bool { - return mgr.GetCache().WaitForCacheSync(ctx) - }, time.Second*10, time.Second*2).To(BeTrue(), "failed to wait for cache to sync") + // Waiting for the cache to sync is not enough: the watchers register their event handlers only when their + // controllers start, which can be after the specs begin. A status update made before then reaches them as part + // of a create event, which they ignore, so wait until both watchers act on a status update. + By("waiting for the watchers to handle status updates") + crb := clusterResourceBindingForTest() + crb.Name = "probe-crb" + waitForWatcher(crb, testPlacementName) + rb := resourceBindingForTest() + rb.Name = "probe-rb" + waitForWatcher(rb, utilcontroller.GetObjectKeyFromNamespaceName(testNamespace, testPlacementName)) }) +// waitForWatcher creates the binding and keeps updating its status until the placement controller receives +// wantKey, then deletes the binding and resets the queue. +func waitForWatcher(binding fleetv1beta1.BindingObj, wantKey string) { + Expect(k8sClient.Create(ctx, binding)).Should(Succeed(), "failed to create the probe binding") + attempt := 0 + Eventually(func() error { + // Check before updating again, so that no update is left in flight once the key arrives. + if fakePlacementController.Key() == wantKey { + return nil + } + attempt++ + if err := k8sClient.Get(ctx, client.ObjectKeyFromObject(binding), binding); err != nil { + return err + } + binding.SetConditions(metav1.Condition{ + Type: string(fleetv1beta1.ResourceBindingRolloutStarted), + Status: metav1.ConditionTrue, + Reason: fmt.Sprintf("Probe%d", attempt), + ObservedGeneration: binding.GetGeneration(), + LastTransitionTime: metav1.Now(), + }) + if err := k8sClient.Status().Update(ctx, binding); err != nil { + return err + } + return fmt.Errorf("the watcher has not enqueued %s yet", wantKey) + }, time.Second*30, time.Second).Should(Succeed(), "the watcher did not act on a status update for %s", wantKey) + Expect(k8sClient.Delete(ctx, binding)).Should(Succeed(), "failed to delete the probe binding") + fakePlacementController.ResetQueue() +} + var _ = AfterSuite(func() { defer klog.Flush() diff --git a/pkg/controllers/membercluster/v1beta1/membercluster_controller.go b/pkg/controllers/membercluster/v1beta1/membercluster_controller.go index 14924e5f2..ca1c7ec96 100644 --- a/pkg/controllers/membercluster/v1beta1/membercluster_controller.go +++ b/pkg/controllers/membercluster/v1beta1/membercluster_controller.go @@ -177,7 +177,7 @@ func (r *Reconciler) handleDelete(ctx context.Context, mc *clusterv1beta1.Member } // this is possible since we garbage collect the internal member cluster first before deleting the MC klog.V(2).Info("InternalMemberCluster not found, start garbage collecting", "memberCluster", mcObjRef) - return runtime.Result{Requeue: true}, r.garbageCollect(ctx, mc) + return runtime.Result{RequeueAfter: time.Second}, r.garbageCollect(ctx, mc) } // calculate the current status of the member cluster from imc status r.syncInternalMemberClusterStatus(currentImc, mc) @@ -188,12 +188,12 @@ func (r *Reconciler) handleDelete(ctx context.Context, mc *clusterv1beta1.Member if gcErr := r.garbageCollect(ctx, mc); gcErr != nil { return runtime.Result{}, gcErr } - return runtime.Result{Requeue: true}, controller.NewUpdateIgnoreConflictError(r.updateMemberClusterStatus(ctx, mc)) + return runtime.Result{RequeueAfter: time.Second}, controller.NewUpdateIgnoreConflictError(r.updateMemberClusterStatus(ctx, mc)) } // check to see if we can force delete member cluster. if currentImc.Spec.State == clusterv1beta1.ClusterStateLeave && time.Since(mc.DeletionTimestamp.Time) >= r.ForceDeleteWaitTime { klog.V(2).InfoS("Force delete the member cluster, by garbage collecting owned resources", "memberCluster", mcObjRef) - return runtime.Result{Requeue: true}, r.garbageCollect(ctx, mc) + return runtime.Result{RequeueAfter: time.Second}, r.garbageCollect(ctx, mc) } klog.V(2).InfoS("Need to wait for the agent to leave", "memberCluster", mcObjRef, "joinedCondition", mcJoinedCondition) // mark the imc as left to make sure the agent is leaving the fleet diff --git a/pkg/controllers/membercluster/v1beta1/membercluster_controller_integration_test.go b/pkg/controllers/membercluster/v1beta1/membercluster_controller_integration_test.go index d39bb7fb6..680732675 100644 --- a/pkg/controllers/membercluster/v1beta1/membercluster_controller_integration_test.go +++ b/pkg/controllers/membercluster/v1beta1/membercluster_controller_integration_test.go @@ -210,7 +210,7 @@ var _ = Describe("Test MemberCluster Controller", func() { result, err = r.Reconcile(ctx, ctrl.Request{ NamespacedName: memberClusterNamespacedName, }) - Expect(result).Should(Equal(ctrl.Result{Requeue: true})) + Expect(result).Should(Equal(ctrl.Result{RequeueAfter: time.Second})) Expect(err).Should(Succeed()) By("verify mc joined status is set to be false") @@ -282,7 +282,7 @@ var _ = Describe("Test MemberCluster Controller", func() { result, err = r.Reconcile(ctx, ctrl.Request{ NamespacedName: memberClusterNamespacedName, }) - Expect(result).Should(Equal(ctrl.Result{Requeue: true})) + Expect(result).Should(Equal(ctrl.Result{RequeueAfter: time.Second})) Expect(err).Should(Succeed()) By("check the workers objects don't have finalizer") @@ -583,7 +583,7 @@ var _ = Describe("Test MemberCluster Controller", func() { result, err = r.Reconcile(ctx, ctrl.Request{ NamespacedName: memberClusterNamespacedName, }) - Expect(result).Should(Equal(ctrl.Result{Requeue: true})) + Expect(result).Should(Equal(ctrl.Result{RequeueAfter: time.Second})) Expect(err).Should(Succeed()) // check the cluster namespace is being deleted. There is no namespace controller so it won't be removed @@ -704,7 +704,7 @@ var _ = Describe("Test MemberCluster Controller", func() { result, err = r.Reconcile(ctx, ctrl.Request{ NamespacedName: memberClusterNamespacedName, }) - Expect(result).Should(Equal(ctrl.Result{Requeue: true})) + Expect(result).Should(Equal(ctrl.Result{RequeueAfter: time.Second})) Expect(err).Should(Succeed()) // check the member cluster namespace is being deleted. There is no namespace controller, so it won't be removed diff --git a/pkg/controllers/membercluster/v1beta1/membercluster_controller_test.go b/pkg/controllers/membercluster/v1beta1/membercluster_controller_test.go index 58e97c370..5b1399106 100644 --- a/pkg/controllers/membercluster/v1beta1/membercluster_controller_test.go +++ b/pkg/controllers/membercluster/v1beta1/membercluster_controller_test.go @@ -2153,7 +2153,7 @@ func TestHandleDelete(t *testing.T) { recorder: events.NewFakeRecorder(1), }, memberCluster: memberClusterWithFinalizer.DeepCopy(), - wantResult: ctrl.Result{Requeue: true}, + wantResult: ctrl.Result{RequeueAfter: time.Second}, wantErr: nil, }, } diff --git a/pkg/controllers/rollout/controller.go b/pkg/controllers/rollout/controller.go index 00e8aaf6a..962be04ea 100644 --- a/pkg/controllers/rollout/controller.go +++ b/pkg/controllers/rollout/controller.go @@ -128,7 +128,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req runtime.Request) (runtim // Note that work generator will skip processing bindings with stale // RolloutStarted conditions. klog.V(2).InfoS("Apply strategy has been updated; requeue the request", "placement", placementObjRef) - return reconcile.Result{Requeue: true}, nil + return reconcile.Result{RequeueAfter: time.Second}, nil default: klog.V(2).InfoS("Apply strategy is up to date on all bindings; continue with the rollout process", "placement", placementObjRef) } @@ -223,7 +223,10 @@ func (r *Reconciler) Reconcile(ctx context.Context, req runtime.Request) (runtim // We need to requeue the request regardless if the binding updates succeed or not // to avoid the case that the rollout process stalling because the time based binding readiness does not trigger any event. // Wait the time we need to wait for the first applied but not ready binding to be ready - return runtime.Result{Requeue: true, RequeueAfter: waitTime}, r.updateBindings(ctx, toBeUpdatedBindings) + if waitTime <= 0 { + waitTime = time.Second + } + return runtime.Result{RequeueAfter: waitTime}, r.updateBindings(ctx, toBeUpdatedBindings) } func (r *Reconciler) checkAndUpdateStaleBindingsStatus(ctx context.Context, bindings []placementv1beta1.BindingObj) error { diff --git a/pkg/controllers/updaterun/controller.go b/pkg/controllers/updaterun/controller.go index 33f3650a8..2590e64ec 100644 --- a/pkg/controllers/updaterun/controller.go +++ b/pkg/controllers/updaterun/controller.go @@ -222,7 +222,10 @@ func (r *Reconciler) handleIncompleteUpdateRun(ctx context.Context, updateRun pl if err != nil { return runtime.Result{}, err } - return runtime.Result{Requeue: true, RequeueAfter: waitTime}, nil + if waitTime <= 0 { + waitTime = time.Second + } + return runtime.Result{RequeueAfter: waitTime}, nil } // handleDelete handles the deletion of the updateRun object. diff --git a/pkg/controllers/updaterun/controller_test.go b/pkg/controllers/updaterun/controller_test.go index 390a13fbb..2ac9b439c 100644 --- a/pkg/controllers/updaterun/controller_test.go +++ b/pkg/controllers/updaterun/controller_test.go @@ -17,19 +17,75 @@ limitations under the License. package updaterun import ( + "errors" "testing" "time" "github.com/google/go-cmp/cmp" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/util/workqueue" + "k8s.io/klog/v2" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/controller/controllertest" "sigs.k8s.io/controller-runtime/pkg/reconcile" placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1" ) +func TestHandleIncompleteUpdateRun(t *testing.T) { + reconcileErr := errors.New("execution failed") + tests := []struct { + name string + waitTime time.Duration + err error + wantResult reconcile.Result + }{ + { + name: "zero wait time uses fallback", + wantResult: reconcile.Result{RequeueAfter: time.Second}, + }, + { + name: "negative wait time uses fallback", + waitTime: -time.Second, + wantResult: reconcile.Result{RequeueAfter: time.Second}, + }, + { + name: "positive wait time is preserved", + waitTime: 100 * time.Millisecond, + wantResult: reconcile.Result{RequeueAfter: 100 * time.Millisecond}, + }, + { + name: "execution errors use normal error retries", + err: reconcileErr, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + scheme := runtime.NewScheme() + if err := placementv1beta1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + updateRun := &placementv1beta1.ClusterStagedUpdateRun{ + ObjectMeta: metav1.ObjectMeta{Name: "test-update-run"}, + } + r := &Reconciler{ + Client: fake.NewClientBuilder().WithScheme(scheme). + WithStatusSubresource(updateRun).WithObjects(updateRun).Build(), + } + got, err := r.handleIncompleteUpdateRun(t.Context(), updateRun, tt.waitTime, tt.err, + placementv1beta1.StateRun, klog.KObj(updateRun)) + if !errors.Is(err, tt.err) { + t.Fatalf("handleIncompleteUpdateRun() error = %v, want %v", err, tt.err) + } + if diff := cmp.Diff(tt.wantResult, got); diff != "" { + t.Errorf("handleIncompleteUpdateRun() mismatch (-want +got):\n%s", diff) + } + }) + } +} + func TestHandleApprovalRequestUpdate(t *testing.T) { tests := map[string]struct { oldObj client.Object diff --git a/pkg/controllers/updaterun/initialization.go b/pkg/controllers/updaterun/initialization.go index c71c67eab..ba3482822 100644 --- a/pkg/controllers/updaterun/initialization.go +++ b/pkg/controllers/updaterun/initialization.go @@ -508,7 +508,6 @@ func validateAfterStageTask(tasks []placementv1beta1.StageTask) error { // recordOverrideSnapshots finds all the override snapshots that are associated with each cluster and record them in the UpdateRun status. func (r *Reconciler) recordOverrideSnapshots(ctx context.Context, placement placementv1beta1.PlacementObj, updateRun placementv1beta1.UpdateRunObj) error { updateRunRef := klog.KObj(updateRun) - updateRunSpec := updateRun.GetUpdateRunSpec() placementKey := types.NamespacedName{Name: placement.GetName(), Namespace: placement.GetNamespace()} resourceSnapshotObjs, err := r.getResourceSnapshotObjs(ctx, placement, updateRun) @@ -543,7 +542,7 @@ func (r *Reconciler) recordOverrideSnapshots(ctx context.Context, placement plac resourceSnapshotRef := klog.KObj(masterResourceSnapshot) // Fetch all the matching overrides. - matchedCRO, matchedRO, err := overrider.FetchAllMatchingOverridesForResourceSnapshot(ctx, r.Client, r.InformerManager, updateRunSpec.PlacementName, masterResourceSnapshot) + matchedCRO, matchedRO, err := overrider.FetchAllMatchingOverridesForResourceSnapshot(ctx, r.Client, r.InformerManager, controller.GetObjectKeyFromNamespaceName(placementKey.Namespace, placementKey.Name), masterResourceSnapshot) if err != nil { klog.ErrorS(err, "Failed to find all matching overrides for the stagedUpdateRun", "resourceSnapshot", resourceSnapshotRef, "updateRun", updateRunRef) // no more retries here. diff --git a/pkg/controllers/updaterun/initialization_test.go b/pkg/controllers/updaterun/initialization_test.go index a72ea12d8..b072ee661 100644 --- a/pkg/controllers/updaterun/initialization_test.go +++ b/pkg/controllers/updaterun/initialization_test.go @@ -24,12 +24,18 @@ import ( "testing" "time" + "github.com/google/go-cmp/cmp" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + clusterv1beta1 "go.goms.io/fleet/apis/cluster/v1beta1" placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1" + testinformer "go.goms.io/fleet/test/utils/informer" + "go.goms.io/fleet/test/utils/resource" ) func TestValidateBeforeStageTask(t *testing.T) { @@ -205,3 +211,114 @@ func TestGenerateStagesByStrategy_InvalidDeleteStageTasks(t *testing.T) { t.Errorf("generateStagesByStrategy() error = %v, want an error containing %q", err, wantErrMsg) } } + +func TestRecordOverrideSnapshots(t *testing.T) { + const ( + placementName = "test-placement" + namespace = "deployment-namespace" + clusterName = "cluster-1" + roName = "test-ro-0" + ) + scheme := runtime.NewScheme() + if err := placementv1beta1.AddToScheme(scheme); err != nil { + t.Fatalf("AddToScheme() = %v, want no error", err) + } + if err := clusterv1beta1.AddToScheme(scheme); err != nil { + t.Fatalf("AddToScheme() = %v, want no error", err) + } + snapshotMeta := func(ns string) metav1.ObjectMeta { + return metav1.ObjectMeta{ + Name: fmt.Sprintf(placementv1beta1.ResourceSnapshotNameFmt, placementName, 0), + Namespace: ns, + Labels: map[string]string{ + placementv1beta1.ResourceIndexLabel: "0", + placementv1beta1.PlacementTrackingLabel: placementName, + }, + Annotations: map[string]string{ + placementv1beta1.ResourceGroupHashAnnotation: "abc", + placementv1beta1.NumberOfResourceSnapshotsAnnotation: "1", + }, + } + } + snapshotSpec := placementv1beta1.ResourceSnapshotSpec{ + SelectedResources: []placementv1beta1.ResourceContent{*resource.DeploymentResourceContentForTest(t)}, + } + roSnapshot := func(scope placementv1beta1.ResourceScope) *placementv1beta1.ResourceOverrideSnapshot { + return &placementv1beta1.ResourceOverrideSnapshot{ + ObjectMeta: metav1.ObjectMeta{ + Name: roName, + Namespace: namespace, + Labels: map[string]string{placementv1beta1.IsLatestSnapshotLabel: "true"}, + }, + Spec: placementv1beta1.ResourceOverrideSnapshotSpec{ + OverrideSpec: placementv1beta1.ResourceOverrideSpec{ + Placement: &placementv1beta1.PlacementRef{Name: placementName, Scope: scope}, + ResourceSelectors: []placementv1beta1.ResourceSelector{ + {Group: "apps", Version: "v1", Kind: "Deployment", Name: "deployment-name"}, + }, + Policy: &placementv1beta1.OverridePolicy{ + OverrideRules: []placementv1beta1.OverrideRule{ + {ClusterSelector: &placementv1beta1.ClusterSelector{}}, + }, + }, + }, + }, + } + } + updateRunStatus := placementv1beta1.UpdateRunStatus{ + StagesStatus: []placementv1beta1.StageUpdatingStatus{ + {StageName: "stage-1", Clusters: []placementv1beta1.ClusterUpdatingStatus{{ClusterName: clusterName}}}, + }, + } + updateRunSpec := placementv1beta1.UpdateRunSpec{PlacementName: placementName, ResourceSnapshotIndex: "0"} + + tests := []struct { + name string + placement placementv1beta1.PlacementObj + snapshot client.Object + ro *placementv1beta1.ResourceOverrideSnapshot + updateRun placementv1beta1.UpdateRunObj + }{ + { + name: "cluster-scoped placement", + placement: &placementv1beta1.ClusterResourcePlacement{ObjectMeta: metav1.ObjectMeta{Name: placementName}}, + snapshot: &placementv1beta1.ClusterResourceSnapshot{ObjectMeta: snapshotMeta(""), Spec: snapshotSpec}, + ro: roSnapshot(placementv1beta1.ClusterScoped), + updateRun: &placementv1beta1.ClusterStagedUpdateRun{ + ObjectMeta: metav1.ObjectMeta{Name: "test-update-run"}, + Spec: updateRunSpec, + Status: *updateRunStatus.DeepCopy(), + }, + }, + { + name: "namespaced placement", + placement: &placementv1beta1.ResourcePlacement{ObjectMeta: metav1.ObjectMeta{Name: placementName, Namespace: namespace}}, + snapshot: &placementv1beta1.ResourceSnapshot{ObjectMeta: snapshotMeta(namespace), Spec: snapshotSpec}, + ro: roSnapshot(placementv1beta1.NamespaceScoped), + updateRun: &placementv1beta1.StagedUpdateRun{ + ObjectMeta: metav1.ObjectMeta{Name: "test-update-run", Namespace: namespace}, + Spec: updateRunSpec, + Status: *updateRunStatus.DeepCopy(), + }, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + cluster := &clusterv1beta1.MemberCluster{ObjectMeta: metav1.ObjectMeta{Name: clusterName}} + r := &Reconciler{ + Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(tc.snapshot, tc.ro, cluster).Build(), + InformerManager: &testinformer.FakeManager{ + APIResources: map[schema.GroupVersionKind]bool{{Group: "apps", Version: "v1", Kind: "Deployment"}: true}, + }, + } + if err := r.recordOverrideSnapshots(context.Background(), tc.placement, tc.updateRun); err != nil { + t.Fatalf("recordOverrideSnapshots() = %v, want no error", err) + } + got := tc.updateRun.GetUpdateRunStatus().StagesStatus[0].Clusters[0].ResourceOverrideSnapshots + want := []placementv1beta1.NamespacedName{{Name: roName, Namespace: namespace}} + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("recordOverrideSnapshots() resourceOverrideSnapshots mismatch (-want +got):\n%s", diff) + } + }) + } +} diff --git a/pkg/controllers/workapplier/apply_test.go b/pkg/controllers/workapplier/apply_test.go index 3d636c2c9..c3314bdac 100644 --- a/pkg/controllers/workapplier/apply_test.go +++ b/pkg/controllers/workapplier/apply_test.go @@ -86,8 +86,9 @@ func TestSanitizeManifestObject(t *testing.T) { DeletionGracePeriodSeconds: ptr.To(int64(30)), Generation: dummyGeneration, ResourceVersion: dummyResourceVersion, - SelfLink: dummySelfLink, - UID: types.UID(dummyUID), + //lint:ignore SA1019 Verify sanitization of the legacy selfLink field. + SelfLink: dummySelfLink, + UID: types.UID(dummyUID), }, Spec: appsv1.DeploymentSpec{ Replicas: ptr.To(int32(1)), diff --git a/pkg/controllers/workapplier/utils_test.go b/pkg/controllers/workapplier/utils_test.go index 81198b033..b183b176c 100644 --- a/pkg/controllers/workapplier/utils_test.go +++ b/pkg/controllers/workapplier/utils_test.go @@ -145,8 +145,9 @@ func TestDiscardFieldsIrrelevantInComparisonFrom(t *testing.T) { DeletionGracePeriodSeconds: ptr.To(int64(30)), Generation: dummyGeneration, ResourceVersion: dummyResourceVersion, - SelfLink: dummySelfLink, - UID: types.UID(dummyUID), + //lint:ignore SA1019 Verify sanitization of the legacy selfLink field. + SelfLink: dummySelfLink, + UID: types.UID(dummyUID), }, Spec: appsv1.DeploymentSpec{ Replicas: ptr.To(int32(1)), diff --git a/pkg/controllers/workgenerator/controller.go b/pkg/controllers/workgenerator/controller.go index 67085fcc5..79d810937 100644 --- a/pkg/controllers/workgenerator/controller.go +++ b/pkg/controllers/workgenerator/controller.go @@ -146,7 +146,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req controllerruntime.Reques // Note that running this branch would also skip the refreshing of apply strategies; // it will resume once the rollout controller updates the rollout started condition. klog.V(2).InfoS("Requeue the resource binding until the rollout controller finishes updating the status", "binding", bindingRef, "generation", resourceBinding.GetGeneration(), "rolloutStartedCondition", rolloutStartedCondition) - return controllerruntime.Result{Requeue: true}, nil + return controllerruntime.Result{RequeueAfter: time.Second}, nil } } @@ -265,7 +265,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req controllerruntime.Reques // However, this error can happen when the resource snapshot exists during the IT test when the client that creates // the resource snapshot is not the same as the controller client so that we need to retry in this case. // This error can also happen if the user uses a customized rollout controller that does not share the same informer cache with this controller. - return controllerruntime.Result{Requeue: true}, nil + return controllerruntime.Result{RequeueAfter: time.Second}, nil } // requeue if we failed to sync the work // If we update the works, their status will be changed and will be detected by the watch event. diff --git a/pkg/scheduler/framework/framework.go b/pkg/scheduler/framework/framework.go index 2c263e876..e2cba2625 100644 --- a/pkg/scheduler/framework/framework.go +++ b/pkg/scheduler/framework/framework.go @@ -81,6 +81,13 @@ const ( // maxClusterInfoForDebugging controls the maximum number of cluster information entries to include in the scheduler debugging output maxClusterInfoForDebugging = 32 + + // batchedSchedulingRequeueDelay is the delay before a placement is requeued when the scheduler + // must finish scheduling in multiple cycles (e.g., a plugin has imposed a per-cycle batch size limit). + // + // Note that this value must be greater than zero, as the scheduler requeues a placement only when + // the scheduling cycle returns a positive RequeueAfter duration. + batchedSchedulingRequeueDelay = 100 * time.Millisecond ) // Handle is an interface which allows plugins to access some shared structs (e.g., client, manager) @@ -1016,7 +1023,7 @@ func (f *framework) runSchedulingCycleForPickNPlacementType( // Also note that if a requeue is needed, the scheduling decisions and condition are updated only // when there are no more clusters to pick. if shouldRequeue(state.desiredBatchSize, state.batchSizeLimit, len(toCreate)+len(toPatch)) { - return ctrl.Result{Requeue: true}, nil + return ctrl.Result{RequeueAfter: batchedSchedulingRequeueDelay}, nil } // Extract the patched bindings. diff --git a/pkg/scheduler/scheduler.go b/pkg/scheduler/scheduler.go index 8cc0658d7..c3932181d 100644 --- a/pkg/scheduler/scheduler.go +++ b/pkg/scheduler/scheduler.go @@ -225,32 +225,22 @@ func (s *Scheduler) scheduleOnce(ctx context.Context, worker int) { return } + // The scheduling cycle has completed without errors; untrack the key from the rate limiter. + s.queue.Forget(placementKey) + // Requeue if the scheduling cycle suggests so. - //nolint:staticcheck - //lint:ignore SA1019 we need more time to fully migrate to RequeueAfter as we used these two fields separately. - if res.Requeue { - if res.RequeueAfter > 0 { - s.queue.AddAfter(placementKey, res.RequeueAfter) - observeSchedulingCycleMetrics(cycleStartTime, false, true) - return - } - // Untrack the key from the rate limiter. - s.queue.Forget(placementKey) - // Requeue for later processing. - // - // Note that the key is added directly to the queue without having to wait for any rate limiter's - // approval. This is necessary as requeues, requested by the scheduler, occur when the scheduler - // is certain that more scheduling work needs to be done but it cannot be completed in - // one cycle (e.g., a plugin sets up a per-cycle batch limit, and consequently the scheduler must - // finish the scheduling in multiple cycles); in such cases, rate limiter should not add - // any delay to the requeues. - s.queue.Add(placementKey) - observeSchedulingCycleMetrics(cycleStartTime, false, true) - } else { - // no more failure, the following queue don't need to be rate limited - s.queue.Forget(placementKey) - observeSchedulingCycleMetrics(cycleStartTime, false, false) + // + // Note that the key is added to the queue without having to wait for any rate limiter's approval. + // This is necessary as requeues, requested by the scheduler, occur when the scheduler is certain + // that more scheduling work needs to be done but it cannot be completed in one cycle (e.g., a plugin + // sets up a per-cycle batch limit, and consequently the scheduler must finish the scheduling in + // multiple cycles); such requeues are not error retries, and the rate limiter should not add any + // backoff to them. + requeue := res.RequeueAfter > 0 + if requeue { + s.queue.AddAfter(placementKey, res.RequeueAfter) } + observeSchedulingCycleMetrics(cycleStartTime, false, requeue) } // Run starts the scheduler. diff --git a/pkg/utils/controller/controller.go b/pkg/utils/controller/controller.go index 1e5067931..47ef8a842 100644 --- a/pkg/utils/controller/controller.go +++ b/pkg/utils/controller/controller.go @@ -297,11 +297,6 @@ func (w *controller) reconcileHandler(ctx context.Context, key interface{}) { w.queue.Forget(key) w.queue.AddAfter(key, result.RequeueAfter) metrics.FleetReconcileTotal.WithLabelValues(w.name, labelRequeueAfter).Inc() - //nolint:staticcheck - //lint:ignore SA1019 we need more time to fully migrate to RequeueAfter as we used these two fields separately. - case result.Requeue: - w.queue.AddRateLimited(key) - metrics.FleetReconcileTotal.WithLabelValues(w.name, labelRequeue).Inc() default: // Forget indicates that an item is finished being retried. Doesn't matter whether it's for perm failing // or for success, we'll stop the rate limiter from tracking it. This only clears the `rateLimiter`, you diff --git a/pkg/utils/controller/resource_selector_resolver_test.go b/pkg/utils/controller/resource_selector_resolver_test.go index 12b403cb0..375057b4f 100644 --- a/pkg/utils/controller/resource_selector_resolver_test.go +++ b/pkg/utils/controller/resource_selector_resolver_test.go @@ -62,9 +62,10 @@ func TestGenerateResourceContent(t *testing.T) { APIVersion: "apiextensions.k8s.io/v1", }, ObjectMeta: metav1.ObjectMeta{ - Name: "object-name", - GenerateName: "object-generateName", - Namespace: "object-namespace", + Name: "object-name", + GenerateName: "object-generateName", + Namespace: "object-namespace", + //lint:ignore SA1019 Verify sanitization of the legacy selfLink field. SelfLink: "object-selflink", UID: types.UID(utilrand.String(10)), ResourceVersion: utilrand.String(10), @@ -125,8 +126,9 @@ func TestGenerateResourceContent(t *testing.T) { Kind: "Service", }, ObjectMeta: metav1.ObjectMeta{ - Name: "svc-name", - Namespace: "svc-namespace", + Name: "svc-name", + Namespace: "svc-namespace", + //lint:ignore SA1019 Verify sanitization of the legacy selfLink field. SelfLink: utilrand.String(10), DeletionTimestamp: &metav1.Time{Time: time.Date(00002, time.January, 1, 1, 1, 1, 1, time.UTC)}, ManagedFields: []metav1.ManagedFieldsEntry{ diff --git a/pkg/utils/controller/resource_snapshot_resolver.go b/pkg/utils/controller/resource_snapshot_resolver.go index f5d91e77d..e617adc87 100644 --- a/pkg/utils/controller/resource_snapshot_resolver.go +++ b/pkg/utils/controller/resource_snapshot_resolver.go @@ -84,7 +84,7 @@ func NewResourceSnapshotConfig(creationInterval, collectionDuration time.Duratio // GetOrCreateResourceSnapshot gets or creates a resource snapshot for the given placement. // It returns the latest resource snapshot if it exists and is up to date, otherwise it creates a new one. // It also returns the ctrl.Result to indicate whether the request should be requeued or not. -// Note: when the ctrl.Result.Requeue is true, it still returns the current latest resourceSnapshot so that +// Note: when the ctrl.Result is set to requeue, it still returns the current latest resourceSnapshot so that // placement can update the rollout status. func (r *ResourceSnapshotResolver) GetOrCreateResourceSnapshot(ctx context.Context, placement fleetv1beta1.PlacementObj, envelopeObjCount int, resourceSnapshotSpec *fleetv1beta1.ResourceSnapshotSpec, revisionHistoryLimit int) (ctrl.Result, fleetv1beta1.ResourceSnapshotObj, error) { placementKObj := klog.KObj(placement) diff --git a/pkg/utils/controller/resource_snapshot_resolver_test.go b/pkg/utils/controller/resource_snapshot_resolver_test.go index 3bd8f52e3..11869b511 100644 --- a/pkg/utils/controller/resource_snapshot_resolver_test.go +++ b/pkg/utils/controller/resource_snapshot_resolver_test.go @@ -3975,13 +3975,13 @@ func TestShouldCreateNewResourceSnapshotNow(t *testing.T) { nilConfig: true, // Even with a very recent creation time, nil Config must not delay. creationTime: time.Now(), - wantRequeue: ctrl.Result{RequeueAfter: 0, Requeue: false}, + wantRequeue: ctrl.Result{}, }, { name: "ResourceSnapshotCreationMinimumInterval and ResourceChangesCollectionDuration are 0", creationInterval: 0, collectionDuration: 0, - wantRequeue: ctrl.Result{Requeue: false}, + wantRequeue: ctrl.Result{}, }, { name: "ResourceSnapshotCreationMinimumInterval is 0", diff --git a/pkg/v1/managers/placementresourcesnapshot/snapshots.go b/pkg/v1/managers/placementresourcesnapshot/snapshots.go index 300c5ac90..0522d601d 100644 --- a/pkg/v1/managers/placementresourcesnapshot/snapshots.go +++ b/pkg/v1/managers/placementresourcesnapshot/snapshots.go @@ -22,13 +22,14 @@ import ( "fmt" "strconv" - placementv1alpha1 "go.goms.io/fleet/apis/kubefleet.dev/placement/v1alpha1" - errors "go.goms.io/fleet/pkg/utils/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/klog/v2" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + placementv1alpha1 "go.goms.io/fleet/apis/kubefleet.dev/placement/v1alpha1" + errors "go.goms.io/fleet/pkg/utils/errors" ) const ( diff --git a/test/apis/v1alpha1/zz_generated.deepcopy.go b/test/apis/v1alpha1/zz_generated.deepcopy.go index 081bec913..143bdee7b 100644 --- a/test/apis/v1alpha1/zz_generated.deepcopy.go +++ b/test/apis/v1alpha1/zz_generated.deepcopy.go @@ -21,7 +21,7 @@ limitations under the License. package v1alpha1 import ( - "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" )