Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions internal/kcp/clustertracker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
Copyright 2026 The KCP Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package kcp

import (
"context"
"fmt"
"sync"
"testing"
"time"

"sigs.k8s.io/multicluster-runtime/pkg/multicluster"
)

func newTestDMCM() *DynamicMultiClusterManager {
dmcm := &DynamicMultiClusterManager{}
dmcm.tracker = newClusterTracker(dmcm)

return dmcm
}

func TestConcurrentClusterEngagements(t *testing.T) {
dmcm := newTestDMCM()

var wg sync.WaitGroup
for i := range 50 {
wg.Go(func() {
clusterCtx, disconnect := context.WithCancel(context.Background())
defer disconnect()

if err := dmcm.tracker.Engage(clusterCtx, multicluster.ClusterName(fmt.Sprintf("cluster-%d", i%5)), nil); err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
wg.Wait()
}

func TestReEngagedClusterStaysTracked(t *testing.T) {
dmcm := newTestDMCM()

oldCtx, disconnectOld := context.WithCancel(context.Background())
if err := dmcm.tracker.Engage(oldCtx, "cluster", nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}

newCtx, disconnectNew := context.WithCancel(context.Background())
defer disconnectNew()

if err := dmcm.tracker.Engage(newCtx, "cluster", nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}

// the old engagement ending must not remove the new one
disconnectOld()
time.Sleep(100 * time.Millisecond)

dmcm.tracker.lock.RLock()
defer dmcm.tracker.lock.RUnlock()

// controllers started from now on are pre-seeded from this entry
engaged, ok := dmcm.tracker.clusters["cluster"]
if !ok {
t.Fatal("the re-engaged cluster is no longer tracked")
}
if engaged.ctx != newCtx {
t.Fatal("the tracked engagement must be the live one")
}
}

func TestEndedEngagementDoesNotReplaceLiveOne(t *testing.T) {
dmcm := newTestDMCM()

liveCtx, disconnect := context.WithCancel(context.Background())
defer disconnect()

if err := dmcm.tracker.Engage(liveCtx, "cluster", nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}

endedCtx, end := context.WithCancel(context.Background())
end()

if err := dmcm.tracker.Engage(endedCtx, "cluster", nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}

time.Sleep(100 * time.Millisecond)

dmcm.tracker.lock.RLock()
defer dmcm.tracker.lock.RUnlock()

engaged, ok := dmcm.tracker.clusters["cluster"]
if !ok {
t.Fatal("the live engagement is no longer tracked")
}
if engaged.ctx != liveCtx {
t.Fatal("the tracked engagement must be the live one")
}
}
30 changes: 19 additions & 11 deletions internal/kcp/multicluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,14 @@ type engagedCluster struct {
type clusterTracker struct {
dynManager *DynamicMultiClusterManager
lock sync.RWMutex
clusters map[multicluster.ClusterName]engagedCluster
clusters map[multicluster.ClusterName]*engagedCluster
}

func newClusterTracker(dmcm *DynamicMultiClusterManager) *clusterTracker {
return &clusterTracker{
dynManager: dmcm,
lock: sync.RWMutex{},
clusters: map[multicluster.ClusterName]engagedCluster{},
clusters: map[multicluster.ClusterName]*engagedCluster{},
}
}

Expand All @@ -180,21 +180,29 @@ func (s *clusterTracker) Start(_ context.Context) error {
}

func (s *clusterTracker) Engage(ctx context.Context, clusterName multicluster.ClusterName, cl cluster.Cluster) error {
if _, ok := s.clusters[clusterName]; !ok {
s.lock.Lock()
s.clusters[clusterName] = engagedCluster{ctx: ctx, cl: cl}
s.lock.Unlock()
// a late Engage() for an engagement that has already ended must neither replace the
// tracked engagement nor be forwarded, as a controller would cancel its live engagement
// in favour of the ended one if the cluster differs
if ctx.Err() != nil {
return nil
}
Comment on lines +183 to +188

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: The early return for an already-cancelled ctx also stops the call from being forwarded to running controllers. The comment says this forwarding is the main reason for the check: a controller would otherwise cancel its live engagement in favour of the ended one. No test covers it, though. newTestDMCM leaves runnables nil, so TestEndedEngagementDoesNotReplaceLiveOne only checks the tracker map, and that test also passed at the base commit. Add a test that registers a fake mcmanager.Runnable in dmcm.runnables and asserts its Engage is not called for the cancelled ctx.


// start a goroutine to make sure we remove the cluster when the context is done
go func() {
<-ctx.Done()
s.lock.Lock()
if old, ok := s.clusters[clusterName]; !ok || old.ctx != ctx || old.cl != cl {
engaged := &engagedCluster{ctx: ctx, cl: cl}
s.clusters[clusterName] = engaged

// remove the cluster when the context is done, unless it has been re-engaged since
context.AfterFunc(ctx, func() {
s.lock.Lock()
defer s.lock.Unlock()

delete(s.clusters, clusterName)
}()
if s.clusters[clusterName] == engaged {
delete(s.clusters, clusterName)
}
})
}
s.lock.Unlock()

// forward the Engage() call to all running controllers
s.dynManager.runnablesLock.RLock()
Expand Down
Loading