-
Notifications
You must be signed in to change notification settings - Fork 787
/
pipeline.go
2507 lines (2190 loc) · 74.4 KB
/
pipeline.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 syntax
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
v1 "github.com/jenkins-x/jx/v2/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/v2/pkg/kube/naming"
"github.com/jenkins-x/jx/v2/pkg/log"
"github.com/jenkins-x/jx/v2/pkg/util"
"github.com/jenkins-x/jx/v2/pkg/versionstream"
"github.com/knative/pkg/apis"
"github.com/pkg/errors"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
tektonv1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/kubernetes"
)
const (
// GitMergeImage is the default image name that is used in the git merge step of a pipeline
GitMergeImage = "gcr.io/jenkinsxio/builder-jx"
// WorkingDirRoot is the root directory for working directories.
WorkingDirRoot = "/workspace"
// braceMatchingRegex matches "${inputs.params.foo}" so we can replace it with "$(inputs.params.foo)"
braceMatchingRegex = "(\\$(\\{(?P<var>inputs\\.params\\.[_a-zA-Z][_a-zA-Z0-9.-]*)\\}))"
)
var (
ipAddressRegistryRegex = regexp.MustCompile(`\d+\.\d+\.\d+\.\d+.\d+(:\d+)?`)
commandIsSkaffoldRegex = regexp.MustCompile(`export VERSION=.*? && skaffold build.*`)
)
// ParsedPipeline is the internal representation of the Pipeline, used to validate and create CRDs
type ParsedPipeline struct {
Agent *Agent `json:"agent,omitempty"`
Env []corev1.EnvVar `json:"env,omitempty"`
Options *RootOptions `json:"options,omitempty"`
Stages []Stage `json:"stages"`
Post []Post `json:"post,omitempty"`
WorkingDir *string `json:"dir,omitempty"`
// Replaced by Env, retained for backwards compatibility
Environment []corev1.EnvVar `json:"environment,omitempty"`
}
// Agent defines where the pipeline, stage, or step should run.
type Agent struct {
// One of label or image is required.
Label string `json:"label,omitempty"`
Image string `json:"image,omitempty"`
// Legacy fields from jenkinsfile.PipelineAgent
Container string `json:"container,omitempty"`
Dir string `json:"dir,omitempty"`
}
// TimeoutUnit is used for calculating timeout duration
type TimeoutUnit string
// The available time units.
const (
TimeoutUnitSeconds TimeoutUnit = "seconds"
TimeoutUnitMinutes TimeoutUnit = "minutes"
TimeoutUnitHours TimeoutUnit = "hours"
TimeoutUnitDays TimeoutUnit = "days"
)
// All possible time units, used for validation
var allTimeoutUnits = []TimeoutUnit{TimeoutUnitSeconds, TimeoutUnitMinutes, TimeoutUnitHours, TimeoutUnitDays}
func allTimeoutUnitsAsStrings() []string {
tu := make([]string, len(allTimeoutUnits))
for i, u := range allTimeoutUnits {
tu[i] = string(u)
}
return tu
}
// Timeout defines how long a stage or pipeline can run before timing out.
type Timeout struct {
Time int64 `json:"time"`
// Has some sane default - probably seconds
Unit TimeoutUnit `json:"unit,omitempty"`
}
// ToDuration generates a duration struct from a Timeout
func (t *Timeout) ToDuration() (*metav1.Duration, error) {
durationStr := ""
// TODO: Populate a default timeout unit, most likely seconds.
if t.Unit != "" {
durationStr = fmt.Sprintf("%d%c", t.Time, t.Unit[0])
} else {
durationStr = fmt.Sprintf("%ds", t.Time)
}
d, err := time.ParseDuration(durationStr)
if err != nil {
return nil, err
}
return &metav1.Duration{Duration: d}, nil
}
// RootOptions contains options that can be configured on either a pipeline or a stage
type RootOptions struct {
Timeout *Timeout `json:"timeout,omitempty"`
Retry int8 `json:"retry,omitempty"`
// ContainerOptions allows for advanced configuration of containers for a single stage or the whole
// pipeline, adding to configuration that can be configured through the syntax already. This includes things
// like CPU/RAM requests/limits, secrets, ports, etc. Some of these things will end up with native syntax approaches
// down the road.
ContainerOptions *corev1.Container `json:"containerOptions,omitempty"`
Volumes []*corev1.Volume `json:"volumes,omitempty"`
DistributeParallelAcrossNodes bool `json:"distributeParallelAcrossNodes,omitempty"`
Tolerations []corev1.Toleration `json:"tolerations,omitempty"`
PodLabels map[string]string `json:"podLabels,omitempty"`
}
// Stash defines files to be saved for use in a later stage, marked with a name
type Stash struct {
Name string `json:"name"`
// Eventually make this optional so that you can do volumes instead
Files string `json:"files"`
}
// Unstash defines a previously-defined stash to be copied into this stage's workspace
type Unstash struct {
Name string `json:"name"`
Dir string `json:"dir,omitempty"`
}
// StageOptions contains both options that can be configured on either a pipeline or a stage, via
// RootOptions, or stage-specific options.
type StageOptions struct {
*RootOptions `json:",inline"`
// TODO: Not yet implemented in build-pipeline
Stash *Stash `json:"stash,omitempty"`
Unstash *Unstash `json:"unstash,omitempty"`
Workspace *string `json:"workspace,omitempty"`
}
// Step defines a single step, from the author's perspective, to be executed within a stage.
type Step struct {
// An optional name to give the step for reporting purposes
Name string `json:"name,omitempty"`
// One of command, step, or loop is required.
Command string `json:"command,omitempty"`
// args is optional, but only allowed with command
Arguments []string `json:"args,omitempty"`
// dir is optional, but only allowed with command. Refers to subdirectory of workspace
Dir string `json:"dir,omitempty"`
Step string `json:"step,omitempty"`
// options is optional, but only allowed with step
// Also, we'll need to do some magic to do type verification during translation - i.e., this step wants a number
// for this option, so translate the string value for that option to a number.
Options map[string]string `json:"options,omitempty"`
Loop *Loop `json:"loop,omitempty"`
// agent can be overridden on a step
Agent *Agent `json:"agent,omitempty"`
// Image alows the docker image for a step to be specified
Image string `json:"image,omitempty"`
// env allows defining per-step environment variables
Env []corev1.EnvVar `json:"env,omitempty"`
// Legacy fields from jenkinsfile.PipelineStep before it was eliminated.
Comment string `json:"comment,omitempty"`
Groovy string `json:"groovy,omitempty"`
Steps []*Step `json:"steps,omitempty"`
When string `json:"when,omitempty"`
Container string `json:"container,omitempty"`
Sh string `json:"sh,omitempty"`
}
// Loop is a special step that defines a variable, a list of possible values for that variable, and a set of steps to
// repeat for each value for the variable, with the variable set with that value in the environment for the execution of
// those steps.
type Loop struct {
// The variable name.
Variable string `json:"variable"`
// The list of values to iterate over
Values []string `json:"values"`
// The steps to run
Steps []Step `json:"steps"`
}
// Stage is a unit of work in a pipeline, corresponding either to a Task or a set of Tasks to be run sequentially or in
// parallel with common configuration.
type Stage struct {
Name string `json:"name"`
Agent *Agent `json:"agent,omitempty"`
Env []corev1.EnvVar `json:"env,omitempty"`
Options *StageOptions `json:"options,omitempty"`
Steps []Step `json:"steps,omitempty"`
Stages []Stage `json:"stages,omitempty"`
Parallel []Stage `json:"parallel,omitempty"`
Post []Post `json:"post,omitempty"`
WorkingDir *string `json:"dir,omitempty"`
// Replaced by Env, retained for backwards compatibility
Environment []corev1.EnvVar `json:"environment,omitempty"`
}
// PostCondition is used to specify under what condition a post action should be executed.
type PostCondition string
// Probably extensible down the road
const (
PostConditionSuccess PostCondition = "success"
PostConditionFailure PostCondition = "failure"
PostConditionAlways PostCondition = "always"
)
// Post contains a PostCondition and one more actions to be executed after a pipeline or stage if the condition is met.
type Post struct {
// TODO: Conditional execution of something after a Task or Pipeline completes is not yet implemented
Condition PostCondition `json:"condition"`
Actions []PostAction `json:"actions"`
}
// PostAction contains the name of a built-in post action and options to pass to that action.
type PostAction struct {
// TODO: Notifications are not yet supported in Build Pipeline per se.
Name string `json:"name"`
// Also, we'll need to do some magic to do type verification during translation - i.e., this action wants a number
// for this option, so translate the string value for that option to a number.
Options map[string]string `json:"options,omitempty"`
}
// StepOverrideType is used to specify whether the existing step should be replaced (default), new step(s) should be
// prepended before the existing step, or new step(s) should be appended after the existing step.
type StepOverrideType string
// The available override types
const (
StepOverrideReplace StepOverrideType = "replace"
StepOverrideBefore StepOverrideType = "before"
StepOverrideAfter StepOverrideType = "after"
)
// PipelineOverride allows for overriding named steps, stages, or pipelines in the build pack or default pipeline
type PipelineOverride struct {
Pipeline string `json:"pipeline,omitempty"`
Stage string `json:"stage,omitempty"`
Name string `json:"name,omitempty"`
Step *Step `json:"step,omitempty"`
Steps []*Step `json:"steps,omitempty"`
Type *StepOverrideType `json:"type,omitempty"`
Agent *Agent `json:"agent,omitempty"`
ContainerOptions *corev1.Container `json:"containerOptions,omitempty"`
Volumes []*corev1.Volume `json:"volumes,omitempty"`
}
var _ apis.Validatable = (*ParsedPipeline)(nil)
// stageLabelName replaces invalid characters in stage names for label usage.
func (s *Stage) stageLabelName() string {
return MangleToRfc1035Label(s.Name, "")
}
// GroovyBlock returns the groovy expression for this step
// Legacy code for Jenkinsfile generation
func (s *Step) GroovyBlock(parentIndent string) string {
var buffer bytes.Buffer
indent := parentIndent
if s.Comment != "" {
buffer.WriteString(indent)
buffer.WriteString("// ")
buffer.WriteString(s.Comment)
buffer.WriteString("\n")
}
if s.GetImage() != "" {
buffer.WriteString(indent)
buffer.WriteString("container('")
buffer.WriteString(s.GetImage())
buffer.WriteString("') {\n")
} else if s.Dir != "" {
buffer.WriteString(indent)
buffer.WriteString("dir('")
buffer.WriteString(s.Dir)
buffer.WriteString("') {\n")
} else if s.GetFullCommand() != "" {
buffer.WriteString(indent)
buffer.WriteString("sh \"")
buffer.WriteString(s.GetFullCommand())
buffer.WriteString("\"\n")
} else if s.Groovy != "" {
lines := strings.Split(s.Groovy, "\n")
lastIdx := len(lines) - 1
for i, line := range lines {
buffer.WriteString(indent)
buffer.WriteString(line)
if i >= lastIdx && len(s.Steps) > 0 {
buffer.WriteString(" {")
}
buffer.WriteString("\n")
}
}
childIndent := indent + " "
for _, child := range s.Steps {
buffer.WriteString(child.GroovyBlock(childIndent))
}
return buffer.String()
}
// ToJenkinsfileStatements converts the step to one or more jenkinsfile statements
// Legacy code for Jenkinsfile generation
func (s *Step) ToJenkinsfileStatements() []*util.Statement {
statements := []*util.Statement{}
if s.Comment != "" {
statements = append(statements, &util.Statement{
Statement: "",
}, &util.Statement{
Statement: "// " + s.Comment,
})
}
if s.GetImage() != "" {
statements = append(statements, &util.Statement{
Function: "container",
Arguments: []string{s.GetImage()},
})
} else if s.Dir != "" {
statements = append(statements, &util.Statement{
Function: "dir",
Arguments: []string{s.Dir},
})
} else if s.GetFullCommand() != "" {
statements = append(statements, &util.Statement{
Statement: "sh \"" + s.GetFullCommand() + "\"",
})
} else if s.Groovy != "" {
lines := strings.Split(s.Groovy, "\n")
for _, line := range lines {
statements = append(statements, &util.Statement{
Statement: line,
})
}
}
if len(statements) > 0 {
last := statements[len(statements)-1]
for _, c := range s.Steps {
last.Children = append(last.Children, c.ToJenkinsfileStatements()...)
}
}
return statements
}
// Validate validates the step is populated correctly
// Legacy code for Jenkinsfile generation
func (s *Step) Validate() error {
if len(s.Steps) > 0 || s.GetCommand() != "" {
return nil
}
return fmt.Errorf("invalid step %#v as no child steps or command", s)
}
// PutAllEnvVars puts all the defined environment variables in the given map
// Legacy code for Jenkinsfile generation
func (s *Step) PutAllEnvVars(m map[string]string) {
for _, step := range s.Steps {
step.PutAllEnvVars(m)
}
}
// GetCommand gets the step's command to execute, opting for Command if set, then Sh.
func (s *Step) GetCommand() string {
if s.Command != "" {
return s.Command
}
return s.Sh
}
// GetFullCommand gets the full command to execute, including arguments.
func (s *Step) GetFullCommand() string {
cmd := s.GetCommand()
// If GetCommand() was an empty string, don't deal with arguments, just return.
if len(s.Arguments) > 0 && cmd != "" {
cmd = fmt.Sprintf("%s %s", cmd, strings.Join(s.Arguments, " "))
}
return cmd
}
// GetImage gets the step's image to run on, opting for Image if set, then Container.
func (s *Step) GetImage() string {
if s.Image != "" {
return s.Image
}
if s.Agent != nil && s.Agent.Image != "" {
return s.Agent.Image
}
return s.Container
}
// DeepCopyForParsedPipeline returns a copy of the Agent with deprecated fields migrated to current ones.
func (a *Agent) DeepCopyForParsedPipeline() *Agent {
agent := a.DeepCopy()
if agent.Container != "" {
agent.Image = agent.GetImage()
agent.Container = ""
agent.Label = ""
}
return agent
}
// Groovy returns the agent groovy expression for the agent or `any` if its blank
// Legacy code for Jenkinsfile generation
func (a *Agent) Groovy() string {
if a.Label != "" {
return fmt.Sprintf(`{
label "%s"
}`, a.Label)
}
// lets use any for Prow
return "any"
}
// GetImage gets the agent's image to run on, opting for Image if set, then Container.
func (a *Agent) GetImage() string {
if a.Image != "" {
return a.Image
}
return a.Container
}
// MangleToRfc1035Label - Task/Step names need to be RFC 1035/1123 compliant DNS labels, so we mangle
// them to make them compliant. Results should match the following regex and be
// no more than 63 characters long:
// [a-z]([-a-z0-9]*[a-z0-9])?
// cf. https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
// body is assumed to have at least one ASCII letter.
// suffix is assumed to be alphanumeric and non-empty.
// TODO: Combine with kube.ToValidName (that function needs to handle lengths)
func MangleToRfc1035Label(body string, suffix string) string {
const maxLabelLength = 63
maxBodyLength := maxLabelLength
if len(suffix) > 0 {
maxBodyLength = maxLabelLength - len(suffix) - 1 // Add an extra hyphen before the suffix
}
var sb strings.Builder
bufferedHyphen := false // Used to make sure we don't output consecutive hyphens.
for _, codepoint := range body {
toWrite := 0
if sb.Len() != 0 { // Digits and hyphens aren't allowed to be the first character
if codepoint == ' ' || codepoint == '-' || codepoint == '.' {
bufferedHyphen = true
} else if codepoint >= '0' && codepoint <= '9' {
toWrite = 1
}
}
if codepoint >= 'A' && codepoint <= 'Z' {
codepoint += ('a' - 'A') // Offset to make character lowercase
toWrite = 1
} else if codepoint >= 'a' && codepoint <= 'z' {
toWrite = 1
}
if toWrite > 0 {
if bufferedHyphen {
toWrite++
}
if sb.Len()+toWrite > maxBodyLength {
break
}
if bufferedHyphen {
sb.WriteRune('-')
bufferedHyphen = false
}
sb.WriteRune(codepoint)
}
}
if suffix != "" {
sb.WriteRune('-')
sb.WriteString(suffix)
}
return sb.String()
}
// GetEnv gets the environment for the ParsedPipeline, returning Env first and Environment if Env isn't populated.
func (j *ParsedPipeline) GetEnv() []corev1.EnvVar {
if j != nil {
if len(j.Env) > 0 {
return j.Env
}
return j.Environment
}
return []corev1.EnvVar{}
}
// GetEnv gets the environment for the Stage, returning Env first and Environment if Env isn't populated.
func (s *Stage) GetEnv() []corev1.EnvVar {
if len(s.Env) > 0 {
return s.Env
}
return s.Environment
}
// Validate checks the ParsedPipeline to find any errors in it, without validating against the cluster.
func (j *ParsedPipeline) Validate(context context.Context) *apis.FieldError {
return j.ValidateInCluster(context, nil, "")
}
// ValidateInCluster checks the parsed ParsedPipeline to find any errors in it, including validation against the cluster.
func (j *ParsedPipeline) ValidateInCluster(context context.Context, kubeClient kubernetes.Interface, ns string) *apis.FieldError {
if err := validateAgent(j.Agent).ViaField("agent"); err != nil {
return err
}
var volumes []*corev1.Volume
if j.Options != nil && len(j.Options.Volumes) > 0 {
volumes = append(volumes, j.Options.Volumes...)
}
if err := validateStages(j.Stages, j.Agent, volumes, kubeClient, ns); err != nil {
return err
}
if err := validateStageNames(j); err != nil {
return err
}
if err := validateRootOptions(j.Options, volumes, kubeClient, ns).ViaField("options"); err != nil {
return err
}
return nil
}
func validateAgent(a *Agent) *apis.FieldError {
// TODO: This is the same whether you specify an agent without label or image, or if you don't specify an agent
// at all, which is nonoptimal.
if a != nil {
if a.Container != "" {
return &apis.FieldError{
Message: "the container field is deprecated - please use image instead",
Paths: []string{"container"},
}
}
if a.Dir != "" {
return &apis.FieldError{
Message: "the dir field is only valid in legacy build packs, not in jenkins-x.yml. Please remove it.",
Paths: []string{"dir"},
}
}
if a.Image != "" && a.Label != "" {
return apis.ErrMultipleOneOf("label", "image")
}
if a.Image == "" && a.Label == "" {
return apis.ErrMissingOneOf("label", "image")
}
}
return nil
}
var containsASCIILetter = regexp.MustCompile(`[a-zA-Z]`).MatchString
func validateStage(s Stage, parentAgent *Agent, parentVolumes []*corev1.Volume, kubeClient kubernetes.Interface, ns string) *apis.FieldError {
if len(s.Steps) == 0 && len(s.Stages) == 0 && len(s.Parallel) == 0 {
return apis.ErrMissingOneOf("steps", "stages", "parallel")
}
if !containsASCIILetter(s.Name) {
return &apis.FieldError{
Message: "Stage name must contain at least one ASCII letter",
Paths: []string{"name"},
}
}
var volumes []*corev1.Volume
volumes = append(volumes, parentVolumes...)
if s.Options != nil && s.Options.RootOptions != nil && len(s.Options.Volumes) > 0 {
volumes = append(volumes, s.Options.Volumes...)
}
stageAgent := s.Agent.DeepCopy()
if stageAgent == nil {
stageAgent = parentAgent.DeepCopy()
}
if stageAgent == nil {
return &apis.FieldError{
Message: "No agent specified for stage or for its parent(s)",
Paths: []string{"agent"},
}
}
if len(s.Steps) > 0 {
if len(s.Stages) > 0 || len(s.Parallel) > 0 {
return apis.ErrMultipleOneOf("steps", "stages", "parallel")
}
seenStepNames := make(map[string]int)
for i, step := range s.Steps {
if err := validateStep(step).ViaFieldIndex("steps", i); err != nil {
return err
}
if step.Name != "" {
if count, exists := seenStepNames[step.Name]; exists {
seenStepNames[step.Name] = count + 1
} else {
seenStepNames[step.Name] = 1
}
}
}
var duplicateSteps []string
for k, v := range seenStepNames {
if v > 1 {
duplicateSteps = append(duplicateSteps, k)
}
}
if len(duplicateSteps) > 0 {
sort.Strings(duplicateSteps)
return &apis.FieldError{
Message: "step names within a stage must be unique",
Details: fmt.Sprintf("The following step names in the stage %s are used more than once: %s", s.Name, strings.Join(duplicateSteps, ", ")),
Paths: []string{"steps"},
}
}
}
if len(s.Stages) > 0 {
if len(s.Parallel) > 0 {
return apis.ErrMultipleOneOf("steps", "stages", "parallel")
}
for i, stage := range s.Stages {
if err := validateStage(stage, parentAgent, volumes, kubeClient, ns).ViaFieldIndex("stages", i); err != nil {
return err
}
}
}
if len(s.Parallel) > 0 {
for i, stage := range s.Parallel {
if err := validateStage(stage, parentAgent, volumes, kubeClient, ns).ViaFieldIndex("parallel", i); err != nil {
return nil
}
}
}
return validateStageOptions(s.Options, volumes, kubeClient, ns).ViaField("options")
}
func moreThanOneAreTrue(vals ...bool) bool {
count := 0
for _, v := range vals {
if v {
count++
}
}
return count > 1
}
func validateStep(s Step) *apis.FieldError {
// Special cases for when you use legacy build pack syntax inside a pipeline definition
if s.Container != "" {
return &apis.FieldError{
Message: "the container field is deprecated - please use image instead",
Paths: []string{"container"},
}
}
if s.Groovy != "" {
return &apis.FieldError{
Message: "the groovy field is only valid in legacy build packs, not in jenkins-x.yml. Please remove it.",
Paths: []string{"groovy"},
}
}
if s.Comment != "" {
return &apis.FieldError{
Message: "the comment field is only valid in legacy build packs, not in jenkins-x.yml. Please remove it.",
Paths: []string{"comment"},
}
}
if s.When != "" {
return &apis.FieldError{
Message: "the when field is only valid in legacy build packs, not in jenkins-x.yml. Please remove it.",
Paths: []string{"when"},
}
}
if len(s.Steps) > 0 {
return &apis.FieldError{
Message: "the steps field is only valid in legacy build packs, not in jenkins-x.yml. Please remove it and list the nested stages sequentially instead.",
Paths: []string{"steps"},
}
}
if s.GetCommand() == "" && s.Step == "" && s.Loop == nil {
return apis.ErrMissingOneOf("command", "step", "loop")
}
if moreThanOneAreTrue(s.GetCommand() != "", s.Step != "", s.Loop != nil) {
return apis.ErrMultipleOneOf("command", "step", "loop")
}
if (s.GetCommand() != "" || s.Loop != nil) && len(s.Options) != 0 {
return &apis.FieldError{
Message: "Cannot set options for a command or a loop",
Paths: []string{"options"},
}
}
if (s.Step != "" || s.Loop != nil) && len(s.Arguments) != 0 {
return &apis.FieldError{
Message: "Cannot set command-line arguments for a step or a loop",
Paths: []string{"args"},
}
}
if err := validateLoop(s.Loop); err != nil {
return err.ViaField("loop")
}
if s.Agent != nil {
return validateAgent(s.Agent).ViaField("agent")
}
return nil
}
func validateLoop(l *Loop) *apis.FieldError {
if l != nil {
if l.Variable == "" {
return apis.ErrMissingField("variable")
}
if len(l.Steps) == 0 {
return apis.ErrMissingField("steps")
}
if len(l.Values) == 0 {
return apis.ErrMissingField("values")
}
for i, step := range l.Steps {
if err := validateStep(step).ViaFieldIndex("steps", i); err != nil {
return err
}
}
}
return nil
}
func validateStages(stages []Stage, parentAgent *Agent, parentVolumes []*corev1.Volume, kubeClient kubernetes.Interface, ns string) *apis.FieldError {
if len(stages) == 0 {
return apis.ErrMissingField("stages")
}
for i, s := range stages {
if err := validateStage(s, parentAgent, parentVolumes, kubeClient, ns).ViaFieldIndex("stages", i); err != nil {
return err
}
}
return nil
}
func validateRootOptions(o *RootOptions, volumes []*corev1.Volume, kubeClient kubernetes.Interface, ns string) *apis.FieldError {
if o != nil {
if o.Timeout != nil {
if err := validateTimeout(o.Timeout); err != nil {
return err.ViaField("timeout")
}
}
// TODO: retry will default to 0, so we're kinda stuck checking if it's less than zero here.
if o.Retry < 0 {
return &apis.FieldError{
Message: "Retry count cannot be negative",
Paths: []string{"retry"},
}
}
for i, v := range o.Volumes {
if err := validateVolume(v, kubeClient, ns).ViaFieldIndex("volumes", i); err != nil {
return err
}
}
return validateContainerOptions(o.ContainerOptions, volumes).ViaField("containerOptions")
}
return nil
}
func validateVolume(v *corev1.Volume, kubeClient kubernetes.Interface, ns string) *apis.FieldError {
if v != nil {
if v.Name == "" {
return apis.ErrMissingField("name")
}
if kubeClient != nil {
if v.Secret != nil {
_, err := kubeClient.CoreV1().Secrets(ns).Get(v.Secret.SecretName, metav1.GetOptions{})
if err != nil {
return &apis.FieldError{
Message: fmt.Sprintf("Secret %s does not exist, so cannot be used as a volume", v.Secret.SecretName),
Paths: []string{"secretName"},
}
}
} else if v.PersistentVolumeClaim != nil {
_, err := kubeClient.CoreV1().PersistentVolumeClaims(ns).Get(v.PersistentVolumeClaim.ClaimName, metav1.GetOptions{})
if err != nil {
return &apis.FieldError{
Message: fmt.Sprintf("PVC %s does not exist, so cannot be used as a volume", v.PersistentVolumeClaim.ClaimName),
Paths: []string{"claimName"},
}
}
}
}
}
return nil
}
func validateContainerOptions(c *corev1.Container, volumes []*corev1.Volume) *apis.FieldError {
if c != nil {
if len(c.Command) != 0 {
return &apis.FieldError{
Message: "Command cannot be specified in containerOptions",
Paths: []string{"command"},
}
}
if len(c.Args) != 0 {
return &apis.FieldError{
Message: "Arguments cannot be specified in containerOptions",
Paths: []string{"args"},
}
}
if c.Image != "" {
return &apis.FieldError{
Message: "Image cannot be specified in containerOptions",
Paths: []string{"image"},
}
}
if c.WorkingDir != "" {
return &apis.FieldError{
Message: "WorkingDir cannot be specified in containerOptions",
Paths: []string{"workingDir"},
}
}
if c.Name != "" {
return &apis.FieldError{
Message: "Name cannot be specified in containerOptions",
Paths: []string{"name"},
}
}
if c.Stdin {
return &apis.FieldError{
Message: "Stdin cannot be specified in containerOptions",
Paths: []string{"stdin"},
}
}
if c.TTY {
return &apis.FieldError{
Message: "TTY cannot be specified in containerOptions",
Paths: []string{"tty"},
}
}
if len(c.VolumeMounts) > 0 {
for i, m := range c.VolumeMounts {
if !isVolumeMountValid(m, volumes) {
fieldErr := &apis.FieldError{
Message: fmt.Sprintf("Volume mount name %s not found in volumes for stage or pipeline", m.Name),
Paths: []string{"name"},
}
return fieldErr.ViaFieldIndex("volumeMounts", i)
}
}
}
}
return nil
}
func isVolumeMountValid(mount corev1.VolumeMount, volumes []*corev1.Volume) bool {
foundVolume := false
for _, v := range volumes {
if v.Name == mount.Name {
foundVolume = true
break
}
}
return foundVolume
}
func validateStageOptions(o *StageOptions, volumes []*corev1.Volume, kubeClient kubernetes.Interface, ns string) *apis.FieldError {
if o != nil {
if err := validateStash(o.Stash); err != nil {
return err.ViaField("stash")
}
if o.Unstash != nil {
if err := validateUnstash(o.Unstash); err != nil {
return err.ViaField("unstash")
}
}
if o.Workspace != nil {
if err := validateWorkspace(*o.Workspace); err != nil {
return err
}
}
if o.RootOptions != nil && o.RootOptions.DistributeParallelAcrossNodes {
return &apis.FieldError{
Message: "distributeParallelAcrossNodes cannot be used in a stage",
Paths: []string{"distributeParallelAcrossNodes"},
}
}
return validateRootOptions(o.RootOptions, volumes, kubeClient, ns)
}
return nil
}
func validateTimeout(t *Timeout) *apis.FieldError {
if t != nil {
isAllowed := false
for _, allowed := range allTimeoutUnits {
if t.Unit == allowed {
isAllowed = true
}
}
if !isAllowed {
return &apis.FieldError{
Message: fmt.Sprintf("%s is not a valid time unit. Valid time units are %s", string(t.Unit),
strings.Join(allTimeoutUnitsAsStrings(), ", ")),
Paths: []string{"unit"},
}
}
if t.Time < 1 {
return &apis.FieldError{
Message: "Timeout must be greater than zero",
Paths: []string{"time"},
}
}
}
return nil
}
func validateUnstash(u *Unstash) *apis.FieldError {
if u != nil {
// TODO: Check to make sure the corresponding stash is defined somewhere
if u.Name == "" {
return &apis.FieldError{
Message: "The unstash name must be provided",
Paths: []string{"name"},
}
}
}
return nil
}
func validateStash(s *Stash) *apis.FieldError {
if s != nil {
if s.Name == "" {