4edc9e83d5a5fcd31adab69b1b59bf450946ab34
[arvados.git] / sdk / go / arvados / vocabulary.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bytes"
9         "encoding/json"
10         "fmt"
11         "reflect"
12         "strings"
13 )
14
15 type Vocabulary struct {
16         reservedTagKeys map[string]bool          `json:"-"`
17         StrictTags      bool                     `json:"strict_tags"`
18         Tags            map[string]VocabularyTag `json:"tags"`
19 }
20
21 type VocabularyTag struct {
22         Strict bool                          `json:"strict"`
23         Labels []VocabularyLabel             `json:"labels"`
24         Values map[string]VocabularyTagValue `json:"values"`
25 }
26
27 // Cannot have a constant map in Go, so we have to use a function
28 func (v *Vocabulary) systemTagKeys() map[string]bool {
29         return map[string]bool{
30                 "type":                  true,
31                 "template_uuid":         true,
32                 "groups":                true,
33                 "username":              true,
34                 "image_timestamp":       true,
35                 "docker-image-repo-tag": true,
36                 "filters":               true,
37                 "container_request":     true,
38         }
39 }
40
41 type VocabularyLabel struct {
42         Label string `json:"label"`
43 }
44
45 type VocabularyTagValue struct {
46         Labels []VocabularyLabel `json:"labels"`
47 }
48
49 // NewVocabulary creates a new Vocabulary from a JSON definition and a list
50 // of reserved tag keys that will get special treatment when strict mode is
51 // enabled.
52 func NewVocabulary(data []byte, managedTagKeys []string) (voc *Vocabulary, err error) {
53         if r := bytes.Compare(data, []byte("")); r == 0 {
54                 return &Vocabulary{}, nil
55         }
56         err = json.Unmarshal(data, &voc)
57         if err != nil {
58                 return nil, fmt.Errorf("invalid JSON format error: %q", err)
59         }
60         if reflect.DeepEqual(voc, &Vocabulary{}) {
61                 return nil, fmt.Errorf("JSON data provided doesn't match Vocabulary format: %q", data)
62         }
63         voc.reservedTagKeys = make(map[string]bool)
64         for _, managedKey := range managedTagKeys {
65                 voc.reservedTagKeys[managedKey] = true
66         }
67         for systemKey := range voc.systemTagKeys() {
68                 voc.reservedTagKeys[systemKey] = true
69         }
70         err = voc.validate()
71         if err != nil {
72                 return nil, err
73         }
74         return voc, nil
75 }
76
77 func (v *Vocabulary) validate() error {
78         if v == nil {
79                 return nil
80         }
81         tagKeys := map[string]string{}
82         // Checks for Vocabulary strictness
83         if v.StrictTags && len(v.Tags) == 0 {
84                 return fmt.Errorf("vocabulary is strict but no tags are defined")
85         }
86         // Checks for collisions between tag keys, reserved tag keys
87         // and tag key labels.
88         for key := range v.Tags {
89                 if v.reservedTagKeys[key] {
90                         return fmt.Errorf("tag key %q is reserved", key)
91                 }
92                 lcKey := strings.ToLower(key)
93                 if tagKeys[lcKey] != "" {
94                         return fmt.Errorf("duplicate tag key %q", key)
95                 }
96                 tagKeys[lcKey] = key
97                 for _, lbl := range v.Tags[key].Labels {
98                         label := strings.ToLower(lbl.Label)
99                         if tagKeys[label] != "" {
100                                 return fmt.Errorf("tag label %q for key %q already seen as a tag key or label", lbl.Label, key)
101                         }
102                         tagKeys[label] = lbl.Label
103                 }
104                 // Checks for value strictness
105                 if v.Tags[key].Strict && len(v.Tags[key].Values) == 0 {
106                         return fmt.Errorf("tag key %q is configured as strict but doesn't provide values", key)
107                 }
108                 // Checks for collisions between tag values and tag value labels.
109                 tagValues := map[string]string{}
110                 for val := range v.Tags[key].Values {
111                         lcVal := strings.ToLower(val)
112                         if tagValues[lcVal] != "" {
113                                 return fmt.Errorf("duplicate tag value %q for tag %q", val, key)
114                         }
115                         tagValues[lcVal] = val
116                         for _, tagLbl := range v.Tags[key].Values[val].Labels {
117                                 label := strings.ToLower(tagLbl.Label)
118                                 if tagValues[label] != "" {
119                                         return fmt.Errorf("tag value label %q for pair (%q:%q) already seen as a value key or label", tagLbl.Label, key, val)
120                                 }
121                                 tagValues[label] = tagLbl.Label
122                         }
123                 }
124         }
125         return nil
126 }
127
128 func (v *Vocabulary) getLabelsToKeys() (labels map[string]string) {
129         if v == nil {
130                 return
131         }
132         labels = make(map[string]string)
133         for key, val := range v.Tags {
134                 for _, lbl := range val.Labels {
135                         label := strings.ToLower(lbl.Label)
136                         labels[label] = key
137                 }
138         }
139         return labels
140 }
141
142 func (v *Vocabulary) getLabelsToValues(key string) (labels map[string]string) {
143         if v == nil {
144                 return
145         }
146         labels = make(map[string]string)
147         if _, ok := v.Tags[key]; ok {
148                 for val := range v.Tags[key].Values {
149                         for _, tagLbl := range v.Tags[key].Values[val].Labels {
150                                 label := strings.ToLower(tagLbl.Label)
151                                 labels[label] = val
152                         }
153                 }
154         }
155         return labels
156 }
157
158 func (v *Vocabulary) checkValue(key, val string) error {
159         if _, ok := v.Tags[key].Values[val]; !ok {
160                 lcVal := strings.ToLower(val)
161                 correctValue, ok := v.getLabelsToValues(key)[lcVal]
162                 if ok {
163                         return fmt.Errorf("tag value %q for key %q is an alias, must be provided as %q", val, key, correctValue)
164                 } else if v.Tags[key].Strict {
165                         return fmt.Errorf("tag value %q is not valid for key %q", val, key)
166                 }
167         }
168         return nil
169 }
170
171 // Check validates the given data against the vocabulary.
172 func (v *Vocabulary) Check(data map[string]interface{}) error {
173         if v == nil {
174                 return nil
175         }
176         for key, val := range data {
177                 // Checks for key validity
178                 if v.reservedTagKeys[key] {
179                         // Allow reserved keys to be used even if they are not defined in
180                         // the vocabulary no matter its strictness.
181                         continue
182                 }
183                 if _, ok := v.Tags[key]; !ok {
184                         lcKey := strings.ToLower(key)
185                         correctKey, ok := v.getLabelsToKeys()[lcKey]
186                         if ok {
187                                 return fmt.Errorf("tag key %q is an alias, must be provided as %q", key, correctKey)
188                         } else if v.StrictTags {
189                                 return fmt.Errorf("tag key %q is not defined in the vocabulary", key)
190                         }
191                         // If the key is not defined, we don't need to check the value
192                         continue
193                 }
194                 // Checks for value validity -- key is defined
195                 switch val := val.(type) {
196                 case string:
197                         err := v.checkValue(key, val)
198                         if err != nil {
199                                 return err
200                         }
201                 case []interface{}:
202                         for _, singleVal := range val {
203                                 switch singleVal := singleVal.(type) {
204                                 case string:
205                                         err := v.checkValue(key, singleVal)
206                                         if err != nil {
207                                                 return err
208                                         }
209                                 default:
210                                         return fmt.Errorf("tag value of type %T for key %q is not a valid", singleVal, key)
211                                 }
212                         }
213                 default:
214                         return fmt.Errorf("tag value of type %T for key %q is not a valid", val, key)
215                 }
216         }
217         return nil
218 }