/
discovery.go
381 lines (336 loc) · 12.1 KB
/
discovery.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package discovery
import (
"encoding/json"
"fmt"
"hash/fnv"
"path/filepath"
"time"
"k8s.io/klog"
"sigs.k8s.io/sig-storage-local-static-provisioner/pkg/common"
"sigs.k8s.io/sig-storage-local-static-provisioner/pkg/metrics"
"k8s.io/api/core/v1"
storagev1listers "k8s.io/client-go/listers/storage/v1"
"k8s.io/client-go/tools/cache"
esUtil "sigs.k8s.io/sig-storage-lib-external-provisioner/util"
"sigs.k8s.io/sig-storage-local-static-provisioner/pkg/deleter"
)
// Discoverer finds available volumes and creates PVs for them
// It looks for volumes in the directories specified in the discoveryMap
type Discoverer struct {
*common.RuntimeConfig
Labels map[string]string
// ProcTable is a reference to running processes so that we can prevent PV from being created while
// it is being cleaned
CleanupTracker *deleter.CleanupStatusTracker
nodeAffinityAnn string
nodeAffinity *v1.VolumeNodeAffinity
classLister storagev1listers.StorageClassLister
}
// NewDiscoverer creates a Discoverer object that will scan through
// the configured directories and create local PVs for any new directories found
func NewDiscoverer(config *common.RuntimeConfig, cleanupTracker *deleter.CleanupStatusTracker) (*Discoverer, error) {
sharedInformer := config.InformerFactory.Storage().V1().StorageClasses()
sharedInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
// We don't need an actual event handler for StorageClasses,
// but we must pass a non-nil one to cache.NewInformer()
AddFunc: nil,
UpdateFunc: nil,
DeleteFunc: nil,
})
labelMap := make(map[string]string)
for _, labelName := range config.NodeLabelsForPV {
labelVal, ok := config.Node.Labels[labelName]
if ok {
labelMap[labelName] = labelVal
}
}
if config.UseAlphaAPI {
nodeAffinity, err := generateNodeAffinity(config.Node)
if err != nil {
return nil, fmt.Errorf("Failed to generate node affinity: %v", err)
}
tmpAnnotations := map[string]string{}
err = StorageNodeAffinityToAlphaAnnotation(tmpAnnotations, nodeAffinity)
if err != nil {
return nil, fmt.Errorf("Failed to convert node affinity to alpha annotation: %v", err)
}
return &Discoverer{
RuntimeConfig: config,
Labels: labelMap,
CleanupTracker: cleanupTracker,
classLister: sharedInformer.Lister(),
nodeAffinityAnn: tmpAnnotations[common.AlphaStorageNodeAffinityAnnotation]}, nil
}
volumeNodeAffinity, err := generateVolumeNodeAffinity(config.Node)
if err != nil {
return nil, fmt.Errorf("Failed to generate volume node affinity: %v", err)
}
return &Discoverer{
RuntimeConfig: config,
Labels: labelMap,
CleanupTracker: cleanupTracker,
classLister: sharedInformer.Lister(),
nodeAffinity: volumeNodeAffinity}, nil
}
func generateNodeAffinity(node *v1.Node) (*v1.NodeAffinity, error) {
if node.Labels == nil {
return nil, fmt.Errorf("Node does not have labels")
}
nodeValue, found := node.Labels[common.NodeLabelKey]
if !found {
return nil, fmt.Errorf("Node does not have expected label %s", common.NodeLabelKey)
}
return &v1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{
NodeSelectorTerms: []v1.NodeSelectorTerm{
{
MatchExpressions: []v1.NodeSelectorRequirement{
{
Key: common.NodeLabelKey,
Operator: v1.NodeSelectorOpIn,
Values: []string{nodeValue},
},
},
},
},
},
}, nil
}
func generateVolumeNodeAffinity(node *v1.Node) (*v1.VolumeNodeAffinity, error) {
if node.Labels == nil {
return nil, fmt.Errorf("Node does not have labels")
}
nodeValue, found := node.Labels[common.NodeLabelKey]
if !found {
return nil, fmt.Errorf("Node does not have expected label %s", common.NodeLabelKey)
}
return &v1.VolumeNodeAffinity{
Required: &v1.NodeSelector{
NodeSelectorTerms: []v1.NodeSelectorTerm{
{
MatchExpressions: []v1.NodeSelectorRequirement{
{
Key: common.NodeLabelKey,
Operator: v1.NodeSelectorOpIn,
Values: []string{nodeValue},
},
},
},
},
},
}, nil
}
// DiscoverLocalVolumes reads the configured discovery paths, and creates PVs for the new volumes
func (d *Discoverer) DiscoverLocalVolumes() {
for class, config := range d.DiscoveryMap {
d.discoverVolumesAtPath(class, config)
}
}
func (d *Discoverer) getReclaimPolicyFromStorageClass(name string) (v1.PersistentVolumeReclaimPolicy, error) {
class, err := d.classLister.Get(name)
if err != nil {
return "", err
}
if class.ReclaimPolicy != nil {
return *class.ReclaimPolicy, nil
}
return v1.PersistentVolumeReclaimDelete, nil
}
func (d *Discoverer) getMountOptionsFromStorageClass(name string) ([]string, error) {
class, err := d.classLister.Get(name)
if err != nil {
return nil, err
}
return class.MountOptions, nil
}
func (d *Discoverer) discoverVolumesAtPath(class string, config common.MountConfig) {
klog.V(7).Infof("Discovering volumes at hostpath %q, mount path %q for storage class %q", config.HostDir, config.MountDir, class)
reclaimPolicy, err := d.getReclaimPolicyFromStorageClass(class)
if err != nil {
klog.Errorf("Failed to get ReclaimPolicy from storage class %q: %v", class, err)
return
}
if reclaimPolicy != v1.PersistentVolumeReclaimRetain && reclaimPolicy != v1.PersistentVolumeReclaimDelete {
klog.Errorf("Unsupported ReclaimPolicy %q from storage class %q, supported policy are Retain and Delete.", reclaimPolicy, class)
return
}
files, err := d.VolUtil.ReadDir(config.MountDir)
if err != nil {
klog.Errorf("Error reading directory: %v", err)
return
}
// Retrieve list of mount points to iterate through discovered paths (aka files) below
mountPoints, err := d.RuntimeConfig.Mounter.List()
if err != nil {
klog.Errorf("Error retreiving mountpoints: %v", err)
return
}
// Put mount points into set for faster checks below
type empty struct{}
mountPointMap := make(map[string]empty)
for _, mp := range mountPoints {
mountPointMap[mp.Path] = empty{}
}
for _, file := range files {
startTime := time.Now()
filePath := filepath.Join(config.MountDir, file)
volMode, err := common.GetVolumeMode(d.VolUtil, filePath)
if err != nil {
klog.Error(err)
continue
}
// Check if PV already exists for it
pvName := generatePVName(file, d.Node.Name, class)
pv, exists := d.Cache.GetPV(pvName)
if exists {
if pv.Spec.VolumeMode != nil && *pv.Spec.VolumeMode == v1.PersistentVolumeBlock &&
volMode == v1.PersistentVolumeFilesystem {
errStr := fmt.Sprintf("Incorrect Volume Mode: PV %q requires block mode but path %q was in fs mode.", pvName, filePath)
klog.Errorf(errStr)
d.Recorder.Eventf(pv, v1.EventTypeWarning, common.EventVolumeFailedDelete, errStr)
}
continue
}
usejob := false
if volMode == v1.PersistentVolumeBlock {
usejob = d.RuntimeConfig.UseJobForCleaning
}
if d.CleanupTracker.InProgress(pvName, usejob) {
klog.Infof("PV %s is still being cleaned, not going to recreate it", pvName)
continue
}
mountOptions, err := d.getMountOptionsFromStorageClass(class)
if err != nil {
klog.Errorf("Failed to get mount options from storage class %s: %v", class, err)
continue
}
var capacityByte int64
desireVolumeMode := v1.PersistentVolumeMode(config.VolumeMode)
switch volMode {
case v1.PersistentVolumeBlock:
capacityByte, err = d.VolUtil.GetBlockCapacityByte(filePath)
if err != nil {
klog.Errorf("Path %q block stats error: %v", filePath, err)
continue
}
if desireVolumeMode == v1.PersistentVolumeBlock && len(mountOptions) != 0 {
klog.Warningf("Path %q will be used to create block volume, "+
"mount options %v will not take effect.", filePath, mountOptions)
}
case v1.PersistentVolumeFilesystem:
if desireVolumeMode == v1.PersistentVolumeBlock {
klog.Errorf("Path %q of filesystem mode cannot be used to create block volume", filePath)
continue
}
// Validate that this path is an actual mountpoint
if _, isMntPnt := mountPointMap[filePath]; isMntPnt == false {
klog.Errorf("Path %q is not an actual mountpoint", filePath)
continue
}
capacityByte, err = d.VolUtil.GetFsCapacityByte(filePath)
if err != nil {
klog.Errorf("Path %q fs stats error: %v", filePath, err)
continue
}
default:
klog.Errorf("Path %q has unexpected volume type %q", filePath, volMode)
continue
}
d.createPV(file, class, reclaimPolicy, mountOptions, config, capacityByte, desireVolumeMode, startTime)
}
}
func generatePVName(file, node, class string) string {
h := fnv.New32a()
h.Write([]byte(file))
h.Write([]byte(node))
h.Write([]byte(class))
// This is the FNV-1a 32-bit hash
return fmt.Sprintf("local-pv-%x", h.Sum32())
}
func (d *Discoverer) createPV(file, class string, reclaimPolicy v1.PersistentVolumeReclaimPolicy, mountOptions []string, config common.MountConfig, capacityByte int64, volMode v1.PersistentVolumeMode, startTime time.Time) {
pvName := generatePVName(file, d.Node.Name, class)
outsidePath := filepath.Join(config.HostDir, file)
klog.Infof("Found new volume at host path %q with capacity %d, creating Local PV %q, required volumeMode %q",
outsidePath, capacityByte, pvName, volMode)
localPVConfig := &common.LocalPVConfig{
Name: pvName,
HostPath: outsidePath,
Capacity: roundDownCapacityPretty(capacityByte),
StorageClass: class,
ReclaimPolicy: reclaimPolicy,
ProvisionerName: d.Name,
VolumeMode: volMode,
Labels: d.Labels,
MountOptions: mountOptions,
}
if d.UseAlphaAPI {
localPVConfig.UseAlphaAPI = true
localPVConfig.AffinityAnn = d.nodeAffinityAnn
} else {
localPVConfig.NodeAffinity = d.nodeAffinity
}
if config.FsType != "" {
localPVConfig.FsType = &config.FsType
}
pvSpec := common.CreateLocalPVSpec(localPVConfig)
_, err := d.APIUtil.CreatePV(pvSpec)
if err != nil {
klog.Errorf("Error creating PV %q for volume at %q: %v", pvName, outsidePath, err)
return
}
klog.Infof("Created PV %q for volume at %q", pvName, outsidePath)
mode := string(volMode)
metrics.PersistentVolumeDiscoveryTotal.WithLabelValues(mode).Inc()
metrics.PersistentVolumeDiscoveryDurationSeconds.WithLabelValues(mode).Observe(time.Since(startTime).Seconds())
}
// Round down the capacity to an easy to read value.
func roundDownCapacityPretty(capacityBytes int64) int64 {
easyToReadUnitsBytes := []int64{esUtil.GiB, esUtil.MiB}
// Round down to the nearest easy to read unit
// such that there are at least 10 units at that size.
for _, easyToReadUnitBytes := range easyToReadUnitsBytes {
// Round down the capacity to the nearest unit.
size := capacityBytes / easyToReadUnitBytes
if size >= 10 {
return size * easyToReadUnitBytes
}
}
return capacityBytes
}
// GetStorageNodeAffinityFromAnnotation gets the json serialized data from PersistentVolume.Annotations
// and converts it to the NodeAffinity type in core.
func GetStorageNodeAffinityFromAnnotation(annotations map[string]string) (*v1.NodeAffinity, error) {
if len(annotations) > 0 && annotations[common.AlphaStorageNodeAffinityAnnotation] != "" {
var affinity v1.NodeAffinity
err := json.Unmarshal([]byte(annotations[common.AlphaStorageNodeAffinityAnnotation]), &affinity)
if err != nil {
return nil, err
}
return &affinity, nil
}
return nil, nil
}
// StorageNodeAffinityToAlphaAnnotation converts NodeAffinity type to Alpha annotation for use in PersistentVolumes
func StorageNodeAffinityToAlphaAnnotation(annotations map[string]string, affinity *v1.NodeAffinity) error {
if affinity == nil {
return nil
}
json, err := json.Marshal(*affinity)
if err != nil {
return err
}
annotations[common.AlphaStorageNodeAffinityAnnotation] = string(json)
return nil
}