-
Notifications
You must be signed in to change notification settings - Fork 783
/
controller_build.go
1469 lines (1333 loc) · 46.2 KB
/
controller_build.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 controller
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"text/template"
"time"
"unicode"
"github.com/jenkins-x/jx/v2/pkg/cmd/step/git/credentials"
"github.com/jenkins-x/jx/v2/pkg/errorutil"
"github.com/ghodss/yaml"
"github.com/jenkins-x/jx/v2/pkg/cmd/helper"
"github.com/jenkins-x/jx/v2/pkg/cmd/opts"
"github.com/jenkins-x/jx/v2/pkg/gits"
"github.com/jenkins-x/jx/v2/pkg/logs"
"k8s.io/apimachinery/pkg/fields"
"github.com/jenkins-x/jx/v2/pkg/collector"
"github.com/jenkins-x/jx/v2/pkg/helm"
"github.com/jenkins-x/jx/v2/pkg/tekton"
"github.com/jenkins-x/jx/v2/pkg/tekton/metapipeline"
"github.com/jenkins-x/jx/v2/pkg/tekton/syntax"
"github.com/pkg/errors"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
"k8s.io/client-go/kubernetes"
v1 "github.com/jenkins-x/jx-api/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx-api/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx-logging/pkg/log"
"github.com/jenkins-x/jx/v2/pkg/builds"
"github.com/jenkins-x/jx/v2/pkg/util"
"github.com/spf13/cobra"
tektonclient "github.com/tektoncd/pipeline/pkg/client/clientset/versioned"
corev1 "k8s.io/api/core/v1"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"github.com/jenkins-x/jx/v2/pkg/kube"
)
const (
defaultTargetURLTemplate = "{{ .BaseURL }}/teams/{{ .Namespace }}/projects/{{ .Owner }}/{{ .Repository }}/{{ .Branch }}/{{ .Build }}"
foghornDeploymentName = "lighthouse-foghorn"
)
// ControllerBuildOptions are the flags for the commands
type ControllerBuildOptions struct {
ControllerOptions
Namespace string
InitGitCredentials bool
GitReporting bool
TargetURLTemplate string
FailIfNoGitProvider bool
JobURLBase string
EnvironmentCache *kube.EnvironmentNamespaceCache
DryRun bool
// private fields added for easier testing
gitHubProvider gits.GitProvider
// private field to record whether the lighthouse-foghorn deployment is present - if so, we skip status reporting
foghornPresent bool
}
// NewCmdControllerBuild creates a command object for the generic "get" action, which
// retrieves one or more resources from a server.
func NewCmdControllerBuild(commonOpts *opts.CommonOptions) *cobra.Command {
options := &ControllerBuildOptions{
ControllerOptions: ControllerOptions{
CommonOptions: commonOpts,
},
}
cmd := &cobra.Command{
Use: "build",
Short: "Runs the build controller",
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
helper.CheckErr(err)
},
Aliases: []string{"builds"},
}
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", "", "The namespace to watch or defaults to the current namespace")
cmd.Flags().BoolVarP(&options.InitGitCredentials, "git-credentials", "", false, "If enable then lets run the 'jx step git credentials' step to initialise git credentials")
cmd.Flags().BoolVarP(&options.FailIfNoGitProvider, "fail-on-git-provider-error", "", false, "If enable then lets terminate quickly if we cannot create a git provider")
// optional git reporting flags
cmd.Flags().StringVarP(&options.TargetURLTemplate, "target-url-template", "", "", "The Go template for generating the target URL of pipeline logs/views if git reporting is enabled. If unspecified, a default will be used based on `--job-url-base`.")
cmd.Flags().BoolVarP(&options.GitReporting, "git-reporting", "", false, "If enabled then lets report pipeline success/failures to the git provider. Note this is purely tactical until we can do this natively inside tekton")
cmd.Flags().StringVarP(&options.JobURLBase, "job-url-base", "", "", "The base URL, such as 'https://dashboard.jenkins-x.live', for generating the target URL for pipeline logs if git reporting is enabled.")
return cmd
}
// Run implements this command
func (o *ControllerBuildOptions) Run() error {
jxClient, devNs, err := o.JXClientAndDevNamespace()
if err != nil {
return err
}
kubeClient, err := o.KubeClient()
if err != nil {
return err
}
tektonClient, _, err := o.TektonClient()
if err != nil {
return err
}
if !o.GitReporting {
if strings.ToLower(os.Getenv("GIT_REPORTING")) == "true" {
o.GitReporting = true
}
}
if o.GitReporting {
_, err = kubeClient.AppsV1().Deployments(devNs).Get(foghornDeploymentName, metav1.GetOptions{})
if err != nil {
if !k8sErrors.IsNotFound(err) {
log.Logger().Warnf("failed to look up deployment %s in namespace %s: %s", foghornDeploymentName, devNs, err)
}
} else {
o.foghornPresent = true
}
if o.TargetURLTemplate == "" {
o.TargetURLTemplate = os.Getenv("TARGET_URL_TEMPLATE")
}
if o.TargetURLTemplate == "" {
o.TargetURLTemplate = defaultTargetURLTemplate
}
}
ns := o.Namespace
if ns == "" {
ns = devNs
}
o.EnvironmentCache = kube.CreateEnvironmentCache(jxClient, ns)
if o.InitGitCredentials {
err = o.InitGitConfigAndUser()
if err != nil {
return err
}
}
err = o.ensureSourceRepositoryHasLabels(jxClient, ns)
if err != nil {
log.Logger().Warnf("failed to label the legacy SourceRepository resources: %s", err)
}
err = o.ensurePipelineActivityHasLabels(jxClient, ns)
if err != nil {
log.Logger().Warnf("failed to label the legacy PipelineActivity resources: %s", err)
}
pod := &corev1.Pod{}
log.Logger().Infof("Watching for Pods in namespace %s", util.ColorInfo(ns))
listWatch := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), "pods", ns, fields.Everything())
kube.SortListWatchByName(listWatch)
_, controller := cache.NewInformer(
listWatch,
pod,
time.Minute*10,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
o.onPipelinePod(obj, kubeClient, jxClient, tektonClient, ns)
},
UpdateFunc: func(oldObj, newObj interface{}) {
o.onPipelinePod(newObj, kubeClient, jxClient, tektonClient, ns)
},
DeleteFunc: func(obj interface{}) {
},
},
)
stop := make(chan struct{})
go controller.Run(stop)
// Wait forever
select {}
}
func (o *ControllerBuildOptions) handleStandalonePod(pod *corev1.Pod, kubeClient kubernetes.Interface, jxClient versioned.Interface, ns string) {
labels := pod.Labels
if labels != nil {
buildName := labels[builds.LabelBuildName]
if buildName == "" {
buildName = labels[builds.LabelOldBuildName]
}
if buildName == "" {
buildName = labels[builds.LabelPipelineRunName]
}
if buildName != "" {
log.Logger().Debugf("Found build pod %s", pod.Name)
activities := jxClient.JenkinsV1().PipelineActivities(ns)
key := o.createPromoteStepActivityKey(buildName, pod)
if key != nil {
name := ""
err := util.Retry(time.Second*20, func() error {
a, created, err := key.GetOrCreate(jxClient, ns)
if err != nil {
operation := "update"
if created {
operation = "create"
}
log.Logger().Warnf("Failed to %s PipelineActivities for build %s: %s", operation, buildName, err)
return err
}
if o.updatePipelineActivity(kubeClient, ns, a, buildName, pod) {
log.Logger().Debugf("updating PipelineActivity %s from handleStandalonePod()", a.Name)
_, err := activities.PatchUpdate(a)
if err != nil {
log.Logger().Warnf("Failed to update PipelineActivity %s due to: %s", a.Name, err.Error())
name = a.Name
return err
}
}
return nil
})
if err != nil {
log.Logger().Warnf("Failed to update PipelineActivities %s: %s", name, err)
}
}
}
}
}
func (o *ControllerBuildOptions) onPipelinePod(obj interface{}, kubeClient kubernetes.Interface, jxClient versioned.Interface, tektonClient tektonclient.Interface, ns string) {
pod, ok := obj.(*corev1.Pod)
if !ok {
log.Logger().Infof("Object is not a Pod %#v", obj)
return
}
if pod != nil {
if pod.Labels[pipeline.GroupName+pipeline.PipelineRunLabelKey] != "" {
if pod.Labels[syntax.LabelStageName] != "" {
prName := pod.Labels[pipeline.GroupName+pipeline.PipelineRunLabelKey]
pr, err := tektonClient.TektonV1alpha1().PipelineRuns(ns).Get(prName, metav1.GetOptions{})
if err != nil {
log.Logger().Warnf("Error getting PipelineRun for name %s: %s", prName, err)
return
}
// Get the Pod for this PipelineRun
podList, err := kubeClient.CoreV1().Pods(ns).List(metav1.ListOptions{
LabelSelector: builds.LabelPipelineRunName + "=" + prName,
})
if err != nil {
log.Logger().Warnf("Error getting PodList for PipelineRun %s: %s", prName, err)
return
}
structure, err := tekton.StructureForPipelineRun(jxClient, ns, pr)
if err != nil {
log.Logger().Warnf("Error getting PipelineStructure for PipelineRun %s: %s", prName, err)
return
}
pri, err := tekton.CreatePipelineRunInfo(prName, podList, structure, pr)
if err != nil {
log.Logger().Warnf("Error creating PipelineRunInfo for PipelineRun %s: %s", prName, err)
return
}
if pri == nil {
log.Logger().Warnf("No PipelineRunInfo created for PipelineRun %s: %s", prName, err)
return
}
log.Logger().Debugf("Found pipeline run %s", pri.Name)
activities := jxClient.JenkinsV1().PipelineActivities(ns)
key := o.createPromoteStepActivityKeyFromRun(pri)
if key != nil {
name := ""
err := util.Retry(time.Second*20, func() error {
a, created, err := key.GetOrCreate(jxClient, ns)
if err != nil {
operation := "update"
if created {
operation = "create"
}
log.Logger().Warnf("Failed to %s PipelineActivities for build %s: %s", operation, pri.Name, err)
return err
}
if o.updatePipelineActivityForRun(kubeClient, ns, a, pri, pod) {
log.Logger().Debugf("updating PipelineActivity %s from updatePipelineActivityForRun()", a.Name)
_, err := activities.PatchUpdate(a)
if err != nil {
log.Logger().Warnf("Failed to update PipelineActivity %s due to: %s", a.Name, err.Error())
name = a.Name
return err
}
}
return nil
})
if err != nil {
log.Logger().Warnf("Failed to update PipelineActivities %s: %s", name, err)
}
}
} else {
o.handleStandalonePod(pod, kubeClient, jxClient, ns)
}
}
}
}
// createPromoteStepActivityKey deduces the pipeline metadata from the build pod
func (o *ControllerBuildOptions) createPromoteStepActivityKey(buildName string, pod *corev1.Pod) *kube.PromoteStepActivityKey {
buildInfo := builds.CreateBuildPodInfo(pod)
if buildInfo.GitURL == "" || buildInfo.GitInfo == nil {
return nil
}
return &kube.PromoteStepActivityKey{
PipelineActivityKey: kube.PipelineActivityKey{
Name: buildInfo.Name,
Pipeline: buildInfo.Pipeline,
Build: buildInfo.Build,
LastCommitSHA: buildInfo.LastCommitSHA,
LastCommitMessage: buildInfo.LastCommitMessage,
LastCommitURL: buildInfo.LastCommitURL,
GitInfo: buildInfo.GitInfo,
Context: buildInfo.Context,
},
}
}
// completeBuildSourceInfo sets the PR author and PR title from GitHub in the given PA
// If the PA is a branch build it then sets the commit author and last commit message
func (o *ControllerBuildOptions) completeBuildSourceInfo(activity *v1.PipelineActivity) error {
log.Logger().Infof("[BuildInfo] Completing build info for PipelineActivity=%s", activity.Name)
gitInfo, err := gits.ParseGitURL(activity.Spec.GitURL)
if err != nil {
return err
}
if activity.Spec.Author != "" {
// info already set, save some GH requests
return nil
}
// get a git API client
provider, err := o.getGithubProvider(gitInfo)
if err != nil {
if o.FailIfNoGitProvider {
log.Logger().Fatalf("could not create git provider: %s", err.Error())
}
return err
}
// extract (org, repo, commit) or (org, repo, #PR) from key
if strings.HasPrefix(strings.ToUpper(activity.Spec.GitBranch), "PR-") {
// this is a PR build
n := strings.Replace(strings.ToUpper(activity.Spec.GitBranch), "PR-", "", -1)
prNumber, err := strconv.Atoi(n)
if err != nil {
return err
}
pr, e := provider.GetPullRequest(gitInfo.Organisation, gitInfo, prNumber)
if e != nil {
return err
}
if pr.Author != nil {
activity.Spec.Author = pr.Author.Login
activity.Spec.AuthorAvatarURL = pr.Author.AvatarURL
activity.Spec.AuthorURL = pr.Author.URL
}
activity.Spec.PullTitle = pr.Title
log.Logger().Infof("[BuildInfo] PipelineActivity set with author=%s and PR title=%s", activity.Spec.Author, activity.Spec.PullTitle)
} else {
// this is a branch build
gitCommits, e := provider.ListCommits(gitInfo.Organisation, gitInfo.Name, &gits.ListCommitsArguments{
SHA: activity.Spec.GitBranch,
Page: 1,
PerPage: 1,
})
if e != nil {
return e
}
if len(gitCommits) > 0 {
if gitCommits[0] != nil && gitCommits[0].Author != nil {
activity.Spec.Author = gitCommits[0].Author.Login
activity.Spec.AuthorAvatarURL = gitCommits[0].Author.AvatarURL
activity.Spec.AuthorURL = gitCommits[0].Author.URL
activity.Spec.LastCommitMessage = gitCommits[0].Message
}
}
log.Logger().Infof("[BuildInfo] PipelineActivity set with author=%s and last message", activity.Spec.Author)
}
return nil
}
func (o *ControllerBuildOptions) getGithubProvider(gitInfo *gits.GitRepository) (gits.GitProvider, error) {
// this internal provider is only used during tests
if o.gitHubProvider != nil {
return o.gitHubProvider, nil
}
// production code always goes this way
server, userAuth, err := o.GetPipelineGitAuthForRepo(gitInfo)
if err != nil {
return nil, err
}
if server == nil {
return nil, fmt.Errorf("no pipeline git auth could be found")
}
if userAuth == nil || userAuth.IsInvalid() {
return nil, fmt.Errorf("no pipeline git user auth could be found")
}
gitProvider, err := gits.CreateProvider(server, userAuth, nil)
if err != nil {
return nil, err
}
return gitProvider, nil
}
// createPromoteStepActivityKeyFromRun deduces the pipeline metadata from the pipeline run info
func (o *ControllerBuildOptions) createPromoteStepActivityKeyFromRun(pri *tekton.PipelineRunInfo) *kube.PromoteStepActivityKey {
if pri.GitURL == "" || pri.GitInfo == nil {
return nil
}
return &kube.PromoteStepActivityKey{
PipelineActivityKey: kube.PipelineActivityKey{
Name: pri.Name,
Pipeline: pri.Pipeline,
Build: pri.Build,
LastCommitSHA: pri.LastCommitSHA,
LastCommitMessage: pri.LastCommitMessage,
LastCommitURL: pri.LastCommitURL,
GitInfo: pri.GitInfo,
Context: pri.Context,
},
}
}
func (o *ControllerBuildOptions) updatePipelineActivity(kubeClient kubernetes.Interface, ns string, activity *v1.PipelineActivity, buildName string, pod *corev1.Pod) bool {
originYaml := toYamlString(activity)
_, containerStatuses, _ := kube.GetContainersWithStatusAndIsInit(pod)
containersTerminated := len(containerStatuses) > 0
for _, c := range containerStatuses {
name := strings.Replace(strings.TrimPrefix(c.Name, "build-step-"), "-", " ", -1)
name = strings.Replace(strings.TrimPrefix(c.Name, "step-"), "-", " ", -1)
title := strings.Title(name)
_, stage, _ := kube.GetOrCreateStage(activity, title)
running := c.State.Running
terminated := c.State.Terminated
var startedAt metav1.Time
var finishedAt metav1.Time
if terminated != nil {
startedAt = terminated.StartedAt
finishedAt = terminated.FinishedAt
if !finishedAt.IsZero() {
stage.CompletedTimestamp = &finishedAt
}
}
if startedAt.IsZero() && running != nil {
startedAt = running.StartedAt
}
if !startedAt.IsZero() {
stage.StartedTimestamp = &startedAt
}
stage.Description = createStepDescription(c.Name, pod)
if terminated != nil {
if terminated.ExitCode == 0 {
stage.Status = v1.ActivityStatusTypeSucceeded
} else {
stage.Status = v1.ActivityStatusTypeFailed
}
} else {
if running != nil {
stage.Status = v1.ActivityStatusTypeRunning
} else {
stage.Status = v1.ActivityStatusTypePending
}
containersTerminated = false
}
}
spec := &activity.Spec
var biggestFinishedAt metav1.Time
allCompleted := true
failed := false
running := true
for i := range spec.Steps {
step := &spec.Steps[i]
stage := step.Stage
if stage != nil {
stageFinished := spec.Status.IsTerminated()
if stage.StartedTimestamp != nil && spec.StartedTimestamp == nil {
spec.StartedTimestamp = stage.StartedTimestamp
}
if stage.CompletedTimestamp != nil {
t := stage.CompletedTimestamp
if !t.IsZero() {
stageFinished = true
if biggestFinishedAt.IsZero() || t.After(biggestFinishedAt.Time) {
biggestFinishedAt = *t
}
}
}
if stageFinished {
switch stage.Status {
case v1.ActivityStatusTypeSucceeded, v1.ActivityStatusTypeNotExecuted:
// stage did not fail
default:
failed = true
}
} else {
allCompleted = false
}
if stage.Status == v1.ActivityStatusTypeRunning {
running = true
}
if stage.Status == v1.ActivityStatusTypeRunning || stage.Status == v1.ActivityStatusTypePending {
allCompleted = false
}
}
}
if !allCompleted && containersTerminated {
allCompleted = true
}
if allCompleted && (spec.Status == v1.ActivityStatusTypeFailed || spec.Status == v1.ActivityStatusTypeSucceeded) {
if failed {
spec.Status = v1.ActivityStatusTypeFailed
} else {
spec.Status = v1.ActivityStatusTypeSucceeded
}
if !biggestFinishedAt.IsZero() {
spec.CompletedTimestamp = &biggestFinishedAt
}
// log that the build completed
logJobCompletedState(activity, nil)
// lets ensure we overwrite any canonical jenkins build URL thats generated automatically
if spec.BuildLogsURL == "" || !strings.Contains(spec.BuildLogsURL, pod.Name) {
log.Logger().Debugf("Storing build logs for %s", activity.Name)
podInterface := kubeClient.CoreV1().Pods(ns)
envName := kube.LabelValueDevEnvironment
devEnv := o.EnvironmentCache.Item(envName)
location := v1.StorageLocation{}
settings := &devEnv.Spec.TeamSettings
if devEnv == nil {
log.Logger().Warnf("No Environment %s found", envName)
} else {
location = settings.StorageLocationOrDefault(kube.ClassificationLogs)
}
if location.IsEmpty() {
location.GitURL = activity.Spec.GitURL
if location.GitURL == "" {
log.Logger().Warnf("No GitURL on PipelineActivity %s", activity.Name)
}
}
masker, err := kube.NewLogMasker(kubeClient, ns)
if err != nil {
log.Logger().Warnf("Failed to create LogMasker in namespace %s: %s", ns, err.Error())
}
logURL, err := o.generateBuildLogURL(podInterface, ns, activity, buildName, pod, location, settings, o.InitGitCredentials, masker)
if err != nil {
log.Logger().Warnf("%s", err)
}
if logURL != "" {
spec.BuildLogsURL = logURL
}
}
} else {
if running {
spec.Status = v1.ActivityStatusTypeRunning
} else {
spec.Status = v1.ActivityStatusTypePending
}
}
if spec.Author == "" && !o.DryRun {
err := o.completeBuildSourceInfo(activity)
if err != nil {
log.Logger().Warnf("Error completing build information: %s", err)
}
}
// lets compare YAML in case we modify arrays in place on a copy (such as the steps) and don't detect we changed things
newYaml := toYamlString(activity)
return originYaml != newYaml
}
func (o *ControllerBuildOptions) updatePipelineActivityForRun(kubeClient kubernetes.Interface, ns string, activity *v1.PipelineActivity, pri *tekton.PipelineRunInfo, pod *corev1.Pod) bool {
originYaml := toYamlString(activity)
for _, stage := range pri.Stages {
updateForStage(stage, activity)
}
spec := &activity.Spec
var biggestFinishedAt metav1.Time
allStagesCompleted := true
failed := false
running := false
for i := range spec.Steps {
step := &spec.Steps[i]
stage := step.Stage
if stage != nil {
stageFinished := spec.Status.IsTerminated()
if stage.StartedTimestamp != nil && spec.StartedTimestamp == nil {
spec.StartedTimestamp = stage.StartedTimestamp
}
if stage.CompletedTimestamp != nil {
t := stage.CompletedTimestamp
if !t.IsZero() {
stageFinished = true
if biggestFinishedAt.IsZero() || t.After(biggestFinishedAt.Time) {
biggestFinishedAt = *t
}
}
}
if stageFinished {
switch stage.Status {
case v1.ActivityStatusTypeSucceeded, v1.ActivityStatusTypeNotExecuted:
// stage did not fail
default:
failed = true
}
} else {
allStagesCompleted = false
}
if stage.Status == v1.ActivityStatusTypeRunning {
running = true
}
if stage.Status == v1.ActivityStatusTypeRunning || stage.Status == v1.ActivityStatusTypePending {
allStagesCompleted = false
}
}
}
// allStagesCompleted means all stages ran and completed. !running && failed means there are no currently running
// stages (i.e., they're all either successful, failed, or pending), and at least one of them failed. This is the
// best way we've got to determine that an earlier stage has failed and later stages never actually launched.
if allStagesCompleted || (!running && failed) {
if failed {
spec.Status = v1.ActivityStatusTypeFailed
// Mark any Pending stages as not executed
for i := range spec.Steps {
step := &spec.Steps[i]
stage := step.Stage
if stage != nil {
if stage.Status == v1.ActivityStatusTypePending {
stage.Status = v1.ActivityStatusTypeNotExecuted
}
}
}
} else if len(spec.Steps) == 1 && spec.Steps[0].Stage.Name == strings.NewReplacer("-", " ").Replace(metapipeline.MetaPipelineStageName) {
// If there's one stage, it's passed, and it's the metapipeline, assume we're still running.
spec.Status = v1.ActivityStatusTypeRunning
} else {
spec.Status = v1.ActivityStatusTypeSucceeded
}
// Only complete the job if it's failed, or if it's finished and the PRI we're looking at is _not_ the metapipeline
if spec.Status == v1.ActivityStatusTypeFailed || (spec.Status.IsTerminated() && pri.Type != tekton.MetaPipeline.String()) {
if !biggestFinishedAt.IsZero() {
spec.CompletedTimestamp = &biggestFinishedAt
}
// log that the build completed
logJobCompletedState(activity, pri)
// TODO: This will need to be reworked for per-step logs, so leaving alone as part of metapipeline work
// lets ensure we overwrite any canonical jenkins build URL thats generated automatically
if spec.BuildLogsURL == "" && !o.DryRun {
podInterface := kubeClient.CoreV1().Pods(ns)
envName := kube.LabelValueDevEnvironment
devEnv := o.EnvironmentCache.Item(envName)
location := v1.StorageLocation{}
settings := &devEnv.Spec.TeamSettings
if devEnv == nil {
log.Logger().Warnf("No Environment %s found", envName)
} else {
location = settings.StorageLocationOrDefault(kube.ClassificationLogs)
}
if location.IsEmpty() {
location.GitURL = activity.Spec.GitURL
if location.GitURL == "" {
log.Logger().Warnf("No GitURL on PipelineActivity %s", activity.Name)
}
}
masker, err := kube.NewLogMasker(kubeClient, ns)
if err != nil {
log.Logger().Warnf("Failed to create LogMasker in namespace %s: %s", ns, err.Error())
}
logURL, err := o.generateBuildLogURL(podInterface, ns, activity, pri.PipelineRun, pod, location, settings, o.InitGitCredentials, masker)
if err != nil {
log.Logger().Warnf("%s", err)
}
if logURL != "" {
spec.BuildLogsURL = logURL
}
}
}
} else {
if running {
spec.Status = v1.ActivityStatusTypeRunning
} else {
spec.Status = v1.ActivityStatusTypePending
}
}
if spec.Author == "" && !o.DryRun {
err := o.completeBuildSourceInfo(activity)
if err != nil {
log.Logger().Warnf("Error completing build information: %s", err)
}
}
// Set the base SHA if present in the run info
if pri.BaseSHA != "" && spec.BaseSHA != pri.BaseSHA {
spec.BaseSHA = pri.BaseSHA
}
// TODO this is a tactical approach until we move all the reporting of tekton pipelines into tekton outputs
o.reportStatus(kubeClient, ns, activity, pri, pod)
// lets compare YAML in case we modify arrays in place on a copy (such as the steps) and don't detect we changed things
newYaml := toYamlString(activity)
return originYaml != newYaml
}
func updateForStage(si *tekton.StageInfo, a *v1.PipelineActivity) {
_, stage, _ := kube.GetOrCreateStage(a, si.GetStageNameIncludingParents())
containersTerminated := false
if si.Pod != nil {
var stageSteps []v1.CoreActivityStep
pod := si.Pod
_, containerStatuses, _ := kube.GetContainersWithStatusAndIsInit(pod)
containersTerminated = len(containerStatuses) > 0
for i, container := range containerStatuses {
title := getStepTitle(container.Name)
step, _ := kube.GetStepValueFromStage(stage, title)
running := container.State.Running
terminated := container.State.Terminated
var startedAt metav1.Time
var finishedAt metav1.Time
if startedAt.IsZero() {
startedAt = determineStepStartTime(i, running, terminated, stageSteps)
}
if terminated != nil {
finishedAt = terminated.FinishedAt
if !finishedAt.IsZero() {
step.CompletedTimestamp = &finishedAt
}
}
if !startedAt.IsZero() {
step.StartedTimestamp = &startedAt
}
step.Description = createStepDescription(container.Name, pod)
if terminated != nil {
if terminated.ExitCode == 0 {
if didPreviousStepFail(i, stageSteps) {
step.Status = v1.ActivityStatusTypeNotExecuted
} else {
step.Status = v1.ActivityStatusTypeSucceeded
}
} else {
step.Status = v1.ActivityStatusTypeFailed
}
} else {
if running != nil && isStepRunning(i, stageSteps) {
step.Status = v1.ActivityStatusTypeRunning
} else {
step.Status = v1.ActivityStatusTypePending
}
containersTerminated = false
}
stageSteps = append(stageSteps, step)
}
stage.Steps = stageSteps
}
for _, nested := range si.Parallel {
updateForStage(nested, a)
}
for _, nested := range si.Stages {
updateForStage(nested, a)
}
var biggestFinishedAt metav1.Time
childStageNames := si.GetFullChildStageNames(false)
if len(childStageNames) > 0 {
var childStages []*v1.StageActivityStep
for _, s := range a.Spec.Steps {
if s.Stage != nil {
for _, c := range childStageNames {
if s.Stage.Name == c {
childStages = append(childStages, s.Stage)
}
}
}
}
childrenCompleted := true
childrenFailed := false
childrenRunning := true
for _, child := range childStages {
childFinished := child.Status.IsTerminated()
if child.StartedTimestamp != nil && stage.StartedTimestamp == nil {
stage.StartedTimestamp = child.StartedTimestamp
}
if child.CompletedTimestamp != nil {
t := child.CompletedTimestamp
if !t.IsZero() {
childFinished = true
if biggestFinishedAt.IsZero() || t.After(biggestFinishedAt.Time) {
biggestFinishedAt = *t
}
}
}
if childFinished {
if child.Status != v1.ActivityStatusTypeSucceeded {
childrenFailed = true
}
} else {
childrenCompleted = false
}
if child.Status == v1.ActivityStatusTypeRunning {
childrenRunning = true
}
if child.Status == v1.ActivityStatusTypeRunning || child.Status == v1.ActivityStatusTypePending {
childrenCompleted = false
}
}
if childrenCompleted {
if childrenFailed {
stage.Status = v1.ActivityStatusTypeFailed
} else {
stage.Status = v1.ActivityStatusTypeSucceeded
}
if !biggestFinishedAt.IsZero() {
stage.CompletedTimestamp = &biggestFinishedAt
}
} else {
if childrenRunning {
stage.Status = v1.ActivityStatusTypeRunning
} else {
stage.Status = v1.ActivityStatusTypePending
}
}
} else {
allCompleted := false
failed := false
running := si.Pod != nil
for i := range stage.Steps {
step := &stage.Steps[i]
if stage != nil {
stepFinished := step.Status.IsTerminated()
if step.StartedTimestamp != nil && stage.StartedTimestamp == nil {
stage.StartedTimestamp = step.StartedTimestamp
}
if step.CompletedTimestamp != nil {
t := step.CompletedTimestamp
if !t.IsZero() {
stepFinished = true
if biggestFinishedAt.IsZero() || t.After(biggestFinishedAt.Time) {
biggestFinishedAt = *t
}
}
}
if stepFinished {
if step.Status != v1.ActivityStatusTypeSucceeded {
failed = true
}
} else {
allCompleted = false
}
if step.Status == v1.ActivityStatusTypeRunning {
running = true
}
if step.Status == v1.ActivityStatusTypeRunning || step.Status == v1.ActivityStatusTypePending {
allCompleted = false
}
}
}
if !allCompleted && containersTerminated {
allCompleted = true
}
if allCompleted {
if failed {
stage.Status = v1.ActivityStatusTypeFailed
} else {
stage.Status = v1.ActivityStatusTypeSucceeded
}
if !biggestFinishedAt.IsZero() {
stage.CompletedTimestamp = &biggestFinishedAt
}
} else {
if running {
stage.Status = v1.ActivityStatusTypeRunning
} else {
stage.Status = v1.ActivityStatusTypePending
}
}
}
}
// didPreviousStepFail checks if the step before the given index failed. This is used to mark not-actually-executed steps
// correctly.
func didPreviousStepFail(index int, stageSteps []v1.CoreActivityStep) bool {
if len(stageSteps) > 0 {
previousStep := stageSteps[index-1]
return previousStep.CompletedTimestamp != nil && previousStep.Status != v1.ActivityStatusTypeSucceeded
}
return false
}
// isStepRunning checks if the step at the given index is actually running its command, not just waiting for the previous
// step to finish. The step is running if either there are no steps yet in the stageSteps slice, meaning this is the first
// step we're adding, or if the step before it in stageSteps has completed.
func isStepRunning(index int, stageSteps []v1.CoreActivityStep) bool {
if len(stageSteps) > 0 {
previousStep := stageSteps[index-1]
return previousStep.CompletedTimestamp != nil
}
return true
}
// determineStepStartTime checks to see if there's a step before this one. If so, it returns the time at which that step
// finished. Otherwise, it checks to see if the current step is running or finished and returns the appropriate start time.
// This is to work around the fact that Tekton steps all have the same start time, since all containers in the pod start
// at once, even though the actual command doesn't get run until the previous step finishes.
func determineStepStartTime(index int, running *corev1.ContainerStateRunning, terminated *corev1.ContainerStateTerminated, stageSteps []v1.CoreActivityStep) metav1.Time {
var startedAt metav1.Time
if len(stageSteps) > 0 {
previousStep := stageSteps[index-1]
if previousStep.CompletedTimestamp != nil {
startedAt = *previousStep.CompletedTimestamp
}
} else {
if running != nil {
startedAt = running.StartedAt
} else if terminated != nil {
startedAt = terminated.StartedAt
}
}
return startedAt
}
// getStepTitle translates the step container's name into the title for the step used in PipelineActivity
func getStepTitle(containerName string) string {
name := strings.Replace(strings.TrimPrefix(containerName, "build-step-"), "-", " ", -1)
name = strings.Replace(strings.TrimPrefix(containerName, "step-"), "-", " ", -1)
return strings.Title(name)
}
// toYamlString returns the YAML string or error when marshalling the given resource
func toYamlString(resource interface{}) string {
data, err := yaml.Marshal(resource)
if err != nil {
return err.Error()
}
return string(data)
}
// generates the build log URL and returns the URL
func (o *ControllerBuildOptions) generateBuildLogURL(podInterface typedcorev1.PodInterface, ns string, activity *v1.PipelineActivity, buildName string, pod *corev1.Pod, location v1.StorageLocation, settings *v1.TeamSettings, initGitCredentials bool, logMasker *kube.LogMasker) (string, error) {
var gitKind string