-
Notifications
You must be signed in to change notification settings - Fork 7
/
controller.go
450 lines (415 loc) · 12.4 KB
/
controller.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package main
import (
"context"
"fmt"
"path"
"strings"
"time"
v1 "k8s.io/api/core/v1"
k8serror "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientset "k8s.io/client-go/kubernetes"
"sigs.k8s.io/sig-storage-lib-external-provisioner/v9/controller"
"k8s.io/klog/v2"
)
const (
keyNode = "kubernetes.io/hostname"
typeAnnotation = "csi-lvm.metal-stack.io/type"
linearType = "linear"
stripedType = "striped"
mirrorType = "mirror"
actionTypeCreate = "create"
actionTypeDelete = "delete"
pullAlways = "always"
pullIfNotPresent = "ifnotpresent"
)
type actionType string
type lvmProvisioner struct {
// The directory to create the directories for every lv and mount them
lvDir string
// devicePattern specifies a pattern of host devices to be part of the main volume group
devicePattern string
// image to execute lvm commands
provisionerImage string
kubeClient clientset.Interface
namespace string
// defaultLVMType the lvm type to use by default if not overwritten in the pvc spec.
defaultLVMType string
pullPolicy v1.PullPolicy
vgName string
}
// NewLVMProvisioner creates a new lvm provisioner
func NewLVMProvisioner(kubeClient clientset.Interface, namespace, vgName, lvDir, devicePattern, provisionerImage, defaultLVMType, pullPolicy string) controller.Provisioner {
pp := v1.PullAlways
if strings.ToLower(pullPolicy) == pullIfNotPresent {
pp = v1.PullIfNotPresent
}
return &lvmProvisioner{
lvDir: lvDir,
devicePattern: devicePattern,
provisionerImage: provisionerImage,
kubeClient: kubeClient,
namespace: namespace,
vgName: vgName,
defaultLVMType: defaultLVMType,
pullPolicy: pp,
}
}
var _ controller.Provisioner = &lvmProvisioner{}
type volumeAction struct {
action actionType
name string
path string
nodeName string
size int64
lvmType string
isBlock bool
}
// SupportsBlock returns whether provisioner supports block volume.
// this is required for mixed setups where pv´s mounted in pods
// and block devices must be possible on the same node
func (p *lvmProvisioner) SupportsBlock(ctx context.Context) bool {
return true
}
// Provision creates a storage asset and returns a PV object representing it.
func (p *lvmProvisioner) Provision(ctx context.Context, options controller.ProvisionOptions) (*v1.PersistentVolume, controller.ProvisioningState, error) {
klog.Infof("start provision %s node:%s devices:%s", options.PVName, options.SelectedNode.GetName(), p.devicePattern)
node := options.SelectedNode
if node == nil {
return nil, controller.ProvisioningFinished, fmt.Errorf("configuration error, no node was specified")
}
name := options.PVName
path := path.Join(p.lvDir, name)
lvmType := p.defaultLVMType
userAnnotation, ok := options.PVC.Annotations[typeAnnotation]
if ok {
lvmType = userAnnotation
}
switch lvmType {
case stripedType, mirrorType, linearType:
default:
return nil, controller.ProvisioningFinished, fmt.Errorf("configuration error, lvmtype %s is invalid", lvmType)
}
klog.Infof("Creating volume %v at %v:%v", name, node.Name, path)
requests, ok := options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
if !ok {
return nil, controller.ProvisioningFinished, fmt.Errorf("configuration error, no volume size was specified")
}
size, ok := requests.AsInt64()
if !ok {
return nil, controller.ProvisioningFinished, fmt.Errorf("configuration error, no volume size not readable")
}
volumeMode := v1.PersistentVolumeFilesystem
isBlock := false
if options.PVC.Spec.VolumeMode != nil && *options.PVC.Spec.VolumeMode == v1.PersistentVolumeBlock {
isBlock = true
volumeMode = v1.PersistentVolumeBlock
}
va := volumeAction{
action: actionTypeCreate,
name: name,
path: path,
nodeName: node.Name,
size: size,
lvmType: lvmType,
isBlock: isBlock,
}
if err := p.createProvisionerPod(ctx, va); err != nil {
klog.Errorf("error creating provisioner pod :%v", err)
return nil, controller.ProvisioningReschedule, err
}
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: options.PVName,
Annotations: map[string]string{
"lvmProvisionerIdentity": node.Name,
},
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: *options.StorageClass.ReclaimPolicy,
AccessModes: options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
},
PersistentVolumeSource: v1.PersistentVolumeSource{
Local: &v1.LocalVolumeSource{
Path: path,
},
},
VolumeMode: &volumeMode,
NodeAffinity: &v1.VolumeNodeAffinity{
Required: &v1.NodeSelector{
NodeSelectorTerms: []v1.NodeSelectorTerm{
{
MatchExpressions: []v1.NodeSelectorRequirement{
{
Key: keyNode,
Operator: v1.NodeSelectorOpIn,
Values: []string{
node.Name,
},
},
},
},
},
},
},
},
}
return pv, controller.ProvisioningFinished, nil
}
// Delete removes the storage asset that was created by Provision represented
// by the given PV.
func (p *lvmProvisioner) Delete(ctx context.Context, volume *v1.PersistentVolume) (err error) {
path, node, err := p.getPathAndNodeForPV(volume)
if err != nil {
return err
}
_, err = p.kubeClient.CoreV1().Nodes().Get(ctx, node, metav1.GetOptions{})
if err != nil {
if k8serror.IsNotFound(err) {
klog.Infof("node %s not found anymore. Assuming volume %s is gone for good.", node, volume.Name)
return nil
}
}
klog.Infof("delete volume: %s on node:%s reclaim:%s", path, node, volume.Spec.PersistentVolumeReclaimPolicy)
if volume.Spec.PersistentVolumeReclaimPolicy != v1.PersistentVolumeReclaimRetain {
isBlock := false
if volume.Spec.VolumeMode != nil && *volume.Spec.VolumeMode == v1.PersistentVolumeBlock {
isBlock = true
}
klog.Infof("deleting volume %v at %v:%v", volume.Name, node, path)
va := volumeAction{
action: actionTypeDelete,
name: volume.Name,
path: path,
nodeName: node,
size: 0,
isBlock: isBlock,
}
if err := p.createProvisionerPod(ctx, va); err != nil {
klog.Infof("clean up volume %v failed: %v", volume.Name, err)
return err
}
return nil
}
klog.Infof("Retained volume %v", volume.Name)
return nil
}
func (p *lvmProvisioner) createProvisionerPod(ctx context.Context, va volumeAction) (err error) {
if va.name == "" || va.path == "" || va.nodeName == "" {
return fmt.Errorf("invalid empty name or path or node")
}
if va.action == actionTypeCreate && va.lvmType == "" {
return fmt.Errorf("createlv without lvm type")
}
args := []string{}
if va.action == actionTypeCreate {
args = append(args, "createlv", "--lvsize", fmt.Sprintf("%d", va.size), "--devices", p.devicePattern, "--lvmtype", va.lvmType)
}
if va.action == actionTypeDelete {
args = append(args, "deletelv")
}
args = append(args, "--lvname", va.name, "--vgname", p.vgName, "--directory", p.lvDir)
if va.isBlock {
args = append(args, "--block")
}
klog.Infof("start provisionerPod with args:%s", args)
hostPathType := v1.HostPathDirectoryOrCreate
mountPropagation := v1.MountPropagationBidirectional
privileged := true
provisionerPod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: string(va.action) + "-" + va.name,
},
Spec: v1.PodSpec{
RestartPolicy: v1.RestartPolicyNever,
NodeName: va.nodeName,
Tolerations: []v1.Toleration{
{
Operator: v1.TolerationOpExists,
},
},
Containers: []v1.Container{
{
Name: "csi-lvm-" + string(va.action),
Image: p.provisionerImage,
Command: []string{"/csi-lvm-provisioner"},
Args: args,
VolumeMounts: []v1.VolumeMount{
{
Name: "data",
ReadOnly: false,
MountPath: p.lvDir,
MountPropagation: &mountPropagation,
},
{
Name: "devices",
ReadOnly: false,
MountPath: "/dev",
},
{
Name: "modules",
ReadOnly: false,
MountPath: "/lib/modules",
},
{
Name: "lvmbackup",
ReadOnly: false,
MountPath: "/etc/lvm/backup",
MountPropagation: &mountPropagation,
},
{
Name: "lvmcache",
ReadOnly: false,
MountPath: "/etc/lvm/cache",
MountPropagation: &mountPropagation,
},
{
Name: "lvmlock",
ReadOnly: false,
MountPath: "/run/lock/lvm",
MountPropagation: &mountPropagation,
},
},
ImagePullPolicy: p.pullPolicy,
SecurityContext: &v1.SecurityContext{
Privileged: &privileged,
},
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
"cpu": resource.MustParse("50m"),
"memory": resource.MustParse("50Mi"),
},
Limits: v1.ResourceList{
"cpu": resource.MustParse("100m"),
"memory": resource.MustParse("100Mi"),
},
},
},
},
Volumes: []v1.Volume{
{
Name: "data",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: p.lvDir,
Type: &hostPathType,
},
},
},
{
Name: "devices",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/dev",
Type: &hostPathType,
},
},
},
{
Name: "modules",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/lib/modules",
Type: &hostPathType,
},
},
},
{
Name: "lvmbackup",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/etc/lvm/backup",
Type: &hostPathType,
},
},
},
{
Name: "lvmcache",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/etc/lvm/cache",
Type: &hostPathType,
},
},
},
{
Name: "lvmlock",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/run/lock/lvm",
Type: &hostPathType,
},
},
},
},
},
}
// If it already exists due to some previous errors, the pod will be cleaned up later automatically
// https://github.com/rancher/local-path-provisioner/issues/27
_, err = p.kubeClient.CoreV1().Pods(p.namespace).Create(ctx, provisionerPod, metav1.CreateOptions{})
if err != nil && !k8serror.IsAlreadyExists(err) {
return err
}
defer func() {
e := p.kubeClient.CoreV1().Pods(p.namespace).Delete(ctx, provisionerPod.Name, metav1.DeleteOptions{})
if e != nil {
klog.Errorf("unable to delete the provisioner pod: %v", e)
}
}()
completed := false
retrySeconds := 120
for i := 0; i < retrySeconds; i++ {
pod, err := p.kubeClient.CoreV1().Pods(p.namespace).Get(ctx, provisionerPod.Name, metav1.GetOptions{})
if err != nil {
klog.Errorf("error reading provisioner pod:%v", err)
} else if pod.Status.Phase == v1.PodSucceeded {
klog.Info("provisioner pod terminated successfully")
completed = true
break
}
klog.Infof("provisioner pod status:%s", pod.Status.Phase)
time.Sleep(1 * time.Second)
}
if !completed {
return fmt.Errorf("create process timeout after %v seconds", retrySeconds)
}
klog.Infof("Volume %v has been %vd on %v:%v", va.name, va.action, va.nodeName, va.path)
return nil
}
func (p *lvmProvisioner) getPathAndNodeForPV(pv *v1.PersistentVolume) (path, node string, err error) {
localPvc := pv.Spec.PersistentVolumeSource.Local
if localPvc == nil {
return "", "", fmt.Errorf("no local PVC set")
}
path = localPvc.Path
nodeAffinity := pv.Spec.NodeAffinity
if nodeAffinity == nil {
return "", "", fmt.Errorf("no NodeAffinity set")
}
required := nodeAffinity.Required
if required == nil {
return "", "", fmt.Errorf("no NodeAffinity.Required set")
}
node = ""
for _, selectorTerm := range required.NodeSelectorTerms {
for _, expression := range selectorTerm.MatchExpressions {
if expression.Key == keyNode && expression.Operator == v1.NodeSelectorOpIn {
if len(expression.Values) != 1 {
return "", "", fmt.Errorf("multiple values for the node affinity")
}
node = expression.Values[0]
break
}
}
if node != "" {
break
}
}
if node == "" {
return "", "", fmt.Errorf("cannot find affinited node")
}
return path, node, nil
}