-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathproject.go
More file actions
1404 lines (1230 loc) · 33.8 KB
/
project.go
File metadata and controls
1404 lines (1230 loc) · 33.8 KB
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 spread
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"gopkg.in/yaml.v2"
)
type Project struct {
Name string `yaml:"project"`
Backends map[string]*Backend
Environment *Environment
Repack string
Reroot string `yaml:"reroot"`
Prepare string
Restore string
Debug string
PrepareEach string `yaml:"prepare-each"`
RestoreEach string `yaml:"restore-each"`
DebugEach string `yaml:"debug-each"`
Suites map[string]*Suite
RemotePath string `yaml:"path"`
Include []string
Exclude []string
Rename []string
Path string `yaml:"-"`
WarnTimeout Timeout `yaml:"warn-timeout"`
KillTimeout Timeout `yaml:"kill-timeout"`
}
func (p *Project) String() string { return "project" }
type Backend struct {
Name string `yaml:"-"`
Type string
Key string
// Only for adhoc.
Allocate string
Discard string
// Only for qemu so far.
Memory Size
// Only for Linode, Google, OpenStack so far.
Plan string
Location string
Storage Size
// Only for OpenStack so far
Account string
Endpoint string
Networks []string
Groups []string
Systems SystemsMap
Prepare string
Restore string
Debug string
PrepareEach string `yaml:"prepare-each"`
RestoreEach string `yaml:"restore-each"`
DebugEach string `yaml:"debug-each"`
Environment *Environment
Variants []string
WarnTimeout Timeout `yaml:"warn-timeout"`
KillTimeout Timeout `yaml:"kill-timeout"`
HaltTimeout Timeout `yaml:"halt-timeout"`
Priority OptionalInt
Manual bool
}
func (b *Backend) String() string { return fmt.Sprintf("backend %q", b.Name) }
func (b *Backend) systemNames() []string {
sysnames := make([]string, 0, len(b.Systems))
for sysname := range b.Systems {
sysnames = append(sysnames, sysname)
}
sort.Strings(sysnames)
return sysnames
}
type SystemsMap map[string]*System
func (sysmap *SystemsMap) UnmarshalYAML(u func(interface{}) error) error {
var systems []*System
if err := u(&systems); err != nil {
return err
}
*sysmap = make(SystemsMap)
for _, sys := range systems {
(*sysmap)[sys.Name] = sys
}
return nil
}
type System struct {
Backend string `json:"-"`
Name string
Image string
Kernel string
Username string
Password string
Workers int
// Only for Linode and Google so far.
Storage Size
// Only for OpenStack so far
Networks []string
Groups []string
// Only for Google so far.
SecureBoot bool `yaml:"secure-boot"`
// Supported are {"uefi",""}, only for qemu so far.
Bios string
// Request a specific CPU family, e.g. "Intel Skylake" The
// exact string is backend specific.
CPUFamily string `yaml:"cpu-family"`
// Specify a backend specific plan, e.g. `e2-standard-2`
Plan string
Environment *Environment
Variants []string
Priority OptionalInt
Manual bool
}
func (system *System) String() string { return system.Backend + ":" + system.Name }
func (system *System) UnmarshalYAML(u func(interface{}) error) error {
if err := u(&system.Name); err == nil {
system.Image = system.Name
return nil
}
type norecurse System
var def map[string]norecurse
if err := u(&def); err != nil {
return err
}
for name, sys := range def {
sys.Name = name
if sys.Image == "" {
sys.Image = name
}
*system = System(sys)
}
return nil
}
type Environment struct {
err error
keys []string
vals map[string]string
}
func (e *Environment) Keys() []string {
if e == nil {
return nil
}
return append([]string(nil), e.keys...)
}
func (e *Environment) Copy() *Environment {
copy := &Environment{}
copy.err = e.err
copy.keys = append([]string(nil), e.keys...)
copy.vals = make(map[string]string)
for k, v := range e.vals {
copy.vals[k] = v
}
return copy
}
func (e *Environment) Variant(variant string) *Environment {
env := e.Copy()
NextKey:
for key, val := range env.vals {
ekey, evariants := SplitVariants(key)
for _, evariant := range evariants {
if evariant == variant {
env.Replace(key, ekey, val)
continue NextKey
}
}
if len(evariants) > 0 {
env.Unset(key)
}
}
return env
}
func (e *Environment) UnmarshalYAML(u func(interface{}) error) error {
var vals map[string]string
if err := u(&vals); err != nil {
return err
}
for k := range vals {
if !varname.MatchString(k) {
e.err = fmt.Errorf("invalid variable name: %q", k)
return nil
}
}
var seen = make(map[string]bool)
var keys = make([]string, len(vals))
var order yaml.MapSlice
if err := u(&order); err != nil {
return err
}
for i, item := range order {
k, ok := item.Key.(string)
_, good := vals[k]
if !ok || !good {
// Shouldn't happen if the regular expression is right.
e.err = fmt.Errorf("invalid variable name: %v", item.Key)
return nil
}
if seen[k] {
e.err = fmt.Errorf("variable %q defined multiple times", k)
return nil
}
seen[k] = true
keys[i] = k
}
e.keys = keys
e.vals = vals
return nil
}
func NewEnvironment(pairs ...string) *Environment {
e := &Environment{
vals: make(map[string]string),
keys: make([]string, len(pairs)/2),
}
for i := 0; i+1 < len(pairs); i += 2 {
e.vals[pairs[i]] = pairs[i+1]
e.keys[i/2] = pairs[i]
}
return e
}
func (e *Environment) MarshalYAML() (interface{}, error) {
lines := make([]string, len(e.keys))
for i := range lines {
key := e.keys[i]
lines[i] = key + "=" + e.vals[key]
}
return lines, nil
}
func (e *Environment) Unset(key string) {
l := len(e.vals)
delete(e.vals, key)
if len(e.vals) != l {
for i, k := range e.keys {
if k == key {
copy(e.keys[i:], e.keys[i+1:])
e.keys = e.keys[:len(e.keys)-1]
}
}
}
}
func (e *Environment) Get(key string) string {
return e.vals[key]
}
func (e *Environment) Set(key, value string) {
if !varname.MatchString(key) {
panic("invalid environment variable name: " + key)
}
e.Unset(key)
e.keys = append(e.keys, key)
e.vals[key] = value
}
func (e *Environment) Replace(oldkey, newkey, value string) {
if _, ok := e.vals[oldkey]; ok && newkey != oldkey {
e.Unset(newkey)
delete(e.vals, oldkey)
for i, key := range e.keys {
if key == oldkey {
e.keys[i] = newkey
break
}
}
} else if _, ok := e.vals[newkey]; !ok {
e.keys = append(e.keys, newkey)
}
e.vals[newkey] = value
}
type Skip struct {
Reason string `yaml:"reason"`
If string `yaml:"if"`
}
type Suite struct {
Summary string
Systems []string
Backends []string
Variants []string
Environment *Environment
Prepare string
Restore string
Debug string
PrepareEach string `yaml:"prepare-each"`
RestoreEach string `yaml:"restore-each"`
DebugEach string `yaml:"debug-each"`
Name string `yaml:"-"`
Path string `yaml:"-"`
Tasks map[string]*Task `yaml:"-"`
WarnTimeout Timeout `yaml:"warn-timeout"`
KillTimeout Timeout `yaml:"kill-timeout"`
Priority OptionalInt
Manual bool
Skip []Skip
}
func (s *Suite) String() string { return "suite " + s.Name }
type Task struct {
Suite string `yaml:"-"`
Summary string
Details string
Systems []string
Backends []string
Variants []string
Environment *Environment
Samples int
Prepare string
Restore string
Execute string
Debug string
Artifacts []string
Name string `yaml:"-"`
Path string `yaml:"-"`
WarnTimeout Timeout `yaml:"warn-timeout"`
KillTimeout Timeout `yaml:"kill-timeout"`
Priority OptionalInt
Manual bool
Skip []Skip
}
func (t *Task) String() string { return t.Name }
type Job struct {
Name string
Project *Project
Backend *Backend
System *System
Suite *Suite
Task *Task
Variant string
Environment *Environment
Sample int
Priority int64
SkipReason string
}
func (job *Job) String() string {
return job.Name
}
func (job *Job) StringFor(context interface{}) string {
switch context {
case job.Project, job.Backend, job.System:
return fmt.Sprintf("%s:%s", job.Backend.Name, job.System.Name)
case job.Suite:
return fmt.Sprintf("%s:%s:%s", job.Backend.Name, job.System.Name, job.Suite.Name)
case job.Task:
return fmt.Sprintf("%s:%s:%s", job.Backend.Name, job.System.Name, job.Task.Name)
case job:
return job.Name
}
panic(fmt.Errorf("job %s asked to stringify unrelated value: %v", job, context))
}
func (job *Job) Prepare() string {
return join(job.Project.PrepareEach, job.Backend.PrepareEach, job.Suite.PrepareEach, job.Task.Prepare)
}
func (job *Job) Restore() string {
return join(job.Task.Restore, job.Suite.RestoreEach, job.Backend.RestoreEach, job.Project.RestoreEach)
}
func (job *Job) Debug() string {
return join(job.Task.Debug, job.Suite.DebugEach, job.Backend.DebugEach, job.Project.DebugEach)
}
func (job *Job) WarnTimeoutFor(context interface{}) time.Duration {
touts := []Timeout{job.Task.WarnTimeout, job.Suite.WarnTimeout, job.Backend.WarnTimeout, job.Project.WarnTimeout}
return job.timeoutFor("warn", context, touts)
}
func (job *Job) KillTimeoutFor(context interface{}) time.Duration {
touts := []Timeout{job.Task.KillTimeout, job.Suite.KillTimeout, job.Backend.KillTimeout, job.Project.KillTimeout}
return job.timeoutFor("kill", context, touts)
}
func (job *Job) timeoutFor(which string, context interface{}, touts []Timeout) time.Duration {
switch context {
case job:
case job.Task:
case job.Suite:
touts = touts[1:]
case job.Backend:
touts = touts[2:]
case job.Project:
touts = touts[3:]
default:
panic(fmt.Errorf("job %s asked for %s-timeout of unrelated value: %v", job, which, context))
}
for _, tout := range touts {
if tout.Duration != 0 {
return tout.Duration
}
}
return 0
}
func join(scripts ...string) string {
var buf bytes.Buffer
for _, script := range scripts {
if len(script) == 0 {
continue
}
if buf.Len() > 0 {
buf.WriteString("\n\n")
}
buf.WriteString("(\n")
buf.WriteString(script)
buf.WriteString("\n)")
}
return buf.String()
}
type jobsByName []*Job
func (jobs jobsByName) Len() int { return len(jobs) }
func (jobs jobsByName) Swap(i, j int) { jobs[i], jobs[j] = jobs[j], jobs[i] }
func (jobs jobsByName) Less(i, j int) bool {
ji, jj := jobs[i], jobs[j]
if ji.Backend == jj.Backend && ji.System == jj.System && ji.Task == jj.Task {
return ji.Sample < jj.Sample
}
return ji.Name < jj.Name
}
func SplitVariants(s string) (prefix string, variants []string) {
if i := strings.LastIndex(s, "/"); i >= 0 {
return s[:i], strings.Split(s[i+1:], ",")
}
return s, nil
}
var (
validName = regexp.MustCompile("^[a-z0-9]+(?:[-._][a-z0-9]+)*$")
validSystem = regexp.MustCompile("^[a-z*]+-[a-z0-9*]+(?:[-.][a-z0-9*]+)*$")
validSuite = regexp.MustCompile("^(?:[a-z0-9]+(?:[-._][a-z0-9]+)*/)+$")
validTask = regexp.MustCompile("^(?:[a-z0-9]+(?:[-._][a-z0-9]+)*/)+[a-z0-9]+(?:[-._][a-z0-9]+)*$")
)
func Load(path string) (*Project, error) {
filename, data, err := readProject(path)
if err != nil {
return nil, fmt.Errorf("cannot load project file from %s: %v", path, err)
}
project := &Project{}
err = yaml.Unmarshal(data, project)
if err != nil {
return nil, fmt.Errorf("cannot load %s: %v", filename, err)
}
if !validName.MatchString(project.Name) {
return nil, fmt.Errorf("invalid project name: %q", project.Name)
}
if project.RemotePath == "" {
return nil, fmt.Errorf("missing project path field with remote project location")
}
project.Path = filepath.Join(filepath.Dir(filename), project.Reroot)
project.Repack = strings.TrimSpace(project.Repack)
project.Prepare = strings.TrimSpace(project.Prepare)
project.Restore = strings.TrimSpace(project.Restore)
project.Debug = strings.TrimSpace(project.Debug)
project.PrepareEach = strings.TrimSpace(project.PrepareEach)
project.RestoreEach = strings.TrimSpace(project.RestoreEach)
project.DebugEach = strings.TrimSpace(project.DebugEach)
if err := checkEnv(project, &project.Environment); err != nil {
return nil, err
}
for bname, backend := range project.Backends {
if !validName.MatchString(bname) {
return nil, fmt.Errorf("invalid backend name: %q", bname)
}
if backend == nil {
delete(project.Backends, bname)
continue
}
backend.Name = bname
if backend.Type == "" {
backend.Type = bname
}
switch backend.Type {
case "google", "openstack", "linode", "lxd", "qemu", "adhoc", "humbox":
default:
return nil, fmt.Errorf("%s has unsupported type %q", backend, backend.Type)
}
if backend.Type != "adhoc" && (backend.Allocate != "" || backend.Discard != "") {
return nil, fmt.Errorf("%s cannot use allocate and dispose fields", backend)
}
if backend.Type == "adhoc" && strings.TrimSpace(backend.Allocate) == "" {
return nil, fmt.Errorf("%s requires an allocate field", backend)
}
backend.Prepare = strings.TrimSpace(backend.Prepare)
backend.Restore = strings.TrimSpace(backend.Restore)
backend.Debug = strings.TrimSpace(backend.Debug)
backend.PrepareEach = strings.TrimSpace(backend.PrepareEach)
backend.RestoreEach = strings.TrimSpace(backend.RestoreEach)
backend.DebugEach = strings.TrimSpace(backend.DebugEach)
// Cascade the backend parameters to the systems
for sysname, system := range backend.Systems {
system.Backend = backend.Name
if system.Workers < 0 {
return nil, fmt.Errorf("%s has system %q with %d workers", backend, sysname, system.Workers)
}
if system.Workers == 0 {
system.Workers = 1
}
if system.Storage == 0 {
system.Storage = backend.Storage
}
if system.Plan == "" {
system.Plan = backend.Plan
}
if len(system.Networks) == 0 {
system.Networks = backend.Networks
}
if len(system.Groups) == 0 {
system.Groups = backend.Groups
}
if err := checkEnv(system, &system.Environment); err != nil {
return nil, err
}
}
sort.Strings(backend.Variants)
if err := checkEnv(backend, &backend.Environment); err != nil {
return nil, err
}
if err = checkSystems(backend, backend.systemNames()); err != nil {
return nil, err
}
if len(backend.Systems) == 0 {
return nil, fmt.Errorf("no systems specified for %s", backend)
}
}
if len(project.Backends) == 0 {
return nil, fmt.Errorf("must define at least one backend")
}
if len(project.Suites) == 0 {
return nil, fmt.Errorf("must define at least one task suite")
}
orig := project.Suites
project.Suites = make(map[string]*Suite)
for sname, suite := range orig {
if suite == nil {
suite = &Suite{}
}
if !strings.HasSuffix(sname, "/") {
return nil, fmt.Errorf("invalid suite name (must end with /): %q", sname)
}
if !validSuite.MatchString(sname) {
return nil, fmt.Errorf("invalid suite name: %q", sname)
}
sname = strings.Trim(sname, "/")
suite.Name = sname + "/"
suite.Path = filepath.Join(project.Path, sname)
suite.Summary = strings.TrimSpace(suite.Summary)
suite.Prepare = strings.TrimSpace(suite.Prepare)
suite.Restore = strings.TrimSpace(suite.Restore)
suite.Debug = strings.TrimSpace(suite.Debug)
suite.PrepareEach = strings.TrimSpace(suite.PrepareEach)
suite.RestoreEach = strings.TrimSpace(suite.RestoreEach)
suite.DebugEach = strings.TrimSpace(suite.DebugEach)
for i := range suite.Skip {
suite.Skip[i].Reason = strings.TrimSpace(suite.Skip[i].Reason)
suite.Skip[i].If = strings.TrimSpace(suite.Skip[i].If)
if suite.Skip[i].If == "" || suite.Skip[i].Reason == "" {
return nil, fmt.Errorf("%s is missing either the if or reason for the skip", suite)
}
}
project.Suites[suite.Name] = suite
if suite.Summary == "" {
return nil, fmt.Errorf("%s is missing a summary", suite)
}
if err := checkEnv(suite, &suite.Environment); err != nil {
return nil, err
}
if err := checkSystems(suite, suite.Systems); err != nil {
return nil, err
}
f, err := os.Open(suite.Path)
if err != nil {
return nil, fmt.Errorf("cannot list %s: %v", suite, err)
}
tnames, err := f.Readdirnames(0)
if err != nil {
return nil, fmt.Errorf("cannot list %s: %v", suite, err)
}
suite.Tasks = make(map[string]*Task)
for _, tname := range tnames {
tfilename := filepath.Join(suite.Path, tname, "task.yaml")
if fi, _ := os.Stat(filepath.Dir(tfilename)); !fi.IsDir() {
continue
}
tdata, err := os.ReadFile(tfilename)
if os.IsNotExist(err) {
debugf("Skipping %s/%s: task.yaml missing", sname, tname)
continue
}
if err != nil {
return nil, err
}
task := &Task{}
err = yaml.Unmarshal(tdata, &task)
if err != nil {
return nil, fmt.Errorf("cannot load %s/%s/task.yaml: %v", sname, tname, err)
}
task.Suite = suite.Name
task.Name = suite.Name + tname
task.Path = filepath.Dir(tfilename)
task.Summary = strings.TrimSpace(task.Summary)
task.Prepare = strings.TrimSpace(task.Prepare)
task.Restore = strings.TrimSpace(task.Restore)
task.Debug = strings.TrimSpace(task.Debug)
for _, skip := range task.Skip {
skip.Reason = strings.TrimSpace(skip.Reason)
skip.If = strings.TrimSpace(skip.If)
if skip.If == "" || skip.Reason == "" {
return nil, fmt.Errorf("%s is missing either the if or reason for the skip", task)
}
}
if !validTask.MatchString(task.Name) {
return nil, fmt.Errorf("invalid task name: %q", task.Name)
}
if task.Summary == "" {
return nil, fmt.Errorf("%s is missing a summary", task)
}
if task.Samples == 0 {
task.Samples = 1
}
if err := checkEnv(task, &task.Environment); err != nil {
return nil, err
}
if err := checkSystems(task, task.Systems); err != nil {
return nil, err
}
for _, fname := range task.Artifacts {
if filepath.IsAbs(fname) || fname != filepath.Clean(fname) || strings.HasPrefix(fname, "../") {
return nil, fmt.Errorf("%s has improper artifact path: %s", task.Name, fname)
}
}
suite.Tasks[tname] = task
}
}
debugf("Loaded project: %# v", project)
return project, nil
}
func readProject(path string) (filename string, data []byte, err error) {
path, err = filepath.Abs(path)
if err != nil {
return "", nil, fmt.Errorf("cannot get absolute path for %s: %v", path, err)
}
for {
filename = filepath.Join(path, "spread.yaml")
debugf("Trying to read %s...", filename)
data, err = os.ReadFile(filename)
if os.IsNotExist(err) {
filename = filepath.Join(path, ".spread.yaml")
debugf("Trying to read %s...", filename)
data, err = os.ReadFile(filename)
}
if err == nil {
logf("Found %s.", filename)
return filename, data, nil
}
newpath := filepath.Dir(path)
if newpath == path {
break
}
path = newpath
}
return "", nil, fmt.Errorf("cannot find spread.yaml or .spread.yaml")
}
func checkEnv(context fmt.Stringer, env **Environment) error {
if *env == nil {
*env = NewEnvironment()
} else if (*env).err != nil {
return fmt.Errorf("invalid %s environment: %s", context, (*env).err)
}
return nil
}
func checkSystems(context fmt.Stringer, systems []string) error {
for _, system := range systems {
if strings.HasPrefix(system, "+") || strings.HasPrefix(system, "-") {
system = system[1:]
}
if !validSystem.MatchString(system) {
return fmt.Errorf("%s refers to invalid system name: %q", context, system)
}
}
return nil
}
type Filter interface {
Pass(job *Job) bool
}
type filterExp struct {
regexp *regexp.Regexp
firstSample int
lastSample int
}
type filter struct {
exps []*filterExp
}
func (f *filter) Pass(job *Job) bool {
if len(f.exps) == 0 {
return true
}
for _, exp := range f.exps {
if exp.firstSample > 0 {
if job.Sample < exp.firstSample {
continue
}
if job.Sample > exp.lastSample {
continue
}
}
if exp.regexp.MatchString(job.Name) {
return true
}
}
return false
}
func NewFilter(args []string) (Filter, error) {
var dots = regexp.MustCompile(`\.+|:+|#`)
var sample = regexp.MustCompile(`^(.*)#(\d+)(?:\.\.(\d+))?$`)
var err error
var exps []*filterExp
for _, arg := range args {
var argre = arg
var firstSample, lastSample int
if m := sample.FindStringSubmatch(argre); len(m) > 0 {
argre = m[1]
firstSample, err = strconv.Atoi(m[2])
if err == nil && m[3] != "" {
lastSample, err = strconv.Atoi(m[3])
}
if err != nil {
panic(fmt.Sprintf("internal error: regexp matched non-int on %q", arg))
}
if firstSample > 0 && lastSample == 0 {
lastSample = firstSample
}
if firstSample < 1 || lastSample < firstSample {
return nil, fmt.Errorf("invalid sample range in filter string: %q", arg)
}
}
argre = dots.ReplaceAllStringFunc(argre, func(s string) string {
switch s {
case ".":
return `\.`
case "...":
return `[^:]*`
case ":":
return "(:.+)*:(.+:)*"
case "#":
// Error below. Should have been parsed above.
}
err = fmt.Errorf("invalid filter string: %q", s)
return s
})
if err != nil {
return nil, err
}
if strings.HasPrefix(argre, "(:.+)*:") || strings.HasPrefix(argre, "/") {
argre = ".+" + argre
}
if strings.HasSuffix(argre, ":(.+:)*") || strings.HasSuffix(argre, "/") {
argre = argre + ".+"
}
exp, err := regexp.Compile("(?:^|:)" + argre + "(?:$|[:#])")
if err != nil {
return nil, fmt.Errorf("invalid filter string: %q", arg)
}
exps = append(exps, &filterExp{
regexp: exp,
firstSample: firstSample,
lastSample: lastSample,
})
}
return &filter{exps}, nil
}
func (p *Project) backendNames() []string {
bnames := make([]string, 0, len(p.Backends))
for bname := range p.Backends {
bnames = append(bnames, bname)
}
return bnames
}
func (p *Project) Jobs(options *Options) ([]*Job, error) {
var jobs []*Job
hasFilter := options.Filter != nil
manualBackends := hasFilter
manualSystems := hasFilter
manualSuites := hasFilter
manualTasks := hasFilter
cmdcache := make(map[string]string)
penv := envmap{p, p.Environment}
pevr := strmap{p, evars(p.Environment, "")}
pbke := strmap{p, p.backendNames()}
value, err := evalone("remote project path", p.RemotePath, cmdcache, true, penv)
if err != nil {
return nil, err
}
p.RemotePath = filepath.Clean(value)
if !filepath.IsAbs(p.RemotePath) || filepath.Dir(p.RemotePath) == p.RemotePath {
return nil, fmt.Errorf("remote project path must be absolute and not /: %s", p.RemotePath)
}
for _, suite := range p.Suites {
senv := envmap{suite, suite.Environment}
sevr := strmap{suite, evars(suite.Environment, "+")}
svar := strmap{suite, suite.Variants}
sbke := strmap{suite, suite.Backends}
ssys := strmap{suite, suite.Systems}
for _, task := range suite.Tasks {
tenv := envmap{task, task.Environment}
tevr := strmap{task, evars(task.Environment, "+")}
tvar := strmap{task, task.Variants}
tbke := strmap{task, task.Backends}
tsys := strmap{task, task.Systems}
backends, err := evalstr("backends", pbke, sbke, tbke)
if err != nil {
return nil, err
}
for _, bname := range backends {
backend := p.Backends[bname]
benv := envmap{backend, backend.Environment}
bevr := strmap{backend, evars(backend.Environment, "+")}
bvar := strmap{backend, backend.Variants}
bsys := strmap{backend, backend.systemNames()}
systems, err := evalstr("systems", bsys, ssys, tsys)
if err != nil {
return nil, err
}
for _, sysname := range systems {
system := backend.Systems[sysname]
// not for us
if system == nil {
continue
}
yenv := envmap{system, system.Environment}
yevr := strmap{system, evars(system.Environment, "+")}
yvar := strmap{system, system.Variants}
priority := evaloint(task.Priority, suite.Priority, system.Priority, backend.Priority)
strmaps := []strmap{pevr, bevr, bvar, yevr, yvar, sevr, svar, tevr, tvar}
variants, err := evalstr("variants", strmaps...)
if err != nil {
return nil, err
}
for _, variant := range variants {
if variant == "" && len(variants) > 1 {
continue
}
for sample := 1; sample <= task.Samples; sample++ {
job := &Job{
Project: p,
Backend: backend,
System: system,
Suite: p.Suites[task.Suite],
Task: task,
Variant: variant,
Sample: sample,
Priority: priority,
}
if job.Variant == "" {
job.Name = fmt.Sprintf("%s:%s:%s", job.Backend.Name, job.System.Name, job.Task.Name)
} else {
job.Name = fmt.Sprintf("%s:%s:%s:%s", job.Backend.Name, job.System.Name, job.Task.Name, job.Variant)
}
if task.Samples > 1 {
job.Name += "#" + strconv.Itoa(sample)
}
sprenv := envmap{stringer("$SPREAD_*"), NewEnvironment(
"SPREAD_JOB", job.Name,
"SPREAD_PROJECT", job.Project.Name,
"SPREAD_PATH", job.Project.RemotePath,
"SPREAD_BACKEND", job.Backend.Name,
"SPREAD_SYSTEM", job.System.Name,
"SPREAD_SUITE", job.Suite.Name,
"SPREAD_TASK", job.Task.Name,
"SPREAD_VARIANT", job.Variant,
"SPREAD_SAMPLE", strconv.Itoa(job.Sample),
)}
env, err := evalenv(cmdcache, true, sprenv, penv, benv, yenv, senv, tenv)
if err != nil {
return nil, err
}
job.Environment = env.Variant(variant)
if options.Filter != nil && !options.Filter.Pass(job) {