/
pod.go
99 lines (86 loc) · 2.14 KB
/
pod.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
package k8s
import (
corev1 "k8s.io/api/core/v1"
)
type Container struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
PodUID string `json:"pod"` // Pod UID
Image string `json:"image"`
Ports []struct {
Port int32 `json:"port"`
Protocol string `json:"protocol"`
} `json:"ports"`
}
func getContainers(pod *corev1.Pod) []*Container {
containers := make([]*Container, 0)
for _, container := range pod.Spec.Containers {
ports := make([]struct {
Port int32 "json:\"port\""
Protocol string "json:\"protocol\""
}, 0)
for _, port := range container.Ports {
ports = append(ports, struct {
Port int32 "json:\"port\""
Protocol string "json:\"protocol\""
}{
Port: port.ContainerPort,
Protocol: string(port.Protocol),
})
}
containers = append(containers, &Container{
Name: container.Name,
Namespace: pod.Namespace,
PodUID: string(pod.UID),
Image: container.Image,
Ports: ports,
})
}
return containers
}
func getOnAddPodFunc(ch chan interface{}) func(interface{}) {
return func(obj interface{}) {
pod := obj.(*corev1.Pod)
containers := getContainers(pod)
ch <- K8sResourceMessage{
ResourceType: POD,
EventType: ADD,
Object: obj,
}
for _, container := range containers {
ch <- K8sResourceMessage{
ResourceType: CONTAINER,
EventType: ADD,
Object: container,
}
}
}
}
func getOnUpdatePodFunc(ch chan interface{}) func(interface{}, interface{}) {
return func(oldObj, newObj interface{}) {
pod := newObj.(*corev1.Pod)
containers := getContainers(pod)
ch <- K8sResourceMessage{
ResourceType: POD,
EventType: UPDATE,
Object: newObj,
}
for _, container := range containers {
ch <- K8sResourceMessage{
ResourceType: CONTAINER,
EventType: UPDATE,
Object: container,
}
}
}
}
func getOnDeletePodFunc(ch chan interface{}) func(interface{}) {
return func(obj interface{}) {
ch <- K8sResourceMessage{
ResourceType: POD,
EventType: DELETE,
Object: obj,
}
// no need to delete containers, they will be deleted automatically
}
}