-
Notifications
You must be signed in to change notification settings - Fork 59
/
meta.go
1515 lines (1385 loc) · 43.9 KB
/
meta.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
// Copyright 2011, 2012, 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package charm
import (
"fmt"
"io"
"io/ioutil"
"regexp"
"sort"
"strconv"
"strings"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/names/v5"
"github.com/juju/os/v2"
"github.com/juju/os/v2/series"
"github.com/juju/schema"
"github.com/juju/utils/v3"
"github.com/juju/version/v2"
"gopkg.in/yaml.v2"
"github.com/juju/charm/v12/assumes"
"github.com/juju/charm/v12/hooks"
"github.com/juju/charm/v12/resource"
)
// RelationScope describes the scope of a relation.
type RelationScope string
// Note that schema doesn't support custom string types,
// so when we use these values in a schema.Checker,
// we must store them as strings, not RelationScopes.
const (
ScopeGlobal RelationScope = "global"
ScopeContainer RelationScope = "container"
)
// RelationRole defines the role of a relation.
type RelationRole string
const (
RoleProvider RelationRole = "provider"
RoleRequirer RelationRole = "requirer"
RolePeer RelationRole = "peer"
)
// StorageType defines a storage type.
type StorageType string
const (
StorageBlock StorageType = "block"
StorageFilesystem StorageType = "filesystem"
)
// Storage represents a charm's storage requirement.
type Storage struct {
// Name is the name of the store.
//
// Name has no default, and must be specified.
Name string `bson:"name"`
// Description is a description of the store.
//
// Description has no default, and is optional.
Description string `bson:"description"`
// Type is the storage type: filesystem or block-device.
//
// Type has no default, and must be specified.
Type StorageType `bson:"type"`
// Shared indicates that the storage is shared between all units of
// an application deployed from the charm. It is an error to attempt to
// assign non-shareable storage to a "shared" storage requirement.
//
// Shared defaults to false.
Shared bool `bson:"shared"`
// ReadOnly indicates that the storage should be made read-only if
// possible. If the storage cannot be made read-only, Juju will warn
// the user.
//
// ReadOnly defaults to false.
ReadOnly bool `bson:"read-only"`
// CountMin is the number of storage instances that must be attached
// to the charm for it to be useful; the charm will not install until
// this number has been satisfied. This must be a non-negative number.
//
// CountMin defaults to 1 for singleton stores.
CountMin int `bson:"countmin"`
// CountMax is the largest number of storage instances that can be
// attached to the charm. If CountMax is -1, then there is no upper
// bound.
//
// CountMax defaults to 1 for singleton stores.
CountMax int `bson:"countmax"`
// MinimumSize is the minimum size of store that the charm needs to
// work at all. This is not a recommended size or a comfortable size
// or a will-work-well size, just a bare minimum below which the charm
// is going to break.
// MinimumSize requires a unit, one of MGTPEZY, and is stored as MiB.
//
// There is no default MinimumSize; if left unspecified, a provider
// specific default will be used, typically 1GB for block storage.
MinimumSize uint64 `bson:"minimum-size"`
// Location is the mount location for filesystem stores. For multi-
// stores, the location acts as the parent directory for each mounted
// store.
//
// Location has no default, and is optional.
Location string `bson:"location,omitempty"`
// Properties allow the charm author to characterise the relative storage
// performance requirements and sensitivities for each store.
// eg “transient” is used to indicate that non persistent storage is acceptable,
// such as tmpfs or ephemeral instance disks.
//
// Properties has no default, and is optional.
Properties []string `bson:"properties,omitempty"`
}
// DeviceType defines a device type.
type DeviceType string
// Device represents a charm's device requirement (GPU for example).
type Device struct {
// Name is the name of the device.
Name string `bson:"name"`
// Description is a description of the device.
Description string `bson:"description"`
// Type is the device type.
// currently supported types are
// - gpu
// - nvidia.com/gpu
// - amd.com/gpu
Type DeviceType `bson:"type"`
// CountMin is the min number of devices that the charm requires.
CountMin int64 `bson:"countmin"`
// CountMax is the max number of devices that the charm requires.
CountMax int64 `bson:"countmax"`
}
// DeploymentType defines a deployment type.
type DeploymentType string
const (
DeploymentStateless DeploymentType = "stateless"
DeploymentStateful DeploymentType = "stateful"
DeploymentDaemon DeploymentType = "daemon"
)
// DeploymentMode defines a deployment mode.
type DeploymentMode string
const (
ModeOperator DeploymentMode = "operator"
ModeWorkload DeploymentMode = "workload"
)
// ServiceType defines a service type.
type ServiceType string
const (
ServiceCluster ServiceType = "cluster"
ServiceLoadBalancer ServiceType = "loadbalancer"
ServiceExternal ServiceType = "external"
ServiceOmit ServiceType = "omit"
)
var validServiceTypes = map[os.OSType][]ServiceType{
os.Kubernetes: {
ServiceCluster,
ServiceLoadBalancer,
ServiceExternal,
ServiceOmit,
},
}
// Deployment represents a charm's deployment requirements in the charm
// metadata.yaml file.
type Deployment struct {
DeploymentType DeploymentType `bson:"type"`
DeploymentMode DeploymentMode `bson:"mode"`
ServiceType ServiceType `bson:"service"`
MinVersion string `bson:"min-version"`
}
// Relation represents a single relation defined in the charm
// metadata.yaml file.
type Relation struct {
Name string `bson:"name"`
Role RelationRole `bson:"role"`
Interface string `bson:"interface"`
Optional bool `bson:"optional"`
Limit int `bson:"limit"`
Scope RelationScope `bson:"scope"`
}
// ImplementedBy returns whether the relation is implemented by the supplied charm.
func (r Relation) ImplementedBy(ch Charm) bool {
if r.IsImplicit() {
return true
}
var m map[string]Relation
switch r.Role {
case RoleProvider:
m = ch.Meta().Provides
case RoleRequirer:
m = ch.Meta().Requires
case RolePeer:
m = ch.Meta().Peers
default:
panic(errors.Errorf("unknown relation role %q", r.Role))
}
rel, found := m[r.Name]
if !found {
return false
}
if rel.Interface == r.Interface {
switch r.Scope {
case ScopeGlobal:
return rel.Scope != ScopeContainer
case ScopeContainer:
return true
default:
panic(errors.Errorf("unknown relation scope %q", r.Scope))
}
}
return false
}
// IsImplicit returns whether the relation is supplied by juju itself,
// rather than by a charm.
func (r Relation) IsImplicit() bool {
return (r.Name == "juju-info" &&
r.Interface == "juju-info" &&
r.Role == RoleProvider)
}
// RunAs defines which user to run a certain process as.
type RunAs string
const (
RunAsDefault RunAs = ""
RunAsRoot RunAs = "root"
RunAsSudoer RunAs = "sudoer"
RunAsNonRoot RunAs = "non-root"
)
// Meta represents all the known content that may be defined
// within a charm's metadata.yaml file.
// Note: Series is serialised for backward compatibility
// as "supported-series" because a previous
// charm version had an incompatible Series field that
// was unused in practice but still serialized. This
// only applies to JSON because Meta has a custom
// YAML marshaller.
type Meta struct {
Name string `bson:"name" json:"Name"`
Summary string `bson:"summary" json:"Summary"`
Description string `bson:"description" json:"Description"`
Subordinate bool `bson:"subordinate" json:"Subordinate"`
Provides map[string]Relation `bson:"provides,omitempty" json:"Provides,omitempty"`
Requires map[string]Relation `bson:"requires,omitempty" json:"Requires,omitempty"`
Peers map[string]Relation `bson:"peers,omitempty" json:"Peers,omitempty"`
ExtraBindings map[string]ExtraBinding `bson:"extra-bindings,omitempty" json:"ExtraBindings,omitempty"`
Categories []string `bson:"categories,omitempty" json:"Categories,omitempty"`
Tags []string `bson:"tags,omitempty" json:"Tags,omitempty"`
Series []string `bson:"series,omitempty" json:"SupportedSeries,omitempty"`
Storage map[string]Storage `bson:"storage,omitempty" json:"Storage,omitempty"`
Devices map[string]Device `bson:"devices,omitempty" json:"Devices,omitempty"`
Deployment *Deployment `bson:"deployment,omitempty" json:"Deployment,omitempty"`
PayloadClasses map[string]PayloadClass `bson:"payloadclasses,omitempty" json:"PayloadClasses,omitempty"`
Resources map[string]resource.Meta `bson:"resources,omitempty" json:"Resources,omitempty"`
Terms []string `bson:"terms,omitempty" json:"Terms,omitempty"`
MinJujuVersion version.Number `bson:"min-juju-version,omitempty" json:"min-juju-version,omitempty"`
// v2
Containers map[string]Container `bson:"containers,omitempty" json:"containers,omitempty" yaml:"containers,omitempty"`
Assumes *assumes.ExpressionTree `bson:"assumes,omitempty" json:"assumes,omitempty" yaml:"assumes,omitempty"`
CharmUser RunAs `bson:"charm-user,omitempty" json:"charm-user,omitempty" yaml:"charm-user,omitempty"`
}
// Container specifies the possible systems it supports and mounts it wants.
type Container struct {
Resource string `bson:"resource,omitempty" json:"resource,omitempty" yaml:"resource,omitempty"`
Mounts []Mount `bson:"mounts,omitempty" json:"mounts,omitempty" yaml:"mounts,omitempty"`
Uid *int `bson:"uid,omitempty" json:"uid,omitempty" yaml:"uid,omitempty"`
Gid *int `bson:"gid,omitempty" json:"gid,omitempty" yaml:"gid,omitempty"`
}
// Mount allows a container to mount a storage filesystem from the storage top-level directive.
type Mount struct {
Storage string `bson:"storage,omitempty" json:"storage,omitempty" yaml:"storage,omitempty"`
Location string `bson:"location,omitempty" json:"location,omitempty" yaml:"location,omitempty"`
}
func generateRelationHooks(relName string, allHooks map[string]bool) {
for _, hookName := range hooks.RelationHooks() {
allHooks[fmt.Sprintf("%s-%s", relName, hookName)] = true
}
}
func generateContainerHooks(containerName string, allHooks map[string]bool) {
// Containers using pebble trigger workload hooks.
for _, hookName := range hooks.WorkloadHooks() {
allHooks[fmt.Sprintf("%s-%s", containerName, hookName)] = true
}
}
func generateStorageHooks(storageName string, allHooks map[string]bool) {
for _, hookName := range hooks.StorageHooks() {
allHooks[fmt.Sprintf("%s-%s", storageName, hookName)] = true
}
}
// Hooks returns a map of all possible valid hooks, taking relations
// into account. It's a map to enable fast lookups, and the value is
// always true.
func (m Meta) Hooks() map[string]bool {
allHooks := make(map[string]bool)
// Unit hooks
for _, hookName := range hooks.UnitHooks() {
allHooks[string(hookName)] = true
}
// Secret hooks
for _, hookName := range hooks.SecretHooks() {
allHooks[string(hookName)] = true
}
// Relation hooks
for hookName := range m.Provides {
generateRelationHooks(hookName, allHooks)
}
for hookName := range m.Requires {
generateRelationHooks(hookName, allHooks)
}
for hookName := range m.Peers {
generateRelationHooks(hookName, allHooks)
}
for storageName := range m.Storage {
generateStorageHooks(storageName, allHooks)
}
for containerName := range m.Containers {
generateContainerHooks(containerName, allHooks)
}
return allHooks
}
// Used for parsing Categories and Tags.
func parseStringList(list interface{}) []string {
if list == nil {
return nil
}
slice := list.([]interface{})
result := make([]string, 0, len(slice))
for _, elem := range slice {
result = append(result, elem.(string))
}
return result
}
var validTermName = regexp.MustCompile(`^[a-z](-?[a-z0-9]+)+$`)
// TermsId represents a single term id. The term can either be owned
// or "public" (meaning there is no owner).
// The Revision starts at 1. Therefore a value of 0 means the revision
// is unset.
type TermsId struct {
Tenant string
Owner string
Name string
Revision int
}
// Validate returns an error if the Term contains invalid data.
func (t *TermsId) Validate() error {
if t.Tenant != "" && t.Tenant != "cs" {
if !validTermName.MatchString(t.Tenant) {
return errors.Errorf("wrong term tenant format %q", t.Tenant)
}
}
if t.Owner != "" && !names.IsValidUser(t.Owner) {
return errors.Errorf("wrong owner format %q", t.Owner)
}
if !validTermName.MatchString(t.Name) {
return errors.Errorf("wrong term name format %q", t.Name)
}
if t.Revision < 0 {
return errors.Errorf("negative term revision")
}
return nil
}
// String returns the term in canonical form.
// This would be one of:
//
// tenant:owner/name/revision
// tenant:name
// owner/name/revision
// owner/name
// name/revision
// name
func (t *TermsId) String() string {
id := make([]byte, 0, len(t.Tenant)+1+len(t.Owner)+1+len(t.Name)+4)
if t.Tenant != "" {
id = append(id, t.Tenant...)
id = append(id, ':')
}
if t.Owner != "" {
id = append(id, t.Owner...)
id = append(id, '/')
}
id = append(id, t.Name...)
if t.Revision != 0 {
id = append(id, '/')
id = strconv.AppendInt(id, int64(t.Revision), 10)
}
return string(id)
}
// ParseTerm takes a termID as a string and parses it into a Term.
// A complete term is in the form:
// tenant:owner/name/revision
// This function accepts partially specified identifiers
// typically in one of the following forms:
// name
// owner/name
// owner/name/27 # Revision 27
// name/283 # Revision 283
// cs:owner/name # Tenant cs
func ParseTerm(s string) (*TermsId, error) {
tenant := ""
termid := s
if t := strings.SplitN(s, ":", 2); len(t) == 2 {
tenant = t[0]
termid = t[1]
}
tokens := strings.Split(termid, "/")
var term TermsId
switch len(tokens) {
case 1: // "name"
term = TermsId{
Tenant: tenant,
Name: tokens[0],
}
case 2: // owner/name or name/123
termRevision, err := strconv.Atoi(tokens[1])
if err != nil { // owner/name
term = TermsId{
Tenant: tenant,
Owner: tokens[0],
Name: tokens[1],
}
} else { // name/123
term = TermsId{
Tenant: tenant,
Name: tokens[0],
Revision: termRevision,
}
}
case 3: // owner/name/123
termRevision, err := strconv.Atoi(tokens[2])
if err != nil {
return nil, errors.Errorf("invalid revision number %q %v", tokens[2], err)
}
term = TermsId{
Tenant: tenant,
Owner: tokens[0],
Name: tokens[1],
Revision: termRevision,
}
default:
return nil, errors.Errorf("unknown term id format %q", s)
}
if err := term.Validate(); err != nil {
return nil, errors.Trace(err)
}
return &term, nil
}
// ReadMeta reads the content of a metadata.yaml file and returns
// its representation.
// The data has verified as unambiguous, but not validated.
func ReadMeta(r io.Reader) (*Meta, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
var meta Meta
err = yaml.Unmarshal(data, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
// UnmarshalYAML
func (meta *Meta) UnmarshalYAML(f func(interface{}) error) error {
raw := make(map[interface{}]interface{})
err := f(&raw)
if err != nil {
return err
}
if err := ensureUnambiguousFormat(raw); err != nil {
return err
}
v, err := charmSchema.Coerce(raw, nil)
if err != nil {
return errors.New("metadata: " + err.Error())
}
m := v.(map[string]interface{})
meta1, err := parseMeta(m)
if err != nil {
return err
}
*meta = *meta1
// Assumes blocks have their own dedicated parser so we need to invoke
// it here and attach the resulting expression tree (if any) to the
// metadata
var assumesBlock = struct {
Assumes *assumes.ExpressionTree `yaml:"assumes"`
}{}
if err := f(&assumesBlock); err != nil {
return err
}
meta.Assumes = assumesBlock.Assumes
return nil
}
func parseMeta(m map[string]interface{}) (*Meta, error) {
var meta Meta
var err error
meta.Name = m["name"].(string)
// Schema decodes as int64, but the int range should be good
// enough for revisions.
meta.Summary = m["summary"].(string)
meta.Description = m["description"].(string)
meta.Provides = parseRelations(m["provides"], RoleProvider)
meta.Requires = parseRelations(m["requires"], RoleRequirer)
meta.Peers = parseRelations(m["peers"], RolePeer)
if meta.ExtraBindings, err = parseMetaExtraBindings(m["extra-bindings"]); err != nil {
return nil, err
}
meta.Categories = parseStringList(m["categories"])
meta.Tags = parseStringList(m["tags"])
if subordinate := m["subordinate"]; subordinate != nil {
meta.Subordinate = subordinate.(bool)
}
meta.Series = parseStringList(m["series"])
meta.Storage = parseStorage(m["storage"])
meta.Devices = parseDevices(m["devices"])
meta.Deployment, err = parseDeployment(m["deployment"], meta.Series, meta.Storage)
if err != nil {
return nil, err
}
meta.PayloadClasses = parsePayloadClasses(m["payloads"])
meta.MinJujuVersion, err = parseMinJujuVersion(m["min-juju-version"])
if err != nil {
return nil, err
}
meta.Terms = parseStringList(m["terms"])
meta.Resources, err = parseMetaResources(m["resources"])
if err != nil {
return nil, err
}
// v2 parsing
meta.Containers, err = parseContainers(m["containers"], meta.Resources, meta.Storage)
if err != nil {
return nil, errors.Annotatef(err, "parsing containers")
}
meta.CharmUser, err = parseCharmUser(m["charm-user"])
if err != nil {
return nil, errors.Annotatef(err, "parsing charm-user")
}
return &meta, nil
}
// MarshalYAML implements yaml.Marshaler (yaml.v2).
// It is recommended to call Check() before calling this method,
// otherwise you make get metadata which is not v1 nor v2 format.
func (m Meta) MarshalYAML() (interface{}, error) {
var minver string
if m.MinJujuVersion != version.Zero {
minver = m.MinJujuVersion.String()
}
return struct {
Name string `yaml:"name"`
Summary string `yaml:"summary"`
Description string `yaml:"description"`
Provides map[string]marshaledRelation `yaml:"provides,omitempty"`
Requires map[string]marshaledRelation `yaml:"requires,omitempty"`
Peers map[string]marshaledRelation `yaml:"peers,omitempty"`
ExtraBindings map[string]interface{} `yaml:"extra-bindings,omitempty"`
Categories []string `yaml:"categories,omitempty"`
Tags []string `yaml:"tags,omitempty"`
Subordinate bool `yaml:"subordinate,omitempty"`
Series []string `yaml:"series,omitempty"`
Storage map[string]Storage `yaml:"storage,omitempty"`
Devices map[string]Device `yaml:"devices,omitempty"`
Deployment *Deployment `yaml:"deployment,omitempty"`
Terms []string `yaml:"terms,omitempty"`
MinJujuVersion string `yaml:"min-juju-version,omitempty"`
Resources map[string]marshaledResourceMeta `yaml:"resources,omitempty"`
Containers map[string]marshaledContainer `yaml:"containers,omitempty"`
Assumes *assumes.ExpressionTree `yaml:"assumes,omitempty"`
}{
Name: m.Name,
Summary: m.Summary,
Description: m.Description,
Provides: marshaledRelations(m.Provides),
Requires: marshaledRelations(m.Requires),
Peers: marshaledRelations(m.Peers),
ExtraBindings: marshaledExtraBindings(m.ExtraBindings),
Categories: m.Categories,
Tags: m.Tags,
Subordinate: m.Subordinate,
Series: m.Series,
Storage: m.Storage,
Devices: m.Devices,
Deployment: m.Deployment,
Terms: m.Terms,
MinJujuVersion: minver,
Resources: marshaledResources(m.Resources),
Containers: marshaledContainers(m.Containers),
Assumes: m.Assumes,
}, nil
}
type marshaledResourceMeta struct {
Path string `yaml:"filename"` // TODO(ericsnow) Change to "path"?
Type string `yaml:"type,omitempty"`
Description string `yaml:"description,omitempty"`
}
func marshaledResources(rs map[string]resource.Meta) map[string]marshaledResourceMeta {
rs1 := make(map[string]marshaledResourceMeta, len(rs))
for name, r := range rs {
r1 := marshaledResourceMeta{
Path: r.Path,
Description: r.Description,
}
if r.Type != resource.TypeFile {
r1.Type = r.Type.String()
}
rs1[name] = r1
}
return rs1
}
func marshaledRelations(relations map[string]Relation) map[string]marshaledRelation {
marshaled := make(map[string]marshaledRelation)
for name, relation := range relations {
marshaled[name] = marshaledRelation(relation)
}
return marshaled
}
type marshaledRelation Relation
func (r marshaledRelation) MarshalYAML() (interface{}, error) {
// See calls to ifaceExpander in charmSchema.
var noLimit int
if !r.Optional && r.Limit == noLimit && r.Scope == ScopeGlobal {
// All attributes are default, so use the simple string form of the relation.
return r.Interface, nil
}
mr := struct {
Interface string `yaml:"interface"`
Limit *int `yaml:"limit,omitempty"`
Optional bool `yaml:"optional,omitempty"`
Scope RelationScope `yaml:"scope,omitempty"`
}{
Interface: r.Interface,
Optional: r.Optional,
}
if r.Limit != noLimit {
mr.Limit = &r.Limit
}
if r.Scope != ScopeGlobal {
mr.Scope = r.Scope
}
return mr, nil
}
func marshaledExtraBindings(bindings map[string]ExtraBinding) map[string]interface{} {
marshaled := make(map[string]interface{})
for _, binding := range bindings {
marshaled[binding.Name] = nil
}
return marshaled
}
type marshaledContainer Container
func marshaledContainers(c map[string]Container) map[string]marshaledContainer {
marshaled := make(map[string]marshaledContainer)
for k, v := range c {
marshaled[k] = marshaledContainer(v)
}
return marshaled
}
func (c marshaledContainer) MarshalYAML() (interface{}, error) {
mc := struct {
Resource string `yaml:"resource,omitempty"`
Mounts []Mount `yaml:"mounts,omitempty"`
}{
Resource: c.Resource,
Mounts: c.Mounts,
}
return mc, nil
}
// Format of the parsed charm.
type Format int
// Formats are the different versions of charm metadata supported.
const (
FormatUnknown Format = iota
FormatV1 Format = iota
FormatV2 Format = iota
)
// Check checks that the metadata is well-formed.
func (m Meta) Check(format Format, reasons ...FormatSelectionReason) error {
switch format {
case FormatV1:
err := m.checkV1(reasons)
if err != nil {
return errors.Trace(err)
}
case FormatV2:
err := m.checkV2(reasons)
if err != nil {
return errors.Trace(err)
}
default:
return errors.Errorf("unknown format %v", format)
}
// Check for duplicate or forbidden relation names or interfaces.
names := make(map[string]bool)
checkRelations := func(src map[string]Relation, role RelationRole) error {
for name, rel := range src {
if rel.Name != name {
return errors.Errorf("charm %q has mismatched relation name %q; expected %q", m.Name, rel.Name, name)
}
if rel.Role != role {
return errors.Errorf("charm %q has mismatched role %q; expected %q", m.Name, rel.Role, role)
}
// Container-scoped require relations on subordinates are allowed
// to use the otherwise-reserved juju-* namespace.
if !m.Subordinate || role != RoleRequirer || rel.Scope != ScopeContainer {
if reserved, _ := reservedName(m.Name, name); reserved {
return errors.Errorf("charm %q using a reserved relation name: %q", m.Name, name)
}
}
if role != RoleRequirer {
if reserved, _ := reservedName(m.Name, rel.Interface); reserved {
return errors.Errorf("charm %q relation %q using a reserved interface: %q", m.Name, name, rel.Interface)
}
}
if names[name] {
return errors.Errorf("charm %q using a duplicated relation name: %q", m.Name, name)
}
names[name] = true
}
return nil
}
if err := checkRelations(m.Provides, RoleProvider); err != nil {
return err
}
if err := checkRelations(m.Requires, RoleRequirer); err != nil {
return err
}
if err := checkRelations(m.Peers, RolePeer); err != nil {
return err
}
if err := validateMetaExtraBindings(m); err != nil {
return errors.Errorf("charm %q has invalid extra bindings: %v", m.Name, err)
}
// Subordinate charms must have at least one relation that
// has container scope, otherwise they can't relate to the
// principal.
if m.Subordinate {
valid := false
if m.Requires != nil {
for _, relationData := range m.Requires {
if relationData.Scope == ScopeContainer {
valid = true
break
}
}
}
if !valid {
return errors.Errorf("subordinate charm %q lacks \"requires\" relation with container scope", m.Name)
}
}
for _, series := range m.Series {
if !IsValidSeries(series) {
return errors.Errorf("charm %q declares invalid series: %q", m.Name, series)
}
}
names = make(map[string]bool)
for name, store := range m.Storage {
if store.Location != "" && store.Type != StorageFilesystem {
return errors.Errorf(`charm %q storage %q: location may not be specified for "type: %s"`, m.Name, name, store.Type)
}
if store.Type == "" {
return errors.Errorf("charm %q storage %q: type must be specified", m.Name, name)
}
if store.CountMin < 0 {
return errors.Errorf("charm %q storage %q: invalid minimum count %d", m.Name, name, store.CountMin)
}
if store.CountMax == 0 || store.CountMax < -1 {
return errors.Errorf("charm %q storage %q: invalid maximum count %d", m.Name, name, store.CountMax)
}
if names[name] {
return errors.Errorf("charm %q storage %q: duplicated storage name", m.Name, name)
}
names[name] = true
}
names = make(map[string]bool)
for name, device := range m.Devices {
if device.Type == "" {
return errors.Errorf("charm %q device %q: type must be specified", m.Name, name)
}
if device.CountMax >= 0 && device.CountMin >= 0 && device.CountMin > device.CountMax {
return errors.Errorf(
"charm %q device %q: maximum count %d can not be smaller than minimum count %d",
m.Name, name, device.CountMax, device.CountMin)
}
if names[name] {
return errors.Errorf("charm %q device %q: duplicated device name", m.Name, name)
}
names[name] = true
}
for name, payloadClass := range m.PayloadClasses {
if payloadClass.Name != name {
return errors.Errorf("mismatch on payload class name (%q != %q)", payloadClass.Name, name)
}
if err := payloadClass.Validate(); err != nil {
return err
}
}
if err := validateMetaResources(m.Resources); err != nil {
return err
}
for _, term := range m.Terms {
if _, terr := ParseTerm(term); terr != nil {
return errors.Trace(terr)
}
}
return nil
}
func (m Meta) checkV1(reasons []FormatSelectionReason) error {
if m.Assumes != nil {
return errors.NotValidf("assumes in metadata v1")
}
if len(m.Containers) != 0 {
if !hasReason(reasons, SelectionManifest) {
return errors.NotValidf("containers without a manifest.yaml")
}
return errors.NotValidf("containers in metadata v1")
}
return nil
}
func (m Meta) checkV2(reasons []FormatSelectionReason) error {
if len(reasons) == 0 {
return errors.NotValidf("metadata v2 without manifest.yaml")
}
if len(m.Series) != 0 {
if hasReason(reasons, SelectionManifest) {
return errors.NotValidf("metadata v2 manifest.yaml with series slice")
}
return errors.NotValidf("series slice in metadata v2")
}
if m.MinJujuVersion != version.Zero {
return errors.NotValidf("min-juju-version in metadata v2")
}
if m.Deployment != nil {
return errors.NotValidf("deployment in metadata v2")
}
return nil
}
func hasReason(reasons []FormatSelectionReason, reason FormatSelectionReason) bool {
return set.NewStrings(reasons...).Contains(reason)
}
func reservedName(charmName, endpointName string) (reserved bool, reason string) {
if strings.HasPrefix(charmName, "juju-") {
return false, ""
}
if endpointName == "juju" {
return true, `"juju" is a reserved name`
}
if strings.HasPrefix(endpointName, "juju-") {
return true, `the "juju-" prefix is reserved`
}
return false, ""
}
func parseRelations(relations interface{}, role RelationRole) map[string]Relation {
if relations == nil {
return nil
}
result := make(map[string]Relation)
for name, rel := range relations.(map[string]interface{}) {
relMap := rel.(map[string]interface{})
relation := Relation{
Name: name,
Role: role,
Interface: relMap["interface"].(string),
Optional: relMap["optional"].(bool),
}
if scope := relMap["scope"]; scope != nil {
relation.Scope = RelationScope(scope.(string))
}
if relMap["limit"] != nil {
// Schema defaults to int64, but we know
// the int range should be more than enough.
relation.Limit = int(relMap["limit"].(int64))
}
result[name] = relation
}
return result
}
// CombinedRelations returns all defined relations, regardless of their type in
// a single map.
func (m Meta) CombinedRelations() map[string]Relation {
combined := make(map[string]Relation)
for name, relation := range m.Provides {
combined[name] = relation
}
for name, relation := range m.Requires {
combined[name] = relation
}
for name, relation := range m.Peers {
combined[name] = relation
}
return combined
}
// Schema coercer that expands the interface shorthand notation.
// A consistent format is easier to work with than considering the
// potential difference everywhere.
//
// Supports the following variants::
//
// provides:
// server: riak
// admin: http
// foobar:
// interface: blah
//
// provides:
// server:
// interface: mysql
// limit:
// optional: false
//
// In all input cases, the output is the fully specified interface
// representation as seen in the mysql interface description above.
func ifaceExpander(limit interface{}) schema.Checker {