File: client_test.go

package info (click to toggle)
gitlab-agent 16.1.3-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 6,324 kB
  • sloc: makefile: 175; sh: 52; ruby: 3
file content (438 lines) | stat: -rw-r--r-- 14,928 bytes parent folder | download
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
package agent

import (
	"context"
	"errors"
	"io"
	"testing"
	"time"

	notificationv1 "github.com/fluxcd/notification-controller/api/v1"
	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/flux/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/retry"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/testing/matcher"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/testing/mock_k8s"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/testing/mock_modagent"
	"go.uber.org/zap/zaptest"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/utils/clock"
)

func TestClient_isEqualProjectSets(t *testing.T) {
	testcases := []struct {
		name                     string
		projects                 []string
		cachedProjects           []string
		expectedIsUpdateRequired bool
	}{
		{
			name:                     "no projects",
			projects:                 []string{},
			cachedProjects:           []string{},
			expectedIsUpdateRequired: true,
		},
		{
			name:                     "new projects on empty cache",
			projects:                 []string{"foo"},
			cachedProjects:           []string{},
			expectedIsUpdateRequired: false,
		},
		{
			name:                     "removed project on existing cache",
			projects:                 []string{},
			cachedProjects:           []string{"foo"},
			expectedIsUpdateRequired: false,
		},
		{
			name:                     "same projects in same order",
			projects:                 []string{"foo", "bar"},
			cachedProjects:           []string{"foo", "bar"},
			expectedIsUpdateRequired: true,
		},
		{
			name:                     "same projects in different order",
			projects:                 []string{"foo", "bar"},
			cachedProjects:           []string{"bar", "foo"},
			expectedIsUpdateRequired: true,
		},
		{
			name:                     "with duplicates",
			projects:                 []string{"foo", "foo", "bar"},
			cachedProjects:           []string{"foo", "bar"},
			expectedIsUpdateRequired: true,
		},
		{
			name:                     "with duplicates in cache",
			projects:                 []string{"foo", "bar"},
			cachedProjects:           []string{"foo", "foo", "bar"},
			expectedIsUpdateRequired: true,
		},
	}
	for _, tc := range testcases {
		t.Run(tc.name, func(t *testing.T) {
			// WHEN
			actualIsEqual := isEqualProjectSets(tc.cachedProjects, tc.projects)

			// THEN
			assert.Equal(t, tc.expectedIsUpdateRequired, actualIsEqual)
		})
	}
}

