-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathresolvers_test.go
783 lines (677 loc) · 25.6 KB
/
resolvers_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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//go:build e2e
// +build e2e
/*
Copyright 2022 The Tekton 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 test
import (
"context"
"encoding/base64"
"fmt"
"net"
"os"
"path/filepath"
"regexp"
"testing"
"time"
"code.gitea.io/sdk/gitea"
"github.com/goccy/kpoward"
"github.com/jenkins-x/go-scm/scm/factory"
resolverconfig "github.com/tektoncd/pipeline/pkg/apis/config/resolver"
v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1"
"github.com/tektoncd/pipeline/pkg/reconciler/pipelinerun"
gitresolution "github.com/tektoncd/pipeline/pkg/resolution/resolver/git"
"github.com/tektoncd/pipeline/test/parse"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
knativetest "knative.dev/pkg/test"
"knative.dev/pkg/test/helpers"
)
const (
scmTokenSecretBase = "tekton-e2e-scm-token"
scmTokenSecretKey = "token"
scmRemoteTaskPath = "tasks/remote-task.yaml"
scmRemoteOrg = "test-org"
scmRemoteRepo = "test-repo"
scmRemoteBranch = "main"
scmRemoteUser = "tekton-bot"
scmRemoteUserPassword = "ab_d1234HIJKL"
// Defined in git-resolver/gitea.yaml's "gitea" StatefulSet, in the env for the "configure-gitea" init container
scmGiteaAdminPassword = "giteaPassword1234"
systemNamespace = "tekton-pipelines"
)
var (
defaultSvcRE = regexp.MustCompile(`\.default\.svc\.cluster`)
hubFeatureFlags = requireAllGates(map[string]string{
"enable-hub-resolver": "true",
"enable-api-fields": "beta",
})
gitFeatureFlags = requireAllGates(map[string]string{
"enable-git-resolver": "true",
"enable-api-fields": "beta",
})
clusterFeatureFlags = requireAllGates(map[string]string{
"enable-cluster-resolver": "true",
"enable-api-fields": "beta",
})
)
func TestHubResolver(t *testing.T) {
ctx := context.Background()
c, namespace := setup(ctx, t, hubFeatureFlags)
t.Parallel()
knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf)
defer tearDown(ctx, t, c, namespace)
prName := helpers.ObjectNameForTest(t)
pipelineRun := parse.MustParseV1PipelineRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
workspaces:
- name: output # this workspace name must be declared in the Pipeline
volumeClaimTemplate:
spec:
accessModes:
- ReadWriteOnce # access mode may affect how you can use this volume in parallel tasks
resources:
requests:
storage: 1Gi
pipelineSpec:
workspaces:
- name: output
tasks:
- name: task1
workspaces:
- name: output
taskRef:
resolver: hub
params:
- name: kind
value: task
- name: name
value: git-clone
- name: version
value: "0.7"
params:
- name: url
value: https://github.com/tektoncd/pipeline
- name: deleteExisting
value: "true"
`, prName, namespace))
_, err := c.V1PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create PipelineRun `%s`: %s", prName, err)
}
t.Logf("Waiting for PipelineRun %s in namespace %s to complete", prName, namespace)
if err := WaitForPipelineRunState(ctx, c, prName, timeout, PipelineRunSucceed(prName), "PipelineRunSuccess", v1Version); err != nil {
t.Fatalf("Error waiting for PipelineRun %s to finish: %s", prName, err)
}
}
func TestHubResolver_Failure(t *testing.T) {
ctx := context.Background()
c, namespace := setup(ctx, t, hubFeatureFlags)
t.Parallel()
knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf)
defer tearDown(ctx, t, c, namespace)
prName := helpers.ObjectNameForTest(t)
pipelineRun := parse.MustParseV1PipelineRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
workspaces:
- name: output # this workspace name must be declared in the Pipeline
volumeClaimTemplate:
spec:
accessModes:
- ReadWriteOnce # access mode may affect how you can use this volume in parallel tasks
resources:
requests:
storage: 1Gi
pipelineSpec:
workspaces:
- name: output
tasks:
- name: task1
workspaces:
- name: output
taskRef:
resolver: hub
params:
- name: kind
value: task
- name: name
value: git-clone-this-does-not-exist
- name: version
value: "0.7"
params:
- name: url
value: https://github.com/tektoncd/pipeline
- name: deleteExisting
value: "true"
`, prName, namespace))
_, err := c.V1PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create PipelineRun `%s`: %s", prName, err)
}
t.Logf("Waiting for PipelineRun %s in namespace %s to complete", prName, namespace)
if err := WaitForPipelineRunState(ctx, c, prName, timeout,
Chain(
FailedWithReason(v1.PipelineRunReasonCouldntGetTask.String(), prName),
FailedWithMessage("fail to fetch Artifact Hub resource: requested resource 'https://artifacthub.io/api/v1/packages/tekton-task/tekton-catalog-tasks/git-clone-this-does-not-exist' not found on hub", prName),
), "PipelineRunFailed", v1Version); err != nil {
t.Fatalf("Error waiting for PipelineRun to finish with expected error: %s", err)
}
}
func TestGitResolver_Clone(t *testing.T) {
ctx := context.Background()
c, namespace := setup(ctx, t, gitFeatureFlags)
t.Parallel()
knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf)
defer tearDown(ctx, t, c, namespace)
prName := helpers.ObjectNameForTest(t)
pipelineRun := parse.MustParseV1PipelineRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
workspaces:
- name: output # this workspace name must be declared in the Pipeline
volumeClaimTemplate:
spec:
accessModes:
- ReadWriteOnce # access mode may affect how you can use this volume in parallel tasks
resources:
requests:
storage: 1Gi
pipelineSpec:
workspaces:
- name: output
tasks:
- name: task1
workspaces:
- name: output
taskRef:
resolver: git
params:
- name: url
value: https://github.com/tektoncd/catalog.git
- name: pathInRepo
value: /task/git-clone/0.7/git-clone.yaml
- name: revision
value: main
params:
- name: url
value: https://github.com/tektoncd/pipeline
- name: deleteExisting
value: "true"
`, prName, namespace))
_, err := c.V1PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create PipelineRun `%s`: %s", prName, err)
}
t.Logf("Waiting for PipelineRun %s in namespace %s to complete", prName, namespace)
if err := WaitForPipelineRunState(ctx, c, prName, timeout, PipelineRunSucceed(prName), "PipelineRunSuccess", v1Version); err != nil {
t.Fatalf("Error waiting for PipelineRun %s to finish: %s", prName, err)
}
}
func TestGitResolver_Clone_Failure(t *testing.T) {
defaultURL := "https://github.com/tektoncd/catalog.git"
defaultPathInRepo := "/task/git-clone/0.7/git-clone.yaml"
defaultCommit := "783b4fe7d21148f3b1a93bfa49b0024d8c6c2955"
testCases := []struct {
name string
url string
pathInRepo string
commit string
expectedErr string
}{
{
name: "repo does not exist",
url: "https://github.com/tektoncd/catalog-does-not-exist.git",
expectedErr: "clone error: authentication required",
}, {
name: "path does not exist",
pathInRepo: "/task/banana/55.55/banana.yaml",
expectedErr: "error opening file \"/task/banana/55.55/banana.yaml\": file does not exist",
}, {
name: "commit does not exist",
commit: "abcd0123",
expectedErr: "revision error: reference not found",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
expectedErr := tc.expectedErr
url := tc.url
if url == "" {
url = defaultURL
}
pathInRepo := tc.pathInRepo
if pathInRepo == "" {
pathInRepo = defaultPathInRepo
}
commit := tc.commit
if commit == "" {
commit = defaultCommit
}
ctx := context.Background()
c, namespace := setup(ctx, t, gitFeatureFlags)
t.Parallel()
knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf)
defer tearDown(ctx, t, c, namespace)
prName := helpers.ObjectNameForTest(t)
pipelineRun := parse.MustParseV1PipelineRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
workspaces:
- name: output # this workspace name must be declared in the Pipeline
volumeClaimTemplate:
spec:
accessModes:
- ReadWriteOnce # access mode may affect how you can use this volume in parallel tasks
resources:
requests:
storage: 1Gi
pipelineSpec:
workspaces:
- name: output
tasks:
- name: task1
workspaces:
- name: output
taskRef:
resolver: git
params:
- name: url
value: %s
- name: pathInRepo
value: %s
- name: revision
value: %s
params:
- name: url
value: https://github.com/tektoncd/pipeline
- name: deleteExisting
value: "true"
`, prName, namespace, url, pathInRepo, commit))
_, err := c.V1PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create PipelineRun `%s`: %s", prName, err)
}
t.Logf("Waiting for PipelineRun %s in namespace %s to complete", prName, namespace)
if err := WaitForPipelineRunState(ctx, c, prName, timeout,
Chain(
FailedWithReason(v1.PipelineRunReasonCouldntGetTask.String(), prName),
FailedWithMessage(expectedErr, prName),
), "PipelineRunFailed", v1Version); err != nil {
t.Fatalf("Error waiting for PipelineRun to finish with expected error: %s", err)
}
})
}
}
func TestClusterResolver(t *testing.T) {
ctx := context.Background()
c, namespace := setup(ctx, t, clusterFeatureFlags)
t.Parallel()
knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf)
defer tearDown(ctx, t, c, namespace)
pipelineName := helpers.ObjectNameForTest(t)
examplePipeline := parse.MustParseV1Pipeline(t, fmt.Sprintf(`
apiVersion: tekton.dev/v1
kind: Pipeline
metadata:
name: %s
namespace: %s
spec:
tasks:
- name: some-pipeline-task
taskSpec:
steps:
- name: echo
image: mirror.gcr.io/ubuntu
script: |
#!/usr/bin/env bash
# Sleep for 10s
sleep 10
`, pipelineName, namespace))
_, err := c.V1PipelineClient.Create(ctx, examplePipeline, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create Pipeline `%s`: %s", pipelineName, err)
}
prName := helpers.ObjectNameForTest(t)
pipelineRun := parse.MustParseV1PipelineRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
pipelineRef:
resolver: cluster
params:
- name: kind
value: pipeline
- name: name
value: %s
- name: namespace
value: %s
`, prName, namespace, pipelineName, namespace))
_, err = c.V1PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create PipelineRun `%s`: %s", prName, err)
}
t.Logf("Waiting for PipelineRun %s in namespace %s to complete", prName, namespace)
if err := WaitForPipelineRunState(ctx, c, prName, timeout, PipelineRunSucceed(prName), "PipelineRunSuccess", v1Version); err != nil {
t.Fatalf("Error waiting for PipelineRun %s to finish: %s", prName, err)
}
}
func TestClusterResolver_Failure(t *testing.T) {
ctx := context.Background()
c, namespace := setup(ctx, t, clusterFeatureFlags)
t.Parallel()
knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf)
defer tearDown(ctx, t, c, namespace)
prName := helpers.ObjectNameForTest(t)
pipelineRun := parse.MustParseV1PipelineRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
pipelineRef:
resolver: cluster
params:
- name: kind
value: pipeline
- name: name
value: does-not-exist
- name: namespace
value: %s
`, prName, namespace, namespace))
_, err := c.V1PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create PipelineRun `%s`: %s", prName, err)
}
t.Logf("Waiting for PipelineRun %s in namespace %s to complete", prName, namespace)
if err := WaitForPipelineRunState(ctx, c, prName, timeout,
Chain(
FailedWithReason(pipelinerun.ReasonCouldntGetPipeline, prName),
FailedWithMessage("pipelines.tekton.dev \"does-not-exist\" not found", prName),
), "PipelineRunFailed", v1Version); err != nil {
t.Fatalf("Error waiting for PipelineRun to finish with expected error: %s", err)
}
}
func TestGitResolver_API(t *testing.T) {
ctx := context.Background()
c, namespace := setup(ctx, t, gitFeatureFlags)
t.Parallel()
knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf)
defer tearDown(ctx, t, c, namespace)
giteaClusterHostname, tokenSecretName := setupGitea(ctx, t, c, namespace)
resovlerNS := resolverconfig.ResolversNamespace(systemNamespace)
originalConfigMap, err := c.KubeClient.CoreV1().ConfigMaps(resovlerNS).Get(ctx, gitresolution.ConfigMapName, metav1.GetOptions{})
if err != nil {
t.Fatalf("Failed to get ConfigMap `%s`: %s", gitresolution.ConfigMapName, err)
}
originalConfigMapData := originalConfigMap.Data
t.Logf("Creating ConfigMap %s", gitresolution.ConfigMapName)
configMapData := map[string]string{
gitresolution.ServerURLKey: fmt.Sprint("http://", net.JoinHostPort(giteaClusterHostname, "3000")),
gitresolution.SCMTypeKey: "gitea",
gitresolution.APISecretNameKey: tokenSecretName,
gitresolution.APISecretKeyKey: scmTokenSecretKey,
gitresolution.APISecretNamespaceKey: namespace,
}
if err := updateConfigMap(ctx, c.KubeClient, resovlerNS, gitresolution.ConfigMapName, configMapData); err != nil {
t.Fatal(err)
}
defer resetConfigMap(ctx, t, c, resovlerNS, gitresolution.ConfigMapName, originalConfigMapData)
trName := helpers.ObjectNameForTest(t)
tr := parse.MustParseV1TaskRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
taskRef:
resolver: git
params:
- name: revision
value: %s
- name: pathInRepo
value: %s
- name: org
value: %s
- name: repo
value: %s
`, trName, namespace, scmRemoteBranch, scmRemoteTaskPath, scmRemoteOrg, scmRemoteRepo))
_, err = c.V1TaskRunClient.Create(ctx, tr, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create TaskRun: %v", err)
}
t.Logf("Waiting for TaskRun %s in namespace %s to complete", trName, namespace)
if err := WaitForTaskRunState(ctx, c, trName, TaskRunSucceed(trName), "TaskRunSuccess", v1Version); err != nil {
t.Fatalf("Error waiting for TaskRun %s to finish: %s", trName, err)
}
}
func TestGitResolver_API_Identifier(t *testing.T) {
ctx := context.Background()
c, namespace := setup(ctx, t, gitFeatureFlags)
t.Parallel()
knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf)
defer tearDown(ctx, t, c, namespace)
giteaClusterHostname, tokenSecretName := setupGitea(ctx, t, c, namespace)
resovlerNS := resolverconfig.ResolversNamespace(systemNamespace)
originalConfigMap, err := c.KubeClient.CoreV1().ConfigMaps(resovlerNS).Get(ctx, gitresolution.ConfigMapName, metav1.GetOptions{})
if err != nil {
t.Fatalf("Failed to get ConfigMap `%s`: %s", gitresolution.ConfigMapName, err)
}
originalConfigMapData := originalConfigMap.Data
t.Logf("Creating ConfigMap %s", gitresolution.ConfigMapName)
configMapData := map[string]string{
"test." + gitresolution.ServerURLKey: fmt.Sprint("http://", net.JoinHostPort(giteaClusterHostname, "3000")),
"test." + gitresolution.SCMTypeKey: "gitea",
"test." + gitresolution.APISecretNameKey: tokenSecretName,
"test." + gitresolution.APISecretKeyKey: scmTokenSecretKey,
"test." + gitresolution.APISecretNamespaceKey: namespace,
}
if err := updateConfigMap(ctx, c.KubeClient, resovlerNS, gitresolution.ConfigMapName, configMapData); err != nil {
t.Fatal(err)
}
defer resetConfigMap(ctx, t, c, resovlerNS, gitresolution.ConfigMapName, originalConfigMapData)
trName := helpers.ObjectNameForTest(t)
tr := parse.MustParseV1TaskRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
taskRef:
resolver: git
params:
- name: revision
value: %s
- name: pathInRepo
value: %s
- name: org
value: %s
- name: repo
value: %s
- name: configKey
value: test
`, trName, namespace, scmRemoteBranch, scmRemoteTaskPath, scmRemoteOrg, scmRemoteRepo))
_, err = c.V1TaskRunClient.Create(ctx, tr, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create TaskRun: %v", err)
}
t.Logf("Waiting for TaskRun %s in namespace %s to complete", trName, namespace)
if err := WaitForTaskRunState(ctx, c, trName, TaskRunSucceed(trName), "TaskRunSuccess", v1Version); err != nil {
t.Fatalf("Error waiting for TaskRun %s to finish: %s", trName, err)
}
}
// setupGitea reads git-resolver/gitea.yaml, replaces "default" namespace references in "namespace: default" and
// svc.cluster.local hostnames with the test namespace, calls kubectl create, and waits for the gitea-0 pod to be up
// and running. At that point, it'll create a test user and token, create a Secret containing that token, create an org
// and repository in gitea, add the test task to that repo, and verify that it's been created properly, returning the
// Gitea service's internal-to-cluster hostname and the token secret name.
// Note that gitea.yaml is generated from https://gitea.com/gitea/helm-chart/, via "helm template gitea gitea-charts/gitea",
// then removing the "gitea-test-connection" pod included in the output, because that never seemed to actually work and
// just confused things.
func setupGitea(ctx context.Context, t *testing.T, c *clients, namespace string) (string, string) {
t.Helper()
giteaYaml, err := os.ReadFile(filepath.Join("git-resolver", "gitea.yaml"))
if err != nil {
t.Fatalf("failed to read gitea.yaml: %v", err)
}
// Replace any "namespace: default"s with the test namespace.
giteaYaml = defaultNamespaceRE.ReplaceAll(giteaYaml, []byte("namespace: "+namespace))
// Replace any ".default.svc.cluster"s with ".(test namespace).svc.cluster"s.
giteaYaml = defaultSvcRE.ReplaceAll(giteaYaml, []byte(fmt.Sprintf(".%s.svc.cluster", namespace)))
giteaInternalHostname := fmt.Sprintf("gitea-http.%s.svc.cluster.local", namespace)
kcOutput, err := kubectlCreate(giteaYaml, namespace)
if err != nil {
t.Logf("failed 'kubectl create' output: %s", string(kcOutput))
t.Fatalf("failed to 'kubectl create' for gitea: %v", err)
}
// Sleep 5 seconds to make sure the pod gets created, then wait for it to be running. It'll take over 30s, due to
// waiting for the postgres and memcached pods it depends on to be running.
time.Sleep(5 * time.Second)
if err := WaitForPodState(ctx, c, "gitea-0", namespace, func(r *corev1.Pod) (bool, error) {
if r.Status.Phase == corev1.PodRunning {
for _, cs := range r.Status.ContainerStatuses {
return cs.Name == "gitea" && cs.State.Running != nil && cs.Ready, nil
}
}
return false, nil
}, "PodRunning"); err != nil {
t.Fatalf("Error waiting for gitea-0 pod to be running: %v", err)
}
giteaUserJSON := fmt.Sprintf(`{"admin":true,"email":"%[email protected]","full_name":"%s","login_name":"%s","must_change_password":false,"password":"%s","send_notify":false,"source_id":0,"username":"%s"}`, scmRemoteUser, scmRemoteUser, scmRemoteUser, scmRemoteUserPassword, scmRemoteUser)
trName := helpers.AppendRandomString("git-resolver-setup-gitea-user")
giteaConfigTaskRun := parse.MustParseV1TaskRun(t, fmt.Sprintf(`
metadata:
name: %s
namespace: %s
spec:
taskSpec:
results:
- name: token
type: string
steps:
- image: docker.io/alpine/curl
script: |
#!/bin/ash
curl -X POST "http://gitea_admin:%s@%s:3000/api/v1/admin/users" -H "accept: application/json" -H "Content-Type: application/json" -d '%s'
curl -X PATCH "http://gitea_admin:%s@%s:3000/api/v1/admin/users/tekton-bot" -H "accept: application/json" -H "Content-Type: application/json" -d '%s'
TOKEN=$(curl -X POST "http://%s:%s@%s:3000/api/v1/users/tekton-bot/tokens" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"name\":\"bot_token_name\"}" | sed 's/.*"sha1":"\([^"]*\)".*/\1/')
# Make sure we don't add a trailing newline to the result!
echo -n "$TOKEN" > $(results.token.path)
`,
trName, namespace,
scmGiteaAdminPassword, giteaInternalHostname, giteaUserJSON,
scmGiteaAdminPassword, giteaInternalHostname, giteaUserJSON,
scmRemoteUser, scmRemoteUserPassword, giteaInternalHostname))
if _, err := c.V1TaskRunClient.Create(ctx, giteaConfigTaskRun, metav1.CreateOptions{}); err != nil {
t.Fatalf("Failed to create gitea user setup TaskRun: %s", err)
}
t.Logf("Waiting for gitea user setup TaskRun in namespace %s to succeed", namespace)
if err := WaitForTaskRunState(ctx, c, trName, TaskRunSucceed(trName), "TaskRunSucceed", v1Version); err != nil {
t.Fatalf("Error waiting for gitea user setup TaskRun to finish: %s", err)
}
tr, err := c.V1TaskRunClient.Get(ctx, trName, metav1.GetOptions{})
if err != nil {
t.Fatalf("Couldn't get expected gitea user setup TaskRun %s: %s", trName, err)
}
token := ""
for _, trr := range tr.Status.Results {
if trr.Name == "token" {
token = trr.Value.StringVal
}
}
if token == "" {
t.Fatalf("didn't find token result on gitea setup TaskRun %s", trName)
}
secretName := helpers.AppendRandomString(scmTokenSecretBase)
_, err = c.KubeClient.CoreV1().Secrets(namespace).Create(ctx, &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: namespace,
},
Type: corev1.SecretTypeOpaque,
Data: map[string][]byte{
scmTokenSecretKey: []byte(base64.StdEncoding.Strict().EncodeToString([]byte(token))),
},
}, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Failed to create gitea token secret %s: %v", secretName, err)
}
remoteTaskBytes, err := os.ReadFile(filepath.Join("git-resolver", "remote-task.yaml"))
if err != nil {
t.Fatalf("Failed to read git-resolver/remote-task.yaml: %v", err)
}
restCfg, err := knativetest.BuildClientConfig(knativetest.Flags.Kubeconfig, knativetest.Flags.Cluster)
if err != nil {
t.Fatalf("failed to create configuration obj from %s for cluster %s: %s", knativetest.Flags.Kubeconfig, knativetest.Flags.Cluster, err)
}
// To do API operations in Gitea from outside of the cluster, we need to forward the gitea-0 pod's port 3000 locally.
// We're using https://github.com/goccy/kpoward so we can do this programmatically.
kpow := kpoward.New(restCfg, "gitea-0", 3000)
kpow.SetNamespace(namespace)
if err := kpow.Run(ctx, func(ctx context.Context, localPort uint16) error {
// To access the Gitea API to create the organization, repository, and file, we're using the Gitea go-sdk. Initial
// attempts to do this with the go-scm client (which wraps the Gitea go-sdk) failed to properly create the repo
// with a default branch, and the task YAML file wasn't created properly either. We still verify that the go-scm
// client can access the newly created file before finishing.
giteaURL := fmt.Sprintf("http://localhost:%d/", localPort)
giteaClient, err := gitea.NewClient(giteaURL, gitea.SetToken(token))
if err != nil {
return fmt.Errorf("failed to create Gitea client: %w", err)
}
_, _, err = giteaClient.CreateOrg(gitea.CreateOrgOption{
Name: scmRemoteOrg,
})
if err != nil {
return fmt.Errorf("failed to create %s organization in gitea: %w", scmRemoteOrg, err)
}
_, _, err = giteaClient.CreateOrgRepo(scmRemoteOrg, gitea.CreateRepoOption{
Name: scmRemoteRepo,
AutoInit: true,
DefaultBranch: scmRemoteBranch,
})
if err != nil {
return fmt.Errorf("failed to create %s repository in gitea: %w", scmRemoteRepo, err)
}
resp, _, err := giteaClient.CreateFile(scmRemoteOrg, scmRemoteRepo, scmRemoteTaskPath, gitea.CreateFileOptions{
FileOptions: gitea.FileOptions{
Message: "create file " + scmRemoteTaskPath,
},
Content: base64.StdEncoding.EncodeToString(remoteTaskBytes),
})
if err != nil {
return fmt.Errorf("failed to create remote-task.yaml in gitea: %w", err)
}
if resp.Content.Type != "file" {
return fmt.Errorf("expected new file to have type file, but was %s", resp.Content.Type)
}
// Verify file can be fetched by the scm-client.
scmClient, err := factory.NewClient("gitea", giteaURL, token)
if err != nil {
return fmt.Errorf("failed to create go-scm client: %w", err)
}
_, _, err = scmClient.Contents.Find(ctx, fmt.Sprintf("%s/%s", scmRemoteOrg, scmRemoteRepo), scmRemoteTaskPath, scmRemoteBranch)
if err != nil {
return fmt.Errorf("couldn't fetch file content from gitea: %w", err)
}
return nil
}); err != nil {
t.Fatalf("failed to set up gitea org/repo/content through port forwarding: %v", err)
}
return giteaInternalHostname, secretName
}