-
Notifications
You must be signed in to change notification settings - Fork 0
/
store_pvc.go
103 lines (86 loc) · 2.22 KB
/
store_pvc.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
package volm
import (
"fmt"
"sync"
"time"
"go.uber.org/zap"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
)
type PVCStoreConfig struct {
Namespace string
Log *zap.Logger
Cs *kubernetes.Clientset
}
type PVCStore struct {
*PVCStoreConfig
Stopper chan struct{}
pvcMap map[string]v1.PersistentVolumeClaim
sync.Mutex
}
func NewPVCStore(cfg *PVCStoreConfig) (*PVCStore, error) {
ps := &PVCStore{PVCStoreConfig: cfg}
if ps.Cs == nil {
return nil, fmt.Errorf("must specify kubernetes.Clientset")
}
if ps.Log == nil {
return nil, fmt.Errorf("must specify zap.Logger")
}
if ps.Namespace == "" {
return nil, fmt.Errorf("must specify a Namespace")
}
ps.pvcMap = make(map[string]v1.PersistentVolumeClaim, 0)
ps.Stopper = make(chan struct{})
ps.PVCWatch()
return ps, nil
}
func (pvcs *PVCStore) PVCWatch() {
factory := informers.NewSharedInformerFactoryWithOptions(pvcs.Cs, time.Second*60, informers.WithNamespace(pvcs.Namespace))
informer := factory.Core().V1().PersistentVolumeClaims().Informer()
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pvc := obj.(*v1.PersistentVolumeClaim)
pvcs.AddPVC(*pvc)
},
DeleteFunc: func(obj interface{}) {
pvc := obj.(*v1.PersistentVolumeClaim)
pvcs.DeletePVC(pvc.Name)
},
UpdateFunc: func(oldObj, newObj interface{}) {
pvc := oldObj.(*v1.PersistentVolumeClaim)
pvcs.AddPVC(*pvc)
},
})
go informer.Run(pvcs.Stopper)
}
func (pvcs *PVCStore) AddPVC(pvc v1.PersistentVolumeClaim) {
pvcs.Lock()
pvcs.Log.Info("AddPVC", zap.String("name", pvc.Name))
pvcs.pvcMap[pvc.Name] = pvc
pvcs.Unlock()
}
func (pvcs *PVCStore) DeletePVC(podName string) {
pvcs.Lock()
_, ok := pvcs.pvcMap[podName]
if ok {
pvcs.Log.Info("DeletePVC", zap.String("name", podName))
delete(pvcs.pvcMap, podName)
}
pvcs.Unlock()
}
func (pvcs *PVCStore) GetPVC(pvcName string) *v1.PersistentVolumeClaim {
pvc, ok := pvcs.pvcMap[pvcName]
if ok {
return &pvc
}
return nil
}
func (pvcs *PVCStore) GetPVCs() []v1.PersistentVolumeClaim {
var pvcList []v1.PersistentVolumeClaim
for _, p := range pvcs.pvcMap {
pvcList = append(pvcList, p)
}
return pvcList
}