/
tools.go
100 lines (89 loc) · 2.39 KB
/
tools.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
package informer
import (
"context"
"fmt"
"io/ioutil"
"reflect"
"github.com/thoas/go-funk"
"gopkg.in/yaml.v2"
api "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func getK8SConfig() *kubernetes.Clientset {
config, err := rest.InClusterConfig()
if err != nil {
panic(err)
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
fmt.Println("Config used")
return clientSet
}
func IsMapPresent(sourceMap map[string]string, subsetMap map[string]string) (bool, error) {
match := true
keysAll := funk.Keys(sourceMap)
keysSubset := funk.Keys(subsetMap)
intersect := funk.Intersect(keysAll, keysSubset)
if !reflect.DeepEqual(intersect, keysSubset) {
match = false
}
funk.ForEach(intersect, func(x string) {
if sourceMap[x] != subsetMap[x] {
match = false
}
})
return match, nil
}
type PatchObject struct {
Op string `json:"op"`
Path string `json:"path"`
Value string `json:"value"`
}
func UpdateStatus(ownerFile string, status string) error {
if ownerFile == "" {
logger.Info(fmt.Sprintf("No owner file provided, skip CRD update. #%s ", ownerFile))
return nil
}
watcherConfig, err := loadWatcherConfig(ownerFile)
if err != nil {
logger.Info(fmt.Sprintf("Error processing owner file #%v ", err))
return err
}
logger.Debug(fmt.Sprintf("Watcher Config: #%v ", watcherConfig))
clientSet := getK8SConfig()
myPatch := fmt.Sprintf(`{"status":{"status":"%s"}}`, status)
logger.Debug(fmt.Sprintf("Watcher Patch: #%v ", myPatch))
_, err = clientSet.RESTClient().
Patch(api.MergePatchType).
AbsPath("/apis/" + watcherConfig.APIVersion).
SubResource("status").
Namespace(watcherConfig.CrdNamespace).
Resource("watchers").
Name(watcherConfig.CrdName).
Body([]byte(myPatch)).
DoRaw(context.TODO())
if err != nil {
logger.Info(fmt.Sprintf("Error updating CRD #%v ", err))
return err
}
logger.Info(fmt.Sprintf("Update status: %#v ", watcherConfig))
return nil
}
func loadWatcherConfig(file string) (*WatcherConfig, error) {
watcherConfig := &WatcherConfig{}
logger.Debug("Loading config file:" + file)
yamlFile, err := ioutil.ReadFile(file)
if err != nil {
logger.Info(fmt.Sprintf("yamlFile.Get err #%v ", err))
return nil, err
}
err = yaml.Unmarshal(yamlFile, watcherConfig)
if err != nil {
logger.Info(fmt.Sprintf("Unmarshal: %v", err))
return nil, err
}
return watcherConfig, nil
}