func TestClient_OnlyRestartReconcilingIndexedProjectsWhenNecessary(t *testing.T) {
	testcases := []struct {
		name                     string
		projects                 []string
		cachedProjects           []string
		expectedIsUpdateRequired bool
	}{
		{
			name:                     "no projects",
			projects:                 []string{},
			cachedProjects:           []string{},
			expectedIsUpdateRequired: false,
		},
		{
			name:                     "new projects on empty cache",
			projects:                 []string{"foo"},
			cachedProjects:           []string{},
			expectedIsUpdateRequired: true,
		},
		{
			name:                     "removed project on existing cache",
			projects:                 []string{},
			cachedProjects:           []string{"foo"},
			expectedIsUpdateRequired: true,
		},
		{
			name:                     "same projects in same order",
			projects:                 []string{"foo", "bar"},
			cachedProjects:           []string{"foo", "bar"},
			expectedIsUpdateRequired: false,
		},
		{
			name:                     "same projects in different order",
			projects:                 []string{"foo", "bar"},
			cachedProjects:           []string{"bar", "foo"},
			expectedIsUpdateRequired: false,
		},
	}
	for _, tc := range testcases {
		t.Run(tc.name, func(t *testing.T) {
			// GIVEN
			var wg wait.Group
			defer wg.Wait()

			ctrl := gomock.NewController(t)
			mockReceiverIndexer := mock_k8s.NewMockIndexer(ctrl)
			mockGitLabFluxClient := NewMockGitLabFluxClient(ctrl)
			mockAgentApi := mock_modagent.NewMockApi(ctrl)
			ch := make(chan []string, 1)
			c := client{
				log:                            zaptest.NewLogger(t),
				agentApi:                       mockAgentApi,
				receiverIndexer:                mockReceiverIndexer,
				fluxGitLabClient:               mockGitLabFluxClient,
				updateProjectsToReconcileC:     ch,
				pollCfgFactory:                 retry.NewPollConfigFactory(1*time.Hour, func() retry.BackoffManager { return &fakeBackoff{1 * time.Hour} }),
				reconciliationDebounceDuration: 0,
			}
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			// setup mock expectations
			gomock.InOrder(
				mockReceiverIndexer.EXPECT().
					ListIndexFuncValues(projectReceiverIndex).
					Return(tc.cachedProjects),
				mockReceiverIndexer.EXPECT().
					ListIndexFuncValues(projectReceiverIndex).
					Return(tc.projects),
			)

			next := make(chan struct{})
			done := make(chan struct{})

			c1 := mockGitLabFluxClient.EXPECT().
				ReconcileProjects(gomock.Any(), matcher.ProtoEq(nil, &rpc.ReconcileProjectsRequest{Project: rpc.ReconcileProjectsFromSlice(tc.cachedProjects)})).
				DoAndReturn(func(_, _ interface{}, _ ...interface{}) (rpc.GitLabFlux_ReconcileProjectsClient, error) {
					close(next)
					return nil, errors.New("just for testing, it's okay")
				})
			c2 := mockAgentApi.EXPECT().HandleProcessingError(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any())
			calls := []*gomock.Call{c1, c2}

			// we need this to abort the PollWithBackoff in reconcileProjects eventually
			if tc.expectedIsUpdateRequired {
				c3 := mockGitLabFluxClient.EXPECT().
					ReconcileProjects(gomock.Any(), matcher.ProtoEq(nil, &rpc.ReconcileProjectsRequest{Project: rpc.ReconcileProjectsFromSlice(tc.projects)})).
					DoAndReturn(func(_, _ interface{}, _ ...interface{}) (rpc.GitLabFlux_ReconcileProjectsClient, error) {
						close(done)
						return nil, errors.New("just for testing, it's okay")
					})
				c4 := mockAgentApi.EXPECT().HandleProcessingError(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any())
				calls = append(calls, c3, c4)
			}
			gomock.InOrder(calls...)

			// start reconciliation ...
			wg.StartWithContext(ctx, c.RunProjectReconciliation)

			// WHEN
			c.ReconcileIndexedProjects(ctx)
			<-next
			c.ReconcileIndexedProjects(ctx)
			// THEN
			if tc.expectedIsUpdateRequired {
				<-done
			} else {
				time.Sleep(100 * time.Millisecond) // wait a bit to ensure there are no unexpected calls.
			}
		})
	}
}

type fakeBackoff struct {
	t time.Duration
}

func (b *fakeBackoff) Backoff() clock.Timer {
	return clock.RealClock{}.NewTimer(b.t)
}

