-
Notifications
You must be signed in to change notification settings - Fork 778
/
node.go
535 lines (447 loc) · 18 KB
/
node.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/*
Copyright 2019 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 driver
import (
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
csi "github.com/container-storage-interface/spec/lib/go/csi"
"github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/cloud"
"github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/driver/internal"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/util/resizefs"
"k8s.io/utils/exec"
"k8s.io/utils/mount"
)
const (
// FSTypeExt2 represents the ext2 filesystem type
FSTypeExt2 = "ext2"
// FSTypeExt3 represents the ext3 filesystem type
FSTypeExt3 = "ext3"
// FSTypeExt4 represents the ext4 filesystem type
FSTypeExt4 = "ext4"
// FSTypeXfs represents te xfs filesystem type
FSTypeXfs = "xfs"
// default file system type to be used when it is not provided
defaultFsType = FSTypeExt4
// defaultMaxEBSVolumes is the maximum number of volumes that an AWS instance can have attached.
// More info at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/volume_limits.html
defaultMaxEBSVolumes = 39
// defaultMaxEBSNitroVolumes is the limit of volumes for some smaller instances, like c5 and m5.
defaultMaxEBSNitroVolumes = 25
)
var (
ValidFSTypes = []string{FSTypeExt2, FSTypeExt3, FSTypeExt4, FSTypeXfs}
)
var (
// nodeCaps represents the capability of node service.
nodeCaps = []csi.NodeServiceCapability_RPC_Type{
csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME,
csi.NodeServiceCapability_RPC_EXPAND_VOLUME,
}
)
// nodeService represents the node service of CSI driver
type nodeService struct {
metadata cloud.MetadataService
mounter Mounter
inFlight *internal.InFlight
}
// newNodeService creates a new node service
// it panics if failed to create the service
func newNodeService() nodeService {
metadata, err := cloud.NewMetadata()
if err != nil {
panic(err)
}
return nodeService{
metadata: metadata,
mounter: newNodeMounter(),
inFlight: internal.NewInFlight(),
}
}
func (d *nodeService) NodeStageVolume(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) {
klog.V(4).Infof("NodeStageVolume: called with args %+v", *req)
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
target := req.GetStagingTargetPath()
if len(target) == 0 {
return nil, status.Error(codes.InvalidArgument, "Staging target not provided")
}
volCap := req.GetVolumeCapability()
if volCap == nil {
return nil, status.Error(codes.InvalidArgument, "Volume capability not provided")
}
if !isValidVolumeCapabilities([]*csi.VolumeCapability{volCap}) {
return nil, status.Error(codes.InvalidArgument, "Volume capability not supported")
}
// If the access type is block, do nothing for stage
switch volCap.GetAccessType().(type) {
case *csi.VolumeCapability_Block:
return &csi.NodeStageVolumeResponse{}, nil
}
mount := volCap.GetMount()
if mount == nil {
return nil, status.Error(codes.InvalidArgument, "NodeStageVolume: mount is nil within volume capability")
}
fsType := mount.GetFsType()
if len(fsType) == 0 {
fsType = defaultFsType
}
var mountOptions []string
for _, f := range mount.MountFlags {
if !hasMountOption(mountOptions, f) {
mountOptions = append(mountOptions, f)
}
}
if ok := d.inFlight.Insert(req); !ok {
msg := fmt.Sprintf("request to stage volume=%q is already in progress", volumeID)
return nil, status.Error(codes.Internal, msg)
}
defer func() {
klog.V(4).Infof("NodeStageVolume: volume=%q operation finished", req.GetVolumeId())
d.inFlight.Delete(req)
klog.V(4).Info("donedone")
}()
devicePath, ok := req.PublishContext[DevicePathKey]
if !ok {
return nil, status.Error(codes.InvalidArgument, "Device path not provided")
}
source, err := d.findDevicePath(devicePath, volumeID)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to find device path %s. %v", devicePath, err)
}
klog.V(4).Infof("NodeStageVolume: find device path %s -> %s", devicePath, source)
exists, err := d.mounter.ExistsPath(target)
if err != nil {
msg := fmt.Sprintf("failed to check if target %q exists: %v", target, err)
return nil, status.Error(codes.Internal, msg)
}
// When exists is true it means target path was created but device isn't mounted.
// We don't want to do anything in that case and let the operation proceed.
// Otherwise we need to create the target directory.
if !exists {
// If target path does not exist we need to create the directory where volume will be staged
klog.V(4).Infof("NodeStageVolume: creating target dir %q", target)
if err = d.mounter.MakeDir(target); err != nil {
msg := fmt.Sprintf("could not create target dir %q: %v", target, err)
return nil, status.Error(codes.Internal, msg)
}
}
// Check if a device is mounted in target directory
device, _, err := d.mounter.GetDeviceName(target)
if err != nil {
msg := fmt.Sprintf("failed to check if volume is already mounted: %v", err)
return nil, status.Error(codes.Internal, msg)
}
// This operation (NodeStageVolume) MUST be idempotent.
// If the volume corresponding to the volume_id is already staged to the staging_target_path,
// and is identical to the specified volume_capability the Plugin MUST reply 0 OK.
if device == source {
klog.V(4).Infof("NodeStageVolume: volume=%q already staged", volumeID)
return &csi.NodeStageVolumeResponse{}, nil
}
// FormatAndMount will format only if needed
klog.V(5).Infof("NodeStageVolume: formatting %s and mounting at %s with fstype %s", source, target, fsType)
err = d.mounter.FormatAndMount(source, target, fsType, mountOptions)
if err != nil {
msg := fmt.Sprintf("could not format %q and mount it at %q", source, target)
return nil, status.Error(codes.Internal, msg)
}
return &csi.NodeStageVolumeResponse{}, nil
}
func (d *nodeService) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) {
klog.V(4).Infof("NodeUnstageVolume: called with args %+v", *req)
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
target := req.GetStagingTargetPath()
if len(target) == 0 {
return nil, status.Error(codes.InvalidArgument, "Staging target not provided")
}
// Check if target directory is a mount point. GetDeviceNameFromMount
// given a mnt point, finds the device from /proc/mounts
// returns the device name, reference count, and error code
dev, refCount, err := d.mounter.GetDeviceName(target)
if err != nil {
msg := fmt.Sprintf("failed to check if volume is mounted: %v", err)
return nil, status.Error(codes.Internal, msg)
}
// From the spec: If the volume corresponding to the volume_id
// is not staged to the staging_target_path, the Plugin MUST
// reply 0 OK.
if refCount == 0 {
klog.V(5).Infof("NodeUnstageVolume: %s target not mounted", target)
return &csi.NodeUnstageVolumeResponse{}, nil
}
if refCount > 1 {
klog.Warningf("NodeUnstageVolume: found %d references to device %s mounted at target path %s", refCount, dev, target)
}
klog.V(5).Infof("NodeUnstageVolume: unmounting %s", target)
err = d.mounter.Unmount(target)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not unmount target %q: %v", target, err)
}
return &csi.NodeUnstageVolumeResponse{}, nil
}
func (d *nodeService) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) {
klog.V(4).Infof("NodeExpandVolume: called with args %+v", *req)
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
args := []string{"-o", "source", "--noheadings", "--target", req.GetVolumePath()}
output, err := d.mounter.Command("findmnt", args...).Output()
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not determine device path: %v", err)
}
devicePath := strings.TrimSpace(string(output))
if len(devicePath) == 0 {
return nil, status.Errorf(codes.Internal, "Could not get valid device for mount path: %q", req.GetVolumePath())
}
// TODO: refactor Mounter to expose a mount.SafeFormatAndMount object
r := resizefs.NewResizeFs(&mount.SafeFormatAndMount{
Interface: mount.New(""),
Exec: exec.New(),
})
// TODO: lock per volume ID to have some idempotency
if _, err := r.Resize(devicePath, req.GetVolumePath()); err != nil {
return nil, status.Errorf(codes.Internal, "Could not resize volume %q (%q): %v", volumeID, devicePath, err)
}
return &csi.NodeExpandVolumeResponse{}, nil
}
func (d *nodeService) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
klog.V(4).Infof("NodePublishVolume: called with args %+v", *req)
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
source := req.GetStagingTargetPath()
if len(source) == 0 {
return nil, status.Error(codes.InvalidArgument, "Staging target not provided")
}
target := req.GetTargetPath()
if len(target) == 0 {
return nil, status.Error(codes.InvalidArgument, "Target path not provided")
}
volCap := req.GetVolumeCapability()
if volCap == nil {
return nil, status.Error(codes.InvalidArgument, "Volume capability not provided")
}
if !isValidVolumeCapabilities([]*csi.VolumeCapability{volCap}) {
return nil, status.Error(codes.InvalidArgument, "Volume capability not supported")
}
mountOptions := []string{"bind"}
if req.GetReadonly() {
mountOptions = append(mountOptions, "ro")
}
switch mode := volCap.GetAccessType().(type) {
case *csi.VolumeCapability_Block:
if err := d.nodePublishVolumeForBlock(req, mountOptions); err != nil {
return nil, err
}
case *csi.VolumeCapability_Mount:
if err := d.nodePublishVolumeForFileSystem(req, mountOptions, mode); err != nil {
return nil, err
}
}
return &csi.NodePublishVolumeResponse{}, nil
}
func (d *nodeService) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {
klog.V(4).Infof("NodeUnpublishVolume: called with args %+v", *req)
volumeID := req.GetVolumeId()
if len(volumeID) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID not provided")
}
target := req.GetTargetPath()
if len(target) == 0 {
return nil, status.Error(codes.InvalidArgument, "Target path not provided")
}
klog.V(5).Infof("NodeUnpublishVolume: unmounting %s", target)
err := d.mounter.Unmount(target)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not unmount %q: %v", target, err)
}
return &csi.NodeUnpublishVolumeResponse{}, nil
}
func (d *nodeService) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {
return nil, status.Error(codes.Unimplemented, "NodeGetVolumeStats is not implemented yet")
}
func (d *nodeService) NodeGetCapabilities(ctx context.Context, req *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) {
klog.V(4).Infof("NodeGetCapabilities: called with args %+v", *req)
var caps []*csi.NodeServiceCapability
for _, cap := range nodeCaps {
c := &csi.NodeServiceCapability{
Type: &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: cap,
},
},
}
caps = append(caps, c)
}
return &csi.NodeGetCapabilitiesResponse{Capabilities: caps}, nil
}
func (d *nodeService) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
klog.V(4).Infof("NodeGetInfo: called with args %+v", *req)
topology := &csi.Topology{
Segments: map[string]string{TopologyKey: d.metadata.GetAvailabilityZone()},
}
return &csi.NodeGetInfoResponse{
NodeId: d.metadata.GetInstanceID(),
MaxVolumesPerNode: d.getVolumesLimit(),
AccessibleTopology: topology,
}, nil
}
func (d *nodeService) nodePublishVolumeForBlock(req *csi.NodePublishVolumeRequest, mountOptions []string) error {
target := req.GetTargetPath()
volumeID := req.GetVolumeId()
devicePath, exists := req.PublishContext[DevicePathKey]
if !exists {
return status.Error(codes.InvalidArgument, "Device path not provided")
}
source, err := d.findDevicePath(devicePath, volumeID)
if err != nil {
return status.Errorf(codes.Internal, "Failed to find device path %s. %v", devicePath, err)
}
klog.V(4).Infof("NodePublishVolume [block]: find device path %s -> %s", devicePath, source)
globalMountPath := filepath.Dir(target)
// create the global mount path if it is missing
// Path in the form of /var/lib/kubelet/plugins/kubernetes.io/csi/volumeDevices/publish/{volumeName}
exists, err = d.mounter.ExistsPath(globalMountPath)
if err != nil {
return status.Errorf(codes.Internal, "Could not check if path exists %q: %v", globalMountPath, err)
}
if !exists {
if err := d.mounter.MakeDir(globalMountPath); err != nil {
return status.Errorf(codes.Internal, "Could not create dir %q: %v", globalMountPath, err)
}
}
// Create the mount point as a file since bind mount device node requires it to be a file
klog.V(5).Infof("NodePublishVolume [block]: making target file %s", target)
err = d.mounter.MakeFile(target)
if err != nil {
if removeErr := os.Remove(target); removeErr != nil {
return status.Errorf(codes.Internal, "Could not remove mount target %q: %v", target, removeErr)
}
return status.Errorf(codes.Internal, "Could not create file %q: %v", target, err)
}
klog.V(5).Infof("NodePublishVolume [block]: mounting %s at %s", source, target)
if err := d.mounter.Mount(source, target, "", mountOptions); err != nil {
if removeErr := os.Remove(target); removeErr != nil {
return status.Errorf(codes.Internal, "Could not remove mount target %q: %v", target, removeErr)
}
return status.Errorf(codes.Internal, "Could not mount %q at %q: %v", source, target, err)
}
return nil
}
func (d *nodeService) nodePublishVolumeForFileSystem(req *csi.NodePublishVolumeRequest, mountOptions []string, mode *csi.VolumeCapability_Mount) error {
target := req.GetTargetPath()
source := req.GetStagingTargetPath()
if m := mode.Mount; m != nil {
for _, f := range m.MountFlags {
if !hasMountOption(mountOptions, f) {
mountOptions = append(mountOptions, f)
}
}
}
klog.V(5).Infof("NodePublishVolume: creating dir %s", target)
if err := d.mounter.MakeDir(target); err != nil {
return status.Errorf(codes.Internal, "Could not create dir %q: %v", target, err)
}
fsType := mode.Mount.GetFsType()
if len(fsType) == 0 {
fsType = defaultFsType
}
klog.V(5).Infof("NodePublishVolume: mounting %s at %s with option %s as fstype %s", source, target, mountOptions, fsType)
if err := d.mounter.Mount(source, target, fsType, mountOptions); err != nil {
if removeErr := os.Remove(target); removeErr != nil {
return status.Errorf(codes.Internal, "Could not remove mount target %q: %v", target, err)
}
return status.Errorf(codes.Internal, "Could not mount %q at %q: %v", source, target, err)
}
return nil
}
// findDevicePath finds path of device and verifies its existence
// if the device is not nvme, return the path directly
// if the device is nvme, finds and returns the nvme device path eg. /dev/nvme1n1
func (d *nodeService) findDevicePath(devicePath, volumeID string) (string, error) {
exists, err := d.mounter.ExistsPath(devicePath)
if err != nil {
return "", err
}
// If the path exists, assume it is not nvme device
if exists {
return devicePath, nil
}
// Else find the nvme device path using volume ID
// This is the magic name on which AWS presents NVME devices under /dev/disk/by-id/
// For example, vol-0fab1d5e3f72a5e23 creates a symlink at
// /dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol0fab1d5e3f72a5e23
nvmeName := "nvme-Amazon_Elastic_Block_Store_" + strings.Replace(volumeID, "-", "", -1)
return findNvmeVolume(nvmeName)
}
// findNvmeVolume looks for the nvme volume with the specified name
// It follows the symlink (if it exists) and returns the absolute path to the device
func findNvmeVolume(findName string) (device string, err error) {
p := filepath.Join("/dev/disk/by-id/", findName)
stat, err := os.Lstat(p)
if err != nil {
if os.IsNotExist(err) {
klog.V(5).Infof("nvme path %q not found", p)
return "", fmt.Errorf("nvme path %q not found", p)
}
return "", fmt.Errorf("error getting stat of %q: %v", p, err)
}
if stat.Mode()&os.ModeSymlink != os.ModeSymlink {
klog.Warningf("nvme file %q found, but was not a symlink", p)
return "", fmt.Errorf("nvme file %q found, but was not a symlink", p)
}
// Find the target, resolving to an absolute path
// For example, /dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol0fab1d5e3f72a5e23 -> ../../nvme2n1
resolved, err := filepath.EvalSymlinks(p)
if err != nil {
return "", fmt.Errorf("error reading target of symlink %q: %v", p, err)
}
if !strings.HasPrefix(resolved, "/dev") {
return "", fmt.Errorf("resolved symlink for %q was unexpected: %q", p, resolved)
}
return resolved, nil
}
// getVolumesLimit returns the limit of volumes that the node supports
func (d *nodeService) getVolumesLimit() int64 {
ebsNitroInstanceTypeRegex := "^[cmr]5.*|t3|z1d"
instanceType := d.metadata.GetInstanceType()
if ok, _ := regexp.MatchString(ebsNitroInstanceTypeRegex, instanceType); ok {
return defaultMaxEBSNitroVolumes
}
return defaultMaxEBSVolumes
}
// hasMountOption returns a boolean indicating whether the given
// slice already contains a mount option. This is used to prevent
// passing duplicate option to the mount command.
func hasMountOption(options []string, opt string) bool {
for _, o := range options {
if o == opt {
return true
}
}
return false
}