forked from jenkins-x/jx
/
step_create_task.go
1628 lines (1479 loc) · 51.1 KB
/
step_create_task.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 create
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"time"
"k8s.io/apimachinery/pkg/watch"
"github.com/olli-ai/jx/v2/pkg/cmd/opts/step"
"github.com/olli-ai/jx/v2/pkg/versionstream"
"github.com/spf13/viper"
"github.com/olli-ai/jx/v2/pkg/cmd/step/git"
"github.com/ghodss/yaml"
jxclient "github.com/jenkins-x/jx-api/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx-logging/pkg/log"
"github.com/olli-ai/jx/v2/pkg/cmd/helper"
"github.com/olli-ai/jx/v2/pkg/cmd/opts"
syntaxstep "github.com/olli-ai/jx/v2/pkg/cmd/step/syntax"
"github.com/olli-ai/jx/v2/pkg/cmd/templates"
"github.com/olli-ai/jx/v2/pkg/config"
"github.com/olli-ai/jx/v2/pkg/gits"
"github.com/olli-ai/jx/v2/pkg/jenkinsfile"
"github.com/olli-ai/jx/v2/pkg/jenkinsfile/gitresolver"
"github.com/olli-ai/jx/v2/pkg/kube"
"github.com/olli-ai/jx/v2/pkg/tekton"
"github.com/olli-ai/jx/v2/pkg/tekton/syntax"
"github.com/olli-ai/jx/v2/pkg/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
pipelineapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
tektonclient "github.com/tektoncd/pipeline/pkg/client/clientset/versioned"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubeclient "k8s.io/client-go/kubernetes"
)
const (
kanikoSecretMount = "/kaniko-secret/secret.json" // #nosec
kanikoSecretName = kube.SecretKaniko
kanikoSecretKey = kube.SecretKaniko
noApplyOptionName = "no-apply"
outputOptionName = "output"
)
var (
createTaskLong = templates.LongDesc(`
Creates a Tekton Pipeline Run for a project
`)
createTaskExample = templates.Examples(`
# create a Tekton Pipeline Run and render to the console
jx step create task
# create a Tekton Pipeline Task
jx step create task -o mytask.yaml
# view the steps that would be created
jx step create task --view
`)
lastPipelineRun = time.Now()
createTaskOutDir string
createTaskNoApply bool
)
// StepCreateTaskOptions contains the command line flags
type StepCreateTaskOptions struct {
step.StepOptions
Pack string
BuildPackURL string
BuildPackRef string
PipelineKind string
Context string
CustomLabels []string
CustomEnvs []string
NoApply *bool
DryRun bool
InterpretMode bool
DisableConcurrent bool
StartStep string
EndStep string
Trigger string
TargetPath string
SourceName string
CustomImage string
DefaultImage string
CloneGitURL string
Branch string
Revision string
PullRequestNumber string
DeleteTempDir bool
ViewSteps bool
EffectivePipeline bool
NoReleasePrepare bool
Duration time.Duration
FromRepo bool
NoKaniko bool
SemanticRelease bool
DisableGitClone bool
NoOutput bool
KanikoImage string
KanikoSecretMount string
KanikoSecret string
KanikoSecretKey string
ProjectID string
DockerRegistry string
DockerRegistryOrg string
KanikoFlags string
AdditionalEnvVars map[string]string
PodTemplates map[string]*corev1.Pod
UseBranchAsRevision bool
GitInfo *gits.GitRepository
BuildNumber string
labels map[string]string
Results tekton.CRDWrapper
pipelineParams []pipelineapi.Param
version string
previewVersionPrefix string
VersionResolver *versionstream.VersionResolver
CloneDir string
EffectiveProjectConfig *config.ProjectConfig
}
// NewCmdStepCreateTask Creates a new Command object
func NewCmdStepCreateTask(commonOpts *opts.CommonOptions) *cobra.Command {
cmd, _ := NewCmdStepCreateTaskAndOption(commonOpts)
return cmd
}
// NewCmdStepCreateTaskAndOption Creates a new Command object and returns the options
func NewCmdStepCreateTaskAndOption(commonOpts *opts.CommonOptions) (*cobra.Command, *StepCreateTaskOptions) {
options := &StepCreateTaskOptions{
StepOptions: step.StepOptions{
CommonOptions: commonOpts,
},
}
cmd := &cobra.Command{
Use: "task",
Short: "Creates a Tekton PipelineRun for the current folder or given build pack",
Long: createTaskLong,
Example: createTaskExample,
Aliases: []string{"bt"},
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
helper.CheckErr(err)
},
}
cmd.Flags().StringVarP(&createTaskOutDir, outputOptionName, "o", "out", "The directory to write the output to as YAML. Defaults to 'out'")
cmd.Flags().StringVarP(&options.Branch, "branch", "", "", "The git branch to trigger the build in. Defaults to the current local branch name")
cmd.Flags().StringVarP(&options.Revision, "revision", "", "", "The git revision to checkout, can be a branch name or git sha")
cmd.Flags().StringVarP(&options.PipelineKind, "kind", "k", "release", "The kind of pipeline to create such as: "+strings.Join(jenkinsfile.PipelineKinds, ", "))
cmd.Flags().StringArrayVarP(&options.CustomLabels, "label", "l", nil, "List of custom labels to be applied to resources that are created")
cmd.Flags().StringArrayVarP(&options.CustomEnvs, "env", "e", nil, "List of custom environment variables to be applied to resources that are created")
cmd.Flags().StringVarP(&options.CloneGitURL, "clone-git-url", "", "", "Specify the git URL to clone to a temporary directory to get the source code")
cmd.Flags().StringVarP(&options.CloneDir, "clone-dir", "", "", "Specify the directory of the directory containing the git clone")
cmd.Flags().StringVarP(&options.PullRequestNumber, "pr-number", "", "", "If a Pull Request this is it's number")
cmd.Flags().StringVarP(&options.BuildNumber, "build-number", "", "", "The build number")
cmd.Flags().BoolVarP(&createTaskNoApply, noApplyOptionName, "", false, "Disables creating the Pipeline resources in the kubernetes cluster and just outputs the generated Task to the console or output file")
cmd.Flags().BoolVarP(&options.DryRun, "dry-run", "", false, "Disables creating the Pipeline resources in the kubernetes cluster and just outputs the generated Task to the console or output file, without side effects")
cmd.Flags().BoolVarP(&options.InterpretMode, "interpret", "", false, "Enable interpret mode. Rather than spinning up Tekton CRDs to create a Pod just invoke the commands in the current shell directly. Useful for bootstrapping installations of Jenkins X and tekton using a pipeline before you have installed Tekton.")
cmd.Flags().StringVarP(&options.StartStep, "start-step", "", "", "When in interpret mode this specifies the step to start at")
cmd.Flags().StringVarP(&options.EndStep, "end-step", "", "", "When in interpret mode this specifies the step to end at")
cmd.Flags().BoolVarP(&options.ViewSteps, "view", "", false, "Just view the steps that would be created")
cmd.Flags().BoolVarP(&options.EffectivePipeline, "effective-pipeline", "", false, "Just view the effective pipeline definition that would be created")
cmd.Flags().BoolVarP(&options.SemanticRelease, "semantic-release", "", false, "Enable semantic releases")
cmd.Flags().BoolVarP(&options.UseBranchAsRevision, "branch-as-revision", "", false, "Use the provided branch as the revision for release pipelines, not the version tag")
options.AddCommonFlags(cmd)
options.setupViper(cmd)
return cmd, options
}
func (o *StepCreateTaskOptions) setupViper(cmd *cobra.Command) {
replacer := strings.NewReplacer("-", "_")
viper.SetEnvKeyReplacer(replacer)
_ = viper.BindEnv(noApplyOptionName)
_ = viper.BindPFlag(noApplyOptionName, cmd.Flags().Lookup(noApplyOptionName))
_ = viper.BindEnv(outputOptionName)
_ = viper.BindPFlag(outputOptionName, cmd.Flags().Lookup(outputOptionName))
}
// AddCommonFlags adds common CLI options
func (o *StepCreateTaskOptions) AddCommonFlags(cmd *cobra.Command) {
cmd.Flags().StringVarP(&o.Pack, "pack", "p", "", "The build pack name. If none is specified its discovered from the source code")
cmd.Flags().StringVarP(&o.BuildPackURL, "url", "u", "", "The URL for the build pack Git repository")
cmd.Flags().StringVarP(&o.BuildPackRef, "ref", "r", "", "The Git reference (branch,tag,sha) in the Git repository to use")
cmd.Flags().StringVarP(&o.Context, "context", "c", "", "The pipeline context if there are multiple separate pipelines for a given branch")
cmd.Flags().StringVarP(&o.ServiceAccount, "service-account", "", tekton.DefaultPipelineSA, "The Kubernetes ServiceAccount to use to run the pipeline")
cmd.Flags().StringVarP(&o.TargetPath, "target-path", "", "", "The target path appended to /workspace/${source} to clone the source code")
cmd.Flags().StringVarP(&o.SourceName, "source", "", "source", "The name of the source repository")
cmd.Flags().StringVarP(&o.CustomImage, "image", "", "", "Specify a custom image to use for the steps which overrides the image in the PodTemplates")
cmd.Flags().StringVarP(&o.DefaultImage, "default-image", "", syntax.DefaultContainerImage, "Specify the docker image to use if there is no image specified for a step and there's no Pod Template")
cmd.Flags().BoolVarP(&o.DeleteTempDir, "delete-temp-dir", "", true, "Deletes the temporary directory of cloned files if using the 'clone-git-url' option")
cmd.Flags().BoolVarP(&o.NoReleasePrepare, "no-release-prepare", "", false, "Disables creating the release version number and tagging git and triggering the release pipeline from the new tag")
cmd.Flags().BoolVarP(&o.NoKaniko, "no-kaniko", "", false, "Disables using kaniko directly for building docker images")
cmd.Flags().StringVarP(&o.KanikoImage, "kaniko-image", "", syntax.KanikoDockerImage, "The docker image for Kaniko")
cmd.Flags().StringVarP(&o.KanikoSecretMount, "kaniko-secret-mount", "", kanikoSecretMount, "The mount point of the Kaniko secret")
cmd.Flags().StringVarP(&o.KanikoSecret, "kaniko-secret", "", kanikoSecretName, "The name of the kaniko secret")
cmd.Flags().StringVarP(&o.KanikoSecretKey, "kaniko-secret-key", "", kanikoSecretKey, "The key in the Kaniko Secret to mount")
cmd.Flags().StringVarP(&o.ProjectID, "project-id", "", "", "The cloud project ID. If not specified we default to the install project")
cmd.Flags().StringVarP(&o.DockerRegistry, "docker-registry", "", "", "The Docker Registry host name to use which is added as a prefix to docker images")
cmd.Flags().StringVarP(&o.DockerRegistryOrg, "docker-registry-org", "", "", "The Docker registry organisation. If blank the git repository owner is used")
cmd.Flags().StringVarP(&o.KanikoFlags, "kaniko-flags", "", "", "Optional flags to pass to kaniko builds; such as to indicate --insecure docker registry being used")
cmd.Flags().DurationVarP(&o.Duration, "duration", "", time.Second*30, "Retry duration when trying to create a PipelineRun")
}
// Run implements this command
func (o *StepCreateTaskOptions) Run() error {
if o.NoApply == nil {
b := viper.GetBool(noApplyOptionName)
o.NoApply = &b
}
if o.OutDir == "" {
s := viper.GetString(outputOptionName)
o.OutDir = s
}
var effectiveProjectConfig *config.ProjectConfig
var err error
tektonClient, jxClient, kubeClient, ns, err := o.getClientsAndNamespace()
if err != nil {
return err
}
if o.CloneDir == "" {
o.CloneDir, err = os.Getwd()
if err != nil {
return err
}
}
if o.VersionResolver == nil {
o.VersionResolver, err = o.GetVersionResolver()
if err != nil {
return errors.Wrap(err, "Unable to create version resolver")
}
}
pr, err := o.parsePullRefs()
if err != nil {
return errors.Wrap(err, "Unable to find or parse PULL_REFS from custom environment")
}
exists, err := o.effectiveProjectConfigExists()
if err != nil {
return err
}
if !exists {
// TODO this branch all things depending on it can be removed once the meta pipeline is working
// TODO keeping this to keep existing behavior until then (HF)
if o.CloneGitURL != "" && !o.DisableGitClone {
o.CloneDir = o.cloneGitRepositoryToTempDir(o.CloneGitURL, o.Branch, o.PullRequestNumber, o.Revision)
if o.DeleteTempDir {
defer func() {
log.Logger().Infof("removing the temp directory %s", o.CloneDir)
err := os.RemoveAll(o.CloneDir)
if err != nil {
log.Logger().Warnf("failed to delete dir %s: %s", o.CloneDir, err.Error())
}
}()
}
// Add the REPO_URL env var
o.CustomEnvs = append(o.CustomEnvs, fmt.Sprintf("%s=%s", "REPO_URL", o.CloneGitURL))
err = o.mergePullRefs(pr, o.CloneDir)
if err != nil {
return errors.Wrapf(err, "Unable to merge PULL_REFS %s in %s", pr, o.CloneDir)
}
}
}
o.GitInfo, err = o.FindGitInfo(o.CloneDir)
if err != nil {
return errors.Wrapf(err, "failed to find git information from dir %s", o.CloneDir)
}
if o.Branch == "" {
o.Branch, err = o.Git().Branch(o.CloneDir)
if err != nil {
return errors.Wrapf(err, "failed to find git branch from dir %s", o.CloneDir)
}
}
o.PodTemplates, err = kube.LoadPodTemplates(kubeClient, ns)
if err != nil {
return errors.Wrap(err, "Unable to load pod templates")
}
pipelineName := tekton.PipelineResourceNameFromGitInfo(o.GitInfo, o.Branch, o.Context, tekton.BuildPipeline.String())
if o.KanikoFlags == "" {
data, err := kube.GetConfigMapData(kubeClient, kube.ConfigMapJenkinsDockerRegistry, ns)
if err == nil {
o.KanikoFlags = data["kaniko.flags"]
}
}
exists, err = o.effectiveProjectConfigExists()
if err != nil {
return err
}
if exists {
effectiveProjectConfig, err = o.loadEffectiveProjectConfig()
log.Logger().Debug("loaded effective project configuration from file")
} else {
// TODO: This branch also goes away when the metapipeline is actually in place in pipelinerunner (AB)
log.Logger().Debug("Creating effective project configuration")
effectiveProjectConfig, err = o.createEffectiveProjectConfigFromOptions(tektonClient, jxClient, kubeClient, ns, pipelineName)
if err != nil {
return errors.Wrap(err, "failed to create effective project configuration")
}
}
o.EffectiveProjectConfig = effectiveProjectConfig
err = o.setBuildValues()
if err != nil {
return err
}
log.Logger().Debug("Setting build version")
err = o.setBuildVersion(effectiveProjectConfig)
if err != nil {
return errors.Wrapf(err, "failed to set the version on release pipelines")
}
log.Logger().Debug("Creating Tekton CRDs")
tektonCRDs, err := o.generateTektonCRDs(effectiveProjectConfig, ns, pipelineName)
if err != nil {
return errors.Wrap(err, "failed to generate Tekton CRDs")
}
log.Logger().Debugf("Tekton CRDs for %s created", tektonCRDs.PipelineRun().Name)
o.Results = *tektonCRDs
if o.ViewSteps {
err = o.viewSteps(tektonCRDs.Tasks()...)
if err != nil {
return errors.Wrap(err, "unable to view pipeline steps")
}
return nil
}
if o.InterpretMode {
return o.interpretPipeline(ns, effectiveProjectConfig, tektonCRDs)
}
if *o.NoApply || o.DryRun {
if !o.NoOutput {
log.Logger().Infof("Writing output ")
err := tektonCRDs.WriteToDisk(o.OutDir, nil)
if err != nil {
return errors.Wrapf(err, "Failed to output Tekton CRDs")
}
}
} else {
activityKey := tekton.GeneratePipelineActivity(o.BuildNumber, o.Branch, o.GitInfo, o.Context, pr)
log.Logger().Debugf(" PipelineActivity for %s created successfully", tektonCRDs.Name())
if o.DisableConcurrent {
o.waitForPreviousPipeline(tektonClient, ns, 10*time.Minute)
}
log.Logger().Infof("Applying changes ")
err := tekton.ApplyPipeline(jxClient, kubeClient, tektonClient, tektonCRDs, ns, activityKey)
if err != nil {
return errors.Wrapf(err, "failed to apply Tekton CRDs")
}
tektonCRDs.AddLabels(o.labels)
log.Logger().Debugf(" for %s", tektonCRDs.PipelineRun().Name)
}
return nil
}
func (o *StepCreateTaskOptions) waitForPreviousPipeline(tektonClient tektonclient.Interface, ns string, defaultWait time.Duration) {
fallbackWait := true
labelSelector := fmt.Sprintf("owner=%s,repository=%s,branch=%s", o.GitInfo.Organisation, o.GitInfo.Name, o.Branch)
if o.Context != "" {
labelSelector += fmt.Sprintf(",context=%s", o.Context)
}
restartWatch:
prs, err := tektonClient.TektonV1alpha1().PipelineRuns(ns).List(metav1.ListOptions{
LabelSelector: labelSelector,
})
if err != nil {
log.Logger().Errorf("Can't list PipelineRuns %s: %s", labelSelector, err)
} else {
pendingPipelineRuns := make(map[string]bool)
for _, pr := range prs.Items {
if !(pr.IsDone() || pr.IsCancelled()) {
pendingPipelineRuns[pr.Name] = true
}
}
if len(pendingPipelineRuns) > 0 {
log.Logger().Infof("Waiting for pending PipelineRuns %v to finish or be deleted", reflect.ValueOf(pendingPipelineRuns).MapKeys())
pipelineWatch, err := tektonClient.TektonV1alpha1().PipelineRuns(ns).Watch(metav1.ListOptions{
LabelSelector: labelSelector,
ResourceVersion: prs.ResourceVersion,
})
if err != nil {
log.Logger().Errorf("Can't watch PipelineRun %s (ResourceVersion %s): %s", labelSelector, prs.ResourceVersion, err)
} else {
for {
update := <-pipelineWatch.ResultChan()
if o.Verbose {
bytes, err := json.MarshalIndent(update, "", "\t")
log.Logger().Debugf("PipelineRun watch update: %s %s", bytes, err)
}
switch update.Type {
case watch.Deleted:
pr := update.Object.(*pipelineapi.PipelineRun)
if pendingPipelineRuns[pr.Name] {
log.Logger().Infof("PipelineRun %s is deleted", pr.Name)
delete(pendingPipelineRuns, pr.Name)
}
case watch.Modified:
pr := update.Object.(*pipelineapi.PipelineRun)
if pendingPipelineRuns[pr.Name] && (pr.IsDone() || pr.IsCancelled()) {
log.Logger().Infof("PipelineRun %s is finished", pr.Name)
delete(pendingPipelineRuns, pr.Name)
}
case watch.Added:
pr := update.Object.(*pipelineapi.PipelineRun)
if !(pr.IsDone() || pr.IsCancelled()) {
log.Logger().Infof("PipelineRun %s is added", pr.Name)
pendingPipelineRuns[pr.Name] = true
}
default:
log.Logger().Errorf("Unknown PipelineRun watch update. Restarting watch.")
pipelineWatch.Stop()
goto restartWatch
}
if len(pendingPipelineRuns) == 0 {
pipelineWatch.Stop()
fallbackWait = false
break
}
}
}
} else {
fallbackWait = false
}
}
// When failing to wait for a pipeline wait for defaultWait.
if fallbackWait {
sleepDuration := defaultWait - time.Now().Sub(lastPipelineRun)
if sleepDuration > 0 {
log.Logger().Errorf("Can't access previous PipelineRun. Waiting %v to ensure it finishes", sleepDuration)
time.Sleep(sleepDuration)
}
lastPipelineRun = time.Now()
}
}
func (o *StepCreateTaskOptions) createEffectiveProjectConfigFromOptions(tektonClient tektonclient.Interface, jxClient jxclient.Interface, kubeClient kubeclient.Interface, ns string, pipelineName string) (*config.ProjectConfig, error) {
if o.InterpretMode {
// lets allow this command to run in an empty cluster
o.RemoteCluster = true
}
settings, err := o.TeamSettings()
if err != nil {
return nil, err
}
if o.ProjectID == "" {
if !o.RemoteCluster {
data, err := kube.ReadInstallValues(kubeClient, ns)
if err != nil {
return nil, errors.Wrapf(err, "failed to read install values from namespace %s", ns)
}
o.ProjectID = data["projectID"]
}
if o.ProjectID == "" {
o.ProjectID = "todo"
}
}
if o.DefaultImage == "" {
o.DefaultImage = syntax.DefaultContainerImage
}
if o.KanikoImage == "" {
o.KanikoImage = syntax.KanikoDockerImage
}
o.KanikoImage, err = o.VersionResolver.ResolveDockerImage(o.KanikoImage)
if err != nil {
return nil, err
}
if o.KanikoSecretMount == "" {
o.KanikoSecretMount = kanikoSecretMount
}
if o.DockerRegistry == "" && !o.InterpretMode {
data, err := kube.GetConfigMapData(kubeClient, kube.ConfigMapJenkinsDockerRegistry, ns)
if err != nil {
return nil, fmt.Errorf("could not find ConfigMap %s in namespace %s: %s", kube.ConfigMapJenkinsDockerRegistry, ns, err)
}
o.DockerRegistry = data["docker.registry"]
if o.DockerRegistry == "" {
return nil, util.MissingOption("docker-registry")
}
}
if o.BuildNumber == "" {
if *o.NoApply || o.DryRun || o.InterpretMode {
o.BuildNumber = "1"
} else {
log.Logger().Debugf("generating build number...")
o.BuildNumber, err = tekton.GenerateNextBuildNumber(tektonClient, jxClient, ns, o.GitInfo, o.Branch, o.Duration, o.Context, false)
if err != nil {
return nil, err
}
log.Logger().Debugf("generated build number %s for %s", o.BuildNumber, o.CloneGitURL)
}
}
projectConfig, projectConfigFile, err := o.loadProjectConfig()
if err != nil {
return nil, errors.Wrapf(err, "failed to load project config in dir %s", o.CloneDir)
}
if o.BuildPackURL == "" || o.BuildPackRef == "" {
if projectConfig.BuildPackGitURL != "" {
o.BuildPackURL = projectConfig.BuildPackGitURL
} else if o.BuildPackURL == "" {
o.BuildPackURL = settings.BuildPackURL
}
if projectConfig.BuildPackGitURef != "" {
o.BuildPackRef = projectConfig.BuildPackGitURef
} else if o.BuildPackRef == "" {
o.BuildPackRef = settings.BuildPackRef
}
}
if o.BuildPackURL == "" {
return nil, util.MissingOption("url")
}
if o.BuildPackRef == "" {
return nil, util.MissingOption("ref")
}
if o.PipelineKind == "" {
return nil, util.MissingOption("kind")
}
if o.Pack == "" {
o.Pack = projectConfig.BuildPack
}
if o.Pack == "" {
o.Pack, err = o.DiscoverBuildPack(o.CloneDir, projectConfig, o.Pack)
if err != nil {
return nil, errors.Wrapf(err, "failed to discover the build pack")
}
}
if o.Pack == "" {
return nil, util.MissingOption("pack")
}
packsDir, err := gitresolver.InitBuildPack(o.Git(), o.BuildPackURL, o.BuildPackRef)
if err != nil {
return nil, err
}
resolver, err := gitresolver.CreateResolver(packsDir, o.Git())
if err != nil {
return nil, err
}
log.Logger().Debug("creating effective project configuration")
effectiveProjectConfig, err := o.createEffectiveProjectConfig(packsDir, projectConfig, projectConfigFile, resolver, ns)
return effectiveProjectConfig, err
}
// createEffectiveProjectConfig creates the effective parsed pipeline which is then used to generate the Tekton CRDs.
func (o *StepCreateTaskOptions) createEffectiveProjectConfig(packsDir string, projectConfig *config.ProjectConfig, projectConfigFile string, resolver jenkinsfile.ImportFileResolver, ns string) (*config.ProjectConfig, error) {
createEffective := &syntaxstep.StepSyntaxEffectiveOptions{
Pack: o.Pack,
BuildPackURL: o.BuildPackURL,
BuildPackRef: o.BuildPackRef,
Context: o.Context,
CustomImage: o.CustomImage,
DefaultImage: o.DefaultImage,
UseKaniko: !o.NoKaniko,
KanikoImage: o.KanikoImage,
ProjectID: o.ProjectID,
DockerRegistry: o.DockerRegistry,
DockerRegistryOrg: o.DockerRegistryOrg,
SourceName: o.SourceName,
CustomEnvs: o.CustomEnvs,
GitInfo: o.GitInfo,
PodTemplates: o.PodTemplates,
VersionResolver: o.VersionResolver,
ValidateInCluster: !o.InterpretMode,
}
commonCopy := *o.CommonOptions
createEffective.CommonOptions = &commonCopy
effectiveProjectConfig, err := createEffective.CreateEffectivePipeline(packsDir, projectConfig, projectConfigFile, resolver)
if err != nil {
return nil, errors.Wrapf(err, "effective pipeline creation failed")
}
// lets allow a `jenkins-x.yml` to specify we want to disable release prepare mode which can be useful for
// working with custom jenkins pipelines in custom jenkins servers
if projectConfig.NoReleasePrepare {
o.NoReleasePrepare = true
}
parsed, err := effectiveProjectConfig.GetPipeline(o.PipelineKind)
if err != nil {
return nil, err
}
if o.EffectivePipeline {
log.Logger().Info("Successfully generated effective pipeline:")
effective := &jenkinsfile.PipelineLifecycles{
Pipeline: parsed,
}
effectiveYaml, _ := yaml.Marshal(effective)
log.Logger().Infof("%s", effectiveYaml)
return nil, nil
}
return effectiveProjectConfig, nil
}
// GenerateTektonCRDs creates the Pipeline, Task, PipelineResource, PipelineRun, and PipelineStructure CRDs that will be applied to actually kick off the pipeline
func (o *StepCreateTaskOptions) generateTektonCRDs(effectiveProjectConfig *config.ProjectConfig, ns string, pipelineName string) (*tekton.CRDWrapper, error) {
if effectiveProjectConfig == nil {
return nil, errors.New("effective project config cannot be nil")
}
effectivePipeline, err := effectiveProjectConfig.GetPipeline(o.PipelineKind)
if err != nil {
return nil, errors.Wrapf(err, "unable to extract the requested pipeline")
}
crdParams := syntax.CRDsFromPipelineParams{
PipelineIdentifier: pipelineName,
BuildIdentifier: o.BuildNumber,
Namespace: ns,
PodTemplates: o.PodTemplates,
VersionsDir: o.VersionResolver.VersionsDir,
TaskParams: o.getDefaultTaskInputs().Params,
SourceDir: o.SourceName,
Labels: o.labels,
DefaultImage: "",
InterpretMode: o.InterpretMode,
}
pipeline, tasks, structure, err := effectivePipeline.GenerateCRDs(crdParams)
if err != nil {
return nil, errors.Wrapf(err, "generation failed for Pipeline")
}
tasks, pipeline = o.enhanceTasksAndPipeline(tasks, pipeline, effectiveProjectConfig.PipelineConfig.Env)
resources := []*pipelineapi.PipelineResource{tekton.GenerateSourceRepoResource(pipelineName, o.GitInfo, o.Revision)}
var timeout *metav1.Duration
if effectivePipeline.Options != nil && effectivePipeline.Options.Timeout != nil {
timeout, err = effectivePipeline.Options.Timeout.ToDuration()
if err != nil {
return nil, errors.Wrapf(err, "parsing of pipeline timeout failed")
}
}
prLabels := util.MergeMaps(o.labels, effectivePipeline.GetPodLabels())
run := tekton.CreatePipelineRun(resources, pipeline.Name, pipeline.APIVersion, prLabels, o.ServiceAccount, o.pipelineParams, timeout, effectivePipeline.GetPossibleAffinityPolicy(pipeline.Name), effectivePipeline.GetTolerations())
tektonCRDs, err := tekton.NewCRDWrapper(pipeline, tasks, resources, structure, run)
if err != nil {
return nil, err
}
return tektonCRDs, nil
}
func (o *StepCreateTaskOptions) loadProjectConfig() (*config.ProjectConfig, string, error) {
if o.Context != "" {
fileName := filepath.Join(o.CloneDir, fmt.Sprintf("jenkins-x-%s.yml", o.Context))
exists, err := util.FileExists(fileName)
if err != nil {
return nil, fileName, errors.Wrapf(err, "failed to check if file exists %s", fileName)
}
if exists {
config, err := config.LoadProjectConfigFile(fileName)
return config, fileName, err
}
}
return config.LoadProjectConfig(o.CloneDir)
}
func (o *StepCreateTaskOptions) effectiveProjectConfigExists() (bool, error) {
fileName := o.CloneDir
if o.Context == "" {
fileName = filepath.Join(fileName, "jenkins-x-effective.yml")
} else {
fileName = filepath.Join(fileName, fmt.Sprintf("jenkins-x-%s-effective.yml", o.Context))
}
exists, err := util.FileExists(fileName)
if err != nil {
return false, errors.Wrapf(err, "failed to check existence of %s", fileName)
}
return exists, nil
}
func (o *StepCreateTaskOptions) loadEffectiveProjectConfig() (*config.ProjectConfig, error) {
fileName := o.CloneDir
if o.Context == "" {
fileName = filepath.Join(fileName, "jenkins-x-effective.yml")
} else {
fileName = filepath.Join(fileName, fmt.Sprintf("jenkins-x-%s-effective.yml", o.Context))
}
projectConfig, err := config.LoadProjectConfigFile(fileName)
return projectConfig, err
}
// getDefaultTaskInputs gets the base, built-in task parameters as an Input.
func (o *StepCreateTaskOptions) getDefaultTaskInputs() *pipelineapi.Inputs {
inputs := &pipelineapi.Inputs{}
taskParams := o.createTaskParams()
if len(taskParams) > 0 {
inputs.Params = taskParams
}
return inputs
}
func (o *StepCreateTaskOptions) enhanceTaskWithVolumesEnvAndInputs(task *pipelineapi.Task, env []corev1.EnvVar, inputs pipelineapi.Inputs) {
volumes := task.Spec.Volumes
for i, step := range task.Spec.Steps {
volumes = o.modifyVolumes(&step.Container, volumes)
o.modifyEnvVars(&step.Container, env)
task.Spec.Steps[i] = step
}
task.Spec.Volumes = volumes
if task.Spec.Inputs == nil {
task.Spec.Inputs = &inputs
} else {
task.Spec.Inputs.Params = inputs.Params
}
}
// enhanceTasksAndPipeline takes a slice of Tasks and a Pipeline and modifies them to include built-in volumes, environment variables, and parameters
func (o *StepCreateTaskOptions) enhanceTasksAndPipeline(tasks []*pipelineapi.Task, pipeline *pipelineapi.Pipeline, env []corev1.EnvVar) ([]*pipelineapi.Task, *pipelineapi.Pipeline) {
taskInputs := o.getDefaultTaskInputs()
for _, t := range tasks {
o.enhanceTaskWithVolumesEnvAndInputs(t, env, *taskInputs)
}
taskParams := o.createPipelineTaskParams()
for i, pt := range pipeline.Spec.Tasks {
for _, tp := range taskParams {
if !hasPipelineParam(pt.Params, tp.Name) {
pt.Params = append(pt.Params, tp)
pipeline.Spec.Tasks[i] = pt
}
}
}
pipeline.Spec.Params = o.createPipelineParams()
if pipeline.APIVersion == "" {
pipeline.APIVersion = syntax.TektonAPIVersion
}
if pipeline.Kind == "" {
pipeline.Kind = "Pipeline"
}
return tasks, pipeline
}
func (o *StepCreateTaskOptions) createTaskParams() []pipelineapi.ParamSpec {
taskParams := []pipelineapi.ParamSpec{}
for _, param := range o.pipelineParams {
name := param.Name
description := ""
defaultValue := ""
switch name {
case "version":
description = "the version number for this pipeline which is used as a tag on docker images and helm charts"
defaultValue = o.version
case "build_id":
description = "the PipelineRun build number"
defaultValue = o.BuildNumber
}
stringParamDefaultValue := syntax.StringParamValue(defaultValue)
taskParams = append(taskParams, pipelineapi.ParamSpec{
Name: name,
Description: description,
Default: &stringParamDefaultValue,
Type: pipelineapi.ParamTypeString,
})
}
return taskParams
}
func (o *StepCreateTaskOptions) createPipelineParams() []pipelineapi.ParamSpec {
answer := []pipelineapi.ParamSpec{}
taskParams := o.createTaskParams()
for _, tp := range taskParams {
answer = append(answer, pipelineapi.ParamSpec{
Name: tp.Name,
Description: tp.Description,
Default: tp.Default,
Type: tp.Type,
})
}
return answer
}
func (o *StepCreateTaskOptions) createPipelineTaskParams() []pipelineapi.Param {
ptp := []pipelineapi.Param{}
for _, p := range o.pipelineParams {
ptp = append(ptp, pipelineapi.Param{
Name: p.Name,
Value: syntax.StringParamValue(fmt.Sprintf("$(params.%s)", p.Name)),
})
}
return ptp
}
func (o *StepCreateTaskOptions) setBuildValues() error {
labels := map[string]string{}
if o.GitInfo != nil {
labels[tekton.LabelOwner] = o.GitInfo.Organisation
labels[tekton.LabelRepo] = o.GitInfo.Name
}
labels[tekton.LabelBranch] = o.Branch
if o.Context != "" {
labels[tekton.LabelContext] = o.Context
}
labels[tekton.LabelBuild] = o.BuildNumber
labels[tekton.LabelType] = tekton.BuildPipeline.String()
return o.combineLabels(labels)
}
func (o *StepCreateTaskOptions) combineLabels(labels map[string]string) error {
// add any custom labels
customLabels, err := util.ExtractKeyValuePairs(o.CustomLabels, "=")
if err != nil {
return err
}
o.labels = util.MergeMaps(labels, customLabels)
return nil
}
func (o *StepCreateTaskOptions) getWorkspaceDir() string {
return filepath.Join("/workspace", o.SourceName)
}
func (o *StepCreateTaskOptions) modifyEnvVars(container *corev1.Container, globalEnv []corev1.EnvVar) {
envVars := []corev1.EnvVar{}
for _, e := range container.Env {
name := e.Name
if name != "JENKINS_URL" {
envVars = append(envVars, e)
}
}
if kube.GetSliceEnvVar(envVars, "DOCKER_REGISTRY") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "DOCKER_REGISTRY",
Value: o.DockerRegistry,
})
}
if kube.GetSliceEnvVar(envVars, "DOCKER_REGISTRY_ORG") == nil && o.DockerRegistryOrg != "" {
envVars = append(envVars, corev1.EnvVar{
Name: "DOCKER_REGISTRY_ORG",
Value: o.DockerRegistryOrg,
})
}
if kube.GetSliceEnvVar(envVars, "KANIKO_FLAGS") == nil && o.KanikoFlags != "" {
envVars = append(envVars, corev1.EnvVar{
Name: "KANIKO_FLAGS",
Value: o.KanikoFlags,
})
}
if kube.GetSliceEnvVar(envVars, "BUILD_NUMBER") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "BUILD_NUMBER",
Value: o.BuildNumber,
})
}
if o.PipelineKind != "" && kube.GetSliceEnvVar(envVars, "PIPELINE_KIND") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "PIPELINE_KIND",
Value: o.PipelineKind,
})
}
if o.Context != "" && kube.GetSliceEnvVar(envVars, "PIPELINE_CONTEXT") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "PIPELINE_CONTEXT",
Value: o.Context,
})
}
gitUserName := util.DefaultGitUserName
gitUserEmail := util.DefaultGitUserEmail
settings, err := o.TeamSettings()
// If there's an error getting the team settings, just ignore it and keep using the defaults.
if err == nil {
if settings.PipelineUsername != "" {
gitUserName = settings.PipelineUsername
}
if settings.PipelineUserEmail != "" {
gitUserEmail = settings.PipelineUserEmail
}
}
if kube.GetSliceEnvVar(envVars, "GIT_AUTHOR_NAME") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "GIT_AUTHOR_NAME",
Value: gitUserName,
})
}
if kube.GetSliceEnvVar(envVars, "GIT_AUTHOR_EMAIL") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "GIT_AUTHOR_EMAIL",
Value: gitUserEmail,
})
}
if kube.GetSliceEnvVar(envVars, "GIT_COMMITTER_NAME") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "GIT_COMMITTER_NAME",
Value: gitUserName,
})
}
if kube.GetSliceEnvVar(envVars, "GIT_COMMITTER_EMAIL") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "GIT_COMMITTER_EMAIL",
Value: gitUserEmail,
})
}
gitInfo := o.GitInfo
branch := o.Branch
if gitInfo != nil {
u := gitInfo.CloneURL
if u != "" && kube.GetSliceEnvVar(envVars, "SOURCE_URL") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "SOURCE_URL",
Value: u,
})
}
repo := gitInfo.Name
owner := gitInfo.Organisation
if owner != "" && kube.GetSliceEnvVar(envVars, "REPO_OWNER") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "REPO_OWNER",
Value: owner,
})
}
if repo != "" && kube.GetSliceEnvVar(envVars, "REPO_NAME") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "REPO_NAME",
Value: repo,
})
}
if owner != "" && repo != "" && branch != "" {
jobName := fmt.Sprintf("%s/%s/%s", owner, repo, branch)
if kube.GetSliceEnvVar(envVars, "JOB_NAME") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "JOB_NAME",
Value: jobName,
})
}
}
// lets keep the APP_NAME environment variable we need for previews
if repo != "" && kube.GetSliceEnvVar(envVars, "APP_NAME") == nil {
envVars = append(envVars, corev1.EnvVar{
Name: "APP_NAME",
Value: repo,
})
}
}
if branch != "" {
if kube.GetSliceEnvVar(envVars, util.EnvVarBranchName) == nil {
envVars = append(envVars, corev1.EnvVar{
Name: util.EnvVarBranchName,