-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathvolume_ops.go
1435 lines (1260 loc) · 38.8 KB
/
volume_ops.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 sdk is the gRPC implementation of the SDK gRPC server
Copyright 2018 Portworx
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 sdk
import (
"context"
"fmt"
"math"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/libopenstorage/openstorage/api"
"github.com/libopenstorage/openstorage/pkg/auth"
"github.com/libopenstorage/openstorage/pkg/correlation"
policy "github.com/libopenstorage/openstorage/pkg/storagepolicy"
"github.com/libopenstorage/openstorage/pkg/util"
"github.com/libopenstorage/openstorage/volume"
"github.com/portworx/kvdb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// When create is called for an existing volume, this function is called to make sure
// the SDK only returns that the volume is ready when the status is UP
func (s *VolumeServer) waitForVolumeReady(ctx context.Context, id string) (*api.Volume, error) {
var v *api.Volume
minTimeout := 1 * time.Second
maxTimeout := 60 * time.Minute
defaultTimeout := 5 * time.Minute
logrus.Infof("Waiting for volume %s to become available", id)
e := util.WaitForWithContext(
ctx,
minTimeout, maxTimeout, defaultTimeout, // timeouts
5*time.Second, // period
func() (bool, error) {
var err error
// Get the latest status from the volume
v, err = util.VolumeFromName(correlation.TODO(), s.driver(ctx), id)
if err != nil {
return false, status.Errorf(codes.Internal, err.Error())
}
// Check if the volume is ready
if v.GetStatus() == api.VolumeStatus_VOLUME_STATUS_UP && v.GetState() != api.VolumeState_VOLUME_STATE_ATTACHED {
return false, nil
}
// The volume has entered a state of that might not recover from hence the status might be down and will be in pending state forever.
if v.GetStatus() == api.VolumeStatus_VOLUME_STATUS_DOWN && v.GetState() != api.VolumeState_VOLUME_STATE_PENDING {
return false, status.Errorf(codes.Internal, "Volume id %s got created but due to Internal issues is in Down State. The Volume creation needs to be retried.", v.GetId())
}
// Continue waiting
return true, nil
})
return v, e
}
func (s *VolumeServer) waitForVolumeRemoved(ctx context.Context, id string) error {
minTimeout := 1 * time.Second
maxTimeout := 10 * time.Minute
defaultTimeout := 5 * time.Minute
logrus.Infof("Waiting for volume %s to be removed", id)
return util.WaitForWithContext(
ctx,
minTimeout, maxTimeout, defaultTimeout, // timeouts
250*time.Millisecond, // period
func() (bool, error) {
// Get the latest status from the volume
if _, err := util.VolumeFromName(correlation.TODO(), s.driver(ctx), id); err != nil {
// Removed
return false, nil
}
// Continue waiting
return true, nil
})
}
func (s *VolumeServer) create(
ctx context.Context,
locator *api.VolumeLocator,
source *api.Source,
spec *api.VolumeSpec,
additionalCloneLabels map[string]string,
) (string, error) {
// Check if the volume has already been created or is in process of creation
volName := locator.GetName()
v, err := util.VolumeFromName(ctx, s.driver(ctx), volName)
// If the volume is still there but it is being delete, then wait until it is removed
if err == nil && v.GetState() == api.VolumeState_VOLUME_STATE_DELETED {
if err = s.waitForVolumeRemoved(ctx, volName); err != nil {
return "", status.Errorf(codes.Internal, "Volume with same name %s is in the process of being deleted. Timed out waiting for deletion to complete: %v", volName, err)
}
// If the volume is there but it is not being deleted then just return the current id
} else if err == nil {
// Check ownership
if !v.IsPermitted(ctx, api.Ownership_Admin) {
return "", status.Errorf(codes.PermissionDenied, "Volume %s already exists and is owned by another user", volName)
}
// Wait until ready
v, err = s.waitForVolumeReady(ctx, volName)
if err != nil {
return "", status.Errorf(codes.Internal, "Timed out waiting for volume %s to be in ready state: %v", volName, err)
}
// Check the requested arguments match that of the existing volume
if v.GetSpec().GetSize() != spec.GetSize() {
return "", status.Errorf(
codes.AlreadyExists,
"Existing volume has a size of %v which differs from requested size of %v",
v.GetSpec().GetSize(),
spec.Size)
}
if v.GetSpec().GetShared() != spec.GetShared() {
return "", status.Errorf(
codes.AlreadyExists,
"Existing volume has shared=%v while request is asking for shared=%v",
v.GetSpec().GetShared(),
spec.GetShared())
}
if v.GetSource().GetParent() != source.GetParent() {
return "", status.Error(codes.AlreadyExists, "Existing volume has conflicting parent value")
}
// Return information on existing volume
return v.GetId(), nil
}
// Check if the caller is asking to create a snapshot or for a new volume
var id string
if len(source.GetParent()) != 0 {
// Get parent volume information
parent, err := util.VolumeFromName(correlation.TODO(), s.driver(ctx), source.Parent)
if err != nil {
return "", status.Errorf(
codes.NotFound,
"unable to get parent volume information: %s",
err.Error())
}
// Check ownership
// Snapshots just need read access
if !parent.IsPermitted(ctx, api.Ownership_Read) {
return "", status.Errorf(codes.PermissionDenied, "Access denied to volume %s", parent.GetId())
}
// Create a snapshot from the parent
id, err = s.driver(ctx).Snapshot(ctx, parent.GetId(), false, &api.VolumeLocator{
Name: volName,
VolumeLabels: locator.GetVolumeLabels(),
}, false)
if err != nil {
if err == kvdb.ErrNotFound {
return "", status.Errorf(
codes.Aborted,
"unable to create snapshot with parent ID %s: %v",
parent.GetId(),
err.Error())
}
return "", status.Errorf(
codes.Aborted,
"unable to create snapshot: %s",
err.Error())
}
// If this is a different owner, make adjust the clone to this owner
clone, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{
VolumeId: id,
})
if err != nil {
return "", err
}
// Generate update request based on input to create w/ parentID
updateReq := &api.SdkVolumeUpdateRequest{
VolumeId: id,
}
newOwnership, ownershipUpdateNeeded := clone.Volume.Spec.GetCloneCreatorOwnership(ctx)
if ownershipUpdateNeeded {
// Set no authentication so that we can override the ownership.
// TODO: this should be fixed to only remove auth metadata
ctx = context.Background()
updateReq.Spec = &api.VolumeSpecUpdate{
Ownership: newOwnership,
}
}
additionalLabelsNeeded := len(additionalCloneLabels) > 0
if additionalLabelsNeeded {
mergedLabels := make(map[string]string)
clonedLabels := make(map[string]string)
// Cloned volume may not have locator or volume.
// This is unlikely, but we'll avoid a panic here.
if clone.GetVolume() != nil && clone.GetVolume().GetLocator() != nil {
clonedLabels = clone.GetVolume().GetLocator().GetVolumeLabels()
}
// add existing labels first from our earlier inspect
for k, v := range clonedLabels {
mergedLabels[k] = v
}
// override existing labels if there's a conflict
for k, v := range additionalCloneLabels {
mergedLabels[k] = v
}
updateReq.Labels = mergedLabels
}
// Only update if required.
if ownershipUpdateNeeded || additionalLabelsNeeded {
_, err = s.Update(ctx, updateReq)
if err != nil {
return "", err
}
}
} else {
// New volume, set ownership
spec.Ownership = api.OwnershipSetUsernameFromContext(ctx, spec.Ownership)
// Create the volume
id, err = s.driver(ctx).Create(ctx, locator, source, spec)
if err != nil {
if spec.IsPureVolume() &&
strings.Contains(err.Error(), "no storage backends were able to meet the request specification") {
return "", status.Errorf(
codes.ResourceExhausted,
"Failed to create volume: %v",
err.Error())
}
return "", status.Errorf(
codes.Internal,
"Failed to create volume: %v",
err.Error())
}
}
return id, nil
}
// Create creates a new volume
func (s *VolumeServer) Create(
ctx context.Context,
req *api.SdkVolumeCreateRequest,
) (*api.SdkVolumeCreateResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
if len(req.GetName()) == 0 {
return nil, status.Error(
codes.InvalidArgument,
"Must supply a unique name")
} else if req.GetSpec() == nil {
return nil, status.Error(
codes.InvalidArgument,
"Must supply spec object")
}
locator := &api.VolumeLocator{
Name: req.GetName(),
VolumeLabels: req.GetLabels(),
}
source := &api.Source{}
// Validate/Update given spec according to default storage policy set
// In case policy is not set, should fall back to default way
// of creating volume
spec, err := GetDefaultVolSpecs(ctx, req.GetSpec(), false)
if err != nil {
return nil, err
}
// Copy any labels from the spec to the locator
locator = locator.MergeVolumeSpecLabels(spec)
// Convert node IP to ID if necessary for API calls
if err := s.updateReplicaSpecNodeIPstoIds(spec.GetReplicaSet()); err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get replicat set information: %v", err)
}
// Create volume
id, err := s.create(ctx, locator, source, spec, nil)
if err != nil {
return nil, err
}
s.auditLog(ctx, "volume.create", "Volume %s created", id)
return &api.SdkVolumeCreateResponse{
VolumeId: id,
}, nil
}
// Clone creates a new volume from an existing volume
func (s *VolumeServer) Clone(
ctx context.Context,
req *api.SdkVolumeCloneRequest,
) (*api.SdkVolumeCloneResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
if len(req.GetName()) == 0 {
return nil, status.Error(
codes.InvalidArgument,
"Must supply a uniqe name")
} else if len(req.GetParentId()) == 0 {
return nil, status.Error(
codes.InvalidArgument,
"Must parent volume id")
}
locator := &api.VolumeLocator{
Name: req.GetName(),
VolumeLabels: req.GetAdditionalLabels(),
}
source := &api.Source{
Parent: req.GetParentId(),
}
// Get spec. This also checks if the parend id exists.
// This will also check for Ownership_Read access.
parentVol, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{
VolumeId: req.GetParentId(),
})
if err != nil {
return nil, err
}
// Create the clone
id, err := s.create(ctx, locator, source, parentVol.GetVolume().GetSpec(), req.GetAdditionalLabels())
if err != nil {
return nil, err
}
s.auditLog(ctx, "volume.clone", "Volume %s created from %s", id, req.GetParentId())
return &api.SdkVolumeCloneResponse{
VolumeId: id,
}, nil
}
// Delete deletes a volume
func (s *VolumeServer) Delete(
ctx context.Context,
req *api.SdkVolumeDeleteRequest,
) (*api.SdkVolumeDeleteResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Must supply volume id")
}
// If the volume is not found, return OK to be idempotent
// This checks access rights also
resp, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{
VolumeId: req.GetVolumeId(),
})
if err != nil {
if IsErrorNotFound(err) {
return &api.SdkVolumeDeleteResponse{}, nil
}
return nil, err
}
vol := resp.GetVolume()
// Only the owner or the admin can delete
if !vol.IsPermitted(ctx, api.Ownership_Admin) {
return nil, status.Errorf(codes.PermissionDenied, "Cannot delete volume %v", vol.GetId())
}
// Delete the volume
err = s.driver(ctx).Delete(ctx, req.GetVolumeId())
if err != nil {
return nil, status.Errorf(
codes.Internal,
"Failed to delete volume %s: %v",
req.GetVolumeId(),
err.Error())
}
s.auditLog(ctx, "volume.delete", "Volume %s deleted", req.GetVolumeId())
return &api.SdkVolumeDeleteResponse{}, nil
}
// InspectWithFilters is a helper function returning information about volumes which match a filter
func (s *VolumeServer) InspectWithFilters(
ctx context.Context,
req *api.SdkVolumeInspectWithFiltersRequest,
) (*api.SdkVolumeInspectWithFiltersResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
var locator *api.VolumeLocator
if len(req.GetName()) != 0 ||
len(req.GetLabels()) != 0 ||
req.GetOwnership() != nil {
locator = &api.VolumeLocator{
Name: req.GetName(),
VolumeLabels: req.GetLabels(),
Ownership: req.GetOwnership(),
}
}
enumVols, err := s.driver(ctx).Enumerate(locator, nil)
if err != nil {
return nil, status.Errorf(
codes.Internal,
"Failed to enumerate volumes: %v",
err.Error())
}
vols := make([]*api.SdkVolumeInspectResponse, 0, len(enumVols))
for _, vol := range enumVols {
// Check access
if vol.IsPermitted(ctx, api.Ownership_Read) {
// Check if the caller wants more information
if req.GetOptions().GetDeep() {
resp, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{
VolumeId: vol.GetId(),
Options: req.GetOptions(),
})
if IsErrorNotFound(err) {
continue
} else if err != nil {
return nil, err
}
vols = append(vols, resp)
} else {
// Caller does not require a deep inspect
// Add the object now
vols = append(vols, &api.SdkVolumeInspectResponse{
Volume: vol,
Name: vol.GetLocator().GetName(),
Labels: vol.GetLocator().GetVolumeLabels(),
})
}
}
}
return &api.SdkVolumeInspectWithFiltersResponse{
Volumes: vols,
}, nil
}
// Inspect returns information about a volume
func (s *VolumeServer) Inspect(
ctx context.Context,
req *api.SdkVolumeInspectRequest,
) (*api.SdkVolumeInspectResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Must supply volume id")
}
var v *api.Volume
if !req.GetOptions().GetDeep() {
vols, err := s.driver(ctx).Enumerate(&api.VolumeLocator{
VolumeIds: []string{req.GetVolumeId()},
}, nil)
if err != nil {
return nil, status.Errorf(
codes.Internal,
"Failed to inspect volume %s: %v",
req.GetVolumeId(), err)
}
if len(vols) == 0 {
return nil, status.Errorf(
codes.NotFound,
"Volume id %s not found",
req.GetVolumeId())
}
v = vols[0]
} else {
vols, err := s.driver(ctx).Inspect(correlation.TODO(), []string{req.GetVolumeId()})
if err == kvdb.ErrNotFound || (err == nil && len(vols) == 0) {
return nil, status.Errorf(
codes.NotFound,
"Volume id %s not found",
req.GetVolumeId())
} else if err != nil {
return nil, status.Errorf(
codes.Internal,
"Failed to inspect volume %s: %v",
req.GetVolumeId(), err)
}
v = vols[0]
}
// Check ownership
if !v.IsPermitted(ctx, api.Ownership_Read) {
return nil, status.Errorf(codes.PermissionDenied, "Access denied to volume %s", v.GetId())
}
return &api.SdkVolumeInspectResponse{
Volume: v,
Name: v.GetLocator().GetName(),
Labels: v.GetLocator().GetVolumeLabels(),
}, nil
}
// Enumerate returns a list of volumes
func (s *VolumeServer) Enumerate(
ctx context.Context,
req *api.SdkVolumeEnumerateRequest,
) (*api.SdkVolumeEnumerateResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
resp, err := s.EnumerateWithFilters(
ctx,
&api.SdkVolumeEnumerateWithFiltersRequest{},
)
if err != nil {
return nil, err
}
return &api.SdkVolumeEnumerateResponse{
VolumeIds: resp.GetVolumeIds(),
}, nil
}
// EnumerateWithFilters returns a list of volumes for the provided filters
func (s *VolumeServer) EnumerateWithFilters(
ctx context.Context,
req *api.SdkVolumeEnumerateWithFiltersRequest,
) (*api.SdkVolumeEnumerateWithFiltersResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
var locator *api.VolumeLocator
if len(req.GetName()) != 0 ||
len(req.GetLabels()) != 0 ||
req.GetOwnership() != nil {
locator = &api.VolumeLocator{
Name: req.GetName(),
VolumeLabels: req.GetLabels(),
Ownership: req.GetOwnership(),
}
}
vols, err := s.driver(ctx).Enumerate(locator, nil)
if err != nil {
return nil, status.Errorf(
codes.Internal,
"Failed to enumerate volumes: %v",
err.Error())
}
ids := make([]string, 0)
for _, vol := range vols {
// Check access
if vol.IsPermitted(ctx, api.Ownership_Read) {
ids = append(ids, vol.GetId())
}
}
return &api.SdkVolumeEnumerateWithFiltersResponse{
VolumeIds: ids,
}, nil
}
// mask all unmodified attributes of the spec before calling Set/Update
func maskUnModified(spec *api.VolumeSpec, req *api.VolumeSpecUpdate) {
// spec has been updated fully for all attributes inclusive of requested attr.
// But it is possible for the current state to be stale and so requesting update with
// all attributes may have a side affect.
// For ex: a size update of the volume, could result in a ha-update
// So clear other attributes, so as not to cause side effect while applying
// the update.
// All state based conditionals are set only for requested attribs.
// boolean based state can still be stale, but the chances are low, because
// they are immediately handled within px, unlike HA updates which needs acknowledgement
// from px-storage to complete processing.
// ScanPolicy
if req.GetScanPolicy() == nil {
spec.ScanPolicy = nil
}
if req.GetSnapshotIntervalOpt() == nil {
spec.SnapshotInterval = math.MaxUint32
}
if req.GetSnapshotScheduleOpt() == nil {
spec.SnapshotSchedule = ""
}
// HA Level
if req.GetHaLevelOpt() == nil {
spec.HaLevel = 0
}
/*
* immediately applied, hence never stale.
* can carry part of the spec always safely.
*/
// if req.GetSizeOpt() == nil {
// spec.Size = 0
// }
if req.GetCosOpt() == nil {
spec.Cos = api.CosType_NONE
}
if req.GetExportSpec() == nil {
spec.ExportSpec = nil
}
if req.GetMountOptSpec() == nil {
spec.MountOptions = nil
}
if req.GetSharedv4MountOptSpec() == nil {
spec.Sharedv4MountOptions = nil
}
if req.GetSharedv4ServiceSpec() == nil {
spec.Sharedv4ServiceSpec = nil
}
if req.GetSharedv4Spec() == nil {
spec.Sharedv4Spec = nil
}
if req.GetGroupOpt() == nil {
spec.Group = nil
}
if req.GetIoStrategy() == nil {
spec.IoStrategy = nil
}
}
// Update allows the caller to change values in the volume specification
func (s *VolumeServer) Update(
ctx context.Context,
req *api.SdkVolumeUpdateRequest,
) (*api.SdkVolumeUpdateResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Must supply volume id")
}
// Get current state
// This checks for Read access in ownership
resp, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{
VolumeId: req.GetVolumeId(),
})
if err != nil {
return nil, err
}
// Check if the caller can update the volume
if !resp.GetVolume().IsPermitted(ctx, api.Ownership_Write) {
return nil, status.Errorf(codes.PermissionDenied, "Cannot update volume")
}
// Merge specs
spec := s.mergeVolumeSpecs(resp.GetVolume().GetSpec(), req.GetSpec())
// Update Ownership... carefully
// First point to the original ownership
spec.Ownership = resp.GetVolume().GetSpec().GetOwnership()
// Check if we have been provided an update to the ownership
if req.GetSpec().GetOwnership() != nil {
if spec.Ownership == nil {
spec.Ownership = &api.Ownership{}
}
user, _ := auth.NewUserInfoFromContext(ctx)
if err := spec.Ownership.Update(req.GetSpec().GetOwnership(), user); err != nil {
return nil, err
}
}
// Check if labels have been updated
var locator *api.VolumeLocator
if len(req.GetLabels()) != 0 {
locator = &api.VolumeLocator{VolumeLabels: req.GetLabels()}
}
// Validate/Update given spec according to default storage policy set
// to make sure if update does not violates default policy
updatedSpec, err := GetDefaultVolSpecs(ctx, spec, true)
if err != nil {
return nil, err
}
// avoid side effect while applying with stale config by masking
// other parts of the spec.
maskUnModified(updatedSpec, req.GetSpec())
// Send to driver
if err := s.driver(ctx).Set(ctx, req.GetVolumeId(), locator, updatedSpec); err != nil {
return nil, status.Errorf(codes.Internal, "Failed to update volume: %v", err)
}
s.auditLog(ctx, "volume.update", "Volume %s updated", req.GetVolumeId())
return &api.SdkVolumeUpdateResponse{}, nil
}
// Stats returns volume statistics
func (s *VolumeServer) Stats(
ctx context.Context,
req *api.SdkVolumeStatsRequest,
) (*api.SdkVolumeStatsResponse, error) {
if s.cluster() == nil || s.driver(ctx) == nil {
return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
}
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Must supply volume id")
}
// Get access rights
if err := s.checkAccessForVolumeId(ctx, req.GetVolumeId(), api.Ownership_Read); err != nil {
return nil, err
}
stats, err := s.driver(ctx).Stats(ctx, req.GetVolumeId(), !req.GetNotCumulative())
if err != nil {
return nil, status.Errorf(
codes.Internal,
"Failed to obtain stats for volume %s: %v",
req.GetVolumeId(),
err.Error())
}
return &api.SdkVolumeStatsResponse{
Stats: stats,
}, nil
}
func (s *VolumeServer) VolumeBytesUsedByNode(
ctx context.Context,
req *api.SdkVolumeBytesUsedRequest,
) (*api.SdkVolumeBytesUsedResponse, error) {
return nil, status.Errorf(
codes.Unimplemented,
"Failed to obtain volume utilization on node %s: %v",
req.GetNodeId(),
volume.ErrNotSupported.Error())
}
func (s *VolumeServer) CapacityUsage(
ctx context.Context,
req *api.SdkVolumeCapacityUsageRequest,
) (*api.SdkVolumeCapacityUsageResponse, error) {
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Must supply volume id")
}
// Get access rights
if err := s.checkAccessForVolumeId(ctx, req.GetVolumeId(), api.Ownership_Read); err != nil {
return nil, err
}
dResp, err := s.driver(ctx).CapacityUsage(req.GetVolumeId())
if err != nil {
return nil, status.Errorf(
codes.Internal,
"Failed to obtain stats for volume %s: %v",
req.GetVolumeId(),
err.Error())
}
resp := &api.SdkVolumeCapacityUsageResponse{}
resp.CapacityUsageInfo = &api.CapacityUsageInfo{}
resp.CapacityUsageInfo.ExclusiveBytes = dResp.CapacityUsageInfo.ExclusiveBytes
resp.CapacityUsageInfo.SharedBytes = dResp.CapacityUsageInfo.SharedBytes
resp.CapacityUsageInfo.TotalBytes = dResp.CapacityUsageInfo.TotalBytes
if dResp.Error != nil {
if dResp.Error == volume.ErrAborted {
return resp, status.Errorf(
codes.Aborted,
"Failed to obtain stats for volume %s: %v",
req.GetVolumeId(),
volume.ErrAborted.Error())
} else if dResp.Error == volume.ErrNotSupported {
return resp, status.Errorf(
codes.Unimplemented,
"Failed to obtain stats for volume %s: %v",
req.GetVolumeId(),
volume.ErrNotSupported.Error())
}
}
return resp, nil
}
func (s *VolumeServer) mergeVolumeSpecs(vol *api.VolumeSpec, req *api.VolumeSpecUpdate) *api.VolumeSpec {
spec := &api.VolumeSpec{}
spec.Shared = setSpecBool(vol.GetShared(), req.GetShared(), req.GetSharedOpt())
spec.Sharedv4 = setSpecBool(vol.GetSharedv4(), req.GetSharedv4(), req.GetSharedv4Opt())
spec.Sticky = setSpecBool(vol.GetSticky(), req.GetSticky(), req.GetStickyOpt())
spec.Journal = setSpecBool(vol.GetJournal(), req.GetJournal(), req.GetJournalOpt())
spec.Nodiscard = setSpecBool(vol.GetNodiscard(), req.GetNodiscard(), req.GetNodiscardOpt())
// fastpath extensions
if req.GetFastpathOpt() != nil {
spec.FpPreference = req.GetFastpath()
} else {
spec.FpPreference = vol.GetFpPreference()
}
if req.GetIoStrategy() != nil {
spec.IoStrategy = req.GetIoStrategy()
} else {
spec.IoStrategy = vol.GetIoStrategy()
}
// Cos
if req.GetCosOpt() != nil {
spec.Cos = req.GetCos()
} else {
spec.Cos = vol.GetCos()
}
// Passphrase
if req.GetPassphraseOpt() != nil {
spec.Passphrase = req.GetPassphrase()
} else {
spec.Passphrase = vol.GetPassphrase()
}
// Snapshot schedule as a string
if req.GetSnapshotScheduleOpt() != nil {
spec.SnapshotSchedule = req.GetSnapshotSchedule()
} else {
spec.SnapshotSchedule = vol.GetSnapshotSchedule()
}
// Scale
if req.GetScaleOpt() != nil {
spec.Scale = req.GetScale()
} else {
spec.Scale = vol.GetScale()
}
// Snapshot Interval
if req.GetSnapshotIntervalOpt() != nil {
spec.SnapshotInterval = req.GetSnapshotInterval()
} else {
spec.SnapshotInterval = vol.GetSnapshotInterval()
}
// Io Profile
if req.GetIoProfileOpt() != nil {
spec.IoProfile = req.GetIoProfile()
} else {
spec.IoProfile = vol.GetIoProfile()
}
// GroupID
if req.GetGroupOpt() != nil {
spec.Group = req.GetGroup()
} else {
spec.Group = vol.GetGroup()
}
// Size
if req.GetSizeOpt() != nil {
spec.Size = req.GetSize()
} else {
spec.Size = vol.GetSize()
}
// ReplicaSet
if req.GetReplicaSet() != nil {
spec.ReplicaSet = req.GetReplicaSet()
} else {
spec.ReplicaSet = vol.GetReplicaSet()
}
// HA Level
if req.GetHaLevelOpt() != nil {
spec.HaLevel = req.GetHaLevel()
} else {
spec.HaLevel = vol.GetHaLevel()
}
// Queue depth
if req.GetQueueDepthOpt() != nil {
spec.QueueDepth = req.GetQueueDepth()
} else {
spec.QueueDepth = vol.GetQueueDepth()
}
// ExportSpec
if req.GetExportSpec() != nil {
spec.ExportSpec = req.GetExportSpec()
} else {
spec.ExportSpec = vol.GetExportSpec()
}
// Xattr
if req.GetXattrOpt() != nil {
spec.Xattr = req.GetXattr()
} else {
spec.Xattr = vol.GetXattr()
}
// ScanPolicy
if req.GetScanPolicy() != nil {
spec.ScanPolicy = req.GetScanPolicy()
} else {
spec.ScanPolicy = vol.GetScanPolicy()
}
// MountOptions
if req.GetMountOptSpec() != nil {
spec.MountOptions = req.GetMountOptSpec()
} else {
spec.MountOptions = vol.GetMountOptions()
}
// Sharedv4MountOptions
if req.GetSharedv4MountOptSpec() != nil {
spec.Sharedv4MountOptions = req.GetSharedv4MountOptSpec()
} else {
spec.Sharedv4MountOptions = vol.GetSharedv4MountOptions()
}
// ProxyWrite
spec.ProxyWrite = setSpecBool(vol.GetProxyWrite(), req.GetProxyWrite(), req.GetProxyWriteOpt())
// ProxySpec
if req.GetProxySpec() != nil {
spec.ProxySpec = req.GetProxySpec()
} else {
spec.ProxySpec = vol.GetProxySpec()
}
// Pure NFS Endpoint
if vol != nil && vol.ProxySpec != nil && vol.ProxySpec.PureFileSpec != nil {
// if volume to be updated is Pure File Direct Access volume
if spec.ProxySpec == nil {
spec.ProxySpec = &api.ProxySpec{
PureFileSpec: &api.PureFileSpec{},
}
}
if req.GetPureNfsEndpoint() != "" {
spec.ProxySpec.PureFileSpec.NfsEndpoint = req.GetPureNfsEndpoint()
} else {
spec.ProxySpec.PureFileSpec.NfsEndpoint = vol.ProxySpec.PureFileSpec.GetNfsEndpoint()
}
}
// Sharedv4ServiceSpec
if req.GetSharedv4ServiceSpec() != nil {
spec.Sharedv4ServiceSpec = req.GetSharedv4ServiceSpec()
} else {
spec.Sharedv4ServiceSpec = vol.GetSharedv4ServiceSpec()
}
// Sharedv4Spec
if req.GetSharedv4Spec() != nil {
spec.Sharedv4Spec = req.GetSharedv4Spec()
} else {
spec.Sharedv4Spec = vol.GetSharedv4Spec()
}