/
driver.go
1537 lines (1298 loc) · 52 KB
/
driver.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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
CSI Driver for Linstor
Copyright © 2018 LINBIT USA, LLC
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package driver
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
lc "github.com/LINBIT/golinstor"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/haySwim/data"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
"github.com/piraeusdatastore/linstor-csi/pkg/client"
"github.com/piraeusdatastore/linstor-csi/pkg/linstor"
"github.com/piraeusdatastore/linstor-csi/pkg/volume"
)
// Version is set via ldflags configued in the Makefile.
var Version = "UNKNOWN"
// Driver fullfils CSI controller, node, and indentity server interfaces.
type Driver struct {
Storage volume.CreateDeleter
Assignments volume.AttacherDettacher
Mounter volume.Mounter
Snapshots volume.SnapshotCreateDeleter
VolumeStatter volume.VolumeStatter
Expander volume.Expander
NodeInformer volume.NodeInformer
kubeClient dynamic.Interface
srv *grpc.Server
log *logrus.Entry
version string
// name distingushes the driver from other drivers and is used to mark
// volumes so that volumes provisioned by another driver are not interfered with.
name string
// endpoint is the socket over which all CSI calls are requested and responded to.
endpoint string
// nodeID is the hostname of the node where this plugin is running locally.
nodeID string
// topologyPrefix is the name
topologyPrefix string
}
// NewDriver builds up a driver.
func NewDriver(options ...func(*Driver) error) (*Driver, error) {
// Set up default noop-ish storage backend.
mockStorage := client.NewMockStorage()
d := &Driver{
name: linstor.DriverName,
version: Version,
nodeID: "localhost",
Storage: mockStorage,
Assignments: mockStorage,
Mounter: mockStorage,
Snapshots: mockStorage,
Expander: mockStorage,
VolumeStatter: mockStorage,
NodeInformer: mockStorage,
log: logrus.NewEntry(logrus.New()),
topologyPrefix: lc.NamespcAuxiliary,
}
d.log.Logger.SetOutput(ioutil.Discard)
d.log.Logger.SetFormatter(&logrus.TextFormatter{})
d.endpoint = fmt.Sprintf("unix:///var/lib/kubelet/plugins/%s/csi.sock", d.name)
// Run options functions.
for _, opt := range options {
err := opt(d)
if err != nil {
return nil, err
}
}
// Add in fields that may have been configured above.
d.log = d.log.WithFields(logrus.Fields{
"linstorCSIComponent": "driver",
"version": d.version,
"provisioner": d.name,
"nodeID": d.nodeID,
})
return d, nil
}
// Storage configures the volume service backend.
func Storage(s volume.CreateDeleter) func(*Driver) error {
return func(d *Driver) error {
d.Storage = s
return nil
}
}
func Expander(s volume.Expander) func(*Driver) error {
return func(d *Driver) error {
d.Expander = s
return nil
}
}
// Assignments configures the volume attachment service backend.
func Assignments(a volume.AttacherDettacher) func(*Driver) error {
return func(d *Driver) error {
d.Assignments = a
return nil
}
}
// Snapshots configures the volume snapshot service backend.
func Snapshots(s volume.SnapshotCreateDeleter) func(*Driver) error {
return func(d *Driver) error {
d.Snapshots = s
return nil
}
}
// Mounter configures the volume mounting service backend.
func Mounter(m volume.Mounter) func(*Driver) error {
return func(d *Driver) error {
d.Mounter = m
return nil
}
}
// VolumeStatter configures the volume stats service backend.
func VolumeStatter(s volume.VolumeStatter) func(*Driver) error {
return func(d *Driver) error {
d.VolumeStatter = s
return nil
}
}
func NodeInformer(n volume.NodeInformer) func(*Driver) error {
return func(d *Driver) error {
d.NodeInformer = n
return nil
}
}
// NodeID configures the driver node ID.
func NodeID(nodeID string) func(*Driver) error {
return func(d *Driver) error {
d.nodeID = nodeID
return nil
}
}
// Endpoint configures the driver name.
func Endpoint(ep string) func(*Driver) error {
return func(d *Driver) error {
d.endpoint = ep
return nil
}
}
// Name configures the driver name.
func Name(name string) func(*Driver) error {
return func(d *Driver) error {
d.name = name
return nil
}
}
func TopologyPrefix(prefix string) func(*Driver) error {
return func(d *Driver) error {
d.topologyPrefix = prefix
return nil
}
}
// LogOut sets the driver to write logs to the provided io.writer
// instead of discarding logs.
func LogOut(out io.Writer) func(*Driver) error {
return func(d *Driver) error {
d.log.Logger.SetOutput(out)
return nil
}
}
// LogFmt sets the format of the log outpout via the provided logrus.Formatter.
func LogFmt(fmt logrus.Formatter) func(*Driver) error {
return func(d *Driver) error {
d.log.Logger.SetFormatter(fmt)
return nil
}
}
// LogLevel sets the logging intensity. Debug additionally reports the function
// from which the logger was called.
func LogLevel(s string) func(*Driver) error {
return func(d *Driver) error {
level, err := logrus.ParseLevel(s)
if err != nil {
return fmt.Errorf("unable to use %s as a logging level: %v", s, err)
}
d.log.Logger.SetLevel(level)
// logs function name from which the logger was called
if level == logrus.DebugLevel {
d.log.Logger.SetReportCaller(true)
}
return nil
}
}
func ConfigureKubernetesIfAvailable() func(*Driver) error {
return func(d *Driver) error {
cfg, err := rest.InClusterConfig()
if err != nil {
// Not running in kubernetes
return nil
}
d.kubeClient, err = dynamic.NewForConfig(cfg)
return err
}
}
// GetPluginInfo https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#getplugininfo
func (d Driver) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {
return &csi.GetPluginInfoResponse{
Name: d.name,
VendorVersion: d.version,
}, nil
}
// GetPluginCapabilities https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#getplugincapabilities
func (d Driver) GetPluginCapabilities(ctx context.Context, req *csi.GetPluginCapabilitiesRequest) (*csi.GetPluginCapabilitiesResponse, error) {
return &csi.GetPluginCapabilitiesResponse{
Capabilities: []*csi.PluginCapability{
{Type: &csi.PluginCapability_Service_{
Service: &csi.PluginCapability_Service{
Type: csi.PluginCapability_Service_CONTROLLER_SERVICE,
},
}},
{Type: &csi.PluginCapability_Service_{
Service: &csi.PluginCapability_Service{
Type: csi.PluginCapability_Service_VOLUME_ACCESSIBILITY_CONSTRAINTS,
},
}},
{Type: &csi.PluginCapability_VolumeExpansion_{
VolumeExpansion: &csi.PluginCapability_VolumeExpansion{
Type: csi.PluginCapability_VolumeExpansion_ONLINE,
},
}},
},
}, nil
}
// Probe https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#probe
func (d Driver) Probe(ctx context.Context, req *csi.ProbeRequest) (*csi.ProbeResponse, error) {
return &csi.ProbeResponse{}, nil
}
// NodeStageVolume https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#nodestagevolume
func (d Driver) NodeStageVolume(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "")
}
// NodeUnstageVolume https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#nodeunstagevolume
func (d Driver) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "")
}
// NodePublishVolume https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#nodepublishvolume
func (d Driver) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
if req.GetVolumeId() == "" {
return &csi.NodePublishVolumeResponse{}, missingAttr("NodePublishVolume", req.GetVolumeId(), "VolumeId")
}
if req.GetTargetPath() == "" {
return &csi.NodePublishVolumeResponse{}, missingAttr("NodePublishVolume", req.GetVolumeId(), "TargetPath")
}
if req.GetVolumeCapability() == nil {
return &csi.NodePublishVolumeResponse{}, missingAttr("NodePublishVolume", req.GetVolumeId(), "VolumeCapability slice")
}
volCtx, err := VolumeContextFromMap(req.GetVolumeContext())
if err != nil {
return nil, status.Errorf(codes.Internal, "NodePublishVolume failed for %s: invalid volume context: %v", req.GetVolumeId(), err)
}
if volCtx == nil {
params, err := d.Storage.GetLegacyVolumeParameters(ctx, req.GetVolumeId())
if err != nil {
return nil, status.Errorf(codes.Internal, "NodePublishVolume failed for %s: could not find volume parameters in context or legacy LINSTOR property", req.GetVolumeId())
}
if params != nil {
volCtx = VolumeContextFromParameters(params)
} else {
volCtx = NewVolumeContext()
}
}
volCtx.MountOptions = append(volCtx.MountOptions, "_netdev")
var fsType string
if block := req.GetVolumeCapability().GetBlock(); block != nil {
volCtx.MountOptions = []string{"bind"}
}
if mnt := req.GetVolumeCapability().GetMount(); mnt != nil {
volCtx.MountOptions = append(volCtx.MountOptions, mnt.GetMountFlags()...)
fsType = "ext4"
if mnt.FsType != "" {
fsType = mnt.FsType
}
}
if fsType == "xfs" {
// Restored snapshots inherit the XFS UUID of the original source. If mounted on the same node as the original
// without this option, XFS will complain about a duplicate UUID and refuse to mount.
volCtx.MountOptions = append(volCtx.MountOptions, "nouuid")
}
assignment, err := d.Assignments.FindAssignmentOnNode(ctx, req.GetVolumeId(), d.nodeID)
if err != nil {
return nil, status.Errorf(codes.Internal, "NodePublishVolume failed for %s: %v", req.GetVolumeId(), err)
}
if assignment == nil {
return nil, status.Errorf(codes.NotFound, "NodePublishVolume failed for %s: assignment not found", req.GetVolumeId())
}
ro := req.GetReadonly() || req.GetVolumeCapability().GetAccessMode().GetMode() == csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY
err = d.Mounter.Mount(ctx, assignment.Path, req.GetTargetPath(), fsType, ro, volCtx.MountOptions)
if err != nil {
return nil, status.Errorf(codes.Internal, "NodePublishVolume failed for %s: %v", req.GetVolumeId(), err)
}
// Runs post-mount xfs_io if PostMountXfsOpts is configured
if fsType == "xfs" && volCtx.PostMountXfsOptions != "" {
d.log.WithFields(logrus.Fields{
"XFS_IO": volCtx.PostMountXfsOptions,
"FSType": fsType,
"targetPath": req.GetTargetPath(),
}).Debug("Post-mount XFS_io")
_, err := exec.Command("xfs_io", "-c", volCtx.PostMountXfsOptions, req.GetTargetPath()).CombinedOutput()
if err != nil {
return nil, status.Errorf(codes.Internal, "NodePublishVolume failed for %s: %v", req.GetVolumeId(), err)
}
}
return &csi.NodePublishVolumeResponse{}, nil
}
// NodeUnpublishVolume https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#nodeunpublishvolume
func (d Driver) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {
if req.GetVolumeId() == "" {
return nil, missingAttr("NodeUnpublishVolume", req.GetVolumeId(), "VolumeId")
}
if req.GetTargetPath() == "" {
return nil, missingAttr("NodeUnpublishVolume", req.GetVolumeId(), "TargetPath")
}
err := d.Mounter.Unmount(req.GetTargetPath())
if err != nil {
return nil, err
}
return &csi.NodeUnpublishVolumeResponse{}, nil
}
// NodeGetVolumeStats https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#nodegetvolumestats
func (d Driver) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {
if req.GetVolumeId() == "" {
return nil, missingAttr("NodeGetVolumeStats", req.GetVolumeId(), "VolumeId")
}
if req.GetVolumePath() == "" {
return nil, missingAttr("NodeGetVolumeStats", req.GetVolumeId(), "VolumeId")
}
notMounted, err := d.Mounter.IsNotMountPoint(req.GetVolumePath())
if err != nil {
return nil, status.Errorf(codes.Internal, "NodeGetVolumeStats failed for %s: failed to check if path %v is mounted: %v", req.GetVolumeId(), req.GetVolumePath(), err)
}
if notMounted {
return nil, status.Errorf(codes.NotFound, "NodeGetVolumeStats failed for %s: path %v is not mounted", req.GetVolumeId(), req.GetVolumePath())
}
stats, err := d.VolumeStatter.GetVolumeStats(req.GetVolumePath())
if err != nil {
return nil, status.Errorf(codes.Internal, "NodeGetVolumeStats failed for %s: failed to get stats: %v", req.GetVolumeId(), err)
}
return &csi.NodeGetVolumeStatsResponse{
Usage: []*csi.VolumeUsage{
{
Available: stats.AvailableBytes,
Total: stats.TotalBytes,
Used: stats.UsedBytes,
Unit: csi.VolumeUsage_BYTES,
},
{
Available: stats.AvailableInodes,
Total: stats.TotalInodes,
Used: stats.UsedInodes,
Unit: csi.VolumeUsage_INODES,
},
},
}, nil
}
// NodeGetCapabilities https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#nodegetcapabilities
func (d Driver) NodeGetCapabilities(context.Context, *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) {
return &csi.NodeGetCapabilitiesResponse{
Capabilities: []*csi.NodeServiceCapability{
{
Type: &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: csi.NodeServiceCapability_RPC_GET_VOLUME_STATS,
},
},
},
{
Type: &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: csi.NodeServiceCapability_RPC_EXPAND_VOLUME,
},
},
},
},
}, nil
}
// NodeGetInfo https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#nodegetinfo
func (d Driver) NodeGetInfo(ctx context.Context, _ *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
topology, err := d.NodeInformer.GetNodeTopologies(ctx, d.nodeID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve node topology: %w", err)
}
return &csi.NodeGetInfoResponse{
NodeId: d.nodeID,
MaxVolumesPerNode: 1048576, // DRBD volumes per node limit.
AccessibleTopology: topology,
}, nil
}
// CreateVolume https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#createvolume
func (d Driver) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {
if req.GetName() == "" {
return nil, missingAttr("CreateVolume", req.GetName(), "Name")
}
if req.GetVolumeCapabilities() == nil || len(req.GetVolumeCapabilities()) == 0 {
return nil, missingAttr("ValidateVolumeCapabilities", req.GetName(), "VolumeCapabilities")
}
fsType, err := fsTypeForCapabilities(req.GetVolumeCapabilities())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "CreateVolume failed for %s: %v", req.Name, err)
}
// Determine how much storage we need to actually allocate for a given number
// of bytes.
requiredKiB, err := d.Storage.AllocationSizeKiB(req.GetCapacityRange().GetRequiredBytes(), req.GetCapacityRange().GetLimitBytes())
if err != nil {
return nil, status.Errorf(
codes.Internal, "CreateVolume failed for %s: %v", req.Name, err)
}
volumeSize := data.NewKibiByte(data.KiB * data.ByteSize(requiredKiB))
params, err := volume.NewParameters(req.GetParameters(), d.topologyPrefix)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to parse parameters: %v", err)
}
var pvcNamespace, pvcName string
if params.UsePvcName {
pvcName = req.GetParameters()[ParameterCsiPvcName]
pvcNamespace = req.GetParameters()[ParameterCsiPvcNamespace]
}
volId := d.Storage.CompatibleVolumeId(req.GetName(), pvcNamespace, pvcName)
log := d.log.WithField("volume", volId)
log.Infof("determined volume id for volume named '%s'", req.GetName())
// Handle case were a volume of the same name is already present.
existingVolume, err := d.Storage.FindByID(ctx, volId)
if err != nil {
return nil, status.Errorf(
codes.Internal, "CreateVolume failed for %s: %v", req.Name, err)
}
// Ignore this check for existing volumes with no FsType set: they may have been provisioned before we used the
// LINSTOR built-in method. Also ignore if we have no fstype set. Using FS as block volume is fine.
if existingVolume != nil && existingVolume.FsType != "" && fsType != "" && existingVolume.FsType != fsType {
return nil, status.Errorf(codes.AlreadyExists, "FsType don't match: existing: '%s', requested: '%s'", existingVolume.FsType, fsType)
}
if existingVolume != nil && strings.HasPrefix(existingVolume.Properties[linstor.PropertyProvisioningCompletedBy], "linstor-csi") {
log.WithField("existingVolume", existingVolume).Info("volume already present")
if existingVolume.SizeBytes != int64(volumeSize.InclusiveBytes()) {
return nil, status.Errorf(codes.AlreadyExists,
"CreateVolume failed for %s: volume already present, but size differs (existing: %d, wanted: %d)",
volId, existingVolume.SizeBytes, int64(volumeSize.InclusiveBytes()))
}
if existingVolume.ResourceGroup != params.ResourceGroup {
return nil, status.Errorf(codes.AlreadyExists,
"CreateVolume failed for %s: volume already present, but resource group differs (existing: %s, wanted: %s)",
volId, existingVolume.ResourceGroup, params.ResourceGroup)
}
log.Info("existing volume matches request")
log.Debug("check if source snapshot exists")
snapId := d.Snapshots.CompatibleSnapshotId(snapshotForVolumeName(req.GetName()))
leftoverSnap, _, err := d.Snapshots.FindSnapByID(ctx, snapId)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check on potential left-over source snapshot: %v", err)
}
if leftoverSnap != nil {
log.Debug("found left-over source snapshot, removing...")
err := d.Snapshots.SnapDelete(ctx, leftoverSnap)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete source snapshot for volume '%s': %v", volId, err)
}
}
topos, err := d.Storage.AccessibleTopologies(ctx, existingVolume.ID, ¶ms)
if err != nil {
return nil, status.Errorf(
codes.Internal, "CreateVolume failed for %s: unable to determine volume topology: %v",
volId, err)
}
volCtx, err := VolumeContextFromParameters(¶ms).ToMap()
if err != nil {
return nil, status.Errorf(codes.Internal, "CreateVolume failed for %s: unable to encode volume context: %v", volId, err)
}
return &csi.CreateVolumeResponse{
Volume: &csi.Volume{
VolumeId: existingVolume.ID,
CapacityBytes: existingVolume.SizeBytes,
ContentSource: req.GetVolumeContentSource(),
AccessibleTopology: topos,
VolumeContext: volCtx,
},
}, nil
}
return d.createNewVolume(
ctx,
&volume.Info{
ID: volId,
SizeBytes: int64(volumeSize.InclusiveBytes()),
ResourceGroup: params.ResourceGroup,
FsType: fsType,
Properties: map[string]string{linstor.PropertyProvisioningCompletedBy: "linstor-csi/" + Version},
},
¶ms,
req,
)
}
// DeleteVolume https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#deletevolume
func (d Driver) DeleteVolume(ctx context.Context, req *csi.DeleteVolumeRequest) (*csi.DeleteVolumeResponse, error) {
if req.GetVolumeId() == "" {
return nil, missingAttr("DeleteVolume", req.GetVolumeId(), "VolumeId")
}
err := d.Storage.Delete(ctx, req.GetVolumeId())
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete volume: %v", err)
}
return &csi.DeleteVolumeResponse{}, nil
}
// ControllerPublishVolume https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#controllerpublishvolume
func (d Driver) ControllerPublishVolume(ctx context.Context, req *csi.ControllerPublishVolumeRequest) (*csi.ControllerPublishVolumeResponse, error) {
if req.GetVolumeId() == "" {
return nil, missingAttr("ControllerPublishVolume", req.GetVolumeId(), "VolumeId")
}
if req.GetNodeId() == "" {
return nil, missingAttr("ControllerPublishVolume", req.GetVolumeId(), "NodeId")
}
if req.GetVolumeCapability() == nil {
return nil, missingAttr("ControllerPublishVolume", req.GetVolumeId(), "VolumeCapability")
}
// Don't try to assign volumes that don't exist.
existingVolume, err := d.Storage.FindByID(ctx, req.GetVolumeId())
if err != nil {
return nil, status.Errorf(codes.Internal,
"ControllerPublishVolume failed for %s: %v", req.GetVolumeId(), err)
}
if existingVolume == nil {
return nil, status.Errorf(codes.NotFound,
"ControllerPublishVolume failed for %s: volume not present in storage backend",
req.GetVolumeId())
}
d.log.WithField("existingVolume", fmt.Sprintf("%+v", existingVolume)).Debug("found existing volume")
// Don't even attempt to put it on nodes that aren't available.
if err := d.Assignments.NodeAvailable(ctx, req.GetNodeId()); err != nil {
return nil, status.Errorf(codes.NotFound,
"ControllerPublishVolume failed for %s on node %s: %v", req.GetVolumeId(), req.GetNodeId(), err)
}
// ReadWriteMany block volume
rwxBlock := req.VolumeCapability.AccessMode.GetMode() == csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER && req.VolumeCapability.GetBlock() != nil
err = d.Assignments.Attach(ctx, req.GetVolumeId(), req.GetNodeId(), rwxBlock)
if err != nil {
return nil, status.Errorf(codes.Internal,
"ControllerPublishVolume failed for %s: %v", req.GetVolumeId(), err)
}
return &csi.ControllerPublishVolumeResponse{}, nil
}
// ControllerUnpublishVolume https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#controllerunpublishvolume
func (d Driver) ControllerUnpublishVolume(ctx context.Context, req *csi.ControllerUnpublishVolumeRequest) (*csi.ControllerUnpublishVolumeResponse, error) {
if req.GetVolumeId() == "" {
return nil, missingAttr("ControllerUnpublishVolume", req.GetVolumeId(), "VolumeId")
}
if req.GetNodeId() == "" {
return nil, missingAttr("ControllerUnpublishVolume", req.GetNodeId(), "NodeId")
}
if err := d.Assignments.Detach(ctx, req.GetVolumeId(), req.GetNodeId()); err != nil {
return nil, status.Errorf(codes.Internal,
"ControllerUnpublishVolume failed for %s: %v", req.GetVolumeId(), err)
}
return &csi.ControllerUnpublishVolumeResponse{}, nil
}
// ValidateVolumeCapabilities https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#validatevolumecapabilities
func (d Driver) ValidateVolumeCapabilities(ctx context.Context, req *csi.ValidateVolumeCapabilitiesRequest) (*csi.ValidateVolumeCapabilitiesResponse, error) {
if req.GetVolumeId() == "" {
return nil, missingAttr("ValidateVolumeCapabilities", req.GetVolumeId(), "volumeId")
}
if req.GetVolumeCapabilities() == nil {
return nil, missingAttr("ValidateVolumeCapabilities", req.GetVolumeId(), "VolumeCapabilities")
}
existingVolume, err := d.Storage.FindByID(ctx, req.GetVolumeId())
if err != nil {
return nil, status.Errorf(codes.Internal,
"ValidateVolumeCapabilities failed for %s: %v", req.GetVolumeId(), err)
}
if existingVolume == nil {
return nil, status.Errorf(codes.NotFound,
"ValidateVolumeCapabilities failed for %s: volume not present in storage backend", req.GetVolumeId())
}
d.log.WithFields(logrus.Fields{
"existingVolume": fmt.Sprintf("%+v", existingVolume),
}).Debug("found existing volume")
for _, requested := range req.VolumeCapabilities {
requestedMode := requested.GetAccessMode().GetMode()
if requestedMode != csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER && requestedMode != csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY {
return nil, status.Errorf(codes.InvalidArgument, "ValidateVolumeCapabilities failed for %s: volumes support only RWO and ROX mode", req.GetVolumeId())
}
}
return &csi.ValidateVolumeCapabilitiesResponse{
Confirmed: &csi.ValidateVolumeCapabilitiesResponse_Confirmed{
VolumeCapabilities: []*csi.VolumeCapability{
// Tell CO we can provision RWO and ROX mount volumes.
{
AccessType: &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{},
},
AccessMode: &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER,
},
},
{
AccessType: &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{},
},
AccessMode: &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY,
},
},
// Tell CO we can provision RWO and ROX block volumes.
{
AccessType: &csi.VolumeCapability_Block{
Block: &csi.VolumeCapability_BlockVolume{},
},
AccessMode: &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER,
},
},
{
AccessType: &csi.VolumeCapability_Block{
Block: &csi.VolumeCapability_BlockVolume{},
},
AccessMode: &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY,
},
},
},
},
}, nil
}
// ListVolumes https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#listvolumes
func (d Driver) ListVolumes(ctx context.Context, req *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {
volumes, err := d.Storage.ListAllWithStatus(ctx)
if err != nil {
return &csi.ListVolumesResponse{}, status.Errorf(codes.Aborted, "ListVolumes failed: %v", err)
}
start, err := parseAsInt(req.GetStartingToken())
if err != nil {
return nil, status.Errorf(codes.Aborted, "ListVolumes failed for: %v", err)
}
if start > len(volumes) {
return &csi.ListVolumesResponse{}, nil
}
// Handle pagination.
var (
end int32
nextToken string
)
totalVols := int32(len(volumes))
if req.GetMaxEntries() == 0 || (totalVols <= req.GetMaxEntries()) {
end = totalVols
} else {
end = req.GetMaxEntries()
nextToken = strconv.Itoa(int(end))
}
volumes = volumes[start:end]
// Build up entries list from paginated volume slice.
entries := make([]*csi.ListVolumesResponse_Entry, len(volumes))
for i, vol := range volumes {
entries[i] = &csi.ListVolumesResponse_Entry{
Volume: &csi.Volume{
VolumeId: vol.ID,
CapacityBytes: vol.SizeBytes,
// NB: Topology is specifically excluded here. For topology we would need the volume context, which
// we don't have here. This might not be strictly to spec, but current consumers don't do anything with
// the information, so it should be fine.
},
Status: &csi.ListVolumesResponse_VolumeStatus{
PublishedNodeIds: vol.Nodes,
VolumeCondition: vol.Conditions,
},
}
}
return &csi.ListVolumesResponse{NextToken: nextToken, Entries: entries}, nil
}
// GetCapacity https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#getcapacity
func (d Driver) GetCapacity(ctx context.Context, req *csi.GetCapacityRequest) (*csi.GetCapacityResponse, error) {
params, err := volume.NewParameters(req.GetParameters(), d.topologyPrefix)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid parameters: %v", err)
}
d.log.WithFields(logrus.Fields{
"parameters": params,
"topology": req.GetAccessibleTopology(),
}).Debug("got capacity request")
// Get the labels for nodes we are allowed to "share" per remote access policy.
accessibleSegments := params.AllowRemoteVolumeAccess.AccessibleSegments(req.GetAccessibleTopology().GetSegments())
d.log.WithField("accessible", accessibleSegments).Trace("got accessible segments for parameters")
maxCap := int64(0)
for _, segment := range accessibleSegments {
d.log.WithField("segment", segment).Debug("Checking capacity of segment")
bytes, err := d.Storage.CapacityBytes(ctx, params.StoragePools, params.OverProvision, segment)
if err != nil {
return nil, status.Errorf(codes.Internal, "%v", err)
}
if bytes > maxCap {
maxCap = bytes
}
}
return &csi.GetCapacityResponse{AvailableCapacity: maxCap}, nil
}
// ControllerGetCapabilities https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#controllergetcapabilities
func (d Driver) ControllerGetCapabilities(ctx context.Context, req *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) {
return &csi.ControllerGetCapabilitiesResponse{
Capabilities: []*csi.ControllerServiceCapability{
// Tell the CO we can create and delete volumes.
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME,
},
}},
// Tell the CO we can make volumes available on remote nodes.
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_PUBLISH_UNPUBLISH_VOLUME,
},
}},
// Tell the CO we can list volumes.
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_LIST_VOLUMES,
},
}},
// Tell the CO we can create and delete snapshots.
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT,
},
}},
// Tell the CO we can create clones of volumes.
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_CLONE_VOLUME,
},
}},
// Tell the CO we can list snapshots.
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS,
},
}},
// Tell the CO we can query our storage space.
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_GET_CAPACITY,
},
}},
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_EXPAND_VOLUME,
},
}},
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_GET_VOLUME,
},
}},
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_LIST_VOLUMES_PUBLISHED_NODES,
},
}},
{Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_VOLUME_CONDITION,
},
}},
},
}, nil
}
// CreateSnapshot https://github.com/container-storage-interface/spec/blob/v1.9.0/spec.md#createsnapshot
func (d Driver) CreateSnapshot(ctx context.Context, req *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) {
if req.GetSourceVolumeId() == "" {
return nil, missingAttr("CreateSnapshot", req.GetSourceVolumeId(), "SourceVolumeId")
}
if req.GetName() == "" {
return nil, missingAttr("CreateSnapshot", req.GetName(), "Name")
}
d.log.WithField("req.parameters", req.GetParameters()).Debug("parsing request")
params, err := volume.NewSnapshotParameters(req.GetParameters(), req.GetSecrets())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid snapshot parameters: %v", err)
}
d.log.WithField("params", params).Debug("got snapshot parameters")
id := d.Snapshots.CompatibleSnapshotId(req.GetName())
d.log.WithField("snapshot id", id).Debug("using snapshot id")
existingSnap, ok, err := d.Snapshots.FindSnapByID(ctx, id)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check for existing snapshot: %v", err)
}
if !ok {
d.log.Debug("existing snapshot is in failed state, deleting")
err := d.Snapshots.SnapDelete(ctx, &volume.Snapshot{
Snapshot: csi.Snapshot{
SourceVolumeId: req.GetSourceVolumeId(),
SnapshotId: req.GetName(),
},
Remote: params.RemoteName,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "tried deleting a leftover unsuccessful snapshot")
}
}
if existingSnap != nil {
// Needed for idempotency.
d.log.WithFields(logrus.Fields{
"requestedSnapshotName": req.GetName(),
"requestedSnapshotSourceVolume": req.GetSourceVolumeId(),
"existingSnapshot": fmt.Sprintf("%+v", existingSnap),
}).Debug("found existing snapshot")
if existingSnap.GetSourceVolumeId() == req.GetSourceVolumeId() {
err = d.maybeDeleteLocalSnapshot(ctx, existingSnap, params)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete local snapshot: %s", err)
}
if existingSnap.ReadyToUse {
d.log.WithField("snapshot id", id).Debug("snapshot ready, delete temporary ID mapping if it exists")
err := d.Snapshots.DeleteTemporarySnapshotID(ctx, id)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete temporary snapshot ID: %v", err)
}
}
return &csi.CreateSnapshotResponse{Snapshot: &existingSnap.Snapshot}, nil
}
return nil, status.Errorf(codes.AlreadyExists, "can't use %q for snapshot name for volume %q, snapshot name is in use for volume %q",
req.GetName(), req.GetSourceVolumeId(), existingSnap.GetSourceVolumeId())
}
snap, err := d.Snapshots.SnapCreate(ctx, id, req.GetSourceVolumeId(), params)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create snapshot: %v", err)
}
err = d.maybeDeleteLocalSnapshot(ctx, snap, params)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete local snapshot: %s", err)
}
if snap.ReadyToUse {
d.log.WithField("snapshot id", id).Debug("snapshot ready, delete temporary ID mapping if it exists")
err := d.Snapshots.DeleteTemporarySnapshotID(ctx, id)
if err != nil {