forked from openshift/ci-chat-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prow.go
1569 lines (1439 loc) · 51.8 KB
/
prow.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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base32"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"k8s.io/klog"
"sigs.k8s.io/yaml"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
coreclientset "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/client-go/transport"
"github.com/openshift/ci-chat-bot/pkg/prow"
citools "github.com/openshift/ci-tools/pkg/api"
prowapiv1 "k8s.io/test-infra/prow/apis/prowjobs/v1"
)
type envVar struct {
name string
value string
platforms sets.String
}
var errJobCompleted = fmt.Errorf("job is complete")
// supportedTests lists any of the suites defined in the standard launch jobs (copied here for user friendliness)
var supportedTests = []string{"e2e", "e2e-serial", "e2e-all", "e2e-disruptive", "e2e-disruptive-all", "e2e-builds", "e2e-image-ecosystem", "e2e-image-registry", "e2e-network-stress"}
// supportedTests lists any of the upgrade suites defined in the standard launch jobs (copied here for user friendliness)
var supportedUpgradeTests = []string{"e2e-upgrade", "e2e-upgrade-all", "e2e-upgrade-partial", "e2e-upgrade-rollback"}
// supportedPlatforms requires a job within the release periodics that can launch a
// cluster that has the label job-env: platform-name.
var supportedPlatforms = []string{"aws", "gcp", "azure", "vsphere", "metal", "hypershift", "ovirt", "openstack"}
// supportedParameters are the allowed parameter keys that can be passed to jobs
var supportedParameters = []string{"ovn", "ovn-hybrid", "proxy", "compact", "fips", "mirror", "shared-vpc", "large", "xlarge", "ipv6", "preserve-bootstrap", "test", "rt", "single-node", "cgroupsv2", "techpreview", "upi", "crun", "nfv", "kuryr"}
// multistageParameters is the mapping of supportedParameters that can be configured via multistage parameters to the correct environment variable format
var multistageParameters = map[string]envVar{
"compact": {
name: "SIZE_VARIANT",
value: "compact",
platforms: sets.NewString("aws", "gcp", "azure"),
},
"large": {
name: "SIZE_VARIANT",
value: "large",
platforms: sets.NewString("aws", "gcp", "azure"),
},
"xlarge": {
name: "SIZE_VARIANT",
value: "xlarge",
platforms: sets.NewString("aws", "gcp", "azure"),
},
"preserve-bootstrap": {
name: "OPENSHIFT_INSTALL_PRESERVE_BOOTSTRAP",
value: "true",
platforms: sets.NewString("aws", "gcp", "azure", "vsphere", "ovirt"),
},
}
// envsForTestType maps tests given by users to corresponding parameters/env vars that need to be set on the test. Currently not platform dependent, so the platforms
// list for the envs will be left blank
var envsForTestType = map[string][]envVar{
"e2e": {{
name: "TEST_SUITE",
value: "openshift/conformance/parallel",
}},
"e2e-serial": {{
name: "TEST_SUITE",
value: "openshift/conformance/serial",
}},
// Metal IPI specific IPv6 cluster
"e2e-ipv6": {{
name: "TEST_SUITE",
value: "openshift/conformance/parallel",
}},
// Metal IPI specific IPv4v6 dualstack cluster
"e2e-dualstack": {{
name: "TEST_SUITE",
value: "openshift/conformance/parallel",
}},
"e2e-all": {{
name: "TEST_SUITE",
value: "openshift/conformance",
}},
"e2e-builds": {{
name: "TEST_SUITE",
value: "openshift/build",
}},
"e2e-image-ecosystem": {{
name: "TEST_SUITE",
value: "openshift/image-ecosystem",
}},
"e2e-image-registry": {{
name: "TEST_SUITE",
value: "openshift/image-registry",
}},
"e2e-network-stress": {{
name: "TEST_SUITE",
value: "openshift/network/stress",
}},
"e2e-disruptive": {{
name: "TEST_REQUIRES_SSH",
value: "true",
}, {
name: "TEST_SUITE",
value: "openshift/disruptive",
}},
"e2e-disruptive-all": {{
name: "TEST_REQUIRES_SSH",
value: "true",
}, {
name: "TEST_SUITE",
value: "openshift/disruptive",
}, {
name: "TEST_TYPE",
value: "suite-conformance",
}},
"e2e-upgrade": {{
name: "TEST_TYPE",
value: "upgrade",
}},
// Currently, the openshift-e2e-test `upgrade-conformance` test type hardcodes the parallel conformance suite to run after the upgrade test.
// However, the template based cluster-bot jobs use the full conformance suite, so there is not a 1-to-1 replacement that can be done here.
// This is not an issue for the upgrade-partial and upgrade-rollback tests, as those were using the parallel conformance suite.
// TODO: Talk with installer about this difference and see if it can be changed to allow for a full conformance test post-upgrade.
/*
"e2e-upgrade-all": {{
name: "TEST_TYPE",
value: "upgrade-conformance",
}},
*/
"e2e-upgrade-partial": {{
name: "TEST_TYPE",
value: "upgrade-conformance",
}, {
name: "TEST_UPGRADE_OPTIONS",
value: "abort-at=random",
}},
"e2e-upgrade-rollback": {{
name: "TEST_TYPE",
value: "upgrade-conformance",
}, {
name: "TEST_UPGRADE_OPTIONS",
value: "abort-at=100",
}},
}
func testStepForPlatform(platform string) string {
switch platform {
case "aws", "gcp", "azure", "vsphere", "ovirt", "openstack":
return "openshift-e2e-test"
case "metal":
return "baremetalds-e2e-test"
default:
// currently hypershift has no workflows that do any tests, so we can't override a launch job for e2e tests
return ""
}
}
// supportedArchitectures are the allowed architectures that can be passed to jobs
var supportedArchitectures = []string{"amd64"}
var (
// reReleaseVersion detects whether a branch appears to correlate to a release branch
reReleaseVersion = regexp.MustCompile(`^(release|openshift)-(\d+\.\d+)`)
// reVersion detects whether a version appears to correlate to a major.minor release
reVersion = regexp.MustCompile(`^(\d+\.\d+)`)
)
// ConfigResolver finds a ci-operator config for the given tuple of organization, repository,
// branch, and variant.
type ConfigResolver interface {
Resolve(org, repo, branch, variant string) ([]byte, bool, error)
}
type URLConfigResolver struct {
URL *url.URL
}
func (r *URLConfigResolver) Resolve(org, repo, branch, variant string) ([]byte, bool, error) {
switch r.URL.Scheme {
case "http", "https":
u := *r.URL
v := make(url.Values)
v.Add("org", org)
v.Add("repo", repo)
v.Add("branch", branch)
if len(variant) > 0 {
v.Add("variant", variant)
}
u.RawQuery = v.Encode()
rt, err := transport.HTTPWrappersForConfig(&transport.Config{}, http.DefaultTransport)
if err != nil {
return nil, false, fmt.Errorf("url resolve failed: %v", err)
}
client := http.Client{Transport: rt}
resp, err := client.Get(u.String())
if err != nil {
return nil, false, fmt.Errorf("url resolve failed: %v", err)
}
defer resp.Body.Close()
switch resp.StatusCode {
case 200:
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, false, fmt.Errorf("url resolve failed to read body: %v", err)
}
return data, true, nil
case 404:
return nil, false, nil
default:
data, _ := ioutil.ReadAll(resp.Body)
return nil, false, fmt.Errorf("url resolve failed with status code %d: %s", resp.StatusCode, string(bytes.TrimSpace(data)))
}
case "file":
filename := fmt.Sprintf("%s-%s-%s", org, repo, branch)
if len(variant) > 0 {
filename = fmt.Sprintf("%s_%s", filename, variant)
}
path := filepath.Join(r.URL.Path, org, repo, filename+".yaml")
klog.V(2).Infof("Attempting to read config from %s", path)
data, err := ioutil.ReadFile(path)
if os.IsNotExist(err) {
return nil, false, nil
}
if err != nil {
return nil, false, fmt.Errorf("file resolve failed: %v", err)
}
return data, true, nil
default:
return nil, false, fmt.Errorf("unrecognized URL config resolver scheme: %s", r.URL.Scheme)
}
}
// stopJob triggers graceful cluster teardown. If this method returns nil,
// it is safe to consider the cluster released.
func (m *jobManager) stopJob(name, cluster string) error {
uns, err := m.prowClient.Namespace(m.prowNamespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
// There may have been an issue creating the prowjob; treat as success
return nil
}
return err
}
var pj prowapiv1.ProwJob
if err := prow.UnstructuredToObject(uns, &pj); err != nil {
return err
}
_, err = m.clusterClients[cluster].CoreClient.CoreV1().Pods(m.prowNamespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
if pj.Status.State == prowapiv1.TriggeredState {
return fmt.Errorf("original request is still initializing -- please try again in a few minutes")
}
// Since prowjob State != Triggered, pod creation should have been attempted.
// If it is not here, there's nothing to stop
return nil
}
return err
}
klog.Infof("ProwJob pod for job %q will be aborted", name)
pj.Status.State = prowapiv1.AbortedState
_, err = m.prowClient.Namespace(m.prowNamespace).Update(context.Background(), prow.ObjectToUnstructured(&pj), metav1.UpdateOptions{})
return err
}
// newJob creates a ProwJob for running the provided job and exits.
func (m *jobManager) newJob(job *Job) (string, error) {
if !m.tryJob(job.Name) {
klog.Infof("Job %q already has a worker", job.Name)
return "", nil
}
defer m.finishJob(job.Name)
if job.IsComplete() && len(job.PasswordSnippet) > 0 {
return "", nil
}
namespace := fmt.Sprintf("ci-ln-%s", namespaceSafeHash(job.Name))
launchDeadline := 45 * time.Minute
// launch a prow job, tied back to this cluster user
pj, err := prow.JobForConfig(m.prowConfigLoader, job.JobName)
if err != nil {
return "", err
}
jobInputData, err := json.Marshal(job.Inputs)
if err != nil {
return "", err
}
pj.ObjectMeta = metav1.ObjectMeta{
Name: job.Name,
Namespace: m.prowNamespace,
Annotations: map[string]string{
"ci-chat-bot.openshift.io/originalMessage": job.OriginalMessage,
"ci-chat-bot.openshift.io/mode": job.Mode,
"ci-chat-bot.openshift.io/jobParams": paramsToString(job.JobParams),
"ci-chat-bot.openshift.io/user": job.RequestedBy,
"ci-chat-bot.openshift.io/channel": job.RequestedChannel,
"ci-chat-bot.openshift.io/ns": namespace,
"ci-chat-bot.openshift.io/platform": job.Platform,
"ci-chat-bot.openshift.io/jobInputs": string(jobInputData),
"ci-chat-bot.openshift.io/buildCluster": job.BuildCluster,
"prow.k8s.io/job": pj.Spec.Job,
"release.openshift.io/architecture": job.Architecture,
},
Labels: map[string]string{
"ci-chat-bot.openshift.io/launch": "true",
"prow.k8s.io/type": string(pj.Spec.Type),
"prow.k8s.io/job": pj.Spec.Job,
},
}
// sort the variant inputs
var variants []string
for k := range job.JobParams {
if contains(supportedParameters, k) {
variants = append(variants, k)
}
}
sort.Strings(variants)
// register annotations the release controller can use to assess the success
// of this job if it is upgrading between two edges
if len(job.Inputs) == 2 && len(job.Inputs[0].Refs) == 0 && len(job.Inputs[1].Refs) == 0 && len(job.Inputs[0].Version) > 0 && len(job.Inputs[1].Version) > 0 {
pj.Labels["release.openshift.io/verify"] = "true"
pj.Annotations["release.openshift.io/from-tag"] = job.Inputs[0].Version
pj.Annotations["release.openshift.io/tag"] = job.Inputs[1].Version
}
// set standard annotations and environment variables
pj.Annotations["ci-chat-bot.openshift.io/expires"] = strconv.Itoa(int(m.maxAge.Seconds() + launchDeadline.Seconds()))
prow.OverrideJobEnvVar(&pj.Spec, "CLUSTER_DURATION", strconv.Itoa(int(m.maxAge.Seconds())))
if job.Mode == "build" {
prow.SetJobEnvVar(&pj.Spec, "PRESERVE_DURATION", "12h")
} else {
prow.SetJobEnvVar(&pj.Spec, "PRESERVE_DURATION", "1h")
}
// guess the most recent branch used by an input (taken from the last possible job input)
var targetRelease string
for _, input := range job.Inputs {
if len(input.Version) == 0 {
continue
}
if m := reVersion.FindStringSubmatch(input.Version); m != nil {
targetRelease = m[1]
}
}
// Identify the images to be placed in RELEASE_IMAGE_INITIAL and RELEASE_IMAGE_LATEST,
// depending on whether this is an upgrade job or not. Create env var definitions for
// use with the final step job (if we build, we unset both variables before the images
// are built and need to restore them for the last step).
var restoreImageVariableScript []string
lastJobInput := len(job.Inputs) - 1
image := job.Inputs[lastJobInput].Image
var initialImage string
if len(job.Inputs) > 1 {
initialImage = job.Inputs[0].Image
if len(job.Inputs[0].Refs) == 0 && len(initialImage) > 0 {
restoreImageVariableScript = append(restoreImageVariableScript, fmt.Sprintf("RELEASE_IMAGE_INITIAL=%s", initialImage))
}
if len(job.Inputs[lastJobInput].Refs) == 0 && len(image) > 0 {
restoreImageVariableScript = append(restoreImageVariableScript, fmt.Sprintf("RELEASE_IMAGE_LATEST=%s", image))
}
}
prow.OverrideJobEnvironment(&pj.Spec, image, initialImage, targetRelease, namespace, variants)
// find the ci-operator config for the job we will run
sourceEnv, _, ok := firstEnvVar(pj.Spec.PodSpec, "CONFIG_SPEC")
if !ok {
sourceEnv, _, ok = firstEnvVar(pj.Spec.PodSpec, "UNRESOLVED_CONFIG")
if !ok {
return "", fmt.Errorf("UNRESOLVED_CONFIG or CONFIG_SPEC for the launch job could not be found in the prow job %s", job.JobName)
}
}
clusterClient, err := getClusterClient(m, job)
if err != nil {
return "", err
}
sourceConfig, srcNamespace, srcName, err := loadJobConfigSpec(clusterClient.CoreClient, sourceEnv, "ci")
if err != nil {
return "", fmt.Errorf("the launch job definition could not be loaded: %v", err)
}
// Which target in the ci-operator config are we going to run?
targetName := "launch"
if job.LegacyConfig {
if testName, ok := job.JobParams["test"]; ok {
targetName = testName
}
} else {
// errors should never occur here as this has already been checked by the calling function
_, targetName, _ = configContainsVariant(job.JobParams, job.Platform, sourceEnv.Value, job.Mode)
}
var stepBasedTarget bool
// For workflows, we configure the tests we run; for others, we need to load and modify the tests
if job.Mode == JobTypeWorkflowLaunch {
// use "launch" test name to identify proper cluster profile
var profile citools.ClusterProfile
for _, test := range sourceConfig.Tests {
if test.As == "launch" {
profile = test.MultiStageTestConfiguration.ClusterProfile
}
}
environment := citools.TestEnvironment{}
for name, value := range job.JobParams {
environment[name] = value
}
waitRef := "clusterbot-wait"
test := citools.TestStepConfiguration{
As: "launch",
MultiStageTestConfiguration: &citools.MultiStageTestConfiguration{
ClusterProfile: profile,
Workflow: &job.WorkflowName,
Environment: environment,
Test: []citools.TestStep{{
Reference: &waitRef,
}},
},
}
baseImages := sourceConfig.BaseImages
for imageName, imageDef := range m.workflowConfig.Workflows[job.WorkflowName].BaseImages {
baseImages[imageName] = imageDef
}
sourceConfig.BaseImages = baseImages
sourceConfig.Tests = []citools.TestStepConfiguration{test}
stepBasedTarget = true
} else {
var matchedTarget *citools.TestStepConfiguration
for _, test := range sourceConfig.Tests {
if test.As == targetName {
matchedTarget = &test
break
}
}
if matchedTarget == nil {
return "", fmt.Errorf("no test definition matched the expected name %q", targetName)
}
commands := matchedTarget.Commands
stepBasedTarget = len(commands) == 0 // if commands are specified, this is a template based target
if !stepBasedTarget {
// TODO: Remove once all launch jobs are step based
prow.SetJobEnvVar(&pj.Spec, "TEST_COMMAND", commands)
} else {
envParams := sets.NewString()
platformParams := multistageParamsForPlatform(job.Platform)
for k := range job.JobParams {
if platformParams.Has(k) {
envParams.Insert(k)
}
}
if len(envParams) != 0 {
if matchedTarget.MultiStageTestConfiguration.Environment == nil {
matchedTarget.MultiStageTestConfiguration.Environment = citools.TestEnvironment{}
}
for param := range envParams {
envForParam := multistageParameters[param]
matchedTarget.MultiStageTestConfiguration.Environment[envForParam.name] = envForParam.value
}
}
if job.Mode == JobTypeTest {
if strings.HasPrefix(targetName, "launch") {
testStep := testStepForPlatform(job.Platform)
matchedTarget.MultiStageTestConfiguration.Test = []citools.TestStep{{
Reference: &testStep,
}}
}
// CLUSTER_DURATION unused by tests; remove to prevent ci-operator from complaining
delete(matchedTarget.MultiStageTestConfiguration.Environment, "CLUSTER_DURATION")
}
if job.Mode == JobTypeUpgrade {
if matchedTarget.MultiStageTestConfiguration.Dependencies == nil {
matchedTarget.MultiStageTestConfiguration.Dependencies = make(citools.TestDependencies)
}
matchedTarget.MultiStageTestConfiguration.Dependencies["OPENSHIFT_INSTALL_RELEASE_IMAGE_OVERRIDE"] = "release:initial"
matchedTarget.MultiStageTestConfiguration.Dependencies["OPENSHIFT_UPGRADE_RELEASE_IMAGE_OVERRIDE"] = "release:latest"
}
if job.Mode == JobTypeTest || job.Mode == JobTypeUpgrade {
if matchedTarget.MultiStageTestConfiguration.Environment == nil {
matchedTarget.MultiStageTestConfiguration.Environment = make(citools.TestEnvironment)
}
if envs, ok := envsForTestType[job.JobParams["test"]]; ok {
for _, env := range envs {
matchedTarget.MultiStageTestConfiguration.Environment[env.name] = env.value
}
} else {
return "", fmt.Errorf("unknown test type %s", job.JobParams["test"])
}
}
}
if targetName != "launch" {
// launch jobs always target 'launch'. If we have selected a different target, rename
// it in the configuration so that it will be run.
matchedTarget.As = "launch"
sourceConfig.Tests = []citools.TestStepConfiguration{*matchedTarget}
}
}
// set releases field and unset tag_specification for all modern jobs
if !job.LegacyConfig {
sourceConfig.Releases = map[string]citools.UnresolvedRelease{
"initial": {
Integration: &citools.Integration{
Name: "ocp",
Namespace: "$(BRANCH)",
},
},
"latest": {
Integration: &citools.Integration{
Name: "ocp",
Namespace: "$(BRANCH)",
IncludeBuiltImages: true,
},
},
}
sourceConfig.ReleaseTagConfiguration = nil
}
var hasRefs bool
for _, input := range job.Inputs {
if len(input.Refs) > 0 {
hasRefs = true
}
}
if hasRefs {
launchDeadline += 30 * time.Minute
// in order to build repos, we need to clone all the refs
boolFalse := false
pj.Spec.DecorationConfig.SkipCloning = &boolFalse
clusterClient, err := getClusterClient(m, job)
if err != nil {
return "", err
}
is, err := clusterClient.TargetImageClient.ImageV1().ImageStreams("openshift").Get(context.TODO(), "cli", metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("unable to lookup registry URL for job")
}
registryHost := strings.SplitN(is.Status.PublicDockerImageRepository, "/", 2)[0]
// NAMESPACE must be set for this job, and be in the first position, so remove it if set
prow.RemoveJobEnvVar(&pj.Spec, "NAMESPACE")
prow.SetJobEnvVar(&pj.Spec, "NAMESPACE", namespace)
switch container := &pj.Spec.PodSpec.Containers[0]; {
case reflect.DeepEqual(container.Command, []string{"ci-operator"}):
var args []string
for _, arg := range container.Args {
if strings.HasPrefix(arg, "--namespace") {
continue
}
args = append(args, arg)
}
args = append(args, fmt.Sprintf(`--namespace=$(NAMESPACE)`))
envPrefix := strings.Join(restoreImageVariableScript, " ")
container.Command = []string{"/bin/bash", "-c"}
if job.Mode == "build" {
container.Command = append(container.Command, fmt.Sprintf("registry_host=%s\n%s\n\n%s\n%s exec ci-operator $@", registryHost, script, permissionsScript, envPrefix), "")
} else {
container.Command = append(container.Command, fmt.Sprintf("registry_host=%s\n%s\n%s exec ci-operator $@", registryHost, script, envPrefix), "")
}
container.Args = args
prow.SetJobEnvVar(&pj.Spec, "INITIAL", configInitial)
default:
return "", fmt.Errorf("the prow job %s does not have a recognizable command/args setup and cannot be used with pull request builds", job.JobName)
}
// For template based jobs, we must rely on "tag_specification"
if job.LegacyConfig {
sourceConfig.Releases = nil
sourceConfig.ReleaseTagConfiguration = &citools.ReleaseTagConfiguration{
Name: "pipeline",
Namespace: "$(NAMESPACE)",
}
} else {
sourceConfig.ReleaseTagConfiguration = nil
sourceConfig.Releases = map[string]citools.UnresolvedRelease{
"initial": {
Integration: &citools.Integration{
Name: "pipeline",
Namespace: "$(NAMESPACE)",
},
},
"latest": {
Integration: &citools.Integration{
Name: "pipeline",
Namespace: "$(NAMESPACE)",
IncludeBuiltImages: true,
},
},
}
}
if len(sourceConfig.Tests) == 0 {
sourceConfig.Tests = []citools.TestStepConfiguration{{
As: "none",
Commands: "true",
ContainerTestConfiguration: &citools.ContainerTestConfiguration{
From: "src",
},
}}
}
index := 0
for i, input := range job.Inputs {
for _, ref := range input.Refs {
configData, ok, err := m.configResolver.Resolve(ref.Org, ref.Repo, ref.BaseRef, "")
if err != nil {
return "", fmt.Errorf("could not resolve config for %s/%s/%s: %v", ref.Org, ref.Repo, ref.BaseRef, err)
}
if !ok {
return "", fmt.Errorf("there is no defined configuration for the organization %s with repo %s and branch %s", ref.Org, ref.Repo, ref.BaseRef)
}
var cfg citools.ReleaseBuildConfiguration
if err := yaml.Unmarshal([]byte(configData), &cfg); err != nil {
return "", fmt.Errorf("unable to parse ci-operator config definition from resolver: %v", err)
}
targetConfig := &cfg
if klog.V(2) {
data, _ := json.MarshalIndent(targetConfig, "", " ")
klog.Infof("Found target job config:\n%s", string(data))
}
// delete sections we don't need
targetConfig.Tests = nil
if i == 0 && len(job.Inputs) > 1 {
targetConfig.PromotionConfiguration = &citools.PromotionConfiguration{
Name: "stable-initial",
Namespace: "$(NAMESPACE)",
RegistryOverride: registryHost,
DisableBuildCache: true,
}
// For template based jobs, we must rely on "tag_specification"
if job.LegacyConfig {
targetConfig.Releases = nil
targetConfig.ReleaseTagConfiguration = &citools.ReleaseTagConfiguration{
Name: "stable-initial",
Namespace: "$(NAMESPACE)",
}
} else {
targetConfig.ReleaseTagConfiguration = nil
targetConfig.Releases = map[string]citools.UnresolvedRelease{
"initial": {
Integration: &citools.Integration{
Name: "stable-initial",
Namespace: "$(NAMESPACE)",
},
},
"latest": {
Integration: &citools.Integration{
Name: "stable-initial",
Namespace: "$(NAMESPACE)",
IncludeBuiltImages: true,
},
},
}
}
} else {
targetConfig.PromotionConfiguration = &citools.PromotionConfiguration{
Name: "stable",
Namespace: "$(NAMESPACE)",
RegistryOverride: registryHost,
DisableBuildCache: true,
}
// For template based jobs, we must rely on "tag_specification"
if job.LegacyConfig {
targetConfig.Releases = nil
targetConfig.ReleaseTagConfiguration = &citools.ReleaseTagConfiguration{
Name: "stable",
Namespace: "$(NAMESPACE)",
}
} else {
targetConfig.Releases = map[string]citools.UnresolvedRelease{
"initial": {
Integration: &citools.Integration{
Name: "stable",
Namespace: "$(NAMESPACE)",
},
},
"latest": {
Integration: &citools.Integration{
Name: "stable",
Namespace: "$(NAMESPACE)",
IncludeBuiltImages: true,
},
},
}
}
}
data, err := json.MarshalIndent(targetConfig, "", " ")
if err != nil {
return "", fmt.Errorf("unable to reformat child job for %#v: %v", ref, err)
}
prow.SetJobEnvVar(&pj.Spec, fmt.Sprintf("CONFIG_SPEC_%d", index), string(data))
data, err = json.MarshalIndent(JobSpec{Refs: &ref}, "", " ")
if err != nil {
return "", fmt.Errorf("unable to reformat child job for %#v: %v", ref, err)
}
prow.SetJobEnvVar(&pj.Spec, fmt.Sprintf("JOB_SPEC_%d", index), string(data))
// this is used by ci-operator to resolve per repo configuration (which is cloned above)
pathAlias := fmt.Sprintf("%d/github.com/%s/%s", index, ref.Org, ref.Repo)
copiedRef := ref
copiedRef.PathAlias = pathAlias
pj.Spec.ExtraRefs = append(pj.Spec.ExtraRefs, copiedRef)
prow.SetJobEnvVar(&pj.Spec, fmt.Sprintf("REPO_PATH_%d", index), pathAlias)
index++
}
}
if klog.V(2) {
data, _ := json.MarshalIndent(pj.Spec, "", " ")
klog.Infof("Job config after override:\n%s", string(data))
}
}
if stepBasedTarget {
job.TargetType = "steps"
} else {
job.TargetType = "template"
}
pj.Annotations["ci-chat-bot.openshift.io/targetType"] = job.TargetType
// build jobs do not launch contents
if job.Mode == JobTypeBuild {
if err := replaceTargetArgument(pj.Spec.PodSpec, "launch", "[release:latest]"); err != nil {
return "", fmt.Errorf("unable to configure pod spec to alter launch target: %v", err)
}
}
data, _ := json.MarshalIndent(sourceConfig, "", " ")
klog.V(2).Infof("Found target job config %s/%s:\n%s", srcNamespace, srcName, string(data))
// Always use UNRESOLVED_CONFIG to support workflow-based runs
prow.SetJobEnvVar(&pj.Spec, "UNRESOLVED_CONFIG", string(data))
prow.RemoveJobEnvVar(&pj.Spec, "CONFIG_SPEC")
if klog.V(2) {
data, _ := json.MarshalIndent(pj, "", " ")
klog.Infof("Job %q will create prow job:\n%s", job.Name, string(data))
}
_, err = m.prowClient.Namespace(m.prowNamespace).Create(context.TODO(), prow.ObjectToUnstructured(pj), metav1.CreateOptions{})
if err != nil && !errors.IsAlreadyExists(err) {
return "", err
}
var prowJobURL string
// Wait for ProwJob URL to be assigned
err = wait.PollImmediate(10*time.Second, 5*time.Minute, func() (bool, error) {
uns, err := m.prowClient.Namespace(m.prowNamespace).Get(context.TODO(), job.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
var latestPJ prowapiv1.ProwJob
if err := prow.UnstructuredToObject(uns, &latestPJ); err != nil {
return false, err
}
if len(latestPJ.Status.URL) > 0 {
prowJobURL = latestPJ.Status.URL
return true, nil
}
return false, nil
})
if err != nil {
return "", fmt.Errorf("did not retrieve job url due to an error: %v", err)
}
return prowJobURL, nil
}
func getClusterClient(m *jobManager, job *Job) (*BuildClusterClientConfig, error) {
clusterClient, ok := m.clusterClients[job.BuildCluster]
if !ok {
return nil, fmt.Errorf("Cluster %s not found in %v", job.BuildCluster, m.clusterClients)
}
return clusterClient, nil
}
func (m *jobManager) waitForJob(job *Job) error {
if job.IsComplete() && len(job.PasswordSnippet) > 0 {
return nil
}
namespace := fmt.Sprintf("ci-ln-%s", namespaceSafeHash(job.Name))
stepBasedMode := job.TargetType == "steps"
klog.Infof("Job %q started a prow job that will create pods in namespace %s", job.Name, namespace)
var pj *prowapiv1.ProwJob
err := wait.PollImmediate(10*time.Second, 15*time.Minute, func() (bool, error) {
if m.jobIsComplete(job) {
return false, errJobCompleted
}
uns, err := m.prowClient.Namespace(m.prowNamespace).Get(context.TODO(), job.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
var latestPJ prowapiv1.ProwJob
if err := prow.UnstructuredToObject(uns, &latestPJ); err != nil {
return false, err
}
pj = &latestPJ
var done bool
switch pj.Status.State {
case prowapiv1.AbortedState, prowapiv1.ErrorState, prowapiv1.FailureState:
job.Failure = "job failed"
job.State = pj.Status.State
done = true
case prowapiv1.SuccessState:
job.Failure = ""
job.State = pj.Status.State
done = true
}
if len(pj.Status.URL) > 0 {
job.URL = pj.Status.URL
done = true
}
return done, nil
})
if err != nil {
return fmt.Errorf("did not retrieve job url due to an error: %v", err)
}
if job.IsComplete() {
if value := pj.Annotations["ci-chat-bot.openshift.io/channel"]; len(value) > 0 {
m.clearNotificationAnnotations(job, false, 0)
}
return nil
}
started := pj.Status.StartTime.Time
if job.Mode != JobTypeLaunch && job.Mode != JobTypeWorkflowLaunch {
klog.Infof("Job %s will report results at %s (to %s / %s)", job.Name, job.URL, job.RequestedBy, job.RequestedChannel)
// loop waiting for job to complete
err = wait.PollImmediate(time.Minute, 5*60*time.Minute, func() (bool, error) {
if m.jobIsComplete(job) {
return false, errJobCompleted
}
uns, err := m.prowClient.Namespace(m.prowNamespace).Get(context.TODO(), job.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
var pj prowapiv1.ProwJob
if err := prow.UnstructuredToObject(uns, &pj); err != nil {
return false, err
}
switch pj.Status.State {
case prowapiv1.AbortedState, prowapiv1.ErrorState, prowapiv1.FailureState:
job.Failure = "job failed"
job.State = pj.Status.State
return true, nil
case prowapiv1.SuccessState:
job.Failure = ""
job.State = pj.Status.State
return true, nil
}
return false, nil
})
if err != nil {
return fmt.Errorf("did not retrieve job completion state due to an error: %v", err)
}
m.clearNotificationAnnotations(job, false, 0)
return nil
}
var targetName string
switch job.Mode {
case JobTypeBuild:
default:
targetName, err = findTargetName(pj.Spec.PodSpec)
if err != nil {
if klog.V(2) {
data, _ := json.MarshalIndent(pj.Spec.PodSpec, "", " ")
klog.Infof("Could not find --target in:\n%s", string(data))
}
return err
}
}
seen := false
err = wait.PollImmediate(5*time.Second, 15*time.Minute, func() (bool, error) {
if m.jobIsComplete(job) {
return false, errJobCompleted
}
clusterClient, err := getClusterClient(m, job)
if err != nil {
return false, err
}
pod, err := clusterClient.CoreClient.CoreV1().Pods(m.prowNamespace).Get(context.TODO(), job.Name, metav1.GetOptions{})
if err != nil {
if !errors.IsNotFound(err) {
return false, err
}
if seen {
return false, fmt.Errorf("cluster has already been torn down")
}
return false, nil
}
seen = true
if pod.Status.Phase == "Succeeded" || pod.Status.Phase == "Failed" {
return false, fmt.Errorf("cluster has already been torn down")
}
return true, nil
})
if err != nil {
if strings.HasPrefix(err.Error(), "cluster ") {
return err
}
return fmt.Errorf("unable to check launch status: %v", err)
}
klog.Infof("Job %q waiting for setup container in pod %s to complete", job.Name, namespace)
seen = false
var lastErr error
err = wait.PollImmediate(15*time.Second, 60*time.Minute, func() (bool, error) {
if m.jobIsComplete(job) {
return false, errJobCompleted
}
clusterClient, err := getClusterClient(m, job)
if err != nil {
return false, err
}
if stepBasedMode {
prowJobPod, err := clusterClient.CoreClient.CoreV1().Pods(m.prowNamespace).Get(context.TODO(), job.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
if prowJobPod.Status.Phase == "Succeeded" || prowJobPod.Status.Phase == "Failed" {
return false, errJobCompleted
}
launchSecret, err := clusterClient.CoreClient.CoreV1().Secrets(namespace).Get(context.TODO(), targetName, metav1.GetOptions{})
if err != nil {
// It will take awhile before the secret is established and for the ci-chat-bot serviceaccount
// to get permission to access it (see openshift-cluster-bot-rbac step). Ignore errors.
return false, nil
}
if _, ok := launchSecret.Data["console.url"]; ok {
// If the console.url is established, the cluster was setup.
return true, nil
}
return false, nil
} else {
// Execute in template based mode where actual installation pod is monitored.