forked from fluxcd/flux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon_test.go
597 lines (519 loc) · 14.4 KB
/
daemon_test.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
597
package daemon
import (
"bufio"
"context"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/go-kit/kit/log"
"github.com/weaveworks/flux"
"github.com/weaveworks/flux/api"
"github.com/weaveworks/flux/api/v6"
"github.com/weaveworks/flux/cluster"
"github.com/weaveworks/flux/cluster/kubernetes"
kresource "github.com/weaveworks/flux/cluster/kubernetes/resource"
"github.com/weaveworks/flux/cluster/kubernetes/testfiles"
"github.com/weaveworks/flux/event"
"github.com/weaveworks/flux/git"
"github.com/weaveworks/flux/git/gittest"
"github.com/weaveworks/flux/image"
"github.com/weaveworks/flux/job"
"github.com/weaveworks/flux/policy"
"github.com/weaveworks/flux/registry"
registryMock "github.com/weaveworks/flux/registry/mock"
"github.com/weaveworks/flux/resource"
"github.com/weaveworks/flux/update"
)
const (
// These have to match the values in cluster/kubernetes/testfiles/data.go
svc = "default:deployment/helloworld"
container = "greeter"
ns = "default"
newHelloImage = "quay.io/weaveworks/helloworld:2"
currentHelloImage = "quay.io/weaveworks/helloworld:master-a000001"
invalidNS = "adsajkfldsa"
testVersion = "test"
)
var (
testBytes = []byte(`{}`)
timeout = 5 * time.Second
)
// When I ping, I should get a response
func TestDaemon_Ping(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
ctx := context.Background()
if d.Ping(ctx) != nil {
t.Fatal("Cluster did not return valid nil ping")
}
}
// When I ask a version, I should get a version
func TestDaemon_Version(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
ctx := context.Background()
v, err := d.Version(ctx)
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
if v != testVersion {
t.Fatalf("Expected %v but got %v", testVersion, v)
}
}
// When I export it should export the current (mocked) k8s cluster
func TestDaemon_Export(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
ctx := context.Background()
bytes, err := d.Export(ctx)
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
if string(testBytes) != string(bytes) {
t.Fatalf("Expected %v but got %v", string(testBytes), string(bytes))
}
}
// When I call list services, it should list all the services
func TestDaemon_ListServices(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
ctx := context.Background()
// No namespace
s, err := d.ListServices(ctx, "")
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
if len(s) != 2 {
t.Fatalf("Expected %v but got %v", 2, len(s))
}
// Just namespace
s, err = d.ListServices(ctx, ns)
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
if 1 != len(s) {
t.Fatalf("Expected %v but got %v", 1, len(s))
}
// Invalid NS
s, err = d.ListServices(ctx, invalidNS)
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
if len(s) != 0 {
t.Fatalf("Expected %v but got %v", 0, len(s))
}
}
// When I call list images for a service, it should return images
func TestDaemon_ListImages(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
ctx := context.Background()
// List all images for services
ss := update.ResourceSpec(update.ResourceSpecAll)
is, err := d.ListImages(ctx, ss)
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
ids := imageIDs(is)
if 3 != len(ids) {
t.Fatalf("Expected %v but got %v", 3, len(ids))
}
// List images for specific service
ss = update.ResourceSpec(svc)
is, err = d.ListImages(ctx, ss)
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
ids = imageIDs(is)
if 2 != len(ids) {
t.Fatalf("Expected %v but got %v", 2, len(ids))
}
}
// When I call notify, it should cause a sync
func TestDaemon_NotifyChange(t *testing.T) {
d, start, clean, mockK8s, events := mockDaemon(t)
w := newWait(t)
ctx := context.Background()
var syncCalled int
var syncDef *cluster.SyncDef
var syncMu sync.Mutex
mockK8s.SyncFunc = func(def cluster.SyncDef) error {
syncMu.Lock()
syncCalled++
syncDef = &def
syncMu.Unlock()
return nil
}
start()
defer clean()
d.NotifyChange(ctx, api.Change{Kind: api.GitChange, Source: api.GitUpdate{}})
w.Eventually(func() bool {
syncMu.Lock()
defer syncMu.Unlock()
return syncCalled == 1
}, "Waiting for sync called")
// Check that sync was called
syncMu.Lock()
defer syncMu.Unlock()
if syncCalled != 1 {
t.Errorf("Sync was not called once, was called %d times", syncCalled)
} else if syncDef == nil {
t.Errorf("Sync was called with a nil syncDef")
} else if len(syncDef.Actions) != len(testfiles.Files) {
t.Errorf("Sync was not called with the %d actions, was called with: %d", len(testfiles.Files), len(syncDef.Actions))
}
// Check that history was written to
var e []event.Event
w.Eventually(func() bool {
e, _ = events.AllEvents(time.Time{}, -1, time.Time{})
return len(e) > 0
}, "Waiting for new events")
if 1 != len(e) {
t.Fatal("Expected one log event from the sync, but got", len(e))
} else if event.EventSync != e[0].Type {
t.Fatalf("Expected event with type %s but got %s", event.EventSync, e[0].Type)
}
}
// When I perform a release, it should add a job to update git to the queue
// When I ask about a Job, it should tell me about a job
// When I perform a release, it should update the git repo
func TestDaemon_Release(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
w := newWait(t)
ctx := context.Background()
// Perform a release
id := updateImage(ctx, d, t)
// Check that job is queued
stat, err := d.JobStatus(ctx, id)
if err != nil {
t.Fatalf("Error: %s", err.Error())
} else if stat.Err != "" {
t.Fatal("Job status error should be empty")
} else if stat.StatusString != job.StatusQueued {
t.Fatalf("Expected %v but got %v", job.StatusQueued, stat.StatusString)
}
// Wait for job to succeed
w.ForJobSucceeded(d, id)
// Wait and check that the git manifest has been altered
w.Eventually(func() bool {
co, err := d.Repo.Clone(ctx, d.GitConfig)
if err != nil {
return false
}
defer co.Clean()
// open a file
if file, err := os.Open(filepath.Join(co.ManifestDir(), "helloworld-deploy.yaml")); err == nil {
// make sure it gets closed
defer file.Close()
// create a new scanner and read the file line by line
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if strings.Contains(scanner.Text(), newHelloImage) {
return true
}
}
} else {
t.Fatal(err)
}
// If we get here we haven't found the line we are looking for.
return false
}, "Waiting for new manifest")
}
// When I update a policy, I expect it to add to the queue
// When I update a policy, it should add an annotation to the manifest
func TestDaemon_PolicyUpdate(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
w := newWait(t)
ctx := context.Background()
// Push an update to a policy
id := updatePolicy(ctx, t, d)
// Wait for job to succeed
w.ForJobSucceeded(d, id)
// Wait and check for new annotation
w.Eventually(func() bool {
co, err := d.Repo.Clone(ctx, d.GitConfig)
if err != nil {
t.Error(err)
return false
}
defer co.Clean()
m, err := d.Manifests.LoadManifests(co.ManifestDir())
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
return len(m[svc].Policy()) > 0
}, "Waiting for new annotation")
}
// When I call sync status, it should return a commit showing the sync
// that is about to take place. Then it should return empty once it is
// complete
func TestDaemon_SyncStatus(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
w := newWait(t)
ctx := context.Background()
// Perform a release
id := updateImage(ctx, d, t)
// Get the commit id
stat := w.ForJobSucceeded(d, id)
// Note: I can't test for an expected number of commits > 0
// because I can't control how fast the sync loop updates the cluster
// Once sync'ed to the cluster, it should empty
w.ForSyncStatus(d, stat.Result.Revision, 0)
}
// When I restart fluxd, there won't be any jobs in the cache
func TestDaemon_JobStatusWithNoCache(t *testing.T) {
d, start, clean, _, _ := mockDaemon(t)
start()
defer clean()
w := newWait(t)
ctx := context.Background()
// Perform update
id := updatePolicy(ctx, t, d)
// Make sure the job finishes first
w.ForJobSucceeded(d, id)
// Clear the cache like we've just restarted
d.JobStatusCache = &job.StatusCache{Size: 100}
// Now check if we can get the job status from the commit
w.ForJobSucceeded(d, id)
}
func makeImageInfo(ref string, t time.Time) image.Info {
r, _ := image.ParseRef(ref)
return image.Info{ID: r, CreatedAt: t}
}
func mockDaemon(t *testing.T) (*Daemon, func(), func(), *cluster.Mock, *mockEventWriter) {
logger := log.NewNopLogger()
singleService := cluster.Controller{
ID: flux.MustParseResourceID(svc),
Containers: cluster.ContainersOrExcuse{
Containers: []cluster.Container{
{
Name: container,
Image: currentHelloImage,
},
},
},
}
multiService := []cluster.Controller{
singleService,
cluster.Controller{
ID: flux.MakeResourceID("another", "deployment", "service"),
Containers: cluster.ContainersOrExcuse{
Containers: []cluster.Container{
{
Name: "it doesn't matter",
Image: "another/service:latest",
},
},
},
},
}
repo, repoCleanup := gittest.Repo(t)
params := git.Config{
Branch: "master",
UserName: "example",
UserEmail: "[email protected]",
SyncTag: "flux-test",
NotesRef: "fluxtest",
}
var k8s *cluster.Mock
{
k8s = &cluster.Mock{}
k8s.AllServicesFunc = func(maybeNamespace string) ([]cluster.Controller, error) {
if maybeNamespace == ns {
return []cluster.Controller{
singleService,
}, nil
} else if maybeNamespace == "" {
return multiService, nil
}
return []cluster.Controller{}, nil
}
k8s.ExportFunc = func() ([]byte, error) { return testBytes, nil }
k8s.FindDefinedServicesFunc = (&kubernetes.Manifests{}).FindDefinedServices
k8s.LoadManifestsFunc = kresource.Load
k8s.ParseManifestsFunc = func(allDefs []byte) (map[string]resource.Resource, error) {
return kresource.ParseMultidoc(allDefs, "test")
}
k8s.PingFunc = func() error { return nil }
k8s.ServicesWithPoliciesFunc = (&kubernetes.Manifests{}).ServicesWithPolicies
k8s.SomeServicesFunc = func([]flux.ResourceID) ([]cluster.Controller, error) {
return []cluster.Controller{
singleService,
}, nil
}
k8s.SyncFunc = func(def cluster.SyncDef) error { return nil }
k8s.UpdatePoliciesFunc = (&kubernetes.Manifests{}).UpdatePolicies
k8s.UpdateDefinitionFunc = (&kubernetes.Manifests{}).UpdateDefinition
}
var imageRegistry registry.Registry
{
img1 := makeImageInfo(currentHelloImage, time.Now())
img2 := makeImageInfo(newHelloImage, time.Now().Add(1*time.Second))
img3 := makeImageInfo("another/service:latest", time.Now().Add(1*time.Second))
imageRegistry = ®istryMock.Registry{
Images: []image.Info{
img1,
img2,
img3,
},
}
}
events := &mockEventWriter{}
// Shutdown chan and waitgroups
shutdown := make(chan struct{})
wg := &sync.WaitGroup{}
// Jobs queue (starts itself)
jobs := job.NewQueue(shutdown, wg)
// Finally, the daemon
d := &Daemon{
Repo: repo,
GitConfig: params,
Cluster: k8s,
Manifests: &kubernetes.Manifests{},
Registry: imageRegistry,
V: testVersion,
Jobs: jobs,
JobStatusCache: &job.StatusCache{Size: 100},
EventWriter: events,
Logger: logger,
LoopVars: &LoopVars{},
}
start := func() {
wg.Add(1)
go repo.Start(shutdown, wg)
gittest.WaitForRepoReady(repo, t)
wg.Add(1)
go d.Loop(shutdown, wg, logger)
}
stop := func() {
// Close daemon first so we don't get errors if the queue closes before the daemon
close(shutdown)
wg.Wait()
repoCleanup()
}
return d, start, stop, k8s, events
}
type mockEventWriter struct {
events []event.Event
sync.Mutex
}
func (w *mockEventWriter) LogEvent(e event.Event) error {
w.Lock()
defer w.Unlock()
w.events = append(w.events, e)
return nil
}
func (w *mockEventWriter) AllEvents(_ time.Time, _ int64, _ time.Time) ([]event.Event, error) {
w.Lock()
defer w.Unlock()
return w.events, nil
}
// DAEMON TEST HELPERS
type wait struct {
t *testing.T
timeout time.Duration
}
func newWait(t *testing.T) wait {
return wait{
t: t,
timeout: timeout,
}
}
const interval = 10 * time.Millisecond
func (w *wait) Eventually(f func() bool, msg string) {
stop := time.Now().Add(w.timeout)
for time.Now().Before(stop) {
if f() {
return
}
time.Sleep(interval)
}
w.t.Fatal(msg)
}
func (w *wait) ForJobSucceeded(d *Daemon, jobID job.ID) job.Status {
var stat job.Status
var err error
ctx := context.Background()
w.Eventually(func() bool {
stat, err = d.JobStatus(ctx, jobID)
if err != nil {
return false
}
switch stat.StatusString {
case job.StatusSucceeded:
return true
case job.StatusFailed:
w.t.Fatal(stat.Err)
return true
default:
return false
}
}, "Waiting for job to succeed")
return stat
}
func (w *wait) ForSyncStatus(d *Daemon, rev string, expectedNumCommits int) []string {
var revs []string
var err error
w.Eventually(func() bool {
ctx := context.Background()
revs, err = d.SyncStatus(ctx, rev)
return err == nil && len(revs) == expectedNumCommits
}, fmt.Sprintf("Waiting for sync status to have %d commits", expectedNumCommits))
return revs
}
func imageIDs(status []v6.ImageStatus) []image.Info {
var availableImgs []image.Info
for _, i := range status {
for _, c := range i.Containers {
availableImgs = append(availableImgs, c.Available...)
}
}
return availableImgs
}
func updateImage(ctx context.Context, d *Daemon, t *testing.T) job.ID {
return updateManifest(ctx, t, d, update.Spec{
Type: update.Images,
Spec: update.ReleaseSpec{
Kind: update.ReleaseKindExecute,
ServiceSpecs: []update.ResourceSpec{update.ResourceSpecAll},
ImageSpec: newHelloImage,
},
})
}
func updatePolicy(ctx context.Context, t *testing.T, d *Daemon) job.ID {
return updateManifest(ctx, t, d, update.Spec{
Type: update.Policy,
Spec: policy.Updates{
flux.MustParseResourceID("default:deployment/helloworld"): {
Add: policy.Set{
policy.Locked: "true",
},
},
},
})
}
func updateManifest(ctx context.Context, t *testing.T, d *Daemon, spec update.Spec) job.ID {
id, err := d.UpdateManifests(ctx, spec)
if err != nil {
t.Fatalf("Error: %s", err.Error())
}
if id == "" {
t.Fatal("id should not be empty")
}
return id
}