-
Notifications
You must be signed in to change notification settings - Fork 1
/
csi_mounts_monitor.go
231 lines (217 loc) · 7.58 KB
/
csi_mounts_monitor.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"sync"
"syscall"
"time"
"golang.org/x/sys/unix"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/klog"
)
const (
KUBELET_PODS_MOUNT_PATH = "/var/lib/kubelet/pods/"
// Example /var/lib/kubelet/pods/<pod-uid>/volumes/kubernetes.io~csi/
KUBELET_POD_CSI_MOUNTS = KUBELET_PODS_MOUNT_PATH + "%s/volumes/kubernetes.io~csi/"
// /var/lib/kubelet/pods/<pod-uid>/volumes/kubernetes.io~csi/<pv-name>/mount
KUBELET_POD_CSI_PVC_MOUNT = KUBELET_POD_CSI_MOUNTS + "%s/mount"
QUOBYTE_CLIENT_X_ATTR = "quobyte.statuspage_port"
CLIENT_X_ATTR_VALUE_SIZE = 100
)
var podDeduplicatorMux sync.Mutex
var podDeduplicator map[string]bool
type CsiMountMonitor struct {
csiDriverName string
clientSet *kubernetes.Clientset
controller_url string
nodeName string
monitoringInterval time.Duration
parallelKills int
podUidResolveBatchSize int
}
func (csiMountMonitor *CsiMountMonitor) Run() {
podDeduplicator = make(map[string]bool)
// Keep Queue >= 2 * podUidResolveBatchSize so that we batch resolve pod uid calls
staleMountsChannel := make(chan StaleMount, csiMountMonitor.podUidResolveBatchSize*3)
resolvedPodsChannel := make(chan ResolvedPod, csiMountMonitor.parallelKills*3)
go csiMountMonitor.walkAndDetectStaleMounts(staleMountsChannel)
go csiMountMonitor.resolvePodsWithStaleMounts(staleMountsChannel, resolvedPodsChannel)
for i := 0; i < csiMountMonitor.parallelKills; i++ {
go csiMountMonitor.deletePodWithStaleMount(resolvedPodsChannel)
}
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
func (csiMountMonitor *CsiMountMonitor) deletePodWithStaleMount(resolvedPodsChannel <-chan ResolvedPod) {
for pod := range resolvedPodsChannel {
klog.Infof("Deleting pod %s/%s with uid %s", pod.Namespace, pod.Name, pod.Uid)
gracePeriod := int64(0)
if err := csiMountMonitor.clientSet.CoreV1().Pods(pod.Namespace).Delete(context.Background(), pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &gracePeriod,
Preconditions: &metav1.Preconditions{UID: (*types.UID)(&pod.Uid)},
}); err != nil {
klog.Errorf("Unable to delete pod %s/%s (uid: %s) due to %v", pod.Namespace, pod.Name, pod.Uid, err)
}
podDeduplicatorMux.Lock()
delete(podDeduplicator, pod.Uid)
podDeduplicatorMux.Unlock()
}
}
func (csiMountMonitor *CsiMountMonitor) resolvePodsWithStaleMounts(
staleMountsChannel <-chan StaleMount,
resolvedPodsChannel chan<- ResolvedPod) {
batch := make([]StaleMount, 0, csiMountMonitor.podUidResolveBatchSize)
for staleMount := range staleMountsChannel { // Blocks if no elements
batch = append(batch, staleMount)
batching:
for i := 1; i < csiMountMonitor.podUidResolveBatchSize; i++ {
select { // non-blocking with default
case staleMount := <-staleMountsChannel:
batch = append(batch, staleMount)
default:
break batching
}
}
if resolvedPods, err := csiMountMonitor.resolvePods(batch); err != nil {
podDeduplicatorMux.Lock()
for _, staleMount := range batch { // remove and let it be requeued for resolution
delete(podDeduplicator, staleMount.PodUid)
}
podDeduplicatorMux.Unlock()
klog.Errorf("Could not resolve pod(s) to name/namespace due to %s. Will retry later again.", err)
} else {
resolvedPodUids := make(map[string]bool)
for _, pod := range resolvedPods.Pods {
klog.Infof("Resolved pod uid %s to %s/%s", pod.Uid, pod.Namespace, pod.Name)
resolvedPodsChannel <- pod
resolvedPodUids[pod.Uid] = true
}
podDeduplicatorMux.Lock()
for _, staleMount := range batch {
if _, ok := resolvedPodUids[staleMount.PodUid]; !ok {
// Pod was not resolved, so let it be requeued again
delete(podDeduplicator, staleMount.PodUid)
}
}
podDeduplicatorMux.Unlock()
}
}
}
func (csiMountMonitor *CsiMountMonitor) resolvePods(staleMounts []StaleMount) (ResolvePodsResponse, error) {
resolvePodsToDelete := &ResolvePodsRequest{
StaleMounts: staleMounts,
NodeName: csiMountMonitor.nodeName,
CsiDriverName: csiMountMonitor.csiDriverName}
var reqBodyJson []byte
var err error
var resolvedPods ResolvePodsResponse
if reqBodyJson, err = json.Marshal(resolvePodsToDelete); err != nil {
return resolvedPods, err
}
client := &http.Client{}
if req, err := http.NewRequest(http.MethodPost, csiMountMonitor.controller_url, bytes.NewBuffer(reqBodyJson)); err != nil {
return resolvedPods, err
} else {
req.Header.Add("Content-Type", "application/json")
if resp, err := client.Do(req); err != nil {
return resolvedPods, err
} else {
if resp.StatusCode != 200 {
return resolvedPods, fmt.Errorf("unexpected error code %d while resolving pod uid", resp.StatusCode)
}
defer resp.Body.Close()
responseBytes, err := io.ReadAll(resp.Body)
if err != nil {
return resolvedPods, err
}
if err = json.Unmarshal(responseBytes, &resolvedPods); err != nil {
return resolvedPods, err
}
return resolvedPods, nil
}
}
}
func (csiMountMonitor *CsiMountMonitor) walkAndDetectStaleMounts(staleMountsChannel chan<- StaleMount) {
for {
if pods, err := getChildDirectoryNames(KUBELET_PODS_MOUNT_PATH); err != nil {
klog.Errorf("Failed listing kubelet pod mounts due to %s", err)
} else {
podDeduplicatorMux.Lock()
for _, podUid := range pods {
if _, ok := podDeduplicator[podUid]; ok {
continue // Already queued this pod for deletion - skip in this round
}
stalePVMounts := getStalePVNames(podUid)
if len(stalePVMounts) > 0 {
podDeduplicator[podUid] = true
staleMountsChannel <- StaleMount{PodUid: podUid, PvNames: stalePVMounts}
}
}
podDeduplicatorMux.Unlock()
}
time.Sleep(csiMountMonitor.monitoringInterval)
}
}
func getStalePVNames(podUid string) []string {
podVolumesPath := fmt.Sprintf(KUBELET_POD_CSI_MOUNTS, podUid)
if dirExists, err := exists(podVolumesPath); !dirExists {
if err != nil {
klog.V(2).Infof("CSI volume mount path for the pod %s not found. Skipping pod", podUid)
}
return nil
}
// Get all the CSI volume dirs for the pod (cannot identify driver specific volume here)
csiPvNames, err := getChildDirectoryNames(podVolumesPath)
if err != nil {
klog.Errorf("Unable to list PVs from pod mount path %s due to %v", podVolumesPath, err)
return nil
}
klog.V(5).Infof("Loaded %v PV Names from the path %s", csiPvNames, podVolumesPath)
var stalePvNames []string
xattr_buf := make([]byte, CLIENT_X_ATTR_VALUE_SIZE)
for _, csiPVName := range csiPvNames {
quobyteCsiVolumePath := fmt.Sprintf(KUBELET_POD_CSI_PVC_MOUNT, podUid, csiPVName)
if _, err = unix.Getxattr(quobyteCsiVolumePath, QUOBYTE_CLIENT_X_ATTR, xattr_buf); err != nil {
klog.V(2).Infof("Encountered error %d executing stat on %s", err.(syscall.Errno), quobyteCsiVolumePath)
if err.(syscall.Errno) == unix.ENOTCONN || err.(syscall.Errno) == unix.ENOENT {
stalePvNames = append(stalePvNames, csiPVName)
}
}
}
if len(stalePvNames) > 0 {
klog.Infof("PVs %v are stale in the path %s", stalePvNames, podVolumesPath)
}
return stalePvNames
}
func exists(dirPath string) (bool, error) {
_, err := os.Stat(dirPath)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func getChildDirectoryNames(podPath string) ([]string, error) {
var resultDirs []string
dirs, err := os.ReadDir(podPath)
if err != nil {
klog.Errorf("Failed to get CSI volume from the pod mount path %s due to %v", podPath, err)
return nil, err
}
for _, dir := range dirs {
if dir.IsDir() {
resultDirs = append(resultDirs, dir.Name())
}
}
return resultDirs, nil
}