-
Notifications
You must be signed in to change notification settings - Fork 3
/
simple.go
executable file
·150 lines (125 loc) · 3.67 KB
/
simple.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
// This controller watches for all pods in a configured namespace and makes sure that they
// all have a hard-coded set of labels. It will add them to existing pods, new pods,
// and will ensure that they have the labels on every update
package main // import "github.com/carsonoid/kube-crds-and-controllers/hard-coded-controller"
import (
"encoding/json"
"flag"
logging "log"
"os"
"path/filepath"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
// "k8s.io/apimachinery/pkg/api/errors"
// metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
var (
log = logging.New(os.Stdout, "", logging.Lshortfile)
)
// "hard-coded" default holders
var labels map[string]string
var targetNamespace string
func main() {
log.SetOutput(os.Stdout)
var kubeconfig *string
kubeconfig = flag.String("kubeconfig", filepath.Join(os.Getenv("HOME"), ".kube", "config"), "(optional) absolute path to the kubeconfig file")
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
// Namespace
targetNamespace = "default"
// initialize labels
labels = make(map[string]string)
labels["is-awesome"] = "true"
labels["is-not-awesome"] = "false"
runController(clientset)
}
func runController(client *kubernetes.Clientset) {
log.Print("Starting Controller")
restClient := client.CoreV1().RESTClient()
listwatch := cache.NewListWatchFromClient(restClient, "pods", targetNamespace, fields.Everything())
_, controller := cache.NewInformer(listwatch, &corev1.Pod{}, 0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
log.Print("Pod Add Event")
if err := handlePod(obj.(*corev1.Pod), client); err != nil {
log.Printf("Error handling pod: %s", err)
}
},
UpdateFunc: func(oldobj interface{}, newobj interface{}) {
log.Print("Pod Update Event")
if err := handlePod(newobj.(*corev1.Pod), client); err != nil {
log.Printf("Error handling pod: %s", err)
}
},
DeleteFunc: func(obj interface{}) {
log.Print("Pod Delete Event")
// nothing to do
},
},
)
stopChan := make(chan struct{})
go controller.Run(stopChan)
<-stopChan
}
func handlePod(pod *corev1.Pod, client *kubernetes.Clientset) error {
o, err := runtime.NewScheme().DeepCopy(pod)
if err != nil {
return err
}
newPod := o.(*corev1.Pod)
// apply labels if needed
// if no changes then return
if !labelPod(newPod) {
return nil
}
oldData, err := json.Marshal(pod)
if err != nil {
return err
}
newData, err := json.Marshal(newPod)
if err != nil {
return err
}
patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, corev1.Pod{})
if err != nil {
return err
}
_, err = client.CoreV1().Pods(pod.Namespace).Patch(pod.Name, types.StrategicMergePatchType, patchBytes)
if err != nil {
return err
}
return nil
}
func labelPod(pod *corev1.Pod) bool {
changed := false
// make sure map is initialized
if len(pod.GetLabels()) == 0 {
pod.ObjectMeta.Labels = make(map[string]string)
}
// check keys
for k, newVal := range labels {
if curVal, ok := pod.GetLabels()[k]; ok && curVal == newVal {
//log.Printf("Pod %s already has label: %s=%s", pod.GetName(), k, newVal)
} else {
log.Printf("Pod %s needs label: %s=%s", pod.GetName(), k, newVal)
pod.Labels[k] = newVal
changed = true
}
}
return changed
}