-
Notifications
You must be signed in to change notification settings - Fork 5
/
hashing.go
49 lines (46 loc) · 1.51 KB
/
hashing.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
package hashing
import (
"encoding/json"
"fmt"
"hash/fnv"
"k8s.io/apimachinery/pkg/util/rand"
"reflect"
)
func ComputeHashForKubernetesObject(object interface{}) (string, error) {
if m, err := GetFilteredK8sObjectForHashing(object); err != nil {
return "", err
} else {
// By using serialized JSON for hashing we're making the hashing process
// a bit easier (like having maps always being sorted by keys).
if b, err := json.Marshal(m); err != nil {
return "", fmt.Errorf("error while encoding %+v into JSON: %s", m, err)
} else {
hasher := fnv.New32a()
hasher.Write(b)
return rand.SafeEncodeString(fmt.Sprint(hasher.Sum32())), nil
}
}
}
func SetKubernetesObjectHash(configHash string, object interface{}) error {
labelsToAdd := map[string]string{}
value := reflect.ValueOf(object)
var objectMeta reflect.Value
if value.Kind() == reflect.Ptr {
objectMeta = value.Elem().FieldByName("ObjectMeta")
} else {
return fmt.Errorf("must pass pointer to AddLabelsToMetadata so we can update labels using reflection")
}
if objectMeta.Kind() == reflect.Struct {
labels := objectMeta.FieldByName("Labels")
if labels.Kind() == reflect.Map {
for _, k := range labels.MapKeys() {
v := labels.MapIndex(k)
labelsToAdd[k.Interface().(string)] = v.Interface().(string)
}
// Set the configHash label last, so that any prior configHash label is overwritten with the new one
labelsToAdd["yelp.com/operator_config_hash"] = configHash
labels.Set(reflect.ValueOf(labelsToAdd))
}
}
return nil
}