-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathmanifest.go
1568 lines (1295 loc) · 48.4 KB
/
manifest.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 manifest
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"path"
"reflect"
"regexp"
"sort"
"strings"
"get.porter.sh/porter/pkg/cnab"
"get.porter.sh/porter/pkg/config"
"get.porter.sh/porter/pkg/experimental"
"get.porter.sh/porter/pkg/portercontext"
"get.porter.sh/porter/pkg/schema"
"get.porter.sh/porter/pkg/tracing"
"get.porter.sh/porter/pkg/yaml"
"github.com/Masterminds/semver/v3"
"github.com/cbroglie/mustache"
"github.com/cnabio/cnab-go/bundle"
"github.com/cnabio/cnab-go/bundle/definition"
"github.com/dustin/go-humanize"
"github.com/hashicorp/go-multierror"
"github.com/opencontainers/go-digest"
"go.opentelemetry.io/otel/attribute"
)
const (
invalidStepErrorFormat = "validation of action \"%s\" failed: %w"
// SchemaTypeBundle is the default schemaType value for Bundle resources
SchemaTypeBundle = "Bundle"
// TemplateDelimiterPrefix must be present at the beginning of any porter.yaml
// that wants to use ${} as the template delimiter instead of the mustache
// default of {{}}.
TemplateDelimiterPrefix = "{{=${ }=}}\n"
)
var (
// TODO(PEP003): Version 1.1.0 is behind the DependenciesV2 feature flag. We update the supported versions later
// when validating a bundle and only allow that version when it is enabled.
// The default version remains on the last stable version 1.0.1.
// When the schema version is stable and not behind a feature flag, we can update the supported versions and default version.
// SupportedSchemaVersions is the Porter manifest (porter.yaml) schema
// versions supported by this version of Porter, specified as a semver range.
// When the Manifest structure is changed, this field should be incremented.
SupportedSchemaVersions, _ = semver.NewConstraint("1.0.0-alpha.1 || 1.0.0 - 1.0.1")
// DefaultSchemaVersion is the most recently supported schema version.
// When the Manifest structure is changed, this field should be incremented.
DefaultSchemaVersion = semver.MustParse("1.0.1")
)
type Manifest struct {
// ManifestPath is location to the original, user-supplied manifest, such as the path on the filesystem or a url
ManifestPath string `yaml:"-"`
// TemplateVariables are the variables used in the templating, e.g. bundle.parameters.NAME, or bundle.outputs.NAME
TemplateVariables []string `yaml:"-"`
// SchemaType indicates the type of resource contained in an imported file.
SchemaType string `yaml:"schemaType,omitempty"`
// SchemaVersion is a semver value that indicates which version of the porter.yaml schema is used in the file.
SchemaVersion string `yaml:"schemaVersion"`
Name string `yaml:"name,omitempty"`
Description string `yaml:"description,omitempty"`
Version string `yaml:"version,omitempty"`
Maintainers []MaintainerDefinition `yaml:"maintainers,omitempty"`
// Registry is the OCI registry and org/subdomain for the bundle
Registry string `yaml:"registry,omitempty"`
// Reference is the optional, full bundle reference
// in the format REGISTRY/NAME or REGISTRY/NAME:TAG
Reference string `yaml:"reference,omitempty"`
// DockerTag is the Docker tag portion of the published bundle
// image and bundle. It will only be set at time of publishing.
DockerTag string `yaml:"-"`
// Image is the name of the bundle image in the format REGISTRY/NAME:TAG
// It doesn't map to any field in the manifest as it has been deprecated
// and isn't meant to be user-specified
Image string `yaml:"-"`
// Dockerfile is the relative path to the Dockerfile template for the bundle image
Dockerfile string `yaml:"dockerfile,omitempty"`
Mixins []MixinDeclaration `yaml:"mixins,omitempty"`
Install Steps `yaml:"install"`
Uninstall Steps `yaml:"uninstall"`
Upgrade Steps `yaml:"upgrade"`
Custom CustomDefinitions `yaml:"custom,omitempty"`
CustomActions map[string]Steps `yaml:"-"`
CustomActionDefinitions map[string]CustomActionDefinition `yaml:"customActions,omitempty"`
StateBag StateBag `yaml:"state,omitempty"`
Parameters ParameterDefinitions `yaml:"parameters,omitempty"`
Credentials CredentialDefinitions `yaml:"credentials,omitempty"`
Dependencies Dependencies `yaml:"dependencies,omitempty"`
Outputs OutputDefinitions `yaml:"outputs,omitempty"`
// ImageMap is a map of images referenced in the bundle. If an image relocation mapping is later provided, that
// will be mounted at as a file at runtime to /cnab/app/relocation-mapping.json.
ImageMap map[string]MappedImage `yaml:"images,omitempty"`
Required []RequiredExtension `yaml:"required,omitempty"`
}
func (m *Manifest) Validate(ctx context.Context, cfg *config.Config) error {
ctx, span := tracing.StartSpan(ctx)
defer span.EndSpan()
var result error
err := m.validateMetadata(ctx, cfg)
if err != nil {
return err
}
err = m.SetDefaults()
if err != nil {
return span.Error(err)
}
if strings.ToLower(m.Dockerfile) == "dockerfile" {
return span.Error(errors.New("Dockerfile template cannot be named 'Dockerfile' because that is the filename generated during porter build"))
}
if len(m.Mixins) == 0 {
result = multierror.Append(result, errors.New("no mixins declared"))
}
if m.Install == nil {
result = multierror.Append(result, errors.New("no install action defined"))
}
err = m.Install.Validate(m)
if err != nil {
result = multierror.Append(result, fmt.Errorf(invalidStepErrorFormat, "install", err))
}
if m.Uninstall == nil {
result = multierror.Append(result, errors.New("no uninstall action defined"))
}
err = m.Uninstall.Validate(m)
if err != nil {
result = multierror.Append(result, fmt.Errorf(invalidStepErrorFormat, "uninstall", err))
}
if m.Upgrade != nil {
err = m.Upgrade.Validate(m)
if err != nil {
result = multierror.Append(result, fmt.Errorf(invalidStepErrorFormat, "upgrade", err))
}
}
for actionName, steps := range m.CustomActions {
err := steps.Validate(m)
if err != nil {
result = multierror.Append(result, fmt.Errorf(invalidStepErrorFormat, actionName, err))
}
}
for _, dep := range m.Dependencies.Requires {
err = dep.Validate(cfg.Context)
if err != nil {
result = multierror.Append(result, err)
}
}
for _, output := range m.Outputs {
err = output.Validate()
if err != nil {
result = multierror.Append(result, err)
}
}
for _, parameter := range m.Parameters {
err = parameter.Validate()
if err != nil {
result = multierror.Append(result, err)
}
}
for _, image := range m.ImageMap {
err = image.Validate()
if err != nil {
result = multierror.Append(result, err)
}
}
return span.Error(result)
}
func (m *Manifest) validateMetadata(ctx context.Context, cfg *config.Config) error {
ctx, span := tracing.StartSpan(ctx)
defer span.EndSpan()
strategy := cfg.GetSchemaCheckStrategy(ctx)
span.SetAttributes(attribute.String("schemaCheckStrategy", string(strategy)))
if m.SchemaType == "" {
m.SchemaType = SchemaTypeBundle
} else if !strings.EqualFold(m.SchemaType, SchemaTypeBundle) {
return span.Errorf("invalid schemaType %s, expected %s", m.SchemaType, SchemaTypeBundle)
}
// Check what the supported schema version is based on if depsv2 is enabled
supportedVersions := SupportedSchemaVersions
if cfg.IsFeatureEnabled(experimental.FlagDependenciesV2) {
supportedVersions, _ = semver.NewConstraint("1.0.0-alpha.1 || 1.0.0 - 1.0.1 || 1.1.0")
}
if warnOnly, err := schema.ValidateSchemaVersion(strategy, supportedVersions, m.SchemaVersion, DefaultSchemaVersion); err != nil {
if warnOnly {
span.Warn(err.Error())
} else {
return span.Error(err)
}
}
if m.Name == "" {
return span.Error(errors.New("bundle name must be set"))
}
if m.Registry == "" && m.Reference == "" {
return span.Error(errors.New("a registry or reference value must be provided"))
}
if m.Reference != "" && m.Registry != "" {
span.Warnf("WARNING: both registry and reference were provided; "+
"using the reference value of %s for the bundle reference\n", m.Reference)
}
// Allow for the user to have specified the version with a leading v prefix but save it as
// proper semver
if m.Version != "" {
v, err := semver.NewVersion(m.Version)
if err != nil {
return span.Errorf("version %q is not a valid semver value: %w", m.Version, err)
}
m.Version = v.String()
}
return nil
}
var templatedOutputRegex = regexp.MustCompile(`^bundle\.outputs\.(.+)$`)
// getTemplateOutputName returns the output name from the template variable.
func (m *Manifest) getTemplateOutputName(value string) (string, bool) {
matches := templatedOutputRegex.FindStringSubmatch(value)
if len(matches) < 2 {
return "", false
}
outputName := matches[1]
return outputName, true
}
var templatedDependencyOutputRegex = regexp.MustCompile(`^bundle\.dependencies\.(.+).outputs.(.+)$`)
// getTemplateDependencyOutputName returns the dependency and output name from the
// template variable.
func (m *Manifest) getTemplateDependencyOutputName(value string) (string, string, bool) {
matches := templatedDependencyOutputRegex.FindStringSubmatch(value)
if len(matches) < 3 {
return "", "", false
}
dependencyName := matches[1]
outputName := matches[2]
return dependencyName, outputName, true
}
var templatedDependencyShortOutputRegex = regexp.MustCompile(`^outputs.(.+)$`)
// getTemplateDependencyShortOutputName returns the dependency output name from the
// template variable.
func (m *Manifest) getTemplateDependencyShortOutputName(value string) (string, bool) {
matches := templatedDependencyShortOutputRegex.FindStringSubmatch(value)
if len(matches) < 2 {
return "", false
}
outputName := matches[1]
return outputName, true
}
var templatedParameterRegex = regexp.MustCompile(`^bundle\.parameters\.(.+)$`)
// GetTemplateParameterName returns the parameter name from the template variable.
func (m *Manifest) GetTemplateParameterName(value string) (string, bool) {
matches := templatedParameterRegex.FindStringSubmatch(value)
if len(matches) < 2 {
return "", false
}
parameterName := matches[1]
return parameterName, true
}
// GetTemplatedOutputs returns the output definitions for any bundle level outputs
// that have been templated, keyed by the output name.
func (m *Manifest) GetTemplatedOutputs() OutputDefinitions {
outputs := make(OutputDefinitions, len(m.TemplateVariables))
for _, tmplVar := range m.TemplateVariables {
if name, ok := m.getTemplateOutputName(tmplVar); ok {
outputDef, ok := m.Outputs[name]
if !ok {
// Only return bundle level definitions
continue
}
outputs[name] = outputDef
}
}
return outputs
}
// GetTemplatedOutputs returns the output definitions for any bundle level outputs
// that have been templated, keyed by "DEPENDENCY.OUTPUT".
func (m *Manifest) GetTemplatedDependencyOutputs() DependencyOutputReferences {
outputs := make(DependencyOutputReferences, len(m.TemplateVariables))
for _, tmplVar := range m.TemplateVariables {
if dep, output, ok := m.getTemplateDependencyOutputName(tmplVar); ok {
ref := DependencyOutputReference{
Dependency: dep,
Output: output,
}
outputs[ref.String()] = ref
}
}
return outputs
}
// GetTemplatedParameters returns the output definitions for any bundle level outputs
// that have been templated, keyed by the output name.
func (m *Manifest) GetTemplatedParameters() ParameterDefinitions {
parameters := make(ParameterDefinitions, len(m.TemplateVariables))
for _, tmplVar := range m.TemplateVariables {
if name, ok := m.GetTemplateParameterName(tmplVar); ok {
parameterDef, ok := m.Parameters[name]
if !ok {
// Only return bundle level definitions
continue
}
parameters[name] = parameterDef
}
}
return parameters
}
// DetermineDependenciesExtensionUsed looks for how dependencies are used
// by the bundle and which version of the dependency extension can be used.
func (m *Manifest) DetermineDependenciesExtensionUsed() string {
// Check if v2 deps are explicitly specified
for _, ext := range m.Required {
if ext.Name == cnab.DependenciesV2ExtensionShortHand ||
ext.Name == cnab.DependenciesV2ExtensionKey {
return cnab.DependenciesV2ExtensionKey
}
}
// Check each dependency for use of v2 only features
for _, dep := range m.Dependencies.Requires {
if dep.UsesV2Features() {
return cnab.DependenciesV2ExtensionKey
}
}
// Check if the bundle declares that it can satisfy a v2 dependency
if m.Dependencies.Provides != nil {
return cnab.DependenciesV2ExtensionKey
}
if len(m.Dependencies.Requires) > 0 {
// Dependencies are declared but only use v1 features
return cnab.DependenciesV1ExtensionKey
}
// No dependencies are used at all
return ""
}
type CustomDefinitions map[string]interface{}
func (cd *CustomDefinitions) UnmarshalYAML(unmarshal func(interface{}) error) error {
raw, err := yaml.UnmarshalMap(unmarshal)
if err != nil {
return err
}
*cd = raw
return nil
}
type DependencyOutputReference struct {
Dependency string
Output string
}
func (r DependencyOutputReference) String() string {
return fmt.Sprintf("%s.%s", r.Dependency, r.Output)
}
type DependencyOutputReferences map[string]DependencyOutputReference
// DependencyProvider specifies how the current bundle can be used to satisfy a dependency.
type DependencyProvider struct {
// Interface declares the bundle interface that the current bundle provides.
Interface InterfaceDeclaration `yaml:"interface,omitempty"`
}
// InterfaceDeclaration declares that the current bundle supports the specified bundle interface
// Reserved for future use. Right now we only use an interface id, but could support other fields later.
type InterfaceDeclaration struct {
// ID is the URI of the interface that this bundle provides. Usually a well-known name defined by Porter or CNAB.
ID string `yaml:"id,omitempty"`
}
// ParameterDefinitions allows us to represent parameters as a list in the YAML
// and work with them as a map internally
type ParameterDefinitions map[string]ParameterDefinition
func (pd ParameterDefinitions) MarshalYAML() (interface{}, error) {
raw := make([]ParameterDefinition, 0, len(pd))
for _, param := range pd {
raw = append(raw, param)
}
return raw, nil
}
func (pd *ParameterDefinitions) UnmarshalYAML(unmarshal func(interface{}) error) error {
var raw []ParameterDefinition
err := unmarshal(&raw)
if err != nil {
return err
}
if *pd == nil {
*pd = make(map[string]ParameterDefinition, len(raw))
}
for _, item := range raw {
(*pd)[item.Name] = item
}
return nil
}
var _ bundle.Scoped = &ParameterDefinition{}
// ParameterDefinition defines a single parameter for a CNAB bundle
type ParameterDefinition struct {
Name string `yaml:"name"`
Sensitive bool `yaml:"sensitive"`
Source ParameterSource `yaml:"source,omitempty"`
// These fields represent a subset of bundle.Parameter as defined in cnabio/cnab-go,
// minus the 'Description' field (definition.Schema's will be used) and `Definition` field
ApplyTo []string `yaml:"applyTo,omitempty"`
Destination Location `yaml:",inline,omitempty"`
definition.Schema `yaml:",inline"`
// IsState identifies if the parameter was generated from a state variable
IsState bool `yaml:"-"`
}
func (pd *ParameterDefinition) GetApplyTo() []string {
return pd.ApplyTo
}
func (pd *ParameterDefinition) Validate() error {
var result *multierror.Error
if pd.Name == "" {
result = multierror.Append(result, errors.New("parameter name is required"))
}
// Porter supports declaring a parameter of type: "file",
// which we will convert to the appropriate bundle.Parameter type in adapter.go
// Here, we copy the ParameterDefinition and make the same modification before validation
pdCopy := pd.DeepCopy()
if pdCopy.Type == "file" {
if pd.Destination.Path == "" {
result = multierror.Append(result, fmt.Errorf("no destination path supplied for parameter %s", pd.Name))
}
pdCopy.Type = "string"
pdCopy.ContentEncoding = "base64"
}
// Validate the Parameter Definition schema itself
if _, err := pdCopy.Schema.ValidateSchema(); err != nil {
return multierror.Append(result, fmt.Errorf("encountered an error while validating definition for parameter %q: %w", pdCopy.Name, err))
}
if pdCopy.Default != nil {
schemaValidationErrs, err := pdCopy.Schema.Validate(pdCopy.Default)
if err != nil {
result = multierror.Append(result, fmt.Errorf("encountered error while validating parameter %s: %w", pdCopy.Name, err))
}
for _, schemaValidationErr := range schemaValidationErrs {
result = multierror.Append(result, fmt.Errorf("encountered an error validating the default value %v for parameter %q: %s", pdCopy.Default, pdCopy.Name, schemaValidationErr.Error))
}
}
return result.ErrorOrNil()
}
// DeepCopy copies a ParameterDefinition and returns the copy
func (pd *ParameterDefinition) DeepCopy() *ParameterDefinition {
p2 := *pd
p2.ApplyTo = make([]string, len(pd.ApplyTo))
copy(p2.ApplyTo, pd.ApplyTo)
return &p2
}
// AppliesTo returns a boolean value specifying whether or not
// the Parameter applies to the provided action
func (pd *ParameterDefinition) AppliesTo(action string) bool {
return bundle.AppliesTo(pd, action)
}
// exemptFromInstall returns true if a parameter definition:
// - has an output source (which will not exist prior to install)
// - doesn't already have applyTo specified
// - doesn't have a default value
func (pd *ParameterDefinition) exemptFromInstall() bool {
return pd.Source.Output != "" && pd.ApplyTo == nil && pd.Default == nil
}
// UpdateApplyTo updates a parameter definition's applyTo section
// based on the provided manifest
func (pd *ParameterDefinition) UpdateApplyTo(m *Manifest) {
if pd.exemptFromInstall() {
applyTo := []string{cnab.ActionUninstall}
// The core action "Upgrade" is technically still optional
// so only add it if it is declared in the manifest
if m.Upgrade != nil {
applyTo = append(applyTo, cnab.ActionUpgrade)
}
// Add all custom actions
for action := range m.CustomActions {
applyTo = append(applyTo, action)
}
sort.Strings(applyTo)
pd.ApplyTo = applyTo
}
}
type ParameterSource struct {
Dependency string `yaml:"dependency,omitempty"`
Output string `yaml:"output"`
}
// CredentialDefinitions allows us to represent credentials as a list in the YAML
// and work with them as a map internally
type CredentialDefinitions map[string]CredentialDefinition
func (cd CredentialDefinitions) MarshalYAML() (interface{}, error) {
raw := make([]CredentialDefinition, 0, len(cd))
for _, cred := range cd {
raw = append(raw, cred)
}
return raw, nil
}
func (cd *CredentialDefinitions) UnmarshalYAML(unmarshal func(interface{}) error) error {
var raw []CredentialDefinition
err := unmarshal(&raw)
if err != nil {
return err
}
if *cd == nil {
*cd = make(map[string]CredentialDefinition, len(raw))
}
for _, item := range raw {
(*cd)[item.Name] = item
}
return nil
}
// CredentialDefinition represents the structure or fields of a credential parameter
type CredentialDefinition struct {
Name string `yaml:"name"`
Description string `yaml:"description,omitempty"`
// Required specifies if the credential must be specified for applicable actions. Defaults to true.
Required bool `yaml:"required,omitempty"`
// ApplyTo lists the actions to which the credential applies. When unset, defaults to all actions.
ApplyTo []string `yaml:"applyTo,omitempty"`
Location `yaml:",inline"`
}
func (cd *CredentialDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {
type rawCreds CredentialDefinition
rawCred := rawCreds{
Name: cd.Name,
Description: cd.Description,
Required: true,
Location: cd.Location,
}
if err := unmarshal(&rawCred); err != nil {
return err
}
*cd = CredentialDefinition(rawCred)
return nil
}
// Location represents a Parameter or Credential location in an InvocationImage
type Location struct {
Path string `yaml:"path,omitempty"`
EnvironmentVariable string `yaml:"env,omitempty"`
}
func (l Location) IsEmpty() bool {
var empty Location
return l == empty
}
type MixinDeclaration struct {
Name string
Version *semver.Constraints
Config interface{}
}
func extractVersionFromName(name string) (string, *semver.Constraints, error) {
parts := strings.Split(name, "@")
// if there isn't a version in the name, just stop!
if len(parts) == 1 {
return name, nil, nil
}
// if we somehow got more parts than expected!
if len(parts) != 2 {
return "", nil, fmt.Errorf("expected name@version, got: %s", name)
}
version, err := semver.NewConstraint(parts[1])
if err != nil {
return "", nil, err
}
return parts[0], version, nil
}
// UnmarshalYAML allows mixin declarations to either be a normal list of strings
// mixins:
// - exec
// - helm3
// or allow some entries to have config data defined
// - az:
// extensions:
// - iot
//
// for each type, we can optionally support a version number in the name field
// mixins:
// - [email protected]
// or
// - [email protected]
// extensions:
// - iot
func (m *MixinDeclaration) UnmarshalYAML(unmarshal func(interface{}) error) error {
// First try to just read the mixin name
var mixinNameOnly string
err := unmarshal(&mixinNameOnly)
if err == nil {
name, version, err := extractVersionFromName(mixinNameOnly)
if err != nil {
return fmt.Errorf("invalid mixin name/version: %w", err)
}
m.Name = name
m.Version = version
m.Config = nil
return nil
}
// Next try to read a mixin name with config defined
mixinWithConfig := map[string]interface{}{}
err = unmarshal(&mixinWithConfig)
if err != nil {
return fmt.Errorf("could not unmarshal raw yaml of mixin declarations: %w", err)
}
if len(mixinWithConfig) == 0 {
return errors.New("mixin declaration was empty")
} else if len(mixinWithConfig) > 1 {
return errors.New("mixin declaration contained more than one mixin")
}
for mixinName, config := range mixinWithConfig {
name, version, err := extractVersionFromName(mixinName)
if err != nil {
return fmt.Errorf("invalid mixin name/version: %w", err)
}
m.Name = name
m.Version = version
m.Config = config
break // There is only one mixin anyway but break for clarity
}
return nil
}
// MarshalYAML allows mixin declarations to either be a normal list of strings
// mixins:
// - exec
// - helm3
// or allow some entries to have config data defined
// - az:
// extensions:
// - iot
func (m MixinDeclaration) MarshalYAML() (interface{}, error) {
if m.Config == nil {
return m.Name, nil
}
raw := map[string]interface{}{
m.Name: m.Config,
}
return raw, nil
}
type MappedImage struct {
Description string `yaml:"description"`
ImageType string `yaml:"imageType"`
Repository string `yaml:"repository"`
Digest string `yaml:"digest,omitempty"`
Size uint64 `yaml:"size,omitempty"`
MediaType string `yaml:"mediaType,omitempty"`
Labels map[string]string `yaml:"labels,omitempty"`
Tag string `yaml:"tag,omitempty"`
}
func (mi *MappedImage) Validate() error {
if mi.Digest != "" {
if _, err := digest.Parse(mi.Digest); err != nil {
return err
}
}
if _, err := cnab.ParseOCIReference(mi.Repository); err != nil {
return err
}
return nil
}
func (mi *MappedImage) ToOCIReference() (cnab.OCIReference, error) {
ref, err := cnab.ParseOCIReference(mi.Repository)
if err != nil {
return cnab.OCIReference{}, err
}
if mi.Digest != "" {
refWithDigest, err := ref.WithDigest(digest.Digest(mi.Digest))
if err != nil {
return cnab.OCIReference{}, fmt.Errorf("failed to create a new reference with digest for repository %s: %w", mi.Repository, err)
}
return refWithDigest, nil
}
if mi.Tag != "" {
refWithTag, err := ref.WithTag(mi.Tag)
if err != nil {
return cnab.OCIReference{}, fmt.Errorf("failed to create a new reference with tag for repository %s: %w", mi.Repository, err)
}
return refWithTag, nil
}
return ref, nil
}
// Dependencies defies both v2 and v1 dependencies.
// Dependencies v1 is a subset of Dependencies v2.
type Dependencies struct {
// Requires specifies bundles required by the current bundle.
Requires []*Dependency `yaml:"requires,omitempty"`
// Provides specifies how the bundle can satisfy a dependency.
// This declares that the bundle can provide a dependency that another bundle requires.
Provides *DependencyProvider `yaml:"provides,omitempty"`
}
// Dependency defines a parent child relationship between this bundle (parent) and the specified bundle (child).
type Dependency struct {
// Name of the dependency, used to reference the dependency from other parts of
// the bundle such as the template syntax, bundle.dependencies.NAME
Name string `yaml:"name"`
// Bundle specifies criteria for selecting a bundle to satisfy the dependency.
Bundle BundleCriteria `yaml:"bundle"`
// Sharing is a set of rules for sharing a dependency with other bundles.
Sharing SharingCriteria `yaml:"sharing,omitempty"`
// Parameters is a map of values, keyed by the destination where the value is the
// source, to pass from the bundle to the dependency. May either be a hard-coded
// value, or a template value such as ${bundle.parameters.NAME}. The key is the
// dependency's parameter name, and the value is the data being passed to the
// dependency parameter.
Parameters map[string]string `yaml:"parameters,omitempty"`
// Credentials is a map of values, keyed by the destination where the value is
// the source, to pass from the bundle to the dependency. May either be a
// hard-coded value, or a template value such as ${bundle.credentials.NAME}. The
// key is the dependency's credential name, and the value is the data being
// passed to the dependency credential.
Credentials map[string]string `yaml:"credentials,omitempty"`
// Outputs is a map of values, keyed by the destination where the value is the
// source, to pass from the dependency and promote to a bundle-level outputs of
// the parent bundle. May either be the name of an output from the dependency, or
// a template value such as ${outputs.NAME} where the outputs variable holds the
// current dependency's outputs. The long form of the template syntax,
// ${bundle.dependencies.DEP.outputs.NAME}, is also supported. The key is the
// parent bundle's output name, and the value is the data being passed to the
// dependency parameter.
Outputs map[string]string `yaml:"outputs,omitempty"`
}
type DependencySource string
// BundleCriteria criteria for selecting a bundle to satisfy a dependency.
type BundleCriteria struct {
// Reference is an OCI reference to a bundle for use as the default implementation of the bundle.
// It should be in the format REGISTRY/NAME:TAG
Reference string `yaml:"reference"`
// "When constraint checking is used for checks or validation
// it will follow a different set of rules that are common for ranges with tools like npm/js and Rust/Cargo.
// This includes considering prereleases to be invalid if the ranges does not include one.
// If you want to have it include pre-releases a simple solution is to include -0 in your range."
// https://github.com/Masterminds/semver/blob/master/README.md#checking-version-constraints
Version string `yaml:"version,omitempty"`
// Interface specifies criteria for allowing a bundle to satisfy a dependency.
Interface *BundleInterface `yaml:"interface,omitempty"`
}
// BundleInterface specifies how a bundle can satisfy a dependency.
// Porter always infers a base interface based on how the dependency is used in porter.yaml
// but this allows the bundle author to extend it and add additional restrictions.
// Either bundle or reference may be specified but not both.
type BundleInterface struct {
// ID is the identifier or name of the bundle interface. It should be matched
// against the Dependencies.Provides.Interface.ID to determine if two interfaces
// are equivalent.
ID string `yaml:"id,omitempty"`
// Reference specifies an OCI reference to a bundle to use as the interface on top of how the bundle is used.
Reference string `yaml:"reference,omitempty"`
// Document specifies additional constraints that should be added to the bundle interface.
// By default, Porter only requires the name and the type to match, additional jsonschema values can be specified to restrict matching bundles even further.
// The value should be a jsonschema document containing relevant sub-documents from a bundle.json that should be applied to the base bundle interface.
Document *BundleInterfaceDocument `yaml:"document,omitempty"`
}
// BundleInterfaceDocument specifies the interface that a bundle must support in
// order to satisfy a dependency.
type BundleInterfaceDocument struct {
// Parameters that are defined on the interface.
Parameters ParameterDefinitions `yaml:"parameters,omitempty"`
// Credentials that are defined on the interface.
Credentials CredentialDefinitions `yaml:"credentials,omitempty"`
// Outputs that are defined on the interface.
Outputs OutputDefinitions `yaml:"outputs,omitempty"`
}
// SharingCriteria is a set of rules for sharing a dependency with other bundles.
type SharingCriteria struct {
// Mode defines how a dependency can be shared.
// - false: The dependency cannot be shared, even within the same dependency graph.
// - true: The dependency is shared with other bundles who defined the dependency
// with the same sharing group. This is the default mode.
Mode bool `yaml:"mode"`
// Group defines matching criteria for determining if two dependencies are in the same sharing group.
Group SharingGroup `yaml:"group,omitempty"`
}
// GetEffectiveMode returns the mode, taking into account the default value when
// no mode is specified.
func (s SharingCriteria) GetEffectiveMode() bool {
return s.Mode
}
// SharingGroup defines a set of characteristics for sharing a dependency with
// other bundles.
// Reserved for future use: We can add more characteristics later to expands how we share if needed
type SharingGroup struct {
// Name of the sharing group. The name of the group must match for two bundles to share the same dependency.
Name string `yaml:"name"`
}
func (d *Dependency) Validate(cxt *portercontext.Context) error {
if d.Name == "" {
return errors.New("dependency name is required")
}
if d.Bundle.Reference == "" {
return fmt.Errorf("reference is required for dependency %q", d.Name)
}
ref, err := cnab.ParseOCIReference(d.Bundle.Reference)
if err != nil {
return fmt.Errorf("invalid reference %s for dependency %s: %w", d.Bundle.Reference, d.Name, err)
}
if ref.IsRepositoryOnly() && d.Bundle.Version == "" {
return fmt.Errorf("reference for dependency %q can specify only a repository, without a digest or tag, when a version constraint is specified", d.Name)
}
return nil
}
// UsesV2Features returns true if the dependency uses features from v2 of
// Porter's implementation of dependencies, and returns false if the v1
// implementation of dependencies would suffice.
func (d *Dependency) UsesV2Features() bool {
// Sharing was added in v2
if d.Sharing != (SharingCriteria{}) {
return true
}
// Credentials and output mapping was added in v2
if len(d.Credentials) > 0 || len(d.Outputs) > 0 {
return true
}
// Bundle interfaces was added in v2
if d.Bundle.Interface != nil {
return true
}
// Anything else can be handled with v1
return false
}
type CustomActionDefinition struct {
Description string `yaml:"description,omitempty"`
ModifiesResources bool `yaml:"modifies,omitempty"`
Stateless bool `yaml:"stateless,omitempty"`
}
// OutputDefinitions allows us to represent parameters as a list in the YAML
// and work with them as a map internally
type OutputDefinitions map[string]OutputDefinition
func (od OutputDefinitions) MarshalYAML() (interface{}, error) {
raw := make([]OutputDefinition, 0, len(od))
for _, output := range od {
raw = append(raw, output)
}
return raw, nil
}
func (od *OutputDefinitions) UnmarshalYAML(unmarshal func(interface{}) error) error {
var raw []OutputDefinition
err := unmarshal(&raw)
if err != nil {
return err
}
if *od == nil {
*od = make(map[string]OutputDefinition, len(raw))
}
for _, item := range raw {
(*od)[item.Name] = item
}