-
Notifications
You must be signed in to change notification settings - Fork 18
/
parser.go
680 lines (570 loc) · 19.3 KB
/
parser.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
package parser
import (
"context"
"errors"
"fmt"
"github.com/cirruslabs/cirrus-ci-agent/api"
"github.com/cirruslabs/cirrus-cli/internal/executor/environment"
"github.com/cirruslabs/cirrus-cli/pkg/larker/fs"
"github.com/cirruslabs/cirrus-cli/pkg/larker/fs/cachinglayer"
"github.com/cirruslabs/cirrus-cli/pkg/larker/fs/dummy"
"github.com/cirruslabs/cirrus-cli/pkg/parser/abstractcontainer"
"github.com/cirruslabs/cirrus-cli/pkg/parser/boolevator"
"github.com/cirruslabs/cirrus-cli/pkg/parser/issue"
"github.com/cirruslabs/cirrus-cli/pkg/parser/modifier/matrix"
"github.com/cirruslabs/cirrus-cli/pkg/parser/nameable"
"github.com/cirruslabs/cirrus-cli/pkg/parser/node"
"github.com/cirruslabs/cirrus-cli/pkg/parser/parseable"
"github.com/cirruslabs/cirrus-cli/pkg/parser/parsererror"
"github.com/cirruslabs/cirrus-cli/pkg/parser/parserkit"
"github.com/cirruslabs/cirrus-cli/pkg/parser/task"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/lestrrat-go/jsschema"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/dynamicpb"
"google.golang.org/protobuf/types/known/anypb"
"os"
"regexp"
"sort"
"strconv"
"strings"
)
const (
metadataPropertyDockerfileHash = "dockerfile_hash"
)
type Parser struct {
// Environment to take into account when expanding variables.
environment map[string]string
// Filesystem to reference when calculating file hashes.
//
// For example, Dockerfile contents are hashed to avoid duplicate builds.
fs fs.FileSystem
// A list of changed files useful when evaluating changesInclude() boolevator's function.
affectedFiles []string
parserKit *parserkit.ParserKit
parsers map[nameable.Nameable]parseable.Parseable
idNumbering int64
indexNumbering int64
additionalInstances map[string]protoreflect.MessageDescriptor
additionalTaskProperties []*descriptor.FieldDescriptorProto
missingInstancesAllowed bool
tasksCountBeforeFiltering int64
disabledTaskNamesAndAliases map[string]struct{}
}
type Result struct {
Tasks []*api.Task
Issues []*api.Issue
// A helper field that lets some external post-processor
// to inject new tasks correctly (e.g. Dockerfile build tasks)
TasksCountBeforeFiltering int64
}
func New(opts ...Option) *Parser {
parser := &Parser{
environment: make(map[string]string),
fs: dummy.New(),
disabledTaskNamesAndAliases: make(map[string]struct{}),
}
// Apply options
for _, opt := range opts {
opt(parser)
}
// Wrap the final file system in a caching layer
wrappedFS, err := cachinglayer.Wrap(parser.fs)
if err != nil {
panic(err)
}
parser.fs = wrappedFS
// Initialize boolevator
parser.parserKit = &parserkit.ParserKit{
Boolevator: boolevator.New(boolevator.WithFunctions(map[string]boolevator.Function{
"changesInclude": parser.bfuncChangesInclude(),
"changesIncludeOnly": parser.bfuncChangesIncludeOnly(),
})),
IssueRegistry: issue.NewRegistry(),
}
// Register parsers
taskParser := task.NewTask(nil, nil, parser.additionalInstances, parser.additionalTaskProperties,
parser.missingInstancesAllowed, 0, 0)
pipeParser := task.NewDockerPipe(nil, nil, parser.additionalTaskProperties, 0, 0)
builderParser := task.NewDockerBuilder(nil, nil, parser.additionalTaskProperties, 0, 0)
parser.parsers = map[nameable.Nameable]parseable.Parseable{
nameable.NewRegexNameable("^(.*)task$"): taskParser,
nameable.NewRegexNameable("^(.*)pipe$"): pipeParser,
nameable.NewRegexNameable("^(.*)docker_builder$"): builderParser,
}
return parser
}
func (p *Parser) parseTasks(tree *node.Node) ([]task.ParseableTaskLike, error) {
var tasks []task.ParseableTaskLike
for _, treeItem := range tree.Children {
if strings.HasPrefix(treeItem.Name, "task_") {
p.parserKit.IssueRegistry.RegisterIssuef(api.Issue_WARNING, treeItem.Line, treeItem.Column,
"you've probably meant %s_task", strings.TrimPrefix(treeItem.Name, "task_"))
}
for key, value := range p.parsers {
var taskLike task.ParseableTaskLike
switch value.(type) {
case *task.Task:
taskLike = task.NewTask(
environment.Copy(p.environment),
p.parserKit,
p.additionalInstances,
p.additionalTaskProperties,
p.missingInstancesAllowed,
treeItem.Line,
treeItem.Column,
)
case *task.DockerPipe:
taskLike = task.NewDockerPipe(
environment.Copy(p.environment),
p.parserKit,
p.additionalTaskProperties,
treeItem.Line,
treeItem.Column,
)
case *task.DockerBuilder:
taskLike = task.NewDockerBuilder(
environment.Copy(p.environment),
p.parserKit,
p.additionalTaskProperties,
treeItem.Line,
treeItem.Column,
)
default:
panic("unknown task-like object")
}
if !key.Matches(treeItem.Name) {
continue
}
err := taskLike.Parse(treeItem, p.parserKit)
if err != nil {
return nil, err
}
taskLike.SetID(p.NextTaskID())
// Set task's name if not set in the definition
if rn, ok := key.(*nameable.RegexNameable); ok {
taskLike.SetFallbackName(rn.FirstGroupOrDefault(treeItem.Name, "main"))
}
if taskLike.Name() == "" {
taskLike.SetName(taskLike.FallbackName())
}
// Filtering based on "only_if" expression evaluation
taskSpecificEnv := map[string]string{
"CIRRUS_TASK_NAME": taskLike.Name(),
}
p.tasksCountBeforeFiltering++
enabled, err := taskLike.Enabled(environment.Merge(taskSpecificEnv, p.environment), p.parserKit.Boolevator)
if err != nil {
return nil, err
}
if !enabled {
p.disabledTaskNamesAndAliases[taskLike.Name()] = struct{}{}
p.disabledTaskNamesAndAliases[taskLike.Alias()] = struct{}{}
continue
}
taskLike.SetIndexWithinBuild(p.NextTaskLocalIndex())
tasks = append(tasks, taskLike)
}
}
return tasks, nil
}
//nolint:gocognit // it's a parser, and it's complicated
func (p *Parser) Parse(ctx context.Context, config string) (result *Result, err error) {
defer func() {
if re, ok := err.(*parsererror.Rich); ok {
re.Enrich(config)
}
}()
// Register additional instances
for _, additionalInstance := range p.additionalInstances {
_, err := protoregistry.GlobalTypes.FindMessageByName(additionalInstance.FullName())
if err == nil {
continue
} else if !errors.Is(err, protoregistry.NotFound) {
return nil, err
}
additionalType := dynamicpb.NewMessageType(additionalInstance)
if err := protoregistry.GlobalTypes.RegisterMessage(additionalType); err != nil {
return nil, err
}
}
// Work around Cirus Cloud parser's historically lax merging
// of the YAML aliases[1]. See yaml-merge-sequence.yml and
// yaml-merge-collectible.yml for examples of conflicting
// behaviors that we should support.
//
// [1]: https://yaml.org/type/merge.html
var mergeExemptions []nameable.Nameable
for _, parser := range p.parsers {
for _, field := range parser.CollectibleFields() {
mergeExemptions = append(mergeExemptions, nameable.NewSimpleNameable(field.Name))
}
for _, field := range parser.Fields() {
if !field.Repeatable() {
continue
}
mergeExemptions = append(mergeExemptions, field.Name())
}
}
// Convert the parsed and nested YAML structure into a tree
// to get the ability to walk parents
tree, err := node.NewFromTextWithMergeExemptions(config, mergeExemptions)
if err != nil {
return nil, err
}
// Run modifiers on it
if err := matrix.ExpandMatrices(tree); err != nil {
return nil, err
}
// Run parsers on the top-level nodes
tasks, err := p.parseTasks(tree)
if err != nil {
return nil, err
}
if err := p.resolveDependenciesShallow(tasks); err != nil {
return nil, err
}
if len(tasks) == 0 {
return &Result{Issues: p.parserKit.IssueRegistry.Issues()}, nil
}
if err := validateDependenciesDeep(tasks); err != nil {
return nil, err
}
p.searchForUnbalancedOnlyIfs(tasks)
protoTaskToInstanceNode := map[int64]*node.Node{}
var protoTasks []*api.Task
for _, task := range tasks {
type HasInstanceNode interface {
InstanceNode() *node.Node
}
if taskWithInstanceNode, ok := task.(HasInstanceNode); ok {
protoTaskToInstanceNode[task.ID()] = taskWithInstanceNode.InstanceNode()
}
protoTask := task.Proto().(*api.Task)
if err := validateTask(protoTask); err != nil {
return nil, err
}
protoTasks = append(protoTasks, protoTask)
}
// Calculate Dockerfile hashes that will be used
// to create service tasks and in the Cirrus Cloud
if err := p.calculateDockerfileHashes(ctx, protoTasks, protoTaskToInstanceNode); err != nil {
return nil, err
}
// Create service tasks
serviceTasks, err := p.createServiceTasks(protoTasks)
if err != nil {
return nil, err
}
protoTasks = append(protoTasks, serviceTasks...)
// Postprocess individual tasks
for _, protoTask := range protoTasks {
// Insert empty clone instruction if custom clone script wasn't provided by the user
ensureCloneInstruction(protoTask)
// Provide unique labels for identically named tasks
uniqueLabelsForTask, err := p.uniqueLabels(protoTask, protoTasks, p.additionalInstances)
if err != nil {
return nil, fmt.Errorf("%w: %v", parsererror.ErrInternal, err)
}
protoTask.Metadata.UniqueLabels = uniqueLabelsForTask
}
// Sort tasks by their IDs to make output consistent across runs
sort.Slice(protoTasks, func(i, j int) bool {
return protoTasks[i].LocalGroupId < protoTasks[j].LocalGroupId
})
return &Result{
Tasks: protoTasks,
TasksCountBeforeFiltering: p.tasksCountBeforeFiltering,
Issues: p.parserKit.IssueRegistry.Issues(),
}, nil
}
func (p *Parser) searchForUnbalancedOnlyIfs(tasks []task.ParseableTaskLike) {
// Create an index
idx := map[int64]task.ParseableTaskLike{}
for _, task := range tasks {
idx[task.ID()] = task
}
// Analyze dependencies
for _, task := range tasks {
for _, dependsOnID := range task.DependsOnIDs() {
dependent, ok := idx[dependsOnID]
if !ok {
continue
}
if dependent.OnlyIfExpression() != "" && task.OnlyIfExpression() != dependent.OnlyIfExpression() {
p.registerUnbalancedOnlyIfIssue(task, dependent.Name())
}
}
}
}
func (p *Parser) registerUnbalancedOnlyIfIssue(dependent task.ParseableTaskLike, dependeeName string) {
p.parserKit.IssueRegistry.RegisterIssuef(api.Issue_WARNING, dependent.Line(), dependent.Column(),
"task \"%s\" depends on task \"%s\", but their only_if conditions are different",
dependent.Name(), dependeeName)
}
func (p *Parser) ParseFromFile(ctx context.Context, path string) (*Result, error) {
config, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return p.Parse(ctx, string(config))
}
func (p *Parser) NextTaskID() int64 {
defer func() {
p.idNumbering++
}()
return p.idNumbering
}
func (p *Parser) NextTaskLocalIndex() int64 {
defer func() {
p.indexNumbering++
}()
return p.indexNumbering
}
func (p *Parser) Schema() *schema.Schema {
schema := &schema.Schema{
Type: schema.PrimitiveTypes{schema.ObjectType},
ID: "https://cirrus-ci.org/",
Title: "JSON schema for Cirrus CI configuration files",
SchemaRef: "http://json-schema.org/draft-04/schema#",
Properties: make(map[string]*schema.Schema),
PatternProperties: make(map[*regexp.Regexp]*schema.Schema),
AdditionalProperties: &schema.AdditionalProperties{Schema: nil},
}
for parserName, parser := range p.parsers {
if parser.Schema() == nil {
continue
}
switch nameable := parserName.(type) {
case *nameable.SimpleNameable:
schema.Properties[nameable.Name()] = parser.Schema()
case *nameable.RegexNameable:
schema.PatternProperties[nameable.Regex()] = parser.Schema()
}
// Note: this is a simplification that doesn't return collectible fields recursively,
// because it assumes that we're only defining collectibles on the first depth level.
for _, collectibleFields := range parser.CollectibleFields() {
if collectibleFields.Schema == nil {
continue
}
schema.Properties[collectibleFields.Name] = collectibleFields.Schema
}
}
return schema
}
func (p *Parser) resolveDependenciesShallow(tasks []task.ParseableTaskLike) error {
fallbackNames := make(map[string]struct{})
for _, task := range tasks {
fallbackNames[task.FallbackName()] = struct{}{}
}
for _, task := range tasks {
var dependsOnIDs []int64
for _, dependsOnName := range task.DependsOnNames() {
// Dependency may be missing due to only_if
if _, ok := p.disabledTaskNamesAndAliases[dependsOnName]; ok {
p.registerUnbalancedOnlyIfIssue(task, dependsOnName)
continue
}
var dependencyWasFound bool
for _, subTask := range tasks {
if subTask.Name() == dependsOnName || subTask.Alias() == dependsOnName {
dependsOnIDs = append(dependsOnIDs, subTask.ID())
dependencyWasFound = true
}
}
if !dependencyWasFound {
if _, ok := fallbackNames[dependsOnName]; ok {
return fmt.Errorf("%w: task '%s' depends on task '%s', which name was overridden by "+
"a name: field inside of that task", parsererror.ErrBasic, task.Name(), dependsOnName)
}
return fmt.Errorf("%w: there's no task '%s', but task '%s' depends on it",
parsererror.ErrBasic, dependsOnName, task.Name())
}
}
sort.Slice(dependsOnIDs, func(i, j int) bool { return dependsOnIDs[i] < dependsOnIDs[j] })
task.SetDependsOnIDs(dependsOnIDs)
}
return nil
}
func (p *Parser) createServiceTask(
dockerfileHash string,
protoTask *api.Task,
abstractContainer abstractcontainer.AbstractContainer,
) (*api.Task, error) {
prebuiltInstance := &api.PrebuiltImageInstance{
Repository: fmt.Sprintf("cirrus-ci-community/%s", dockerfileHash),
Reference: "latest",
Platform: abstractContainer.Platform(),
Dockerfile: abstractContainer.Dockerfile(),
Arguments: abstractContainer.DockerArguments(),
}
anyInstance, err := anypb.New(prebuiltInstance)
if err != nil {
return nil, fmt.Errorf("%w: %v", parsererror.ErrInternal, err)
}
// Craft Docker build arguments: task name
var buildArgsSlice []string
for key, value := range abstractContainer.DockerArguments() {
buildArgsSlice = append(buildArgsSlice, fmt.Sprintf("%s=%s", key, value))
}
sort.Strings(buildArgsSlice)
var buildArgs string
for _, buildArg := range buildArgsSlice {
buildArgs += fmt.Sprintf(" %s", buildArg)
}
// Craft Docker build arguments: docker build command
var dockerBuildArgsSlice []string
for key, value := range abstractContainer.DockerArguments() {
dockerBuildArgsSlice = append(dockerBuildArgsSlice, fmt.Sprintf("%s=\"%s\"", key, value))
}
sort.Strings(dockerBuildArgsSlice)
var dockerBuildArgs string
for _, dockerBuildArg := range dockerBuildArgsSlice {
dockerBuildArgs += fmt.Sprintf(" --build-arg %s", dockerBuildArg)
}
script := fmt.Sprintf("docker build "+
"--tag gcr.io/%s:%s "+
"--file %s%s ",
prebuiltInstance.Repository, prebuiltInstance.Reference,
abstractContainer.Dockerfile(), dockerBuildArgs)
if abstractContainer.Platform() == api.Platform_WINDOWS {
script += "."
} else {
script += "${CIRRUS_DOCKER_CONTEXT:-$CIRRUS_WORKING_DIR}"
}
serviceTask := &api.Task{
Name: fmt.Sprintf("Prebuild %s%s", abstractContainer.Dockerfile(), buildArgs),
LocalGroupId: p.NextTaskID(),
Instance: anyInstance,
Commands: []*api.Command{
{
Name: "build",
Instruction: &api.Command_ScriptInstruction{
ScriptInstruction: &api.ScriptInstruction{
Scripts: []string{script},
},
},
},
{
Name: "push",
Instruction: &api.Command_ScriptInstruction{
ScriptInstruction: &api.ScriptInstruction{
Scripts: []string{fmt.Sprintf("gcloud docker -- push gcr.io/cirrus-ci-community/%s:latest",
dockerfileHash)},
},
},
},
},
Environment: protoTask.Environment,
Metadata: &api.Task_Metadata{
Properties: environment.Merge(
task.DefaultTaskProperties(),
map[string]string{
"skip_notifications": "true",
},
),
},
}
// Some metadata property fields duplicate other fields
serviceTask.Metadata.Properties["indexWithinBuild"] = strconv.FormatInt(p.NextTaskLocalIndex(), 10)
// Some metadata property fields are preserved from the original task
serviceTask.Metadata.Properties["timeout_in"] = protoTask.Metadata.Properties["timeout_in"]
return serviceTask, nil
}
func (p *Parser) createServiceTasks(protoTasks []*api.Task) ([]*api.Task, error) {
serviceTasks := make(map[string]*api.Task)
for _, protoTask := range protoTasks {
if protoTask.Instance == nil && p.missingInstancesAllowed {
continue
}
dynamicInstance, err := anypb.UnmarshalNew(protoTask.Instance, proto.UnmarshalOptions{})
if errors.Is(err, protoregistry.NotFound) {
continue
}
if err != nil {
return nil, fmt.Errorf("%w: failed to unmarshal task's instance: %v", parsererror.ErrInternal, err)
}
var abstractContainer abstractcontainer.AbstractContainer
switch instance := dynamicInstance.(type) {
case *api.ContainerInstance:
abstractContainer = &abstractcontainer.ContainerInstance{
Proto: instance,
}
case *api.PersistentWorkerInstance:
if instance.Isolation == nil {
continue
}
container := instance.Isolation.GetContainer()
if container == nil {
continue
}
abstractContainer = &abstractcontainer.IsolationContainer{
Proto: instance,
}
default:
continue
}
if abstractContainer.Dockerfile() == "" {
continue
}
// Retrieve the Dockerfile hash calculated for this task earlier in the parsing routine
dockerfileHash, ok := protoTask.Metadata.Properties[metadataPropertyDockerfileHash]
if !ok {
return nil, fmt.Errorf("%w: %q is missing it's Dockerfile hash which should've been pre-calculated",
parsererror.ErrInternal, protoTask.Name)
}
// Find or create service task
serviceTask, ok := serviceTasks[dockerfileHash]
if !ok {
serviceTask, err = p.createServiceTask(dockerfileHash, protoTask, abstractContainer)
if err != nil {
return nil, err
}
serviceTasks[dockerfileHash] = serviceTask
}
// Set dependency to the found or created service task
protoTask.RequiredGroups = append(protoTask.RequiredGroups, serviceTask.LocalGroupId)
// Ensure that the task will use our to-be-created image
abstractContainer.SetImage(fmt.Sprintf("gcr.io/cirrus-ci-community/%s:latest", dockerfileHash))
updatedInstance, err := anypb.New(abstractContainer.Message())
if err != nil {
return nil, fmt.Errorf("%w: %v", parsererror.ErrInternal, err)
}
protoTask.Instance = updatedInstance
}
// Extract map values to a slice
var result []*api.Task
for _, serviceTask := range serviceTasks {
result = append(result, serviceTask)
}
return result, nil
}
func ensureCloneInstruction(task *api.Task) {
for _, command := range task.Commands {
if command.Name == "clone" {
return
}
}
// Inherit "image" property from the first task (if any),
// or otherwise we might break Docker Pipe
var properties map[string]string
if len(task.Commands) != 0 {
image, ok := task.Commands[0].Properties["image"]
if ok {
properties = map[string]string{
"image": image,
}
delete(task.Commands[0].Properties, "image")
}
}
cloneCommand := &api.Command{
Name: "clone",
Instruction: &api.Command_CloneInstruction{
CloneInstruction: &api.CloneInstruction{},
},
Properties: properties,
}
task.Commands = append([]*api.Command{cloneCommand}, task.Commands...)
}