func TestClient_RestartsProjectReconciliationOnProjectsUpdate(t *testing.T) {
	// GIVEN
	var wg wait.Group
	defer wg.Wait()

	ctrl := gomock.NewController(t)
	mockGitLabFluxClient := NewMockGitLabFluxClient(ctrl)
	mockReceiverIndexer := mock_k8s.NewMockIndexer(ctrl)
	mockAgentApi := mock_modagent.NewMockApi(ctrl)
	ch := make(chan []string)
	c := client{
		log:                            zaptest.NewLogger(t),
		agentApi:                       mockAgentApi,
		fluxGitLabClient:               mockGitLabFluxClient,
		receiverIndexer:                mockReceiverIndexer,
		updateProjectsToReconcileC:     ch,
		pollCfgFactory:                 retry.NewPollConfigFactory(1*time.Hour, func() retry.BackoffManager { return &fakeBackoff{1 * time.Hour} }),
		reconciliationDebounceDuration: 0,
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	firstProjects := []string{"foo", "bar"}
	secondProjects := []string{"tst", "baz"}

	// setup mock expectations
	// we need this to abort the PollWithBackoff in reconcileProjects eventually
	mockAgentApi.EXPECT().HandleProcessingError(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(2)
	mockGitLabFluxClient.EXPECT().
		ReconcileProjects(gomock.Any(), &rpc.ReconcileProjectsRequest{Project: rpc.ReconcileProjectsFromSlice(firstProjects)}).
		Return(nil, errors.New("just for testing, it's okay"))
	mockGitLabFluxClient.EXPECT().
		ReconcileProjects(gomock.Any(), &rpc.ReconcileProjectsRequest{Project: rpc.ReconcileProjectsFromSlice(secondProjects)}).
		DoAndReturn(func(_, _ interface{}, _ ...interface{}) (rpc.GitLabFlux_ReconcileProjectsClient, error) {
			cancel()
			return nil, errors.New("just for testing, it's okay")
		})

	// WHEN
	// start reconciliation ...
	wg.StartWithContext(ctx, c.RunProjectReconciliation)

	// start with first set of projects
	ch <- firstProjects

	// give some time to start reconciliation after debounce
	time.Sleep(1 * time.Second)

	// update to the second set of projects
	ch <- secondProjects

	// give some time to start reconciliation after debounce
	time.Sleep(1 * time.Second)

	// THEN
	// we cancel the context in the mock function - that's all we need to know regarding execution.
	<-ctx.Done()
}

func TestClient_SuccessfullyReconcileProjects(t *testing.T) {
	// GIVEN
	var wg wait.Group
	defer wg.Wait()

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// projects to reconcile
	projects := []string{"foo", "bar"}

	c, _, _, mockReceiverIndexer, mockReconcileTrigger := setupClientForProjectReconciliation(t, projects, "foo")

	receiverObjs := []*notificationv1.Receiver{{
		ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{projectAnnotationKey: "foo"}},
		Status:     notificationv1.ReceiverStatus{WebhookPath: "/some/webhook/path"},
	}}
	mockReceiverIndexer.EXPECT().
		ByIndex(projectReceiverIndex, "foo").
		Return(receiversToUnstructuredInterfaceSlice(t, receiverObjs), nil)
	mockReconcileTrigger.EXPECT().
		reconcile(gomock.Any(), "/some/webhook/path").
		DoAndReturn(func(_, _ interface{}) error {
			cancel()
			return nil
		})

	// WHEN
	wg.Start(func() {
		c.reconcileProjects(ctx, projects)
	})

	// THEN
	// we cancel the ctx in reconcile mock function to signal that the last call we expected has been executed.
	<-ctx.Done()
}

func TestClient_ReconcileProjectsWithoutAnyInIndex(t *testing.T) {
	// GIVEN
	var wg wait.Group
	defer wg.Wait()

	// projects to reconcile
	projects := []string{"foo", "bar"}

	c, _, _, mockReceiverIndexer, mockReconcileTrigger := setupClientForProjectReconciliation(t, projects, "foo")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	mockReceiverIndexer.EXPECT().ByIndex(projectReceiverIndex, "foo").DoAndReturn(func(string, string) ([]interface{}, error) {
		cancel()
		return []interface{}{}, nil
	})
	mockReconcileTrigger.EXPECT().reconcile(gomock.Any(), gomock.Any()).Times(0)

	// WHEN
	wg.Start(func() {
		c.reconcileProjects(ctx, projects)
	})

	// THEN
	// we cancel the context in the ByIndex mock function
	<-ctx.Done()
}

func TestClient_ReconcileProjectsReceiverWithoutProjectAnnotationIsIgnored(t *testing.T) {
	// GIVEN
	var wg wait.Group
	defer wg.Wait()

	// projects to reconcile
	projects := []string{"foo", "bar"}

	c, _, _, mockReceiverIndexer, mockReconcileTrigger := setupClientForProjectReconciliation(t, projects, "foo")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	receiverObjs := []*notificationv1.Receiver{{
		ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{}},
		Status:     notificationv1.ReceiverStatus{WebhookPath: "/some/webhook/path"},
	}}
	mockReceiverIndexer.EXPECT().
		ByIndex(projectReceiverIndex, "foo").
		DoAndReturn(func(string, string) ([]interface{}, error) {
			cancel()
			return receiversToUnstructuredInterfaceSlice(t, receiverObjs), nil
		})
	mockReconcileTrigger.EXPECT().reconcile(gomock.Any(), gomock.Any()).Times(0)

	// WHEN
	wg.Start(func() {
		c.reconcileProjects(ctx, projects)
	})

	// THEN
	// we cancel the context in the ByIndex mock function
	<-ctx.Done()
}

