-
Notifications
You must be signed in to change notification settings - Fork 26
/
linstor.go
2071 lines (1657 loc) · 59.9 KB
/
linstor.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 client
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
lapiconsts "github.com/LINBIT/golinstor"
lapi "github.com/LINBIT/golinstor/client"
"github.com/LINBIT/golinstor/devicelayerkind"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/haySwim/data"
"github.com/pborman/uuid"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/types/known/timestamppb"
"k8s.io/mount-utils"
utilexec "k8s.io/utils/exec"
"github.com/piraeusdatastore/linstor-csi/pkg/linstor"
lc "github.com/piraeusdatastore/linstor-csi/pkg/linstor/highlevelclient"
"github.com/piraeusdatastore/linstor-csi/pkg/linstor/util"
"github.com/piraeusdatastore/linstor-csi/pkg/slice"
"github.com/piraeusdatastore/linstor-csi/pkg/topology"
"github.com/piraeusdatastore/linstor-csi/pkg/topology/scheduler"
"github.com/piraeusdatastore/linstor-csi/pkg/topology/scheduler/autoplace"
"github.com/piraeusdatastore/linstor-csi/pkg/topology/scheduler/autoplacetopology"
"github.com/piraeusdatastore/linstor-csi/pkg/topology/scheduler/balancer"
"github.com/piraeusdatastore/linstor-csi/pkg/topology/scheduler/followtopology"
"github.com/piraeusdatastore/linstor-csi/pkg/topology/scheduler/manual"
"github.com/piraeusdatastore/linstor-csi/pkg/volume"
)
// Linstor is a high-level client for use with CSI.
type Linstor struct {
log *logrus.Entry
fallbackPrefix string
client *lc.HighLevelClient
mounter *mount.SafeFormatAndMount
}
// NewLinstor returns a high-level linstor client for CSI applications to interact with
// By default, it will try to connect with localhost:3370.
func NewLinstor(options ...func(*Linstor) error) (*Linstor, error) {
// Set up zero values.
c, err := lc.NewHighLevelClient()
if err != nil {
return nil, err
}
l := &Linstor{
fallbackPrefix: "csi-",
log: logrus.NewEntry(logrus.New()),
client: c,
}
// run all option functions.
for _, opt := range options {
err := opt(l)
if err != nil {
return nil, err
}
}
// Add in fields that may have been configured above.
l.log = l.log.WithFields(logrus.Fields{
"linstorCSIComponent": "client",
})
l.mounter = &mount.SafeFormatAndMount{
Interface: mount.New("/bin/mount"),
Exec: utilexec.New(),
}
l.log.WithFields(logrus.Fields{
"APIClient": fmt.Sprintf("%+v", l.client),
"highLevelClient": fmt.Sprintf("%+v", l),
}).Debug("generated new linstor client")
return l, nil
}
// APIClient the configured LINSTOR API client that will be used to communicate
// with the LINSTOR cluster.
func APIClient(c *lc.HighLevelClient) func(*Linstor) error {
return func(l *Linstor) error {
cp := l.client
*cp = *c
return nil
}
}
// LogOut sets the Linstor client to write logs to the provided io.Writer
// instead of discarding logs.
func LogOut(out io.Writer) func(*Linstor) error {
return func(l *Linstor) error {
l.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(*Linstor) error {
return func(l *Linstor) error {
l.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(*Linstor) error {
return func(l *Linstor) error {
level, err := logrus.ParseLevel(s)
if err != nil {
return fmt.Errorf("unable to use %s as a logging level: %v", s, err)
}
l.log.Logger.SetLevel(level)
// Report function names on debug
if level == logrus.DebugLevel {
l.log.Logger.SetReportCaller(true)
}
return nil
}
}
// ListAll returns a sorted list of pointers to volume.Info. Only the LINSTOR
// volumes that can be serialized into a volume.Info are included.
func (s *Linstor) ListAll(ctx context.Context) ([]*volume.Info, error) {
vols := make([]*volume.Info, 0)
resDefs, err := s.client.ResourceDefinitions.GetAll(ctx, lapi.RDGetAllRequest{WithVolumeDefinitions: true})
if err != nil {
return vols, nil
}
for _, rd := range resDefs {
vol := s.resourceDefinitionToVolume(rd)
if vol != nil {
vols = append(vols, vol)
}
}
sort.Slice(vols, func(i, j int) bool {
return vols[i].ID < vols[j].ID
})
return vols, nil
}
// AllocationSizeKiB returns LINSTOR's smallest possible number of KiB that can
// satisfy the requiredBytes.
func (s *Linstor) AllocationSizeKiB(requiredBytes, limitBytes int64) (int64, error) {
requestedSize := data.ByteSize(requiredBytes)
minVolumeSize := data.ByteSize(4096)
maxVolumeSize := data.ByteSize(limitBytes)
unlimited := maxVolumeSize == 0
if minVolumeSize > maxVolumeSize && !unlimited {
return 0, fmt.Errorf("LINSTOR's minimum volume size exceeds the maximum size limit of the requested volume")
}
if requestedSize < minVolumeSize {
requestedSize = minVolumeSize
}
// make sure there are enough KiBs to fit the required number of bytes,
// e.g. 1025 bytes require 2 KiB worth of space to be allocated.
volumeSize := data.NewKibiByte(data.NewKibiByte(requestedSize).InclusiveBytes())
limit := data.NewByte(maxVolumeSize)
if volumeSize.InclusiveBytes() > limit.InclusiveBytes() && !unlimited {
return int64(volumeSize.Value()),
fmt.Errorf("got request for %d bytes of storage, but needed to allocate %d more bytes than the %d byte limit",
requiredBytes, int64(volumeSize.To(data.B)-limit.To(data.B)), int64(limit.To(data.B)))
}
return int64(volumeSize.Value()), nil
}
// resourceDefinitionToVolume reads the serialized volume info on the lapi.ResourceDefinitionWithVolumeDefinition
// and constructs a pointer to a volume.Info from it.
func (s *Linstor) resourceDefinitionToVolume(resDef lapi.ResourceDefinitionWithVolumeDefinition) *volume.Info {
if len(resDef.VolumeDefinitions) != 1 {
// Not a CSI enabled volume
return nil
}
fsType := resDef.Props[lapiconsts.NamespcFilesystem+"/"+lapiconsts.KeyFsType]
props := make(map[string]string)
for k, v := range resDef.Props {
if strings.HasPrefix(k, lapiconsts.NamespcAuxiliary+"/") {
props[k] = v
}
}
return &volume.Info{
ID: resDef.Name,
SizeBytes: int64(resDef.VolumeDefinitions[0].SizeKib << 10),
ResourceGroup: resDef.ResourceGroupName,
FsType: fsType,
Properties: props,
UseQuorum: resDef.Props["DrbdOptions/Resource/quorum"] != "off",
}
}
// FindByID retrieves a volume.Info that has an id that matches the CSI volume
// id. Matches the LINSTOR resource name.
func (s *Linstor) FindByID(ctx context.Context, id string) (*volume.Info, error) {
s.log.WithFields(logrus.Fields{
"csiVolumeID": id,
}).Debug("looking up resource by CSI volume id")
res, err := s.client.ResourceDefinitions.Get(ctx, id)
if err != nil {
return nil, nil404(err)
}
vds, err := s.client.ResourceDefinitions.GetVolumeDefinitions(ctx, id)
if err != nil {
return nil, nil404(err)
}
return s.resourceDefinitionToVolume(lapi.ResourceDefinitionWithVolumeDefinition{
ResourceDefinition: res,
VolumeDefinitions: vds,
}), nil
}
func (s *Linstor) CompatibleVolumeId(name, pvcNamespace, pvcName string) string {
if pvcNamespace != "" && pvcName != "" {
s.log.Debug("try creating valid volume name based on PVC")
generatedName := fmt.Sprintf("%s-%s", pvcNamespace, pvcName)
if validResourceName(generatedName) == nil {
return generatedName
}
}
invalid := validResourceName(name)
if invalid == nil {
return name
}
s.log.WithField("reason", invalid).Debug("volume name is invalid, will generate fallback")
uuidv5 := uuid.NewSHA1([]byte(linstor.DriverName), []byte(name))
return fmt.Sprintf("vol-%s", uuidv5.String())
}
// Create creates the resource definition, volume definition, and assigns the
// resulting resource to LINSTOR nodes.
func (s *Linstor) Create(ctx context.Context, vol *volume.Info, params *volume.Parameters, topologies *csi.TopologyRequirement) error {
logger := s.log.WithFields(logrus.Fields{
"volume": fmt.Sprintf("%+v", vol),
})
logger.Debug("reconcile resource group from storage class")
rGroup, err := s.reconcileResourceGroup(ctx, params)
if err != nil {
logger.Debugf("reconcile resource group failed: %v", err)
return err
}
logger.Debug("reconcile resource definition for volume")
_, err = s.reconcileResourceDefinition(ctx, vol.ID, rGroup.Name, vol.FsType, params.FSOpts)
if err != nil {
logger.Debugf("reconcile resource definition failed: %v", err)
return err
}
logger.Debug("reconcile volume definition for volume")
_, err = s.reconcileVolumeDefinition(ctx, vol)
if err != nil {
logger.Debugf("reconcile volume definition failed: %v", err)
return err
}
logger.Debug("reconcile volume placement")
err = s.reconcileResourcePlacement(ctx, vol, params, topologies)
if err != nil {
logger.Debugf("reconcile volume placement failed: %v", err)
return err
}
logger.Debug("reconcile extra properties")
err = s.client.ResourceDefinitions.Modify(ctx, vol.ID, lapi.GenericPropsModify{OverrideProps: vol.Properties})
if err != nil {
logger.Debugf("reconcile extra properties failed: %v", err)
return err
}
return nil
}
// Delete removes a persistent volume from LINSTOR.
//
// In order to support Snapshots living longer than their volumes, we have to keep the resource definition around while
// the actual resources are gone. An elegant way to go about this is by simply deleting the volume definition. This
// hides
func (s *Linstor) Delete(ctx context.Context, volId string) error {
s.log.WithFields(logrus.Fields{
"volume": volId,
}).Info("deleting volume")
// Delete the volume definition. This marks a resources as being in the process of deletion.
err := s.client.ResourceDefinitions.DeleteVolumeDefinition(ctx, volId, 0)
if nil404(err) != nil {
// We continue with the cleanup on 404, maybe the previous cleanup was interrupted
return err
}
resources, err := s.client.Resources.GetAll(ctx, volId)
if err != nil {
return nil404(err)
}
// Need to ensure that diskless resources are always deleted first, otherwise the last diskfull resource won't be
// deleted
sort.Slice(resources, func(i, j int) bool {
return !util.DeployedDiskfully(resources[i]) && util.DeployedDiskfully(resources[j])
})
for _, res := range resources {
err := s.client.Resources.Delete(ctx, volId, res.NodeName)
if err != nil {
// If two deletions run in parallel, one could get a 404 message, which we treat as "everything finished"
return nil404(err)
}
}
err = s.deleteResourceDefinitionAndGroupIfUnused(ctx, volId)
if err != nil {
return err
}
return nil
}
// AccessibleTopologies returns a list of pointers to csi.Topology from where the
// volume is reachable, based on the localStoragePolicy reported by the volume.
func (s *Linstor) AccessibleTopologies(ctx context.Context, volId string, params *volume.Parameters) ([]*csi.Topology, error) {
volumeScheduler, err := s.schedulerByPlacementPolicy(params.PlacementPolicy)
if err != nil {
return nil, err
}
return volumeScheduler.AccessibleTopologies(ctx, volId, params.AllowRemoteVolumeAccess)
}
func (s *Linstor) schedulerByPlacementPolicy(policy topology.PlacementPolicy) (scheduler.Interface, error) {
switch policy {
case topology.AutoPlace:
return autoplace.NewScheduler(s.client), nil
case topology.Manual:
return manual.NewScheduler(s.client), nil
case topology.FollowTopology:
return followtopology.NewScheduler(s.client, s.log), nil
case topology.Balanced:
return balancer.NewScheduler(s.client, s.log)
case topology.AutoPlaceTopology:
return autoplacetopology.NewScheduler(s.client, s.log), nil
default:
return nil, fmt.Errorf("unsupported volume scheduler: %s", policy)
}
}
func (s *Linstor) GetLegacyVolumeParameters(ctx context.Context, volId string) (*volume.Parameters, error) {
rd, err := s.client.ResourceDefinitions.Get(ctx, volId)
if err != nil {
return nil, err
}
raw, ok := rd.Props[linstor.LegacyParameterPassKey]
if !ok {
return nil, nil
}
decoded := struct {
Parameters map[string]string `json:"parameters"`
}{}
err = json.Unmarshal([]byte(raw), &decoded)
if err != nil {
return nil, err
}
params, err := volume.NewParameters(decoded.Parameters)
if err != nil {
return nil, err
}
return ¶ms, nil
}
// Attach idempotently creates a resource on the given node.
func (s *Linstor) Attach(ctx context.Context, volId, node string, readOnly, volQuorum bool) error {
s.log.WithFields(logrus.Fields{
"volume": volId,
"targetNode": node,
}).Info("attaching volume")
ress, err := s.client.Resources.GetResourceView(ctx, &lapi.ListOpts{Resource: []string{volId}})
if nil404(err) != nil {
return err
}
var existingRes *lapi.Resource
existingSharedName := ""
for i := range ress {
if ress[i].NodeName == node {
existingRes = &ress[i].Resource
existingSharedName = ress[i].SharedName
break
}
}
propsModify := lapi.GenericPropsModify{OverrideProps: map[string]string{
linstor.PublishedReadOnlyKey: strconv.FormatBool(readOnly),
}}
// If the resource is already on the node, don't worry about attaching.
if existingRes == nil {
// In certain circumstances it is necessary to create a diskfull resource to make it usable.
// The bug report that introduced this variable is a good example:
// * Our cluster has 4 identical nodes called A, B, C, D.
// * A resource was placed in a typical 2 + 1 Tiebreaker configuration, let's say the diskfull resources are
// on A and B, the Tiebreaker on C.
// * A Pod attaches on node A.
// * Node A goes down/becomes unreachable/etc. That leaves us with 1 diskfull resource on B + 1 diskless on C.
// * The Pod is deleted and a replacement scheduled on node D (i.e. after deletion by the HA Controller).
// * Now, this method will be called, since we need to Attach on node D, and there is currently no resource on that
// node.
// * Using a diskless resource will not work, as the newly created resource would not get quorum.
// * Using a diskfull resource will work and sync up to the remaining diskfull resource on B.
availableDiskfullResources := 0
unavailableDiskfullResources := 0
disklessCreateFlag := ""
for i := range ress {
drbdDiskfull, flag := inspectExistingResource(&ress[i].Resource)
if disklessCreateFlag == "" {
disklessCreateFlag = flag
}
if drbdDiskfull != nil {
if *drbdDiskfull {
availableDiskfullResources++
} else {
unavailableDiskfullResources++
}
}
}
s.log.Infof("volume %s does not exist on node %s, creating new resource", volId, node)
// If only half of the expected resources are available, we need a diskfull deployment to have any hope
// of achieving quorum on the node. See the comment above availableDiskfullResources.
shouldDeployDiskful := availableDiskfullResources > 0 && unavailableDiskfullResources >= availableDiskfullResources && volQuorum
if shouldDeployDiskful {
s.log.Infof("%d replicas of %d are apparently not reachable, create a new diskfull resource for quorum", unavailableDiskfullResources, unavailableDiskfullResources+availableDiskfullResources)
err = s.client.Resources.MakeAvailable(ctx, volId, node, lapi.ResourceMakeAvailable{Diskful: true})
} else {
err = s.client.Resources.MakeAvailable(ctx, volId, node, lapi.ResourceMakeAvailable{Diskful: false})
}
if errors.Is(err, lapi.NotFoundError) {
// Make-available honors replica-on-same and replicas-on-different. We do not, as the import parts of that
// are already covered in the allowed topology bits.
s.log.WithError(err).Info("fall back to manual diskless creation after make-available refused")
rCreate := lapi.ResourceCreate{Resource: lapi.Resource{
Name: volId,
NodeName: node,
}}
if !shouldDeployDiskful {
rCreate.Resource.Flags = append(rCreate.Resource.Flags, disklessCreateFlag)
}
err = s.client.Resources.Create(ctx, rCreate)
}
propsModify.OverrideProps[linstor.PropertyCreatedFor] = linstor.CreatedForTemporaryDisklessAttach
if err != nil {
return err
}
newRsc, err := s.client.Resources.Get(ctx, volId, node)
if err != nil {
return err
}
existingRes = &newRsc
}
err = s.client.Resources.ModifyVolume(ctx, volId, node, 0, propsModify)
if err != nil {
return err
}
if slice.ContainsString(existingRes.Flags, lapiconsts.FlagDelete) {
return &DeleteInProgressError{
Operation: "attach volume",
Kind: "resource",
Name: volId,
}
}
if slice.ContainsString(existingRes.Flags, lapiconsts.FlagRscInactive) {
for i := range ress {
res := &ress[i]
if res.SharedName == "" {
continue
}
if res.SharedName != existingSharedName {
continue
}
if slice.ContainsString(res.Flags, lapiconsts.FlagRscInactive) {
continue
}
err := s.client.Resources.Deactivate(ctx, res.Name, res.NodeName)
if err != nil {
return fmt.Errorf("failed to deactivate node %s in shared storage pool %s for volume %s: %w", res.NodeName, res.SharedName, volId, err)
}
}
return s.client.Resources.Activate(ctx, volId, node)
}
return nil
}
// inspectExistingResource inspects a resource to determine the right diskless
func inspectExistingResource(resource *lapi.Resource) (*bool, string) {
layer := &resource.LayerObject
isAvailableDiskful := true
isUnavailableDiskful := false
for layer != nil {
if layer.Type == devicelayerkind.Drbd {
if slice.ContainsString(layer.Drbd.Flags, lapiconsts.FlagDiskless) {
return nil, lapiconsts.FlagDrbdDiskless
}
if layer.Drbd.PromotionScore != 0 {
return &isAvailableDiskful, lapiconsts.FlagDrbdDiskless
} else {
return &isUnavailableDiskful, lapiconsts.FlagDrbdDiskless
}
}
if layer.Type == devicelayerkind.Nvme {
return nil, lapiconsts.FlagNvmeInitiator
}
if len(layer.Children) != 1 {
// No idea how to deal with layer depending on children anyways, so we just ignore those
break
}
layer = &layer.Children[0]
}
return nil, ""
}
// Detach removes a volume from the node.
func (s *Linstor) Detach(ctx context.Context, volId, node string) error {
log := s.log.WithFields(logrus.Fields{
"volume": volId,
"targetNode": node,
})
vols, err := s.client.Resources.GetVolumes(ctx, volId, node)
if err != nil {
return nil404(err)
}
if len(vols) != 1 {
return fmt.Errorf("expected exactly 1 volume, got %d instead", len(vols))
}
createdFor, ok := vols[0].Props[linstor.PropertyCreatedFor]
if !ok || createdFor != linstor.CreatedForTemporaryDisklessAttach {
log.Info("resource not temporary (not created by Attach) not deleting")
return nil
}
if vols[0].ProviderKind != lapi.DISKLESS {
log.Info("temporary resource created by Attach is now diskfull, not deleting")
return nil
}
log.Info("removing temporary resource")
return nil404(s.client.Resources.Delete(ctx, volId, node))
}
// CapacityBytes returns the amount of free space in the storage pool specified by the params and topology.
func (s *Linstor) CapacityBytes(ctx context.Context, storagePool string, segments map[string]string) (int64, error) {
log := s.log.WithField("storage-pool", storagePool).WithField("segments", segments)
var requestedStoragePools []string
for k := range segments {
if strings.HasPrefix(k, topology.LinstorStoragePoolKeyPrefix) {
requestedStoragePools = append(requestedStoragePools, k[len(topology.LinstorStoragePoolKeyPrefix):])
}
}
log.Trace("request nodes for segments")
requestedNodes, err := s.client.NodesForTopology(ctx, segments)
if err != nil {
return 0, fmt.Errorf("unable to get capacity: %w", err)
}
log.WithField("nodes", requestedNodes).Trace("got nodes")
log.Trace("get storage pools")
cached := true
pools, err := s.client.Nodes.GetStoragePoolView(ctx, &lapi.ListOpts{Cached: &cached})
if err != nil {
return 0, fmt.Errorf("unable to get capacity: %w", err)
}
var total int64
for _, sp := range pools {
log := log.WithField("pool-to-check", sp.StoragePoolName).WithField("node", sp.NodeName)
if !slice.ContainsString(requestedNodes, sp.NodeName) {
log.Trace("not an allowed node")
continue
}
if len(requestedStoragePools) > 0 && !slice.ContainsString(requestedStoragePools, sp.StoragePoolName) {
log.Trace("not an allowed storage pool")
continue
}
if storagePool == "" || storagePool == sp.StoragePoolName {
log.Trace("adding storage pool capacity")
total += sp.FreeCapacity
}
}
return int64(data.NewKibiByte(data.KiB * data.ByteSize(total)).To(data.B)), nil
}
func (s *Linstor) CompatibleSnapshotId(name string) string {
invalid := validResourceName(name)
if invalid == nil {
return name
}
s.log.WithField("reason", invalid).Debug("snapshot name is invalid, will generate fallback")
uuidv5 := uuid.NewSHA1([]byte(linstor.DriverName), []byte(name))
return fmt.Sprintf("snapshot-%s", uuidv5.String())
}
// SnapCreate calls LINSTOR to create a new snapshot name "id" or backup of the volume "sourceVolId".
func (s *Linstor) SnapCreate(ctx context.Context, id, sourceVolId string, params *volume.SnapshotParameters) (*csi.Snapshot, error) {
var lsnap *lapi.Snapshot
var err error
if params.Type == volume.SnapshotTypeInCluster {
lsnap, err = s.createInClusterSnapshot(ctx, id, sourceVolId)
} else {
lsnap, err = s.reconcileBackup(ctx, id, sourceVolId, params)
}
if err != nil {
return nil, err
}
return linstorSnapshotToCSI(lsnap)
}
func (s *Linstor) createInClusterSnapshot(ctx context.Context, id, sourceVolId string) (*lapi.Snapshot, error) {
log := s.log.WithField("resource", sourceVolId).WithField("id", id)
log.Debug("Creating in-cluster snapshot")
ress, err := s.client.Resources.GetAll(ctx, sourceVolId)
if err != nil {
return nil, fmt.Errorf("failed to list source resources: %w", err)
}
for i := range ress {
if ress[i].State == nil {
return nil, fmt.Errorf("resource in unknown state, refusing to snapshot")
}
}
snapConfig := lapi.Snapshot{
Name: id,
ResourceName: sourceVolId,
}
err = s.client.Resources.CreateSnapshot(ctx, snapConfig)
if err != nil {
return nil, fmt.Errorf("failed to create snapshot: %v", err)
}
log.Debug("Fetch newly created snapshot")
lsnap, err := s.client.Resources.GetSnapshot(ctx, sourceVolId, id)
if err != nil {
return nil, err
}
return &lsnap, nil
}
// reconcileBackup ensure a backup exists at the given remote
func (s *Linstor) reconcileBackup(ctx context.Context, id, sourceVolId string, params *volume.SnapshotParameters) (*lapi.Snapshot, error) {
log := s.log.WithField("resource", sourceVolId).WithField("id", id)
log.Debug("reconcile remote")
err := s.reconcileRemote(ctx, params)
if err != nil {
return nil, err
}
switch params.Type {
case volume.SnapshotTypeS3:
info, err := s.client.Backup.Info(ctx, params.RemoteName, lapi.BackupInfoRequest{
SrcRscName: sourceVolId,
SrcSnapName: id,
})
if nil404(err) != nil {
return nil, fmt.Errorf("error checking for existing S3 backup: %w", err)
}
if info == nil {
_, err := s.client.Backup.Create(ctx, params.RemoteName, lapi.BackupCreate{
RscName: sourceVolId,
SnapName: id,
Incremental: params.AllowIncremental,
})
if err != nil {
return nil, fmt.Errorf("error creating S3 backup: %w", err)
}
}
snap, err := s.client.Resources.GetSnapshot(ctx, sourceVolId, id)
if err != nil {
return nil, fmt.Errorf("error fetching snapshot for backup: %w", err)
}
return &snap, nil
case volume.SnapshotTypeLinstor:
return nil, fmt.Errorf("linstor-to-linstor snapshots not implemented")
default:
return nil, fmt.Errorf("unsupported snapshot type '%s', don't know how to create a backup", params.Type)
}
}
func (s *Linstor) reconcileRemote(ctx context.Context, params *volume.SnapshotParameters) error {
log := s.log.WithField("remote-name", params.RemoteName)
switch params.Type {
case volume.SnapshotTypeS3:
log.Debug("search for S3 remote with matching name")
remotes, err := s.client.Remote.GetAllS3(ctx)
if err != nil {
return fmt.Errorf("failed to list existing remotes: %w", err)
}
for _, r := range remotes {
if r.RemoteName == params.RemoteName {
log.WithField("remote", r).Debug("found existing S3 remote with matching name")
return nil
}
}
log.Debug("No existing remote found, creating a new one")
err = s.client.Remote.CreateS3(ctx, lapi.S3Remote{
RemoteName: params.RemoteName,
Bucket: params.S3Bucket,
Region: params.S3SigningRegion,
Endpoint: params.S3Endpoint,
AccessKey: params.S3AccessKey,
SecretKey: params.S3SecretKey,
UsePathStyle: params.S3UsePathStyle,
})
if err != nil {
return fmt.Errorf("failed to create new S3 remote: %w", err)
}
return nil
case volume.SnapshotTypeLinstor:
return fmt.Errorf("Linstor-to-Linstor snapshots not implemented")
default:
return fmt.Errorf("unsupported snapshot type '%s', don't know how to configure remote", params.Type)
}
}
// SnapDelete calls LINSTOR to delete the snapshot based on the CSI Snapshot ID.
func (s *Linstor) SnapDelete(ctx context.Context, snap *csi.Snapshot) error {
log := s.log.WithField("snapshot", snap)
log.Debug("deleting snapshot")
err := s.client.Resources.DeleteSnapshot(ctx, snap.GetSourceVolumeId(), snap.SnapshotId)
if nil404(err) != nil {
return fmt.Errorf("failed to remove snaphsot: %v", err)
}
err = s.deleteResourceDefinitionAndGroupIfUnused(ctx, snap.GetSourceVolumeId())
return nil
}
// VolFromSnap creates the volume using the data contained within the snapshot.
func (s *Linstor) VolFromSnap(ctx context.Context, snap *csi.Snapshot, vol *volume.Info, params *volume.Parameters, topologies *csi.TopologyRequirement) error {
logger := s.log.WithFields(logrus.Fields{
"volume": fmt.Sprintf("%+v", vol),
"snapshot": fmt.Sprintf("%+v", snap),
})
logger.Debug("find requisite nodes")
nodes, err := s.client.GetAllTopologyNodes(ctx, params.AllowRemoteVolumeAccess, topologies.GetRequisite())
if err != nil {
return err
}
logger.Debug("sort nodes by preference")
preferredNodes, err := s.SortByPreferred(ctx, nodes, params.AllowRemoteVolumeAccess, topologies.GetPreferred())
if err != nil {
return err
}
logger.Debug("reconcile resource group from storage class")
rGroup, err := s.reconcileResourceGroup(ctx, params)
if err != nil {
return err
}
logger.Debug("reconcile resource definition for volume")
rDef, err := s.reconcileResourceDefinition(ctx, vol.ID, rGroup.Name, vol.FsType, params.FSOpts)
if err != nil {
return err
}
logger.Debug("reconcile snapshot")
err = s.reconcileSnapshot(ctx, snap.SourceVolumeId, snap.SnapshotId, preferredNodes, params.StoragePool)
if err != nil {
return err
}
logger.Debug("reconcile volume definition from snapshot")
err = s.reconcileSnapshotVolumeDefinitions(ctx, snap, rDef.Name)
if err != nil {
return err
}
logger.Debug("reconcile resources from snapshot")
err = s.reconcileSnapshotResources(ctx, snap, rDef.Name, preferredNodes)
if err != nil {
return err
}
logger.Debug("reconcile volume definition from request (may expand volume)")
_, err = s.reconcileVolumeDefinition(ctx, vol)
if err != nil {
return err
}
logger.Debug("reconcile resource placement after restore")
err = s.reconcileResourcePlacement(ctx, vol, params, topologies)
if err != nil {
return err
}
logger.Debug("reconcile extra properties")
err = s.client.ResourceDefinitions.Modify(ctx, vol.ID, lapi.GenericPropsModify{OverrideProps: vol.Properties})
if err != nil {
logger.Debugf("reconcile extra properties failed: %v", err)
return err
}
logger.Debug("success")
return nil
}
// reconcileSnapshot ensures that the snapshot exists on a node in the cluster.
func (s *Linstor) reconcileSnapshot(ctx context.Context, sourceVolId, snapId string, nodes []string, targetPool string) error {
logger := s.log.WithField("snapshot", snapId).WithField("source", sourceVolId)
logger.Debug("checking for existing local snapshot")
snap, err := s.client.Resources.GetSnapshot(ctx, sourceVolId, snapId)
if nil404(err) != nil {
return fmt.Errorf("failed to check for presence of local snapshot '%s': %w", snapId, err)
}
if err == nil {
return s.waitLocalSnapshotSuccessful(ctx, &snap)
}
logger.Debug("no local snapshot present, search backups")
remote, info, err := s.findBackupInfo(ctx, sourceVolId, snapId)
if err != nil {
return fmt.Errorf("failed to check for presence of remote snapshot '%s': %w", snapId, err)
}
if info == nil {
return fmt.Errorf("snapshot '%s' not found", snapId)
}
sourcePool := info.Storpools[0].TargetName
for _, node := range nodes {
var rename map[string]string
if targetPool != "" && sourcePool != targetPool {
rename = map[string]string{sourcePool: targetPool}
}
err = s.client.Backup.Restore(ctx, remote, lapi.BackupRestoreRequest{
LastBackup: info.Latest,
SrcRscName: info.Rsc,
SrcSnapName: info.Snap,
NodeName: node,
DownloadOnly: true,
StorPoolMap: rename,
TargetRscName: info.Rsc,
})
if err == nil {
break
}
logger.WithError(err).WithField("node", node).Info("failed to restore backup to node")
}
if err != nil {
return fmt.Errorf("failed to restore backup to any node (%v), last error: %w", nodes, err)
}