/
node.go
945 lines (836 loc) · 26.6 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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
/*
Copyright 2018 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 service
import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/akutz/gofsutil"
"github.com/container-storage-interface/spec/lib/go/csi"
csictx "github.com/rexray/gocsi/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/klog"
csipbv1 "github.com/container-storage-interface/spec/lib/go/csi"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8svol "k8s.io/kubernetes/pkg/volume"
"k8s.io/kubernetes/pkg/volume/util/fs"
cnsvsphere "sigs.k8s.io/vsphere-csi-driver/pkg/common/cns-lib/vsphere"
cnsconfig "sigs.k8s.io/vsphere-csi-driver/pkg/common/config"
"sigs.k8s.io/vsphere-csi-driver/pkg/csi/service/common"
csitypes "sigs.k8s.io/vsphere-csi-driver/pkg/csi/types"
)
const (
devDiskID = "/dev/disk/by-id"
blockPrefix = "wwn-0x"
dmiDir = "/sys/class/dmi"
)
func (s *service) NodeStageVolume(
ctx context.Context,
req *csi.NodeStageVolumeRequest) (
*csi.NodeStageVolumeResponse, error) {
volID := req.GetVolumeId()
pubCtx := req.GetPublishContext()
diskID, err := getDiskID(volID, pubCtx)
if err != nil {
klog.Errorf("Failed to get diskID. Error: %v", err)
return nil, err
}
klog.V(2).Infof("Checking if volume: %s with diskID: %s is attached", volID, diskID)
volPath, err := verifyVolumeAttached(diskID)
if err != nil {
klog.Errorf("Failed to verify volume attachment. Error: %v", err)
return nil, err
}
// Check that block device looks good
dev, err := getDevice(volPath)
if err != nil {
return nil, status.Errorf(codes.Internal,
"error getting block device for volume: %s, err: %s",
volID, err.Error())
}
// Check if this is a MountvVolume or BlockVolume
volCap := req.GetVolumeCapability()
if _, ok := volCap.GetAccessType().(*csi.VolumeCapability_Block); ok {
// Volume is a block volume, so skip all the rest
klog.V(2).Infof("skipping staging for block access type for volume: %s, diskID: %s, device :%s", volID, diskID, dev.RealDev)
return &csi.NodeStageVolumeResponse{}, nil
}
// Extract fs details
fs, mntFlags, err := ensureMountVol(volCap)
if err != nil {
return nil, err
}
// Check that target_path is created by CO and is a directory
target := req.GetStagingTargetPath()
if err = verifyTargetDir(target); err != nil {
return nil, err
}
accMode := volCap.GetAccessMode().GetMode()
ro := false
if accMode == csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY ||
accMode == csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY {
ro = true
}
// Get mounts to check if already staged
mnts, err := gofsutil.GetDevMounts(context.Background(), dev.RealDev)
if err != nil {
return nil, status.Errorf(codes.Internal,
"could not reliably determine existing mount status: %s",
err.Error())
}
attributes := req.VolumeContext
fsType := attributes[common.AttributeFsType]
klog.V(2).Infof("fsType from VolumeContext: %s", fsType)
if fsType == "" {
// no fsType is set in VolumeContext, use default "ext4"
fsType = common.DefaultFsType
klog.V(2).Infof("fsType is not set in VolumeContext, use default type")
}
if len(mnts) == 0 {
// Device isn't mounted anywhere, stage the volume
if fs == "" {
fs = fsType
}
// If read-only access mode, we don't allow formatting
if ro {
mntFlags = append(mntFlags, "ro")
if err := gofsutil.Mount(ctx, dev.FullPath, target, fs, mntFlags...); err != nil {
return nil, status.Errorf(codes.Internal,
"error with mount during staging: %s",
err.Error())
}
return &csi.NodeStageVolumeResponse{}, nil
}
if err := gofsutil.FormatAndMount(ctx, dev.FullPath, target, fs, mntFlags...); err != nil {
return nil, status.Errorf(codes.Internal,
"error with format and mount during staging: %s",
err.Error())
}
return &csi.NodeStageVolumeResponse{}, nil
}
// Device is already mounted. Need to ensure that it is already
// mounted to the expected staging target, with correct rw/ro perms
mounted := false
for _, m := range mnts {
if m.Path == target {
mounted = true
rwo := "rw"
if ro {
rwo = "ro"
}
if contains(m.Opts, rwo) {
//TODO make sure that mount options match
//log.WithFields(f).Debug(
// "private mount already in place")
return &csi.NodeStageVolumeResponse{}, nil
}
return nil, status.Error(codes.AlreadyExists,
"access mode conflicts with existing mount")
}
}
if !mounted {
return nil, status.Error(codes.Internal,
"device already in use and mounted elsewhere")
}
return nil, nil
}
func (s *service) NodeUnstageVolume(
ctx context.Context,
req *csi.NodeUnstageVolumeRequest) (
*csi.NodeUnstageVolumeResponse, error) {
volID := req.GetVolumeId()
target := req.GetStagingTargetPath()
if err := verifyTargetDir(target); err != nil {
return nil, err
}
// Look up block device mounted to target
// BlockVolume: Here we are relying on the fact that the CO is required to
// have created the staging path per the spec, even for BlockVolumes. Even
// though we don't use the staging path for block, the fact nothing will be
// mounted still indicates that unstaging is done.
dev, err := getDevFromMount(target)
if err != nil {
return nil, status.Errorf(codes.Internal,
"error getting block device for volume: %s, err: %s",
volID, err.Error())
}
if dev == nil {
// Nothing is mounted, so unstaging is already done
return &csi.NodeUnstageVolumeResponse{}, nil
}
klog.V(2).Infof("found device. volID: %q, path: %q, block: %q, target: %q", volID, dev.FullPath, dev.RealDev, target)
// Get mounts for device
mnts, err := gofsutil.GetDevMounts(context.Background(), dev.RealDev)
if err != nil {
return nil, status.Errorf(codes.Internal,
"could not reliably determine existing mount status: %s",
err.Error())
}
// device is mounted. Should only be mounted to target
if len(mnts) > 1 {
return nil, status.Errorf(codes.Internal,
"volume: %s appears mounted in multiple places", volID)
}
// Since we looked up the block volume from the target path, we assume that
// the one existing mount is from the block to the target
// unstage this
if err := gofsutil.Unmount(context.Background(), target); err != nil {
return nil, status.Errorf(codes.Internal,
"Error unmounting target: %s", err.Error())
}
return &csi.NodeUnstageVolumeResponse{}, nil
}
func (s *service) NodePublishVolume(
ctx context.Context,
req *csi.NodePublishVolumeRequest) (
*csi.NodePublishVolumeResponse, error) {
volID := req.GetVolumeId()
pubCtx := req.GetPublishContext()
diskID, err := getDiskID(volID, pubCtx)
if err != nil {
return nil, err
}
klog.V(2).Infof("Checking if volume: %s with diskID: %s is attached", volID, diskID)
volPath, err := verifyVolumeAttached(diskID)
if err != nil {
klog.Errorf("Failed to verify volume attachment. Error: %v", err)
return nil, err
}
// Get underlying block device
dev, err := getDevice(volPath)
if err != nil {
return nil, status.Errorf(codes.Internal,
"error getting block device for volume: %s, err: %s",
volID, err.Error())
}
// check for Block vs Mount
volCap := req.GetVolumeCapability()
if _, ok := volCap.GetAccessType().(*csi.VolumeCapability_Block); ok {
// bind mount device to target
return publishBlockVol(ctx, req, dev)
}
// Volume must be a mount volume
return publishMountVol(ctx, req, dev)
}
func (s *service) NodeUnpublishVolume(
ctx context.Context,
req *csi.NodeUnpublishVolumeRequest) (
*csi.NodeUnpublishVolumeResponse, error) {
volID := req.GetVolumeId()
target := req.GetTargetPath()
_, err := os.Stat(target)
if err != nil {
if os.IsNotExist(err) {
// target path does not exist, so we must be Unpublished
return &csi.NodeUnpublishVolumeResponse{}, nil
}
return nil, status.Errorf(codes.Internal,
"failed to stat target, err: %s", err.Error())
}
// Look up block device mounted to target
dev, err := getDevFromMount(target)
if err != nil {
return nil, status.Errorf(codes.Internal,
"error getting block device for volume: %s, err: %s",
volID, err.Error())
}
if dev == nil {
// Nothing is mounted, so unpublish is already done. However, we also know
// that the target path exists, and it is our job to remove it.
if err := rmpath(target); err != nil {
return nil, err
}
return &csi.NodeUnpublishVolumeResponse{}, nil
}
// get mounts
// Check if device is already unmounted
mnts, err := gofsutil.GetMounts(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal,
"could not reliably determine existing mount status: %s",
err.Error())
}
for _, m := range mnts {
if m.Source == dev.RealDev || m.Device == dev.RealDev {
if m.Path == target {
if err := gofsutil.Unmount(ctx, target); err != nil {
return nil, status.Errorf(codes.Internal,
"Error unmounting target: %s", err.Error())
}
if err := rmpath(target); err != nil {
return nil, err
}
}
}
}
return &csi.NodeUnpublishVolumeResponse{}, nil
}
func (s *service) NodeGetVolumeStats(
ctx context.Context,
req *csi.NodeGetVolumeStatsRequest) (
*csi.NodeGetVolumeStatsResponse, error) {
var err error
targetPath := req.GetVolumePath()
if targetPath == "" {
err = fmt.Errorf("targetpath %v is empty", targetPath)
return nil, status.Error(codes.InvalidArgument, err.Error())
}
dev, err := getDevFromMount(targetPath)
if err != nil {
err = fmt.Errorf("unable to get targetpath %v device", targetPath)
return nil, status.Error(codes.Internal, err.Error())
}
if dev == nil {
err = fmt.Errorf("could not find device mounted on targetpath %v", targetPath)
return nil, status.Error(codes.Internal, err.Error())
}
//TODO Check that the matching device is a vSphere volume, and that the volID matches the mount point
volMetrics, err := getMetrics(targetPath)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
available, ok := (*(volMetrics.Available)).AsInt64()
if !ok {
klog.Errorf("failed to fetch available bytes")
}
capacity, ok := (*(volMetrics.Capacity)).AsInt64()
if !ok {
klog.Errorf("failed to fetch capacity bytes")
return nil, status.Error(codes.Unknown, "failed to fetch capacity bytes")
}
used, ok := (*(volMetrics.Used)).AsInt64()
if !ok {
klog.Errorf("failed to fetch used bytes")
}
inodes, ok := (*(volMetrics.Inodes)).AsInt64()
if !ok {
klog.Errorf("failed to fetch available inodes")
return nil, status.Error(codes.Unknown, "failed to fetch available inodes")
}
inodesFree, ok := (*(volMetrics.InodesFree)).AsInt64()
if !ok {
klog.Errorf("failed to fetch free inodes")
}
inodesUsed, ok := (*(volMetrics.InodesUsed)).AsInt64()
if !ok {
klog.Errorf("failed to fetch used inodes")
}
return &csi.NodeGetVolumeStatsResponse{
Usage: []*csi.VolumeUsage{
{
Available: available,
Total: capacity,
Used: used,
Unit: csipbv1.VolumeUsage_BYTES,
},
{
Available: inodesFree,
Total: inodes,
Used: inodesUsed,
Unit: csipbv1.VolumeUsage_INODES,
},
},
}, nil
}
//Get volume metrics using k8s fsInfo strategy
func getMetrics(path string) (*k8svol.Metrics, error) {
if path == "" {
return nil, fmt.Errorf("No path given")
}
available, capacity, usage, inodes, inodesFree, inodesUsed, err := fs.FsInfo(path)
metrics := &k8svol.Metrics{Time: metav1.Now()}
if err != nil {
return nil, err
}
metrics.Available = resource.NewQuantity(available, resource.BinarySI)
metrics.Capacity = resource.NewQuantity(capacity, resource.BinarySI)
metrics.Used = resource.NewQuantity(usage, resource.BinarySI)
metrics.Inodes = resource.NewQuantity(inodes, resource.BinarySI)
metrics.InodesFree = resource.NewQuantity(inodesFree, resource.BinarySI)
metrics.InodesUsed = resource.NewQuantity(inodesUsed, resource.BinarySI)
if err != nil {
return metrics, err
}
return metrics, nil
}
func (s *service) NodeGetCapabilities(
ctx context.Context,
req *csi.NodeGetCapabilitiesRequest) (
*csi.NodeGetCapabilitiesResponse, error) {
return &csi.NodeGetCapabilitiesResponse{
Capabilities: []*csi.NodeServiceCapability{
{
Type: &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME,
},
},
},
{
Type: &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: csi.NodeServiceCapability_RPC_GET_VOLUME_STATS,
},
},
},
},
}, nil
}
func (s *service) NodeGetInfo(
ctx context.Context,
req *csi.NodeGetInfoRequest) (
*csi.NodeGetInfoResponse, error) {
nodeID := os.Getenv("NODE_NAME")
if nodeID == "" {
return nil, status.Error(codes.Internal, "ENV NODE_NAME is not set")
}
var cfg *cnsconfig.Config
cfgPath = csictx.Getenv(ctx, cnsconfig.EnvCloudConfig)
if cfgPath == "" {
cfgPath = cnsconfig.DefaultCloudConfigPath
}
cfg, err := cnsconfig.GetCnsconfig(cfgPath)
if err != nil {
if os.IsNotExist(err) {
klog.V(2).Infof("Config file not provided to node daemonset. Assuming non-topology aware cluster.")
return &csi.NodeGetInfoResponse{
NodeId: nodeID,
}, nil
}
klog.Errorf("Failed to read cnsconfig. Error: %v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
var accessibleTopology map[string]string
topology := &csi.Topology{}
if cfg.Labels.Zone != "" && cfg.Labels.Region != "" {
klog.V(2).Infof("Config file provided to node daemonset with zones and regions. Assuming topology aware cluster.")
vcenterconfig, err := cnsvsphere.GetVirtualCenterConfig(cfg)
if err != nil {
klog.Errorf("Failed to get VirtualCenterConfig from cns config. err=%v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
vcManager := cnsvsphere.GetVirtualCenterManager()
vcenter, err := vcManager.RegisterVirtualCenter(vcenterconfig)
if err != nil {
klog.Errorf("Failed to register vcenter with virtualCenterManager.")
return nil, status.Errorf(codes.Internal, err.Error())
}
defer vcManager.UnregisterAllVirtualCenters()
//Connect to vCenter
err = vcenter.Connect(ctx)
if err != nil {
klog.Errorf("Failed to connect to vcenter host: %s. err=%v", vcenter.Config.Host, err)
return nil, status.Errorf(codes.Internal, err.Error())
}
// Get VM UUID
uuid, err := getSystemUUID()
if err != nil {
klog.Errorf("Failed to get system uuid for node VM")
return nil, status.Errorf(codes.Internal, err.Error())
}
klog.V(4).Infof("Successfully retrieved uuid:%s from the node: %s", uuid, nodeID)
nodeVM, err := cnsvsphere.GetVirtualMachineByUUID(uuid, false)
if err != nil || nodeVM == nil {
klog.Errorf("Failed to get nodeVM for uuid: %s. err: %+v", uuid, err)
uuid, err = convertUUID(uuid)
if err != nil {
klog.Errorf("convertUUID failed with error: %v", err)
return nil, status.Errorf(codes.Internal, err.Error())
}
nodeVM, err = cnsvsphere.GetVirtualMachineByUUID(uuid, false)
if err != nil || nodeVM == nil {
klog.Errorf("Failed to get nodeVM for uuid: %s. err: %+v", uuid, err)
return nil, status.Errorf(codes.Internal, err.Error())
}
}
zone, region, err := nodeVM.GetZoneRegion(ctx, cfg.Labels.Zone, cfg.Labels.Region)
if err != nil {
klog.Errorf("Failed to get accessibleTopology for vm: %v, err: %v", nodeVM.Reference(), err)
return nil, status.Errorf(codes.Internal, err.Error())
}
klog.V(4).Infof("zone: [%s], region: [%s], Node VM: [%s]", zone, region, nodeID)
if zone != "" && region != "" {
accessibleTopology = make(map[string]string)
accessibleTopology[csitypes.LabelRegionFailureDomain] = region
accessibleTopology[csitypes.LabelZoneFailureDomain] = zone
}
}
if len(accessibleTopology) > 0 {
topology.Segments = accessibleTopology
}
return &csi.NodeGetInfoResponse{
NodeId: nodeID,
AccessibleTopology: topology,
}, nil
}
func publishMountVol(
ctx context.Context,
req *csi.NodePublishVolumeRequest,
dev *Device) (
*csi.NodePublishVolumeResponse, error) {
volCap := req.GetVolumeCapability()
// Extract fs details
_, mntFlags, err := ensureMountVol(volCap)
if err != nil {
return nil, err
}
// We are responsible for creating target dir, per spec
target := req.GetTargetPath()
_, err = mkdir(target)
if err != nil {
return nil, status.Errorf(codes.Internal,
"Unable to create target dir: %s, err: %v", target, err)
}
stagingTarget := req.GetStagingTargetPath()
if err := verifyTargetDir(stagingTarget); err != nil {
return nil, err
}
ro := req.GetReadonly()
// get block device mounts
// Check if device is already mounted
devMnts, err := getDevMounts(dev)
if err != nil {
return nil, status.Errorf(codes.Internal,
"could not reliably determine existing mount status: %s",
err.Error())
}
// We expect that block device already staged, so there should be at least 1
// mount already. if it's > 1, it may already be published
if len(devMnts) > 1 {
// check if publish is already there
for _, m := range devMnts {
if m.Path == target {
// volume already published to target
// if mount options look good, do nothing
rwo := "rw"
if ro {
rwo = "ro"
}
if !contains(m.Opts, rwo) {
return nil, status.Error(codes.AlreadyExists,
"volume previously published with different options")
}
// Existing mount satisfies request
klog.V(3).Infof("volume already published to target. volumePath: %q, device: %q, req: %v", dev.FullPath, dev.RealDev, req)
return &csi.NodePublishVolumeResponse{}, nil
}
}
} else if len(devMnts) == 0 {
return nil, status.Errorf(codes.FailedPrecondition,
"Volume ID: %s does not appear staged to %s", req.GetVolumeId(), stagingTarget)
}
// Do the bind mount to publish the volume
if ro {
mntFlags = append(mntFlags, "ro")
}
if err := gofsutil.BindMount(ctx, stagingTarget, target, mntFlags...); err != nil {
return nil, status.Errorf(codes.Internal,
"error publish volume to target path: %s",
err.Error())
}
return &csi.NodePublishVolumeResponse{}, nil
}
func publishBlockVol(
ctx context.Context,
req *csi.NodePublishVolumeRequest,
dev *Device) (
*csi.NodePublishVolumeResponse, error) {
// We are responsible for creating target file, per spec
target := req.GetTargetPath()
_, err := mkfile(target)
if err != nil {
return nil, status.Errorf(codes.Internal,
"Unable to create target file: %s, err: %v", target, err)
}
ro := req.GetReadonly()
// Read-only is not supported for BlockVolume. Doing a read-only
// bind mount of the device to the target path does not prevent
// the underlying block device from being modified, so don't
// advertise a false sense of security
if ro {
return nil, status.Error(codes.InvalidArgument,
"read only not supported for Block Volume")
}
// get block device mounts
devMnts, err := getDevMounts(dev)
if err != nil {
return nil, status.Errorf(codes.Internal,
"could not reliably determine existing mount status: %s",
err.Error())
}
// check if device is already mounted
if len(devMnts) == 0 {
// do the bind mount
mntFlags := make([]string, 0)
if err := gofsutil.BindMount(ctx, dev.FullPath, target, mntFlags...); err != nil {
return nil, status.Errorf(codes.Internal,
"error publish volume to target path: %s",
err.Error())
}
} else if len(devMnts) == 1 {
// already mounted, make sure it's what we want
if devMnts[0].Path != target {
return nil, status.Error(codes.Internal,
"device already in use and mounted elsewhere")
}
klog.V(3).Infof("volume already published to target. volumePath: %q, device: %q, target: %q", dev.FullPath, dev.RealDev, req.GetTargetPath())
} else {
return nil, status.Error(codes.Internal,
"block volume already mounted in more than one place")
}
// existing or new mount satisfies request
return &csi.NodePublishVolumeResponse{}, nil
}
// Device is a struct for holding details about a block device
type Device struct {
FullPath string
Name string
RealDev string
}
// getDevice returns a Device struct with info about the given device, or
// an error if it doesn't exist or is not a block device
func getDevice(path string) (*Device, error) {
fi, err := os.Lstat(path)
if err != nil {
return nil, err
}
// eval any symlinks and make sure it points to a device
d, err := filepath.EvalSymlinks(path)
if err != nil {
return nil, err
}
ds, err := os.Stat(d)
if err != nil {
return nil, err
}
dm := ds.Mode()
if dm&os.ModeDevice == 0 {
return nil, fmt.Errorf(
"%s is not a block device", path)
}
return &Device{
Name: fi.Name(),
FullPath: path,
RealDev: d,
}, nil
}
// The files parameter is optional for testing purposes
func getDiskPath(id string, files []os.FileInfo) (string, error) {
var (
devs []os.FileInfo
err error
)
if files == nil {
devs, err = ioutil.ReadDir(devDiskID)
if err != nil {
return "", err
}
} else {
devs = files
}
targetDisk := blockPrefix + id
for _, f := range devs {
if f.Name() == targetDisk {
return filepath.Join(devDiskID, f.Name()), nil
}
}
return "", nil
}
func contains(list []string, item string) bool {
for _, x := range list {
if x == item {
return true
}
}
return false
}
func verifyVolumeAttached(diskID string) (string, error) {
// Check that volume is attached
volPath, err := getDiskPath(diskID, nil)
if err != nil {
return "", status.Errorf(codes.Internal,
"Error trying to read attached disks: %v", err)
}
if volPath == "" {
return "", status.Errorf(codes.NotFound,
"disk: %s not attached to node", diskID)
}
klog.V(2).Infof("found disk. diskID: %q, path: %q", diskID, volPath)
return volPath, nil
}
func verifyTargetDir(target string) error {
if target == "" {
return status.Error(codes.InvalidArgument,
"target path required")
}
tgtStat, err := os.Stat(target)
if err != nil {
if os.IsNotExist(err) {
return status.Errorf(codes.FailedPrecondition,
"target: %s not pre-created", target)
}
return status.Errorf(codes.Internal,
"failed to stat target, err: %s", err.Error())
}
// This check is mandated by the spec, but this would/should fail if the
// volume has a block accessType. Maybe staging isn't intended to be used
// with block? That would make sense you cannot share the volume for block.
if !tgtStat.IsDir() {
return status.Errorf(codes.FailedPrecondition,
"existing path: %s is not a directory", target)
}
return nil
}
// mkdir creates the directory specified by path if needed.
// return pair is a bool flag of whether dir was created, and an error
func mkdir(path string) (bool, error) {
st, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
if err := os.Mkdir(path, 0750); err != nil {
klog.Errorf("Unable to create dir :%q", path)
return false, err
}
klog.V(3).Infof("created directory. Path: %q", path)
return true, nil
}
return false, err
}
if !st.IsDir() {
return false, fmt.Errorf("existing path is not a directory")
}
return false, nil
}
// mkfile creates a file specified by the path if needed.
// return pair is a bool flag of whether file was created, and an error
func mkfile(path string) (bool, error) {
st, err := os.Stat(path)
if os.IsNotExist(err) {
file, err := os.OpenFile(path, os.O_CREATE, 0755)
if err != nil {
klog.Errorf("Unable to create a file :%q", path)
return false, err
}
file.Close()
klog.V(3).Infof("created file. Path: %q", path)
return true, nil
}
if st.IsDir() {
return false, fmt.Errorf("existing path is a directory")
}
return false, nil
}
// rmpath removes the given target path, whether it is a file or a directory
// for directories, an error is returned if the dir is not empty
func rmpath(target string) error {
// target should be empty
klog.V(3).Infof("removing target path: %q", target)
if err := os.Remove(target); err != nil {
return status.Errorf(codes.Internal,
"Unable to remove target path: %s, err: %v", target, err)
}
return nil
}
func ensureMountVol(volCap *csi.VolumeCapability) (string, []string, error) {
mountVol := volCap.GetMount()
if mountVol == nil {
return "", nil, status.Error(codes.InvalidArgument,
"access type missing")
}
fs := mountVol.GetFsType()
mntFlags := mountVol.GetMountFlags()
return fs, mntFlags, nil
}
// a wrapper around gofsutil.GetMounts that handles bind mounts
func getDevMounts(
sysDevice *Device) ([]gofsutil.Info, error) {
ctx := context.Background()
devMnts := make([]gofsutil.Info, 0)
mnts, err := gofsutil.GetMounts(ctx)
if err != nil {
return devMnts, err
}
for _, m := range mnts {
if m.Device == sysDevice.RealDev || (m.Device == "devtmpfs" && m.Source == sysDevice.RealDev) {
devMnts = append(devMnts, m)
}
}
return devMnts, nil
}
func getSystemUUID() (string, error) {
idb, err := ioutil.ReadFile(path.Join(dmiDir, "id", "product_uuid"))
if err != nil {
return "", err
}
klog.V(4).Infof("uuid in bytes: %v", idb)
id := strings.TrimSpace(string(idb))
klog.V(4).Infof("uuid in string: %s", id)
return strings.ToLower(id), nil
}
// convertUUID helps convert UUID to vSphere format
//input uuid: 6B8C2042-0DD1-D037-156F-435F999D94C1
//returned uuid: 42208c6b-d10d-37d0-156f-435f999d94c1
func convertUUID(uuid string) (string, error) {
if len(uuid) != 36 {
return "", errors.New("uuid length should be 36")
}
convertedUUID := fmt.Sprintf("%s%s%s%s-%s%s-%s%s-%s-%s",
uuid[6:8], uuid[4:6], uuid[2:4], uuid[0:2],
uuid[11:13], uuid[9:11],
uuid[16:18], uuid[14:16],
uuid[19:23],
uuid[24:36])
return strings.ToLower(convertedUUID), nil
}
func getDiskID(volID string, pubCtx map[string]string) (string, error) {
if volID == "" {
return "", status.Error(codes.InvalidArgument,
"Volume ID required")
}
if _, ok := pubCtx[common.AttributeFirstClassDiskUUID]; !ok {
return "", status.Errorf(codes.InvalidArgument,
"Attribute: %s required in publish context",
common.AttributeFirstClassDiskUUID)
}
return pubCtx[common.AttributeFirstClassDiskUUID], nil
}
func getDevFromMount(target string) (*Device, error) {
// Get list of all mounts on system
mnts, err := gofsutil.GetMounts(context.Background())
if err != nil {
return nil, err
}
for _, m := range mnts {
if m.Path == target {
// something is mounted to target, get underlying disk
d := m.Device
if m.Device == "devtmpfs" {
d = m.Source
}
dev, err := getDevice(d)
if err != nil {
return nil, err
}
return dev, nil
}
}
// Did not identify a device mounted to target
return nil, nil
}