func TestClient_ReconcileProjectsReceiverWithoutWebhookPathIsIgnored(t *testing.T) {
	// GIVEN
	var wg wait.Group
	defer wg.Wait()

	// projects to reconcile
	projects := []string{"foo", "bar"}

	c, _, _, mockReceiverIndexer, mockReconcileTrigger := setupClientForProjectReconciliation(t, projects, "foo")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	receiverObjs := []*notificationv1.Receiver{{
		ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{projectAnnotationKey: "foo"}},
		Status:     notificationv1.ReceiverStatus{},
	}}
	mockReceiverIndexer.EXPECT().
		ByIndex(projectReceiverIndex, "foo").
		DoAndReturn(func(string, string) ([]interface{}, error) {
			cancel()
			return receiversToUnstructuredInterfaceSlice(t, receiverObjs), nil
		})
	mockReconcileTrigger.EXPECT().reconcile(gomock.Any(), gomock.Any()).Times(0)

	// WHEN
	wg.Start(func() {
		c.reconcileProjects(ctx, projects)
	})

	// THEN
	// we cancel the context in the ByIndex mock function
	<-ctx.Done()
}

func setupClientForProjectReconciliation(t *testing.T, projects []string, projectToReconcile string) (*client, *MockGitLabFluxClient, *MockGitLabFlux_ReconcileProjectsClient, *mock_k8s.MockIndexer, *MockreconcileTrigger) { // nolint:unparam
	ctrl := gomock.NewController(t)
	mockGitLabFluxClient := NewMockGitLabFluxClient(ctrl)
	mockRpcClient := NewMockGitLabFlux_ReconcileProjectsClient(ctrl)
	mockReceiverIndexer := mock_k8s.NewMockIndexer(ctrl)
	mockReconcileTrigger := NewMockreconcileTrigger(ctrl)
	ch := make(chan []string)
	c := &client{
		log:                        zaptest.NewLogger(t),
		fluxGitLabClient:           mockGitLabFluxClient,
		receiverIndexer:            mockReceiverIndexer,
		reconcileTrigger:           mockReconcileTrigger,
		updateProjectsToReconcileC: ch,
		pollCfgFactory:             retry.NewPollConfigFactory(1*time.Hour, func() retry.BackoffManager { return &fakeBackoff{1 * time.Hour} }),
	}

	// setup mock expectations
	mockGitLabFluxClient.EXPECT().
		ReconcileProjects(gomock.Any(), &rpc.ReconcileProjectsRequest{Project: rpc.ReconcileProjectsFromSlice(projects)}).
		Return(mockRpcClient, nil)

	mockRpcClient.EXPECT().Recv().Return(&rpc.ReconcileProjectsResponse{Project: &rpc.Project{Id: projectToReconcile}}, nil)
	mockRpcClient.EXPECT().Recv().Return(nil, io.EOF)

	return c, mockGitLabFluxClient, mockRpcClient, mockReceiverIndexer, mockReconcileTrigger
}

func receiversToUnstructuredInterfaceSlice(t *testing.T, receivers []*notificationv1.Receiver) []interface{} {
	var objs = make([]interface{}, len(receivers))
	for i, o := range receivers {
		u, err := runtime.DefaultUnstructuredConverter.ToUnstructured(o)
		assert.NoError(t, err)
		objs[i] = &unstructured.Unstructured{Object: u}
	}
	return objs
}