This repository has been archived by the owner on Mar 20, 2024. It is now read-only.
forked from cilium/cilium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
labels.go
463 lines (404 loc) · 12 KB
/
labels.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
// Copyright 2016-2017 Authors of Cilium
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package labels
import (
"bytes"
"crypto/sha512"
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/cilium/cilium/api/v1/models"
"github.com/cilium/cilium/common"
)
const (
// IDNameAll is a special label which matches all labels.
IDNameAll = "all"
// IDNameHost is the label used for the hostname ID.
IDNameHost = "host"
// IDNameWorld is the label used for the world ID.
IDNameWorld = "world"
)
// OpLabels represents the the possible types.
type OpLabels struct {
// Active labels that are enabled and disabled but not deleted
Custom Labels
// Labels derived from orchestration system
Orchestration Labels
// Orchestration labels which have been disabled
Disabled Labels
}
// DeepCopy returns deep copy of the label.
func (o *OpLabels) DeepCopy() *OpLabels {
return &OpLabels{
Custom: o.Custom.DeepCopy(),
Disabled: o.Disabled.DeepCopy(),
Orchestration: o.Orchestration.DeepCopy(),
}
}
// Enabled returns map of enabled labels.
func (o *OpLabels) Enabled() Labels {
enabled := make(Labels, len(o.Custom)+len(o.Orchestration))
for k, v := range o.Custom {
enabled[k] = v
}
for k, v := range o.Orchestration {
enabled[k] = v
}
return enabled
}
// NewOplabelsFromModel creates new label from the model.
func NewOplabelsFromModel(base *models.LabelConfiguration) *OpLabels {
if base == nil {
return nil
}
return &OpLabels{
Custom: NewLabelsFromModel(base.Custom),
Disabled: NewLabelsFromModel(base.Disabled),
Orchestration: NewLabelsFromModel(base.OrchestrationSystem),
}
}
// Label is the cilium's representation of a container label.
type Label struct {
Key string `json:"key"`
Value string `json:"value,omitempty"`
// Source can be on of the values present in const.go (e.g.: CiliumLabelSource)
Source string `json:"source"`
// Mark element to be used to find unused labels in lists
DeletionMark bool `json:"-"`
}
// Labels is a map of labels where the map's key is the same as the label's key.
type Labels map[string]*Label
// MarkAllForDeletion marks all the labels with the DeletionMark.
func (l Labels) MarkAllForDeletion() {
for k := range l {
l[k].DeletionMark = true
}
}
// DeleteMarked deletes the labels which have the DeletionMark set and returns
// true if any of them were deleted.
func (l Labels) DeleteMarked() bool {
deleted := false
for k := range l {
if l[k].DeletionMark {
delete(l, k)
deleted = true
}
}
return deleted
}
// AppendPrefixInKey appends the given prefix to all the Key's of the map and the
// respective Labels' Key.
func (l Labels) AppendPrefixInKey(prefix string) Labels {
newLabels := Labels{}
for k, v := range l {
newLabels[prefix+k] = &Label{
Key: prefix + v.Key,
Value: v.Value,
Source: v.Source,
}
}
return newLabels
}
// NewLabel returns a new label from the given key, value and source. If source is empty,
// the default value will be common.CiliumLabelSource. If key starts with '$', the source
// will be overwritten with common.ReservedLabelSource. If key contains ':', the value
// before ':' will be used as source if given source is empty, otherwise the value before
// ':' will be deleted and unused.
func NewLabel(key string, value string, source string) *Label {
var src string
src, key = parseSource(key)
if source == "" {
if src == "" {
source = common.CiliumLabelSource
} else {
source = src
}
}
if src == common.ReservedLabelSource && key == "" {
key = value
value = ""
}
return &Label{
Key: key,
Value: value,
Source: source,
}
}
// DeepCopy returns a Deep copy of the receiver's label.
func (l *Label) DeepCopy() *Label {
ret := NewLabel(l.Key, l.Value, l.Source)
ret.DeletionMark = l.DeletionMark
return ret
}
// Equals returns true if source, AbsoluteKey() and Value are equal and false otherwise.
func (l *Label) Equals(b *Label) bool {
if !l.IsAnySource() {
if l.Source != b.Source {
return false
}
}
return l.Key == b.Key && l.Value == b.Value
}
// IsAllLabel returns true if the label is reserved and matches with IDNameAll.
func (l *Label) IsAllLabel() bool {
return l.Source == common.ReservedLabelSource && l.Key == "all"
}
// IsAnySource return if the label was set with source "any".
func (l *Label) IsAnySource() bool {
return l.Source == common.AnyLabelSource
}
// Matches returns true if it's a special label or the label equals the target.
func (l *Label) Matches(target *Label) bool {
return l.IsAllLabel() || l.Equals(target)
}
// String returns the string representation of Label in the for of Source:Key=Value or
// Source:Key if Value is empty.
func (l *Label) String() string {
if len(l.Value) != 0 {
return fmt.Sprintf("%s:%s=%s", l.Source, l.Key, l.Value)
}
return fmt.Sprintf("%s:%s", l.Source, l.Key)
}
// IsValid returns true if Key != "".
func (l *Label) IsValid() bool {
return l.Key != ""
}
// UnmarshalJSON TODO create better explanation about unmarshall with examples
func (l *Label) UnmarshalJSON(data []byte) error {
decoder := json.NewDecoder(bytes.NewReader(data))
if l == nil {
return fmt.Errorf("cannot unmarhshal to nil pointer")
}
if len(data) == 0 {
return fmt.Errorf("invalid Label: empty data")
}
var aux struct {
Source string `json:"source"`
Key string `json:"key"`
Value string `json:"value,omitempty"`
}
err := decoder.Decode(&aux)
if err != nil {
// If parsing of the full representation failed then try the short
// form in the format:
//
// [SOURCE:]KEY[=VALUE]
var aux string
decoder = json.NewDecoder(bytes.NewReader(data))
if err := decoder.Decode(&aux); err != nil {
return fmt.Errorf("decode of Label as string failed: %+v", err)
}
if aux == "" {
return fmt.Errorf("invalid Label: Failed to parse %s as a string", data)
}
*l = *ParseLabel(aux)
} else {
if aux.Key == "" {
return fmt.Errorf("invalid Label: '%s' does not contain label key", data)
}
l.Source = aux.Source
l.Key = aux.Key
l.Value = aux.Value
}
return nil
}
// GetExtendedKey returns the key of a label with the source encoded.
func (l *Label) GetExtendedKey() string {
return l.Source + common.PathDelimiter + l.Key
}
// GetCiliumKeyFrom returns the label's source and key from the an extended key
// in the format SOURCE:KEY.
func GetCiliumKeyFrom(extKey string) string {
sourceSplit := strings.SplitN(extKey, common.PathDelimiter, 2)
if len(sourceSplit) == 2 {
return sourceSplit[0] + ":" + sourceSplit[1]
}
return common.AnyLabelSource + ":" + sourceSplit[0]
}
// GetExtendedKeyFrom returns the extended key of a label string.
// For example:
// `k8s:foo=bar` returns `k8s.foo`
// `cilium:foo=bar` returns `cilium.foo`
// `foo=bar` returns `cilium.foo=bar`
func GetExtendedKeyFrom(str string) string {
src, next := parseSource(str)
if src == "" {
src = common.AnyLabelSource
}
// Remove an eventually value
nextSplit := strings.SplitN(next, "=", 2)
next = nextSplit[0]
return src + common.PathDelimiter + next
}
// Map2Labels transforms in the form: map[key(string)]value(string) into Labels. The
// source argument will overwrite the source written in the key of the given map.
// Example:
// l := Map2Labels(map[string]string{"k8s:foo": "bar"}, "cilium")
// fmt.Printf("%+v\n", l)
// map[string]Label{"foo":Label{Key:"foo", Value:"bar", Source:"cilium"}}
func Map2Labels(m map[string]string, source string) Labels {
o := Labels{}
for k, v := range m {
l := NewLabel(k, v, source)
o[l.Key] = l
}
return o
}
// DeepCopy returns a deep copy of the labels.
func (l Labels) DeepCopy() Labels {
o := Labels{}
for k, v := range l {
o[k] = &Label{
Key: v.Key,
Value: v.Value,
Source: v.Source,
}
}
return o
}
// NewLabelsFromModel creates labels from string array.
func NewLabelsFromModel(base []string) Labels {
lbls := Labels{}
for _, v := range base {
lbl := ParseLabel(v)
lbls[lbl.Key] = lbl
}
return lbls
}
// NewLabelArrayFromModel creates labels from string array.
func NewLabelArrayFromModel(base []string) LabelArray {
lbls := LabelArray{}
for _, v := range base {
lbl := ParseLabel(v)
lbls = append(lbls, lbl)
}
return lbls
}
// GetModel returns model with all the values of the labels.
func (l Labels) GetModel() []string {
res := []string{}
for _, v := range l {
res = append(res, v.String())
}
return res
}
// MergeLabels merges labels from into to. It overwrites all labels with the same Key as
// from written into to.
// Example:
// to := Labels{Label{key1, value1, source1}, Label{key2, value3, source4}}
// from := Labels{Label{key1, value3, source4}}
// to.MergeLabels(from)
// fmt.Printf("%+v\n", to)
// Labels{Label{key1, value3, source4}, Label{key2, value3, source4}}
func (l Labels) MergeLabels(from Labels) {
fromCpy := from.DeepCopy()
for k, v := range fromCpy {
l[k] = v
}
}
// SHA256Sum calculates l' internal SHA256Sum. For a particular set of labels is
// guarantee that it will always have the same SHA256Sum.
func (l Labels) SHA256Sum() string {
return fmt.Sprintf("%x", sha512.New512_256().Sum(l.sortedList()))
}
func (l Labels) sortedList() []byte {
var keys []string
for k := range l {
keys = append(keys, k)
}
sort.Strings(keys)
result := ""
for _, k := range keys {
// We don't care if the values already have a '=' since this method is
// only used to calculate a SHA256Sum
result += fmt.Sprintf(`%s=%s;`, k, l[k].Value)
}
return []byte(result)
}
// ToSlice returns a slice of label with the values of the given Labels' map.
func (l Labels) ToSlice() []*Label {
labels := []*Label{}
for _, v := range l {
labels = append(labels, v.DeepCopy())
}
return labels
}
// parseSource returns the parsed source of the given str. It also returns the next piece
// of text that is after the source.
// Example:
// src, next := parseSource("foo:bar==value")
// Println(src) // foo
// Println(next) // bar==value
func parseSource(str string) (src, next string) {
if str == "" {
return "", ""
}
if str[0] == '$' {
str = strings.Replace(str, "$", common.ReservedLabelSource+":", 1)
}
sourceSplit := strings.SplitN(str, ":", 2)
if len(sourceSplit) != 2 {
next = sourceSplit[0]
if strings.HasPrefix(next, common.ReservedLabelSource) {
src = common.ReservedLabelSource
next = strings.TrimPrefix(next, common.ReservedLabelSourceKeyPrefix)
}
} else {
if sourceSplit[0] != "" {
src = sourceSplit[0]
}
next = sourceSplit[1]
}
return
}
// ParseLabel returns the label representation of the given string. The str should be
// in the form of Source:Key=Value or Source:Key if Value is empty. It also parses short
// forms, for example: $host will be Label{Key: "host", Source: "reserved", Value: ""}.
func ParseLabel(str string) *Label {
lbl := Label{}
src, next := parseSource(str)
if src != "" {
lbl.Source = src
} else {
lbl.Source = common.CiliumLabelSource
}
keySplit := strings.SplitN(next, "=", 2)
lbl.Key = keySplit[0]
if len(keySplit) > 1 {
if src == common.ReservedLabelSource && keySplit[0] == "" {
lbl.Key = keySplit[1]
} else {
lbl.Value = keySplit[1]
}
}
return &lbl
}
// ParseStringLabels returns label representations from strings.
func ParseStringLabels(strLbls []string) Labels {
lbls := Labels{}
for _, l := range strLbls {
lbl := ParseLabel(l)
lbls[lbl.Key] = lbl
}
return lbls
}
// LabelSliceSHA256Sum returns SHA256 checksum from the labels.
func LabelSliceSHA256Sum(labels []*Label) (string, error) {
sha := sha512.New512_256()
if err := json.NewEncoder(sha).Encode(labels); err != nil {
return "", err
}
return fmt.Sprintf("%x", sha.Sum(nil)), nil
}