forked from kubernetes-retired/external-storage
/
discovery.go
243 lines (210 loc) · 7.35 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
/*
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 (
"fmt"
"hash/fnv"
"path/filepath"
"github.com/golang/glog"
"github.com/kubernetes-incubator/external-storage/local-volume/provisioner/pkg/common"
esUtil "github.com/kubernetes-incubator/external-storage/lib/util"
"github.com/kubernetes-incubator/external-storage/local-volume/provisioner/pkg/deleter"
"k8s.io/api/core/v1"
"k8s.io/kubernetes/pkg/api/v1/helper"
)
// 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
ProcTable deleter.ProcTable
nodeAffinityAnn string
}
// 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, procTable deleter.ProcTable) (*Discoverer, error) {
affinity, err := generateNodeAffinity(config.Node)
if err != nil {
return nil, fmt.Errorf("Failed to generate node affinity: %v", err)
}
tmpAnnotations := map[string]string{}
err = helper.StorageNodeAffinityToAlphaAnnotation(tmpAnnotations, affinity)
if err != nil {
return nil, fmt.Errorf("Failed to convert node affinity to alpha annotation: %v", err)
}
labelMap := make(map[string]string)
for _, labelName := range config.NodeLabelsForPV {
labelVal, ok := config.Node.Labels[labelName]
if ok {
labelMap[labelName] = labelVal
}
}
return &Discoverer{
RuntimeConfig: config,
Labels: labelMap,
ProcTable: procTable,
nodeAffinityAnn: tmpAnnotations[v1.AlphaStorageNodeAffinityAnnotation]}, 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
}
// 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) discoverVolumesAtPath(class string, config common.MountConfig) {
glog.V(7).Infof("Discovering volumes at hostpath %q, mount path %q for storage class %q", config.HostDir, config.MountDir, class)
files, err := d.VolUtil.ReadDir(config.MountDir)
if err != nil {
glog.Errorf("Error reading directory: %v", err)
return
}
// Retreive list of mount points to iterate through discovered paths (aka files) below
mountPoints, mountPointsErr := d.RuntimeConfig.Mounter.List()
if mountPointsErr != nil {
glog.Errorf("Error retreiving mountpoints: %v", err)
return
}
// Put mount moints 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 {
// Check if PV already exists for it
pvName := generatePVName(file, d.Node.Name, class)
_, exists := d.Cache.GetPV(pvName)
if exists {
continue
}
if d.ProcTable.IsRunning(pvName) {
glog.Infof("PV %s is still being cleaned, not going to recreate it", pvName)
continue
}
filePath := filepath.Join(config.MountDir, file)
volType, err := d.getVolumeType(filePath)
if err != nil {
glog.Error(err)
continue
}
var capacityByte int64
switch volType {
case common.VolumeTypeBlock:
if d.RuntimeConfig.BlockDisabled {
glog.Warningf("Block device (%q) PVs are currently disabled", filePath)
continue
}
capacityByte, err = d.VolUtil.GetBlockCapacityByte(filePath)
if err != nil {
glog.Errorf("Path %q block stats error: %v", filePath, err)
continue
}
case common.VolumeTypeFile:
capacityByte, err = d.VolUtil.GetFsCapacityByte(filePath)
if err != nil {
glog.Errorf("Path %q fs stats error: %v", filePath, err)
continue
}
default:
glog.Errorf("Path %q has unexpected volume type %q", filePath, volType)
continue
}
// Validate that this path is an actual mountpoint
if _, isMntPnt := mountPointMap[filePath]; isMntPnt == false {
glog.Errorf("Path %q is not an actual mountpoint", filePath)
continue
}
d.createPV(file, class, config, capacityByte, volType)
}
}
func (d *Discoverer) getVolumeType(fullPath string) (string, error) {
isdir, errdir := d.VolUtil.IsDir(fullPath)
if isdir {
return common.VolumeTypeFile, nil
}
isblk, errblk := d.VolUtil.IsBlock(fullPath)
if isblk {
return common.VolumeTypeBlock, nil
}
return "", fmt.Errorf("Block device check for %q failed: DirErr - %v BlkErr - %v", fullPath, errdir, errblk)
}
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, config common.MountConfig, capacityByte int64, volType string) {
pvName := generatePVName(file, d.Node.Name, class)
outsidePath := filepath.Join(config.HostDir, file)
glog.Infof("Found new volume of volumeType %q at host path %q with capacity %d, creating Local PV %q",
volType, outsidePath, capacityByte, pvName)
// TODO: Set block volumeType when the API is ready.
pvSpec := common.CreateLocalPVSpec(&common.LocalPVConfig{
Name: pvName,
HostPath: outsidePath,
Capacity: roundDownCapacityPretty(capacityByte),
StorageClass: class,
ProvisionerName: d.Name,
AffinityAnn: d.nodeAffinityAnn,
Labels: d.Labels,
})
_, err := d.APIUtil.CreatePV(pvSpec)
if err != nil {
glog.Errorf("Error creating PV %q for volume at %q: %v", pvName, outsidePath, err)
return
}
glog.Infof("Created PV %q for volume at %q", pvName, outsidePath)
}
// 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
}