-
Notifications
You must be signed in to change notification settings - Fork 2k
/
csi.go
1424 lines (1219 loc) · 38.4 KB
/
csi.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
package structs
import (
"fmt"
"strings"
"time"
multierror "github.com/hashicorp/go-multierror"
"github.com/hashicorp/nomad/helper"
)
// CSISocketName is the filename that Nomad expects plugins to create inside the
// PluginMountDir.
const CSISocketName = "csi.sock"
// CSIIntermediaryDirname is the name of the directory inside the PluginMountDir
// where Nomad will expect plugins to create intermediary mounts for volumes.
const CSIIntermediaryDirname = "volumes"
// VolumeTypeCSI is the type in the volume stanza of a TaskGroup
const VolumeTypeCSI = "csi"
// CSIPluginType is an enum string that encapsulates the valid options for a
// CSIPlugin stanza's Type. These modes will allow the plugin to be used in
// different ways by the client.
type CSIPluginType string
const (
// CSIPluginTypeNode indicates that Nomad should only use the plugin for
// performing Node RPCs against the provided plugin.
CSIPluginTypeNode CSIPluginType = "node"
// CSIPluginTypeController indicates that Nomad should only use the plugin for
// performing Controller RPCs against the provided plugin.
CSIPluginTypeController CSIPluginType = "controller"
// CSIPluginTypeMonolith indicates that Nomad can use the provided plugin for
// both controller and node rpcs.
CSIPluginTypeMonolith CSIPluginType = "monolith"
)
// CSIPluginTypeIsValid validates the given CSIPluginType string and returns
// true only when a correct plugin type is specified.
func CSIPluginTypeIsValid(pt CSIPluginType) bool {
switch pt {
case CSIPluginTypeNode, CSIPluginTypeController, CSIPluginTypeMonolith:
return true
default:
return false
}
}
// TaskCSIPluginConfig contains the data that is required to setup a task as a
// CSI plugin. This will be used by the csi_plugin_supervisor_hook to configure
// mounts for the plugin and initiate the connection to the plugin catalog.
type TaskCSIPluginConfig struct {
// ID is the identifier of the plugin.
// Ideally this should be the FQDN of the plugin.
ID string
// Type instructs Nomad on how to handle processing a plugin
Type CSIPluginType
// MountDir is the destination that nomad should mount in its CSI
// directory for the plugin. It will then expect a file called CSISocketName
// to be created by the plugin, and will provide references into
// "MountDir/CSIIntermediaryDirname/{VolumeName}/{AllocID} for mounts.
MountDir string
}
func (t *TaskCSIPluginConfig) Copy() *TaskCSIPluginConfig {
if t == nil {
return nil
}
nt := new(TaskCSIPluginConfig)
*nt = *t
return nt
}
// CSIVolumeCapability is the requested attachment and access mode for a
// volume
type CSIVolumeCapability struct {
AttachmentMode CSIVolumeAttachmentMode
AccessMode CSIVolumeAccessMode
}
// CSIVolumeAttachmentMode chooses the type of storage api that will be used to
// interact with the device.
type CSIVolumeAttachmentMode string
const (
CSIVolumeAttachmentModeUnknown CSIVolumeAttachmentMode = ""
CSIVolumeAttachmentModeBlockDevice CSIVolumeAttachmentMode = "block-device"
CSIVolumeAttachmentModeFilesystem CSIVolumeAttachmentMode = "file-system"
)
func ValidCSIVolumeAttachmentMode(attachmentMode CSIVolumeAttachmentMode) bool {
switch attachmentMode {
case CSIVolumeAttachmentModeBlockDevice, CSIVolumeAttachmentModeFilesystem:
return true
default:
return false
}
}
// CSIVolumeAccessMode indicates how a volume should be used in a storage topology
// e.g whether the provider should make the volume available concurrently.
type CSIVolumeAccessMode string
const (
CSIVolumeAccessModeUnknown CSIVolumeAccessMode = ""
CSIVolumeAccessModeSingleNodeReader CSIVolumeAccessMode = "single-node-reader-only"
CSIVolumeAccessModeSingleNodeWriter CSIVolumeAccessMode = "single-node-writer"
CSIVolumeAccessModeMultiNodeReader CSIVolumeAccessMode = "multi-node-reader-only"
CSIVolumeAccessModeMultiNodeSingleWriter CSIVolumeAccessMode = "multi-node-single-writer"
CSIVolumeAccessModeMultiNodeMultiWriter CSIVolumeAccessMode = "multi-node-multi-writer"
)
// ValidCSIVolumeAccessMode checks to see that the provided access mode is a valid,
// non-empty access mode.
func ValidCSIVolumeAccessMode(accessMode CSIVolumeAccessMode) bool {
switch accessMode {
case CSIVolumeAccessModeSingleNodeReader, CSIVolumeAccessModeSingleNodeWriter,
CSIVolumeAccessModeMultiNodeReader, CSIVolumeAccessModeMultiNodeSingleWriter,
CSIVolumeAccessModeMultiNodeMultiWriter:
return true
default:
return false
}
}
// ValidCSIVolumeWriteAccessMode checks for a writable access mode.
func ValidCSIVolumeWriteAccessMode(accessMode CSIVolumeAccessMode) bool {
switch accessMode {
case CSIVolumeAccessModeSingleNodeWriter,
CSIVolumeAccessModeMultiNodeSingleWriter,
CSIVolumeAccessModeMultiNodeMultiWriter:
return true
default:
return false
}
}
// CSIMountOptions contain optional additional configuration that can be used
// when specifying that a Volume should be used with VolumeAccessTypeMount.
type CSIMountOptions struct {
// FSType is an optional field that allows an operator to specify the type
// of the filesystem.
FSType string
// MountFlags contains additional options that may be used when mounting the
// volume by the plugin. This may contain sensitive data and should not be
// leaked.
MountFlags []string
}
func (o *CSIMountOptions) Copy() *CSIMountOptions {
if o == nil {
return nil
}
no := *o
no.MountFlags = helper.CopySliceString(o.MountFlags)
return &no
}
func (o *CSIMountOptions) Merge(p *CSIMountOptions) {
if p == nil {
return
}
if p.FSType != "" {
o.FSType = p.FSType
}
if p.MountFlags != nil {
o.MountFlags = p.MountFlags
}
}
// CSIMountOptions implements the Stringer and GoStringer interfaces to prevent
// accidental leakage of sensitive mount flags via logs.
var _ fmt.Stringer = &CSIMountOptions{}
var _ fmt.GoStringer = &CSIMountOptions{}
func (v *CSIMountOptions) String() string {
mountFlagsString := "nil"
if len(v.MountFlags) != 0 {
mountFlagsString = "[REDACTED]"
}
return fmt.Sprintf("csi.CSIOptions(FSType: %s, MountFlags: %s)", v.FSType, mountFlagsString)
}
func (v *CSIMountOptions) GoString() string {
return v.String()
}
// CSISecrets contain optional additional configuration that can be used
// when specifying that a Volume should be used with VolumeAccessTypeMount.
type CSISecrets map[string]string
// CSISecrets implements the Stringer and GoStringer interfaces to prevent
// accidental leakage of secrets via logs.
var _ fmt.Stringer = &CSISecrets{}
var _ fmt.GoStringer = &CSISecrets{}
func (s *CSISecrets) String() string {
redacted := map[string]string{}
for k := range *s {
redacted[k] = "[REDACTED]"
}
return fmt.Sprintf("csi.CSISecrets(%v)", redacted)
}
func (s *CSISecrets) GoString() string {
return s.String()
}
type CSIVolumeClaim struct {
AllocationID string
NodeID string
ExternalNodeID string
Mode CSIVolumeClaimMode
AccessMode CSIVolumeAccessMode
AttachmentMode CSIVolumeAttachmentMode
State CSIVolumeClaimState
}
type CSIVolumeClaimState int
const (
CSIVolumeClaimStateTaken CSIVolumeClaimState = iota
CSIVolumeClaimStateNodeDetached
CSIVolumeClaimStateControllerDetached
CSIVolumeClaimStateReadyToFree
CSIVolumeClaimStateUnpublishing
)
// CSIVolume is the full representation of a CSI Volume
type CSIVolume struct {
// ID is a namespace unique URL safe identifier for the volume
ID string
// Name is a display name for the volume, not required to be unique
Name string
// ExternalID identifies the volume for the CSI interface, may be URL unsafe
ExternalID string
Namespace string
Topologies []*CSITopology
AccessMode CSIVolumeAccessMode // *current* access mode
AttachmentMode CSIVolumeAttachmentMode // *current* attachment mode
MountOptions *CSIMountOptions
Secrets CSISecrets
Parameters map[string]string
Context map[string]string
Capacity int64 // bytes
// These values are used only on volume creation but we record them
// so that we can diff the volume later
RequestedCapacityMin int64 // bytes
RequestedCapacityMax int64 // bytes
RequestedCapabilities []*CSIVolumeCapability
CloneID string
SnapshotID string
// Allocations, tracking claim status
ReadAllocs map[string]*Allocation // AllocID -> Allocation
WriteAllocs map[string]*Allocation // AllocID -> Allocation
ReadClaims map[string]*CSIVolumeClaim // AllocID -> claim
WriteClaims map[string]*CSIVolumeClaim // AllocID -> claim
PastClaims map[string]*CSIVolumeClaim // AllocID -> claim
// Schedulable is true if all the denormalized plugin health fields are true, and the
// volume has not been marked for garbage collection
Schedulable bool
PluginID string
Provider string
ProviderVersion string
ControllerRequired bool
ControllersHealthy int
ControllersExpected int
NodesHealthy int
NodesExpected int
ResourceExhausted time.Time
CreateIndex uint64
ModifyIndex uint64
}
// CSIVolListStub is partial representation of a CSI Volume for inclusion in lists
type CSIVolListStub struct {
ID string
Namespace string
Name string
ExternalID string
Topologies []*CSITopology
AccessMode CSIVolumeAccessMode
AttachmentMode CSIVolumeAttachmentMode
CurrentReaders int
CurrentWriters int
Schedulable bool
PluginID string
Provider string
ControllersHealthy int
ControllersExpected int
NodesHealthy int
NodesExpected int
CreateIndex uint64
ModifyIndex uint64
}
// NewCSIVolume creates the volume struct. No side-effects
func NewCSIVolume(volumeID string, index uint64) *CSIVolume {
out := &CSIVolume{
ID: volumeID,
CreateIndex: index,
ModifyIndex: index,
}
out.newStructs()
return out
}
func (v *CSIVolume) newStructs() {
v.Topologies = []*CSITopology{}
v.MountOptions = new(CSIMountOptions)
v.Secrets = CSISecrets{}
v.Parameters = map[string]string{}
v.Context = map[string]string{}
v.ReadAllocs = map[string]*Allocation{}
v.WriteAllocs = map[string]*Allocation{}
v.ReadClaims = map[string]*CSIVolumeClaim{}
v.WriteClaims = map[string]*CSIVolumeClaim{}
v.PastClaims = map[string]*CSIVolumeClaim{}
}
func (v *CSIVolume) RemoteID() string {
if v.ExternalID != "" {
return v.ExternalID
}
return v.ID
}
func (v *CSIVolume) Stub() *CSIVolListStub {
stub := CSIVolListStub{
ID: v.ID,
Namespace: v.Namespace,
Name: v.Name,
ExternalID: v.ExternalID,
Topologies: v.Topologies,
AccessMode: v.AccessMode,
AttachmentMode: v.AttachmentMode,
CurrentReaders: len(v.ReadAllocs),
CurrentWriters: len(v.WriteAllocs),
Schedulable: v.Schedulable,
PluginID: v.PluginID,
Provider: v.Provider,
ControllersHealthy: v.ControllersHealthy,
ControllersExpected: v.ControllersExpected,
NodesHealthy: v.NodesHealthy,
NodesExpected: v.NodesExpected,
CreateIndex: v.CreateIndex,
ModifyIndex: v.ModifyIndex,
}
return &stub
}
func (v *CSIVolume) ReadSchedulable() bool {
if !v.Schedulable {
return false
}
return v.ResourceExhausted == time.Time{}
}
// WriteSchedulable determines if the volume is schedulable for writes,
// considering only volume capabilities and plugin health
func (v *CSIVolume) WriteSchedulable() bool {
if !v.Schedulable {
return false
}
switch v.AccessMode {
case CSIVolumeAccessModeSingleNodeWriter,
CSIVolumeAccessModeMultiNodeSingleWriter,
CSIVolumeAccessModeMultiNodeMultiWriter:
return v.ResourceExhausted == time.Time{}
case CSIVolumeAccessModeUnknown:
// this volume was created but not currently claimed, so we check what
// it's capable of, not what it's been previously assigned
for _, cap := range v.RequestedCapabilities {
switch cap.AccessMode {
case CSIVolumeAccessModeSingleNodeWriter,
CSIVolumeAccessModeMultiNodeSingleWriter,
CSIVolumeAccessModeMultiNodeMultiWriter:
return v.ResourceExhausted == time.Time{}
}
}
}
return false
}
// WriteFreeClaims determines if there are any free write claims available
func (v *CSIVolume) WriteFreeClaims() bool {
switch v.AccessMode {
case CSIVolumeAccessModeSingleNodeWriter, CSIVolumeAccessModeMultiNodeSingleWriter:
return len(v.WriteClaims) == 0
case CSIVolumeAccessModeMultiNodeMultiWriter:
// the CSI spec doesn't allow for setting a max number of writers.
// we track node resource exhaustion through v.ResourceExhausted
// which is checked in WriteSchedulable
return true
case CSIVolumeAccessModeUnknown:
// this volume was created but not yet claimed, so we check what it's
// capable of, not what it's been assigned
if len(v.RequestedCapabilities) == 0 {
// COMPAT: a volume that was registered before 1.1.0 and has not
// had a change in claims could have no requested caps. It will
// get corrected on the first claim.
return true
}
for _, cap := range v.RequestedCapabilities {
switch cap.AccessMode {
case CSIVolumeAccessModeSingleNodeWriter, CSIVolumeAccessModeMultiNodeSingleWriter:
return len(v.WriteClaims) == 0
case CSIVolumeAccessModeMultiNodeMultiWriter:
return true
}
}
}
return false
}
// InUse tests whether any allocations are actively using the volume
func (v *CSIVolume) InUse() bool {
return len(v.ReadAllocs) != 0 ||
len(v.WriteAllocs) != 0
}
// Copy returns a copy of the volume, which shares only the Topologies slice
func (v *CSIVolume) Copy() *CSIVolume {
out := new(CSIVolume)
*out = *v
out.newStructs() // zero-out the non-primitive structs
for _, t := range v.Topologies {
out.Topologies = append(out.Topologies, t.Copy())
}
if v.MountOptions != nil {
*out.MountOptions = *v.MountOptions
}
for k, v := range v.Secrets {
out.Secrets[k] = v
}
for k, v := range v.Parameters {
out.Parameters[k] = v
}
for k, v := range v.Context {
out.Context[k] = v
}
for k, alloc := range v.ReadAllocs {
out.ReadAllocs[k] = alloc.Copy()
}
for k, alloc := range v.WriteAllocs {
out.WriteAllocs[k] = alloc.Copy()
}
for k, v := range v.ReadClaims {
claim := *v
out.ReadClaims[k] = &claim
}
for k, v := range v.WriteClaims {
claim := *v
out.WriteClaims[k] = &claim
}
for k, v := range v.PastClaims {
claim := *v
out.PastClaims[k] = &claim
}
return out
}
// Claim updates the allocations and changes the volume state
func (v *CSIVolume) Claim(claim *CSIVolumeClaim, alloc *Allocation) error {
// COMPAT: volumes registered prior to 1.1.0 will be missing caps for the
// volume on any claim. Correct this when we make the first change to a
// claim by setting its currently claimed capability as the only requested
// capability
if len(v.RequestedCapabilities) == 0 && v.AccessMode != "" && v.AttachmentMode != "" {
v.RequestedCapabilities = []*CSIVolumeCapability{
{
AccessMode: v.AccessMode,
AttachmentMode: v.AttachmentMode,
},
}
}
if v.AttachmentMode != CSIVolumeAttachmentModeUnknown &&
claim.AttachmentMode != CSIVolumeAttachmentModeUnknown &&
v.AttachmentMode != claim.AttachmentMode {
return fmt.Errorf("cannot change attachment mode of claimed volume")
}
if claim.State == CSIVolumeClaimStateTaken {
switch claim.Mode {
case CSIVolumeClaimRead:
return v.claimRead(claim, alloc)
case CSIVolumeClaimWrite:
return v.claimWrite(claim, alloc)
}
}
// either GC or a Unpublish checkpoint
return v.claimRelease(claim)
}
// claimRead marks an allocation as using a volume read-only
func (v *CSIVolume) claimRead(claim *CSIVolumeClaim, alloc *Allocation) error {
if _, ok := v.ReadAllocs[claim.AllocationID]; ok {
return nil
}
if alloc == nil {
return fmt.Errorf("allocation missing: %s", claim.AllocationID)
}
if !v.ReadSchedulable() {
return fmt.Errorf("unschedulable")
}
// Allocations are copy on write, so we want to keep the id but don't need the
// pointer. We'll get it from the db in denormalize.
v.ReadAllocs[claim.AllocationID] = nil
delete(v.WriteAllocs, claim.AllocationID)
v.ReadClaims[claim.AllocationID] = claim
delete(v.WriteClaims, claim.AllocationID)
delete(v.PastClaims, claim.AllocationID)
v.setModesFromClaim(claim)
return nil
}
// claimWrite marks an allocation as using a volume as a writer
func (v *CSIVolume) claimWrite(claim *CSIVolumeClaim, alloc *Allocation) error {
if _, ok := v.WriteAllocs[claim.AllocationID]; ok {
return nil
}
if alloc == nil {
return fmt.Errorf("allocation missing: %s", claim.AllocationID)
}
if !v.WriteSchedulable() {
return fmt.Errorf("unschedulable")
}
if !v.WriteFreeClaims() {
// Check the blocking allocations to see if they belong to this job
for _, a := range v.WriteAllocs {
if a != nil && (a.Namespace != alloc.Namespace || a.JobID != alloc.JobID) {
return fmt.Errorf("volume max claim reached")
}
}
}
// Allocations are copy on write, so we want to keep the id but don't need the
// pointer. We'll get it from the db in denormalize.
v.WriteAllocs[alloc.ID] = nil
delete(v.ReadAllocs, alloc.ID)
v.WriteClaims[alloc.ID] = claim
delete(v.ReadClaims, alloc.ID)
delete(v.PastClaims, alloc.ID)
v.setModesFromClaim(claim)
return nil
}
// setModesFromClaim sets the volume AttachmentMode and AccessMode based on
// the first claim we make. Originally the volume AccessMode and
// AttachmentMode were set during registration, but this is incorrect once we
// started creating volumes ourselves. But we still want these values for CLI
// and UI status.
func (v *CSIVolume) setModesFromClaim(claim *CSIVolumeClaim) {
if v.AttachmentMode == CSIVolumeAttachmentModeUnknown {
v.AttachmentMode = claim.AttachmentMode
}
if v.AccessMode == CSIVolumeAccessModeUnknown {
v.AccessMode = claim.AccessMode
}
}
// claimRelease is called when the allocation has terminated and
// already stopped using the volume
func (v *CSIVolume) claimRelease(claim *CSIVolumeClaim) error {
if claim.State == CSIVolumeClaimStateReadyToFree {
delete(v.ReadAllocs, claim.AllocationID)
delete(v.WriteAllocs, claim.AllocationID)
delete(v.ReadClaims, claim.AllocationID)
delete(v.WriteClaims, claim.AllocationID)
delete(v.PastClaims, claim.AllocationID)
// remove AccessMode/AttachmentMode if this is the last claim
if len(v.ReadClaims) == 0 && len(v.WriteClaims) == 0 && len(v.PastClaims) == 0 {
v.AccessMode = CSIVolumeAccessModeUnknown
v.AttachmentMode = CSIVolumeAttachmentModeUnknown
}
} else {
v.PastClaims[claim.AllocationID] = claim
}
return nil
}
// Equal checks equality by value.
func (v *CSIVolume) Equal(o *CSIVolume) bool {
if v == nil || o == nil {
return v == o
}
// Omit the plugin health fields, their values are controlled by plugin jobs
if v.ID == o.ID &&
v.Namespace == o.Namespace &&
v.AccessMode == o.AccessMode &&
v.AttachmentMode == o.AttachmentMode &&
v.PluginID == o.PluginID {
// Setwise equality of topologies
var ok bool
for _, t := range v.Topologies {
ok = false
for _, u := range o.Topologies {
if t.Equal(u) {
ok = true
break
}
}
if !ok {
return false
}
}
return true
}
return false
}
// Validate validates the volume struct, returning all validation errors at once
func (v *CSIVolume) Validate() error {
errs := []string{}
if v.ID == "" {
errs = append(errs, "missing volume id")
}
if v.PluginID == "" {
errs = append(errs, "missing plugin id")
}
if v.Namespace == "" {
errs = append(errs, "missing namespace")
}
if v.SnapshotID != "" && v.CloneID != "" {
errs = append(errs, "only one of snapshot_id and clone_id is allowed")
}
if len(v.RequestedCapabilities) == 0 {
errs = append(errs, "must include at least one capability block")
}
// TODO: Volume Topologies are optional - We should check to see if the plugin
// the volume is being registered with requires them.
// var ok bool
// for _, t := range v.Topologies {
// if t != nil && len(t.Segments) > 0 {
// ok = true
// break
// }
// }
// if !ok {
// errs = append(errs, "missing topology")
// }
if len(errs) > 0 {
return fmt.Errorf("validation: %s", strings.Join(errs, ", "))
}
return nil
}
// Request and response wrappers
type CSIVolumeRegisterRequest struct {
Volumes []*CSIVolume
WriteRequest
}
type CSIVolumeRegisterResponse struct {
QueryMeta
}
type CSIVolumeDeregisterRequest struct {
VolumeIDs []string
Force bool
WriteRequest
}
type CSIVolumeDeregisterResponse struct {
QueryMeta
}
type CSIVolumeCreateRequest struct {
Volumes []*CSIVolume
WriteRequest
}
type CSIVolumeCreateResponse struct {
Volumes []*CSIVolume
QueryMeta
}
type CSIVolumeDeleteRequest struct {
VolumeIDs []string
WriteRequest
}
type CSIVolumeDeleteResponse struct {
QueryMeta
}
type CSIVolumeClaimMode int
const (
CSIVolumeClaimRead CSIVolumeClaimMode = iota
CSIVolumeClaimWrite
// for GC we don't have a specific claim to set the state on, so instead we
// create a new claim for GC in order to bump the ModifyIndex and trigger
// volumewatcher
CSIVolumeClaimGC
)
type CSIVolumeClaimBatchRequest struct {
Claims []CSIVolumeClaimRequest
}
type CSIVolumeClaimRequest struct {
VolumeID string
AllocationID string
NodeID string
ExternalNodeID string
Claim CSIVolumeClaimMode
AccessMode CSIVolumeAccessMode
AttachmentMode CSIVolumeAttachmentMode
State CSIVolumeClaimState
WriteRequest
}
func (req *CSIVolumeClaimRequest) ToClaim() *CSIVolumeClaim {
return &CSIVolumeClaim{
AllocationID: req.AllocationID,
NodeID: req.NodeID,
ExternalNodeID: req.ExternalNodeID,
Mode: req.Claim,
AccessMode: req.AccessMode,
AttachmentMode: req.AttachmentMode,
State: req.State,
}
}
type CSIVolumeClaimResponse struct {
// Opaque static publish properties of the volume. SP MAY use this
// field to ensure subsequent `NodeStageVolume` or `NodePublishVolume`
// calls calls have contextual information.
// The contents of this field SHALL be opaque to nomad.
// The contents of this field SHALL NOT be mutable.
// The contents of this field SHALL be safe for the nomad to cache.
// The contents of this field SHOULD NOT contain sensitive
// information.
// The contents of this field SHOULD NOT be used for uniquely
// identifying a volume. The `volume_id` alone SHOULD be sufficient to
// identify the volume.
// This field is OPTIONAL and when present MUST be passed to
// `NodeStageVolume` or `NodePublishVolume` calls on the client
PublishContext map[string]string
// Volume contains the expanded CSIVolume for use on the client after a Claim
// has completed.
Volume *CSIVolume
QueryMeta
}
type CSIVolumeListRequest struct {
PluginID string
NodeID string
QueryOptions
}
type CSIVolumeListResponse struct {
Volumes []*CSIVolListStub
QueryMeta
}
// CSIVolumeExternalListRequest is a request to a controller plugin to list
// all the volumes known to the the storage provider. This request is
// paginated by the plugin and accepts the QueryOptions.PerPage and
// QueryOptions.NextToken fields
type CSIVolumeExternalListRequest struct {
PluginID string
QueryOptions
}
type CSIVolumeExternalListResponse struct {
Volumes []*CSIVolumeExternalStub
NextToken string
QueryMeta
}
// CSIVolumeExternalStub is the storage provider's view of a volume, as
// returned from the controller plugin; all IDs are for external resources
type CSIVolumeExternalStub struct {
ExternalID string
CapacityBytes int64
VolumeContext map[string]string
CloneID string
SnapshotID string
// TODO: topology support
// AccessibleTopology []*Topology
PublishedExternalNodeIDs []string
IsAbnormal bool
Status string
}
type CSIVolumeGetRequest struct {
ID string
QueryOptions
}
type CSIVolumeGetResponse struct {
Volume *CSIVolume
QueryMeta
}
type CSIVolumeUnpublishRequest struct {
VolumeID string
Claim *CSIVolumeClaim
WriteRequest
}
type CSIVolumeUnpublishResponse struct {
QueryMeta
}
// CSISnapshot is the storage provider's view of a volume snapshot
type CSISnapshot struct {
// These fields map to those returned by the storage provider plugin
ID string // storage provider's ID
ExternalSourceVolumeID string // storage provider's ID for volume
SizeBytes int64
CreateTime int64
IsReady bool
// These fields are controlled by Nomad
SourceVolumeID string
PluginID string
// These field are only used during snapshot creation and will not be
// populated when the snapshot is returned
Name string
Secrets CSISecrets
Parameters map[string]string
}
type CSISnapshotCreateRequest struct {
Snapshots []*CSISnapshot
WriteRequest
}
type CSISnapshotCreateResponse struct {
Snapshots []*CSISnapshot
QueryMeta
}
type CSISnapshotDeleteRequest struct {
Snapshots []*CSISnapshot
WriteRequest
}
type CSISnapshotDeleteResponse struct {
QueryMeta
}
// CSISnapshotListRequest is a request to a controller plugin to list all the
// snapshot known to the the storage provider. This request is paginated by
// the plugin and accepts the QueryOptions.PerPage and QueryOptions.NextToken
// fields
type CSISnapshotListRequest struct {
PluginID string
Secrets CSISecrets
QueryOptions
}
type CSISnapshotListResponse struct {
Snapshots []*CSISnapshot
NextToken string
QueryMeta
}
// CSIPlugin collects fingerprint info context for the plugin for clients
type CSIPlugin struct {
ID string
Provider string // the vendor name from CSI GetPluginInfoResponse
Version string // the vendor verson from CSI GetPluginInfoResponse
ControllerRequired bool
// Map Node.IDs to fingerprint results, split by type. Monolith type plugins have
// both sets of fingerprinting results.
Controllers map[string]*CSIInfo
Nodes map[string]*CSIInfo
// Allocations are populated by denormalize to show running allocations
Allocations []*AllocListStub
// Jobs are populated to by job update to support expected counts and the UI
ControllerJobs JobDescriptions
NodeJobs JobDescriptions
// Cache the count of healthy plugins
ControllersHealthy int
ControllersExpected int
NodesHealthy int
NodesExpected int
CreateIndex uint64
ModifyIndex uint64
}
// NewCSIPlugin creates the plugin struct. No side-effects
func NewCSIPlugin(id string, index uint64) *CSIPlugin {
out := &CSIPlugin{
ID: id,
CreateIndex: index,
ModifyIndex: index,
}
out.newStructs()
return out
}
func (p *CSIPlugin) newStructs() {
p.Controllers = map[string]*CSIInfo{}
p.Nodes = map[string]*CSIInfo{}
p.ControllerJobs = make(JobDescriptions)
p.NodeJobs = make(JobDescriptions)
}
func (p *CSIPlugin) Copy() *CSIPlugin {
copy := *p
out := ©
out.newStructs()
for k, v := range p.Controllers {
out.Controllers[k] = v.Copy()
}
for k, v := range p.Nodes {
out.Nodes[k] = v.Copy()
}
for k, v := range p.ControllerJobs {
out.ControllerJobs[k] = v.Copy()
}
for k, v := range p.NodeJobs {
out.NodeJobs[k] = v.Copy()
}
return out
}
type CSIControllerCapability byte
const (
// CSIControllerSupportsCreateDelete indicates plugin support for
// CREATE_DELETE_VOLUME
CSIControllerSupportsCreateDelete CSIControllerCapability = 0
// CSIControllerSupportsAttachDetach is true when the controller
// implements the methods required to attach and detach volumes. If this
// is false Nomad should skip the controller attachment flow.
CSIControllerSupportsAttachDetach CSIControllerCapability = 1
// CSIControllerSupportsListVolumes is true when the controller implements
// the ListVolumes RPC. NOTE: This does not guarantee that attached nodes
// will be returned unless SupportsListVolumesAttachedNodes is also true.
CSIControllerSupportsListVolumes CSIControllerCapability = 2
// CSIControllerSupportsGetCapacity indicates plugin support for
// GET_CAPACITY