-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdriver_truenas_volumes.go
More file actions
1918 lines (1553 loc) · 56.5 KB
/
driver_truenas_volumes.go
File metadata and controls
1918 lines (1553 loc) · 56.5 KB
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 drivers
import (
"bufio"
"errors"
"fmt"
"io"
"io/fs"
"os"
"strconv"
"strings"
"github.com/google/uuid"
"github.com/lxc/incus/v6/internal/instancewriter"
"github.com/lxc/incus/v6/internal/linux"
"github.com/lxc/incus/v6/internal/migration"
"github.com/lxc/incus/v6/internal/server/backup"
localMigration "github.com/lxc/incus/v6/internal/server/migration"
"github.com/lxc/incus/v6/internal/server/operations"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/revert"
"github.com/lxc/incus/v6/shared/units"
"github.com/lxc/incus/v6/shared/util"
"github.com/lxc/incus/v6/shared/validate"
"golang.org/x/sys/unix"
)
// CreateVolume creates an empty volume and can optionally fill it by executing the supplied
// filler function.
func (d *truenas) CreateVolume(vol Volume, filler *VolumeFiller, op *operations.Operation) error {
// Revert handling
reverter := revert.New()
defer reverter.Fail()
if vol.contentType == ContentTypeFS {
// Create mountpoint.
err := vol.EnsureMountPath()
if err != nil {
return err
}
reverter.Add(func() { _ = os.Remove(vol.MountPath()) })
}
reverter.Add(func() { _ = os.Remove(vol.MountPath()) })
// Look for previously deleted images. (don't look for underlying, or we'll look after we've looked)
if vol.volType == VolumeTypeImage {
dataset := d.dataset(vol, true)
exists, err := d.datasetExists(dataset)
if err != nil {
return err
}
if exists {
canRestore := true
//check if the cached image volume is larger than the current pool volume.size setting (if so we won't be
// able to resize the snapshot to that the smaller size later).
volSize, err := d.getDatasetProperty(dataset, "volsize")
if err != nil {
return err
}
volSizeBytes, err := strconv.ParseInt(volSize, 10, 64)
if err != nil {
return err
}
poolVolSize := DefaultBlockSize
if vol.poolConfig["volume.size"] != "" {
poolVolSize = vol.poolConfig["volume.size"]
}
poolVolSizeBytes, err := units.ParseByteSizeString(poolVolSize)
if err != nil {
return err
}
// Round to block boundary.
poolVolSizeBytes, err = d.roundVolumeBlockSizeBytes(vol, poolVolSizeBytes)
if err != nil {
return err
}
// If the cached volume size is different than the pool volume size, then we can't use the
// deleted cached image volume and instead we will rename it to a random UUID so it can't
// be restored in the future and a new cached image volume will be created instead.
if volSizeBytes != poolVolSizeBytes {
d.logger.Debug("Renaming deleted cached image volume so that regeneration is used", logger.Ctx{"fingerprint": vol.Name()})
randomVol := NewVolume(d, d.name, vol.volType, vol.contentType, d.randomVolumeName(vol), vol.config, vol.poolConfig)
_, err := d.runTool("dataset", "rename", dataset, d.dataset(randomVol, true))
if err != nil {
return err
}
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
randomFsVol := randomVol.NewVMBlockFilesystemVolume()
_, err := d.runTool("dataset", "rename", d.dataset(fsVol, true), d.dataset(randomFsVol, true))
if err != nil {
return err
}
}
// We have renamed the deleted cached image volume, so we don't want to try and
// restore it.
canRestore = false
}
// Restore the image.
if canRestore {
d.logger.Debug("Restoring previously deleted cached image volume", logger.Ctx{"fingerprint": vol.Name()})
_, err := d.runTool("dataset", "rename", dataset, d.dataset(vol, false))
if err != nil {
return err
}
// After this point we have a restored image, so setup reverter.
reverter.Add(func() { _ = d.DeleteVolume(vol, op) })
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
_, err := d.runTool("dataset", "rename", d.dataset(fsVol, true), d.dataset(fsVol, false))
if err != nil {
return err
}
// no need for reverter.add here as we have succeeded
}
reverter.Success()
return nil
}
}
}
var opts []string
// Add custom property incus:content_type which allows distinguishing between regular volumes, block_mode enabled volumes, and ISO volumes.
if vol.volType == VolumeTypeCustom {
opts = append(opts, fmt.Sprintf("user-props=incus:content_type=%s", vol.contentType))
}
blockSize := vol.ExpandedConfig("truenas.blocksize")
if blockSize != "" {
// Convert to bytes.
sizeBytes, err := units.ParseByteSizeString(blockSize)
if err != nil {
return err
}
// volblocksize maximum value is 128KiB so if the value of truenas.blocksize is bigger set it to 128KiB.
if sizeBytes > zfsMaxVolBlocksize {
sizeBytes = zfsMaxVolBlocksize
}
opts = append(opts, fmt.Sprintf("volblocksize=%d", sizeBytes))
}
sizeBytes, err := units.ParseByteSizeString(vol.ConfigSize())
if err != nil {
return err
}
sizeBytes, err = d.roundVolumeBlockSizeBytes(vol, sizeBytes)
if err != nil {
return err
}
dataset := d.dataset(vol, false)
// Create the volume dataset.
err = d.createVolume(dataset, sizeBytes, opts...)
if err != nil {
return err
}
// After this point we'll have a volume, so setup reverter.
reverter.Add(func() { _ = d.DeleteVolume(vol, op) })
err = d.createIscsiShare(dataset, false)
if err != nil {
return err
}
if vol.contentType == ContentTypeFS {
// activateIscsiDataset does not check if the dataset has been activated.
devPath, err := d.activateIscsiDataset(dataset)
if err != nil {
return err
}
fsVolFilesystem := vol.ConfigBlockFilesystem()
_, err = makeFSType(devPath, fsVolFilesystem, nil)
// de-activate even if there is an err
err2 := d.deactivateIscsiDataset(dataset)
if err != nil {
return err
}
if err2 != nil {
return err2
}
}
// For VM images, create a filesystem volume too.
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err := d.CreateVolume(fsVol, nil, op)
if err != nil {
return err
}
reverter.Add(func() { _ = d.DeleteVolume(fsVol, op) })
}
err = vol.MountTask(func(mountPath string, op *operations.Operation) error {
// Run the volume filler function if supplied.
if filler != nil && filler.Fill != nil {
var err error
var devPath string
if IsContentBlock(vol.contentType) {
// Get the device path.
devPath, err = d.GetVolumeDiskPath(vol)
if err != nil {
return err
}
}
allowUnsafeResize := false
if vol.volType == VolumeTypeImage {
// Allow filler to resize initial image volume as needed.
// Some storage drivers don't normally allow image volumes to be resized due to
// them having read-only snapshots that cannot be resized. However when creating
// the initial image volume and filling it before the snapshot is taken resizing
// can be allowed and is required in order to support unpacking images larger than
// the default volume size. The filler function is still expected to obey any
// volume size restrictions configured on the pool.
// Unsafe resize is also needed to disable filesystem resize safety checks.
// This is safe because if for some reason an error occurs the volume will be
// discarded rather than leaving a corrupt filesystem.
allowUnsafeResize = true
}
// Run the filler.
err = d.runFiller(vol, devPath, filler, allowUnsafeResize)
if err != nil {
return err
}
// Move the GPT alt header to end of disk if needed.
if vol.IsVMBlock() {
err = d.moveGPTAltHeader(devPath)
if err != nil {
return err
}
}
}
if vol.contentType == ContentTypeFS {
// Run EnsureMountPath again after mounting and filling to ensure the mount directory has
// the correct permissions set.
err := vol.EnsureMountPath()
if err != nil {
return err
}
}
return nil
}, op)
if err != nil {
return err
}
// Setup snapshot and unset mountpoint on image.
if vol.volType == VolumeTypeImage {
// ideally, we don't want to snap the underlying when we create the img, but rather after we've unpacked.
// note: we may need to sync the underlying filesystem, it depends if its still mounted, I think it shouldn't be.
dataset := d.dataset(vol, false)
snapName := fmt.Sprintf("%s@readonly", dataset)
// Create snapshot of the main dataset.
err := d.createSnapshot(snapName, false)
if err != nil {
return err
}
if vol.contentType == ContentTypeBlock {
// Re-create the FS config volume's readonly snapshot now that the filler function has run
// and unpacked into both config and block volumes.
fsVol := vol.NewVMBlockFilesystemVolume()
snapName = fmt.Sprintf("%s@readonly", d.dataset(fsVol, false))
err := d.createSnapshot(snapName, true) // delete, then snap.
if err != nil {
return err
}
}
}
// All done.
reverter.Success()
return nil
}
// CreateVolumeFromBackup re-creates a volume from its exported state.
func (d *truenas) CreateVolumeFromBackup(vol Volume, srcBackup backup.Info, srcData io.ReadSeeker, op *operations.Operation) (VolumePostHook, revert.Hook, error) {
// TODO: optimized version
return genericVFSBackupUnpack(d, d.state.OS, vol, srcBackup.Snapshots, srcData, op)
}
// same as CreateVolumeFromCopy, but will refresh if refresh is true.
func (d *truenas) createOrRefeshVolumeFromCopy(vol Volume, srcVol Volume, refresh bool, copySnapshots bool, allowInconsistent bool, op *operations.Operation) error {
var err error
// Revert handling
reverter := revert.New()
defer reverter.Fail()
if vol.contentType == ContentTypeFS {
// Create mountpoint.
err = vol.EnsureMountPath()
if err != nil {
return err
}
reverter.Add(func() { _ = os.Remove(vol.MountPath()) })
}
// For VMs, also copy the filesystem dataset.
if vol.IsVMBlock() {
// For VMs, also copy the filesystem volume.
srcFSVol := srcVol.NewVMBlockFilesystemVolume()
fsVol := vol.NewVMBlockFilesystemVolume()
err = d.createOrRefeshVolumeFromCopy(fsVol, srcFSVol, refresh, copySnapshots, false, op)
if err != nil {
return err
}
// Delete on revert.
if !refresh {
reverter.Add(func() { _ = d.DeleteVolume(fsVol, op) })
}
}
// Retrieve snapshots on the source.
snapshots := []string{}
if !srcVol.IsSnapshot() && copySnapshots {
snapshots, err = d.VolumeSnapshots(srcVol, op)
if err != nil {
return err
}
}
// When not allowing inconsistent copies and the volume has a mounted filesystem, we must ensure it is
// consistent by syncing and freezing the filesystem to ensure unwritten pages are flushed and that no
// further modifications occur while taking the source snapshot.
var unfreezeFS func() error
sourcePath := srcVol.MountPath()
if !allowInconsistent && srcVol.contentType == ContentTypeFS && linux.IsMountPoint(sourcePath) {
unfreezeFS, err = d.filesystemFreeze(sourcePath)
if err != nil {
return err
}
reverter.Add(func() { _ = unfreezeFS() })
}
srcDataset := d.dataset(srcVol, false)
var srcSnapshot string
if srcVol.volType == VolumeTypeImage {
srcSnapshot = fmt.Sprintf("%s@readonly", srcDataset)
} else if srcVol.IsSnapshot() {
srcSnapshot = srcDataset
} else {
// Create a new snapshot for copy.
srcSnapshot = fmt.Sprintf("%s@copy-%s", srcDataset, uuid.New().String())
err := d.createSnapshot(srcSnapshot, false)
if err != nil {
return err
}
// If truenas.clone_copy is disabled delete the snapshot at the end.
if util.IsFalse(d.config["truenas.clone_copy"]) || len(snapshots) > 0 {
// Delete the snapshot at the end.
defer func() {
// Delete snapshot (or mark for deferred deletion if cannot be deleted currently).
err = d.deleteSnapshot(srcSnapshot, true, "defer")
if err != nil {
d.logger.Warn("Failed deleting temporary snapshot for copy", logger.Ctx{"snapshot": srcSnapshot, "err": err})
}
}()
} else {
// Delete the snapshot on revert.
reverter.Add(func() {
// Delete snapshot (or mark for deferred deletion if cannot be deleted currently).
err = d.deleteSnapshot(srcSnapshot, true, "defer")
if err != nil {
d.logger.Warn("Failed deleting temporary snapshot for copy", logger.Ctx{"snapshot": srcSnapshot, "err": err})
}
})
}
}
// Now that source snapshot has been taken we can safely unfreeze the source filesystem.
if unfreezeFS != nil {
_ = unfreezeFS()
}
// Delete the volume created on failure.
if !refresh {
reverter.Add(func() { _ = d.DeleteVolume(vol, op) })
}
destDataset := d.dataset(vol, false)
// If truenas.clone_copy is disabled or source volume has snapshots, then use full copy mode.
if util.IsFalse(d.config["truenas.clone_copy"]) || len(snapshots) > 0 {
// Run the replication, snaps + copy- snap. TODO: verify necessary props are replicated.
args := []string{"replication", "start", "--recursive", "--readonly-policy=ignore"}
if refresh {
/*
refresh is essentially an optimized form of replace.
refresh implies that we may have a dest already, and since the source may be unrelated,
we may need to replicate from scratch. The retention policy ensures obsoleted snaps are
removed from the dest.
*/
args = append(args, "--retention-policy=source", "--allow-from-scratch=true")
}
/*
instead of using full replication, and then removing snapshots, we instead take advantage of the replication task's
ability to filter snapshots as they are sent.
*/
snapName := strings.SplitN(srcSnapshot, "@", 2)[1]
snapRegex := fmt.Sprintf("(snapshot-.*|%s)", snapName)
args = append(args, "--name-regex", snapRegex, srcDataset, destDataset)
_, err := d.runTool(args...)
if err != nil {
return fmt.Errorf("Failed to replicate dataset: %w", err)
}
// Delete the copy- snapshot on the dest.
err = d.deleteSnapshot(fmt.Sprintf("%s@%s", destDataset, snapName), true)
if err != nil {
return err
}
} else {
// Perform volume clone.
err = d.cloneSnapshot(srcSnapshot, destDataset)
if err != nil {
return err
}
// Note: user props aren't cloned, so we re-add the content_type if necessary
if vol.volType == VolumeTypeCustom {
// Add custom property incus:content_type which allows distinguishing between regular volumes, block_mode enabled volumes, and ISO volumes.
props := fmt.Sprintf("user-props=incus:content_type=%s", vol.contentType) // TODO: this needs to be better.
d.setDatasetProperties(destDataset, props)
}
}
// and share the clone/copy.
err = d.createIscsiShare(destDataset, false)
if err != nil {
return err
}
// Apply the properties.
if vol.contentType == ContentTypeFS {
if renegerateFilesystemUUIDNeeded(vol.ConfigBlockFilesystem()) {
// regen must be done with vol unmounted.
_, volPath, err := d.activateVolume(vol)
if err != nil {
return err
}
d.logger.Debug("Regenerating filesystem UUID", logger.Ctx{"dev": volPath, "fs": vol.ConfigBlockFilesystem()})
err = regenerateFilesystemUUID(vol.ConfigBlockFilesystem(), volPath)
if err != nil {
return err
}
}
// Mount the volume and ensure the permissions are set correctly inside the mounted volume.
err := vol.MountTask(func(_ string, _ *operations.Operation) error {
return vol.EnsureMountPath()
}, op)
if err != nil {
return err
}
}
// Pass allowUnsafeResize as true when resizing block backed filesystem volumes because we want to allow
// the filesystem to be shrunk as small as possible without needing the safety checks that would prevent
// leaving the filesystem in an inconsistent state if the resize couldn't be completed. This is because if
// the resize fails we will delete the volume anyway so don't have to worry about it being inconsistent.
var allowUnsafeResize bool
if vol.contentType == ContentTypeFS {
allowUnsafeResize = true
}
// Resize volume to the size specified. Only uses volume "size" property and does not use pool/defaults
// to give the caller more control over the size being used.
err = d.SetVolumeQuota(vol, vol.config["size"], allowUnsafeResize, op)
if err != nil {
return err
}
// All done.
reverter.Success()
return nil
}
// CreateVolumeFromCopy provides same-pool volume copying functionality.
func (d *truenas) CreateVolumeFromCopy(vol Volume, srcVol Volume, copySnapshots bool, allowInconsistent bool, op *operations.Operation) error {
return d.createOrRefeshVolumeFromCopy(vol, srcVol, false, copySnapshots, allowInconsistent, op) // not refreshing.
}
// CreateVolumeFromMigration creates a volume being sent via a migration. TODO: need to ensure that incus:content_type is copied.
func (d *truenas) CreateVolumeFromMigration(vol Volume, conn io.ReadWriteCloser, volTargetArgs localMigration.VolumeTargetArgs, preFiller *VolumeFiller, op *operations.Operation) error {
if volTargetArgs.ClusterMoveSourceName != "" && volTargetArgs.StoragePool == "" {
d.logger.Debug("Detected migration between cluster members on the same storage pool")
err := vol.EnsureMountPath()
if err != nil {
return err
}
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err := d.CreateVolumeFromMigration(fsVol, conn, volTargetArgs, preFiller, op)
if err != nil {
return err
}
}
return nil
}
// Handle simple rsync and block_and_rsync through generic.
if volTargetArgs.MigrationType.FSType == migration.MigrationFSType_RSYNC || volTargetArgs.MigrationType.FSType == migration.MigrationFSType_BLOCK_AND_RSYNC {
return genericVFSCreateVolumeFromMigration(d, nil, vol, conn, volTargetArgs, preFiller, op)
}
// TODO: optimized migration
return ErrNotSupported
}
// RefreshVolume updates an existing volume to match the state of another.
func (d *truenas) RefreshVolume(vol Volume, srcVol Volume, srcSnapshots []Volume, allowInconsistent bool, op *operations.Operation) error {
var err error
var targetSnapshots []Volume
var srcSnapshotsAll []Volume
if !srcVol.IsSnapshot() {
// Get target snapshots
targetSnapshots, err = vol.Snapshots(op)
if err != nil {
return fmt.Errorf("Failed to get target snapshots: %w", err)
}
srcSnapshotsAll, err = srcVol.Snapshots(op)
if err != nil {
return fmt.Errorf("Failed to get source snapshots: %w", err)
}
}
// If there are no source or target snapshots, perform a simple replacement copy
if len(srcSnapshotsAll) == 0 || len(targetSnapshots) == 0 {
// this ensures that recursive deletions are performed.
err = d.DeleteVolume(vol, op)
if err != nil {
return err
}
return d.CreateVolumeFromCopy(vol, srcVol, len(srcSnapshotsAll) == 0, false, op)
}
// repl task can "refresh"
return d.createOrRefeshVolumeFromCopy(vol, srcVol, true, true, false, op)
}
// DeleteVolume deletes a volume of the storage device. If any snapshots of the volume remain then
// this function will return an error.
// For image volumes, both filesystem and block volumes will be removed.
func (d *truenas) DeleteVolume(vol Volume, op *operations.Operation) error {
// We need to be able to delete the block-backed fs even if we don't know the filesystem.
if vol.volType == VolumeTypeImage && vol.contentType == ContentTypeFS {
// We need to clone vol the otherwise changing `block.filesystem`
// in tmpVol will also change it in vol.
tmpVol := vol.Clone()
// TODO: use bulk existance checks, before iterating.
// we don't pre-delete the filesystem that would be deleted by the main call to deleteVolume.
volFs := vol.ConfigBlockFilesystem()
for _, filesystem := range blockBackedAllowedFilesystems {
if filesystem != volFs {
tmpVol.config["block.filesystem"] = filesystem
err := d.deleteVolume(tmpVol, op)
if err != nil {
return err
}
}
}
}
return d.deleteVolume(vol, op)
}
func (d *truenas) deleteVolume(vol Volume, op *operations.Operation) error {
// Check that we have a dataset to delete.
dataset := d.dataset(vol, false)
exists, err := d.datasetExists(dataset)
if err != nil {
return err
}
if exists {
// Deleted volumes do not need shares
_ = d.deleteIscsiShare(dataset) // will implicitly deactivate, if activated.
// Handle clones.
clones, err := d.getClones(dataset)
if err != nil {
return err
}
if len(clones) > 0 {
// Move to the deleted path.
err := d.renameDataset(dataset, d.dataset(vol, true), false)
if err != nil {
return err
}
} else {
err := d.deleteDatasetRecursive(dataset)
if err != nil {
return err
}
}
}
if vol.contentType == ContentTypeFS {
// Delete the mountpoint if present.
err := os.Remove(vol.MountPath())
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("Failed to remove '%s': %w", vol.MountPath(), err)
}
// Delete the snapshot storage.
err = os.RemoveAll(GetVolumeSnapshotDir(d.name, vol.volType, vol.name))
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("Failed to remove '%s': %w", GetVolumeSnapshotDir(d.name, vol.volType, vol.name), err)
}
}
// For VMs, also delete the filesystem dataset.
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err := d.DeleteVolume(fsVol, op)
if err != nil {
return err
}
}
return nil
}
// HasVolume indicates whether a specific volume exists on the storage pool.
func (d *truenas) HasVolume(vol Volume) (bool, error) {
// Check if the dataset exists.
dataset := d.dataset(vol, false)
return d.datasetExists(dataset)
}
// ValidateTruenasBlocksize validates blocksize property value on the pool, matches volblocksize
func ValidateTrueNasVolBlocksize(value string) error {
/*
For volumes, specifies the block size of the volume. The blocksize cannot be changed once the volume has been written,
so it should be set at volume creation time. The default blocksize for volumes is 16 KiB. Any power of 2 from 512 bytes to 128 KiB is valid.
*/
// Convert to bytes.
sizeBytes, err := units.ParseByteSizeString(value)
if err != nil {
return err
}
if sizeBytes < zfsMinBlocksize || sizeBytes > zfsMaxVolBlocksize || (sizeBytes&(sizeBytes-1)) != 0 {
return errors.New("Value should be between 512B and 128KiB, and be power of 2")
}
return nil
}
// commonVolumeRules returns validation rules which are common for pool and volume.
func (d *truenas) commonVolumeRules() map[string]func(value string) error {
return map[string]func(value string) error{
"block.filesystem": validate.Optional(validate.IsOneOf(blockBackedAllowedFilesystems...)),
"block.mount_options": validate.IsAny,
"truenas.blocksize": validate.Optional(ValidateTrueNasVolBlocksize), // used for volblocksize only. NOTE: zfs.blocksize is hard-coded in backend.shouldUseOptimizedImage...
"truenas.remove_snapshots": validate.Optional(validate.IsBool),
"truenas.use_refquota": validate.Optional(validate.IsBool),
}
}
// ValidateVolume validates the supplied volume config.
func (d *truenas) ValidateVolume(vol Volume, removeUnknownKeys bool) error {
commonRules := d.commonVolumeRules()
// Disallow block.* settings for regular custom block volumes. These settings only make sense
// when using custom filesystem volumes. Incus will create the filesystem
// for these volumes, and use the mount options. When attaching a regular block volume to a VM,
// these are not mounted by Incus and therefore don't need these config keys.
if vol.IsVMBlock() || vol.volType == VolumeTypeCustom && vol.contentType == ContentTypeBlock {
delete(commonRules, "block.filesystem")
delete(commonRules, "block.mount_options")
}
return d.validateVolume(vol, commonRules, removeUnknownKeys)
}
// // UpdateVolume applies config changes to the volume.
func (d *truenas) UpdateVolume(vol Volume, changedConfig map[string]string) error {
// Mangle the current volume to its old values.
old := make(map[string]string)
for k, v := range changedConfig {
if k == "size" || k == "truenas.use_refquota" {
old[k] = vol.config[k]
vol.config[k] = v
}
}
defer func() {
for k, v := range old {
vol.config[k] = v
}
}()
// If any of the relevant keys changed, re-apply the quota.
if len(old) != 0 {
err := d.SetVolumeQuota(vol, vol.ExpandedConfig("size"), false, nil)
if err != nil {
return err
}
}
return nil
}
// CacheVolumeSnapshots fetches snapshot usage properties for all snapshots on the volume.
func (d *truenas) CacheVolumeSnapshots(vol Volume) error {
// NOTE: this actually gets info for all datasets and snapshots.
// Lock the cache.
d.cacheMu.Lock()
defer d.cacheMu.Unlock()
// Check if we've already cached the data.
if d.cache != nil {
return nil
}
// Get the usage data.
out, err := d.runTool("list", "--no-headers", "--parsable", "-o", "name,used,referenced", "-r", "-t", "snap,fs,vol", d.dataset(vol, false))
if err != nil {
d.logger.Warn("Coulnd't list volume snapshots", logger.Ctx{"err": err})
// The cache is an optional performance improvement, don't block on failure.
return nil
}
// Parse and update the cache.
d.cache = map[string]map[string]int64{}
for _, line := range strings.Split(out, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
fields := strings.Fields(line)
if len(fields) != 3 {
continue
}
usedInt, err := strconv.ParseInt(fields[1], 10, 64)
if err != nil {
continue
}
referencedInt, err := strconv.ParseInt(fields[2], 10, 64)
if err != nil {
continue
}
d.cache[fields[0]] = map[string]int64{
"used": usedInt,
"referenced": referencedInt,
}
}
return nil
}
// GetVolumeUsage returns the disk space used by the volume.
func (d *truenas) GetVolumeUsage(vol Volume) (int64, error) {
// Determine what key to use.
key := "used"
// If volume isn't snapshot then we can take into account the truenas.use_refquota setting.
// Snapshots should also use the "used" ZFS property because the snapshot usage size represents the CoW
// usage not the size of the snapshot volume.
if !vol.IsSnapshot() {
if util.IsTrue(vol.ExpandedConfig("truenas.use_refquota")) {
key = "referenced"
}
// Shortcut for mounted refquota filesystems.
if key == "referenced" && vol.contentType == ContentTypeFS && linux.IsMountPoint(vol.MountPath()) {
var stat unix.Statfs_t
err := unix.Statfs(vol.MountPath(), &stat)
if err != nil {
return -1, err
}
return int64(stat.Blocks-stat.Bfree) * int64(stat.Bsize), nil
}
}
// Try to use the cached data.
d.cacheMu.Lock()
defer d.cacheMu.Unlock()
dataset := d.dataset(vol, false)
if d.cache != nil {
cache, ok := d.cache[dataset]
if ok {
value, ok := cache[key]
if ok {
return value, nil
}
}
}
// Get the current value.
value, err := d.getDatasetProperty(dataset, key)
if err != nil {
return -1, err
}
// Convert to int.
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return -1, err
}
return valueInt, nil
}
// SetVolumeQuota sets the quota/reservation on the volume.
// Does nothing if supplied with an empty/zero size for block volumes.
func (d *truenas) SetVolumeQuota(vol Volume, size string, allowUnsafeResize bool, op *operations.Operation) error {
// Convert to bytes.
sizeBytes, err := units.ParseByteSizeString(size)
if err != nil {
return err
}
inUse := vol.MountInUse()
dataset := d.dataset(vol, false)
// always zvols with blockbacking.
// Do nothing if size isn't specified.
if sizeBytes <= 0 {
return nil
}
sizeBytes, err = d.roundVolumeBlockSizeBytes(vol, sizeBytes)
if err != nil {
return err
}
oldSizeBytesStr, err := d.getDatasetProperty(dataset, "volsize")
if err != nil {
return err
}
oldVolSizeBytesInt, err := strconv.ParseInt(oldSizeBytesStr, 10, 64)
if err != nil {
return err
}
oldVolSizeBytes := int64(oldVolSizeBytesInt)
if oldVolSizeBytes == sizeBytes {
return nil
}
if vol.contentType == ContentTypeFS {
// Activate volume if needed.
activated, volDevPath, err := d.activateVolume(vol)
if err != nil {
return err
}
if activated {
defer func() { _, _ = d.deactivateVolume(vol) }()
}
if vol.volType == VolumeTypeImage {
return fmt.Errorf("Image volumes cannot be resized: %w", ErrCannotBeShrunk)
}
fsType := vol.ConfigBlockFilesystem()
l := d.logger.AddContext(logger.Ctx{"dev": volDevPath, "size": fmt.Sprintf("%db", sizeBytes)})
if sizeBytes < oldVolSizeBytes {
if !filesystemTypeCanBeShrunk(fsType) {
return fmt.Errorf("Filesystem %q cannot be shrunk: %w", fsType, ErrCannotBeShrunk)
}
if inUse {
return ErrInUse // We don't allow online shrinking of filesystem block volumes.
}
// Shrink filesystem first.
// Pass allowUnsafeResize to allow disabling of filesystem resize safety checks.
err = shrinkFileSystem(fsType, volDevPath, vol, sizeBytes, allowUnsafeResize)
if err != nil {
return err
}
l.Debug("TrueNAS volume filesystem shrunk")
// Shrink the block device.
err = d.setVolsize(dataset, sizeBytes, true) // allow shrink, shrink errors will be ignored.
if err != nil {
return err
}
} else if sizeBytes > oldVolSizeBytes {
// Grow block device first, ignoring any shrink errors, which could happen because we've
// already ignored a shrink error when shrinking.
err = d.setVolsize(dataset, sizeBytes, false)
if err != nil {
return err
}
// Grow the filesystem to fill block device.
err = growFileSystem(fsType, volDevPath, vol)
if err != nil {
return err
}
l.Debug("TrueNAS volume filesystem grown")
}
} else {
// Block image volumes cannot be resized because they have a readonly snapshot that doesn't get
// updated when the volume's size is changed, and this is what instances are created from.
// During initial volume fill allowUnsafeResize is enabled because snapshot hasn't been taken yet.
if !allowUnsafeResize && vol.volType == VolumeTypeImage {
return ErrNotSupported