-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathpods.go
More file actions
99 lines (83 loc) · 1.95 KB
/
pods.go
File metadata and controls
99 lines (83 loc) · 1.95 KB
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 (
"fmt"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
)
const podResource = "pods"
type PodIndex struct {
indexer *cache.Indexer
reflector *cache.Reflector
stopCh chan struct{}
}
func NewPodIndex(clientset *kubernetes.Clientset, index cache.IndexFunc) (*PodIndex, error) {
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"index": index})
podListWatcher := cache.NewListWatchFromClient(
clientset.CoreV1().RESTClient(),
podResource,
v1.NamespaceAll,
fields.Everything(),
)
reflector := cache.NewReflector(
podListWatcher,
&v1.Pod{},
indexer,
time.Duration(0),
)
stopCh := make(chan struct{})
return &PodIndex{
indexer: &indexer,
reflector: reflector,
stopCh: stopCh,
}, nil
}
func (p *PodIndex) Run() error {
return newWatcher(p.reflector, podResource, p.reflector.ListAndWatch, p.stopCh).run()
}
func (p *PodIndex) Stop() {
p.stopCh <- struct{}{}
}
func (p *PodIndex) GetPod(key string) (*v1.Pod, error) {
item, exists, err := (*p.indexer).GetByKey(key)
if err != nil {
return nil, err
}
if !exists {
return nil, fmt.Errorf("no pod exists for key %s", key)
}
pod, ok := item.(*v1.Pod)
if !ok {
return nil, fmt.Errorf("%v is not a Pod", item)
}
return pod, nil
}
func (p *PodIndex) GetPodsByIndex(key string) ([]*v1.Pod, error) {
items, err := (*p.indexer).ByIndex("index", key)
if err != nil {
return nil, err
}
pods := make([]*v1.Pod, len(items))
for i, item := range items {
pod, ok := item.(*v1.Pod)
if !ok {
return nil, fmt.Errorf("%v is not a Pod", item)
}
pods[i] = pod
}
return pods, nil
}
func (p *PodIndex) List() ([]*v1.Pod, error) {
pods := make([]*v1.Pod, 0)
items := (*p.indexer).List()
for _, pod := range items {
pod, ok := pod.(*v1.Pod)
if !ok {
return nil, fmt.Errorf("%v is not a Pod", pod)
}
pods = append(pods, pod)
}
return pods, nil
}