-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathworker_manager_test.go
More file actions
418 lines (351 loc) · 12.5 KB
/
Copy pathworker_manager_test.go
File metadata and controls
418 lines (351 loc) · 12.5 KB
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
// SPDX-License-Identifier: Apache-2.0
package git
import (
"context"
"path/filepath"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
configv1alpha3 "github.com/ConfigButler/gitops-reverser/api/v1alpha3"
"github.com/ConfigButler/gitops-reverser/internal/types"
"github.com/ConfigButler/gitops-reverser/internal/typeset"
)
// TestWorkerManager_SetMapperInjectsIntoWorkers proves the production wiring: a mapper
// set on the manager is handed to every worker it creates, so the live writer builds a
// resource-identity inventory. Without injection worker.mapper is nil and object-less
// deletes have no resource index to target.
func TestWorkerManager_SetMapperInjectsIntoWorkers(t *testing.T) {
client := fake.NewClientBuilder().WithScheme(setupScheme()).Build()
manager := NewWorkerManager(client, logr.Discard(), 0, types.SensitiveResourcePolicy{})
mapper := typeset.NewSnapshotRegistry(typeset.Snapshot{})
manager.SetMapper(mapper)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
go func() { _ = manager.Start(ctx) }()
time.Sleep(100 * time.Millisecond) // allow Start to set m.ctx
require.NoError(t, manager.EnsureWorker(ctx, "repo1", testProviderNamespace, "main"))
worker, exists := manager.GetWorkerForTarget("repo1", testProviderNamespace, "main")
require.True(t, exists)
require.NotNil(t, worker)
assert.NotNil(t, worker.mapper, "the created worker must carry the injected mapper")
assert.Equal(t, typeset.Lookup(mapper), worker.mapper)
}
const (
testProviderNamespace = "gitops-system"
testTargetNamespace = "default"
)
func setupScheme() *runtime.Scheme {
scheme := runtime.NewScheme()
_ = clientgoscheme.AddToScheme(scheme)
_ = configv1alpha3.AddToScheme(scheme)
return scheme
}
func createProviderWithLocalRepo(
ctx context.Context,
t *testing.T,
k8sClient client.Client,
name string,
) {
t.Helper()
remotePath := filepath.Join(t.TempDir(), name+".git")
createBareRepo(t, remotePath)
provider := &configv1alpha3.GitProvider{
Spec: configv1alpha3.GitProviderSpec{
URL: "file://" + remotePath,
},
}
provider.Name = name
provider.Namespace = testProviderNamespace
require.NoError(t, k8sClient.Create(ctx, provider))
}
func createTargetForRegister(
ctx context.Context,
t *testing.T,
k8sClient client.Client,
name, providerName, branch, path string,
) {
t.Helper()
target := &configv1alpha3.GitTarget{}
target.Name = name
target.Namespace = testTargetNamespace
target.Spec.ProviderRef = configv1alpha3.GitProviderReference{
Name: providerName,
}
target.Spec.Branch = branch
target.Spec.Path = path
require.NoError(t, k8sClient.Create(ctx, target))
}
// TestWorkerManagerRegisterTarget verifies worker registration.
func TestWorkerManagerRegisterTarget(t *testing.T) {
scheme := setupScheme()
client := fake.NewClientBuilder().WithScheme(scheme).Build()
log := logr.Discard()
manager := NewWorkerManager(client, log, 0, types.SensitiveResourcePolicy{})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Start manager
go func() {
_ = manager.Start(ctx)
}()
time.Sleep(100 * time.Millisecond) // Allow manager to start
createProviderWithLocalRepo(ctx, t, client, "repo1")
createTargetForRegister(ctx, t, client, "target1", "repo1", "main", "clusters/prod")
// Register first target
err := manager.RegisterTarget(ctx,
"target1", "default",
"repo1", "gitops-system",
"main", "clusters/prod")
if err != nil {
t.Fatalf("Failed to register target: %v", err)
}
// Verify worker was created
worker, exists := manager.GetWorkerForTarget("repo1", "gitops-system", "main")
if !exists {
t.Fatal("Worker should exist after registration")
}
if worker == nil {
t.Fatal("Worker should not be nil")
}
// Verify worker has correct identity
if worker.GitProviderRef != "repo1" {
t.Errorf("Worker RepoRef = %q, want 'repo1'", worker.GitProviderRef)
}
if worker.GitProviderNamespace != "gitops-system" {
t.Errorf("Worker Namespace = %q, want 'gitops-system'", worker.GitProviderNamespace)
}
if worker.Branch != "main" {
t.Errorf("Worker Branch = %q, want 'main'", worker.Branch)
}
// Verify target registration succeeded (no longer tracks internally)
// The worker exists and registration completed without error
// Cleanup
cancel()
time.Sleep(100 * time.Millisecond)
}
// TestWorkerManagerMultipleTargetsSameBranch verifies multiple targets can share a worker.
func TestWorkerManagerMultipleTargetsSameBranch(t *testing.T) {
scheme := setupScheme()
client := fake.NewClientBuilder().WithScheme(scheme).Build()
log := logr.Discard()
manager := NewWorkerManager(client, log, 0, types.SensitiveResourcePolicy{})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
go func() {
_ = manager.Start(ctx)
}()
time.Sleep(100 * time.Millisecond)
createProviderWithLocalRepo(ctx, t, client, "shared-repo")
createTargetForRegister(ctx, t, client, "target-apps", "shared-repo", "main", "apps/")
createTargetForRegister(ctx, t, client, "target-infra", "shared-repo", "main", "infra/")
// Register two targets for same repo+branch, different paths
err := manager.RegisterTarget(ctx,
"target-apps", "default",
"shared-repo", "gitops-system",
"main", "apps/")
if err != nil {
t.Fatalf("Failed to register target-apps: %v", err)
}
err = manager.RegisterTarget(ctx,
"target-infra", "default",
"shared-repo", "gitops-system",
"main", "infra/")
if err != nil {
t.Fatalf("Failed to register target-infra: %v", err)
}
// Verify only one worker exists
manager.mu.RLock()
workerCount := len(manager.workers)
manager.mu.RUnlock()
if workerCount != 1 {
t.Errorf("Should have exactly 1 worker for shared repo+branch, got %d", workerCount)
}
// Verify worker exists for both targets
_, exists := manager.GetWorkerForTarget("shared-repo", "gitops-system", "main")
if !exists {
t.Fatal("Worker should exist")
}
cancel()
time.Sleep(100 * time.Millisecond)
}
// TestWorkerManagerDifferentBranches verifies different branches get different workers.
func TestWorkerManagerDifferentBranches(t *testing.T) {
scheme := setupScheme()
client := fake.NewClientBuilder().WithScheme(scheme).Build()
log := logr.Discard()
manager := NewWorkerManager(client, log, 0, types.SensitiveResourcePolicy{})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
go func() {
_ = manager.Start(ctx)
}()
time.Sleep(100 * time.Millisecond)
createProviderWithLocalRepo(ctx, t, client, "repo1")
createTargetForRegister(ctx, t, client, "target-main", "repo1", "main", "base/")
createTargetForRegister(ctx, t, client, "target-dev", "repo1", "develop", "base/")
// Register targets for same repo, different branches
err := manager.RegisterTarget(ctx,
"target-main", "default",
"repo1", "gitops-system",
"main", "base/")
if err != nil {
t.Fatalf("Failed to register target-main: %v", err)
}
err = manager.RegisterTarget(ctx,
"target-dev", "default",
"repo1", "gitops-system",
"develop", "base/")
if err != nil {
t.Fatalf("Failed to register target-dev: %v", err)
}
// Verify two workers exist
manager.mu.RLock()
workerCount := len(manager.workers)
manager.mu.RUnlock()
if workerCount != 2 {
t.Errorf("Should have 2 workers for different branches, got %d", workerCount)
}
// Verify each worker exists and has correct branch
workerMain, exists := manager.GetWorkerForTarget("repo1", "gitops-system", "main")
if !exists || workerMain.Branch != "main" {
t.Error("Main branch worker not found or has wrong branch")
}
workerDev, exists := manager.GetWorkerForTarget("repo1", "gitops-system", "develop")
if !exists || workerDev.Branch != "develop" {
t.Error("Develop branch worker not found or has wrong branch")
}
cancel()
time.Sleep(100 * time.Millisecond)
}
// TestWorkerManagerUnregisterTarget verifies target unregistration.
func TestWorkerManagerUnregisterTarget(t *testing.T) {
scheme := setupScheme()
client := fake.NewClientBuilder().WithScheme(scheme).Build()
log := logr.Discard()
manager := NewWorkerManager(client, log, 0, types.SensitiveResourcePolicy{})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
go func() {
_ = manager.Start(ctx)
}()
time.Sleep(100 * time.Millisecond)
createProviderWithLocalRepo(ctx, t, client, "repo1")
createTargetForRegister(ctx, t, client, "target1", "repo1", "main", "apps/")
createTargetForRegister(ctx, t, client, "target2", "repo1", "main", "infra/")
// Register two targets
_ = manager.RegisterTarget(ctx,
"target1", "default",
"repo1", "gitops-system",
"main", "apps/")
_ = manager.RegisterTarget(ctx,
"target2", "default",
"repo1", "gitops-system",
"main", "infra/")
// Verify worker exists
_, exists := manager.GetWorkerForTarget("repo1", "gitops-system", "main")
if !exists {
t.Fatal("Worker should exist")
}
// Unregister first target
err := manager.UnregisterTarget("target1", "default", "repo1", "gitops-system", "main")
if err != nil {
t.Fatalf("Failed to unregister target1: %v", err)
}
// Verify worker was destroyed (WorkerManager now destroys on any unregister)
_, exists = manager.GetWorkerForTarget("repo1", "gitops-system", "main")
if exists {
t.Error("Worker should be destroyed when target unregistered")
}
// Unregister last target
err = manager.UnregisterTarget("target2", "default", "repo1", "gitops-system", "main")
if err != nil {
t.Fatalf("Failed to unregister target2: %v", err)
}
// Verify worker was destroyed
_, exists = manager.GetWorkerForTarget("repo1", "gitops-system", "main")
if exists {
t.Error("Worker should be destroyed when last target unregistered")
}
manager.mu.RLock()
finalWorkerCount := len(manager.workers)
manager.mu.RUnlock()
if finalWorkerCount != 0 {
t.Errorf("Manager should have 0 workers, got %d", finalWorkerCount)
}
cancel()
time.Sleep(100 * time.Millisecond)
}
// TestWorkerManagerConcurrentRegistration verifies thread safety.
func TestWorkerManagerConcurrentRegistration(t *testing.T) {
scheme := setupScheme()
client := fake.NewClientBuilder().WithScheme(scheme).Build()
log := logr.Discard()
manager := NewWorkerManager(client, log, 0, types.SensitiveResourcePolicy{})
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
go func() {
_ = manager.Start(ctx)
}()
time.Sleep(100 * time.Millisecond)
createProviderWithLocalRepo(ctx, t, client, "repo1")
createTargetForRegister(ctx, t, client, "target", "repo1", "main", "base/")
// Concurrently register multiple targets
done := make(chan bool, 10)
for i := range 10 {
go func(index int) {
targetName := "target"
err := manager.RegisterTarget(ctx,
targetName, "default",
"repo1", "gitops-system",
"main", "base/")
if err != nil {
t.Errorf("Failed to register target %d: %v", index, err)
}
done <- true
}(i)
}
// Wait for all goroutines
for range 10 {
<-done
}
// Verify only one worker was created (same repo+branch)
manager.mu.RLock()
workerCount := len(manager.workers)
manager.mu.RUnlock()
if workerCount != 1 {
t.Errorf("Should have exactly 1 worker despite concurrent registration, got %d", workerCount)
}
cancel()
time.Sleep(100 * time.Millisecond)
}
// TestWorkerManagerGetNonexistentWorker verifies getting nonexistent worker returns false.
func TestWorkerManagerGetNonexistentWorker(t *testing.T) {
scheme := setupScheme()
client := fake.NewClientBuilder().WithScheme(scheme).Build()
log := logr.Discard()
manager := NewWorkerManager(client, log, 0, types.SensitiveResourcePolicy{})
worker, exists := manager.GetWorkerForTarget("nonexistent", "default", "main")
if exists {
t.Error("Should return exists=false for nonexistent worker")
}
if worker != nil {
t.Error("Worker should be nil for nonexistent key")
}
}
// TestWorkerManagerUnregisterNonexistent verifies unregistering nonexistent target is safe.
func TestWorkerManagerUnregisterNonexistent(t *testing.T) {
scheme := setupScheme()
client := fake.NewClientBuilder().WithScheme(scheme).Build()
log := logr.Discard()
manager := NewWorkerManager(client, log, 0, types.SensitiveResourcePolicy{})
// Unregister should be idempotent and not error
err := manager.UnregisterTarget("nonexistent", "default", "repo1", "gitops-system", "main")
if err != nil {
t.Errorf("Unregister nonexistent should not error: %v", err)
}
}