-
Notifications
You must be signed in to change notification settings - Fork 907
/
driver_zfs.go
745 lines (627 loc) · 19.2 KB
/
driver_zfs.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
package drivers
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
deviceConfig "github.com/canonical/lxd/lxd/device/config"
"github.com/canonical/lxd/lxd/migration"
"github.com/canonical/lxd/lxd/operations"
"github.com/canonical/lxd/lxd/util"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/logger"
"github.com/canonical/lxd/shared/revert"
"github.com/canonical/lxd/shared/units"
"github.com/canonical/lxd/shared/validate"
"github.com/canonical/lxd/shared/version"
)
var zfsVersion string
var zfsLoaded bool
var zfsDirectIO bool
var zfsTrim bool
var zfsRaw bool
var zfsDelegate bool
var zfsDefaultSettings = map[string]string{
"relatime": "on",
"mountpoint": "legacy",
"setuid": "on",
"exec": "on",
"devices": "on",
"acltype": "posixacl",
"xattr": "sa",
}
type zfs struct {
common
}
// load is used to run one-time action per-driver rather than per-pool.
func (d *zfs) load() error {
// Register the patches.
d.patches = map[string]func() error{
"storage_lvm_skipactivation": nil,
"storage_missing_snapshot_records": nil,
"storage_delete_old_snapshot_records": nil,
"storage_zfs_drop_block_volume_filesystem_extension": d.patchDropBlockVolumeFilesystemExtension,
"storage_prefix_bucket_names_with_project": nil,
}
// Done if previously loaded.
if zfsLoaded {
return nil
}
// Load the kernel module.
err := util.LoadModule("zfs")
if err != nil {
return fmt.Errorf("Error loading %q module: %w", "zfs", err)
}
// Validate the needed tools are present.
for _, tool := range []string{"zpool", "zfs"} {
_, err := exec.LookPath(tool)
if err != nil {
return fmt.Errorf("Required tool '%s' is missing", tool)
}
}
// Get the version information.
if zfsVersion == "" {
version, err := d.version()
if err != nil {
return err
}
zfsVersion = version
}
// Decide whether we can use features added by 0.8.0.
ver080, err := version.Parse("0.8.0")
if err != nil {
return err
}
ourVer, err := version.Parse(zfsVersion)
if err != nil {
return err
}
// If running 0.8.0 or newer, we can use direct I/O, trim and raw.
if ourVer.Compare(ver080) >= 0 {
zfsDirectIO = true
zfsTrim = true
zfsRaw = true
}
// Detect support for ZFS delegation.
ver220, err := version.Parse("2.2.0")
if err != nil {
return err
}
if ourVer.Compare(ver220) >= 0 {
zfsDelegate = true
}
zfsLoaded = true
return nil
}
// Info returns info about the driver and its environment.
func (d *zfs) Info() Info {
info := Info{
Name: "zfs",
Version: zfsVersion,
DefaultVMBlockFilesystemSize: deviceConfig.DefaultVMBlockFilesystemSize,
OptimizedImages: true,
OptimizedBackups: true,
PreservesInodes: true,
Remote: d.isRemote(),
VolumeTypes: []VolumeType{VolumeTypeBucket, VolumeTypeCustom, VolumeTypeImage, VolumeTypeContainer, VolumeTypeVM},
BlockBacking: shared.IsTrue(d.config["volume.zfs.block_mode"]),
RunningCopyFreeze: false,
DirectIO: zfsDirectIO,
MountedRoot: false,
Buckets: true,
}
return info
}
// ensureInitialDatasets creates missing initial datasets or configures existing ones with current policy.
// Accepts warnOnExistingPolicyApplyError argument, if true will warn rather than fail if applying current policy
// to an existing dataset fails.
func (d zfs) ensureInitialDatasets(warnOnExistingPolicyApplyError bool) error {
properties := make([]string, 0, len(zfsDefaultSettings))
for k, v := range zfsDefaultSettings {
properties = append(properties, fmt.Sprintf("%s=%s", k, v))
}
properties, err := d.filterRedundantOptions(d.config["zfs.pool_name"], properties...)
if err != nil {
return err
}
if len(properties) > 0 {
err := d.setDatasetProperties(d.config["zfs.pool_name"], properties...)
if err != nil {
if !warnOnExistingPolicyApplyError {
return fmt.Errorf("Failed applying policy to existing dataset %q: %w", d.config["zfs.pool_name"], err)
}
d.logger.Warn("Failed applying policy to existing dataset", logger.Ctx{"dataset": d.config["zfs.pool_name"], "err": err})
}
}
for _, dataset := range d.initialDatasets() {
properties := []string{"mountpoint=legacy"}
if shared.ValueInSlice(dataset, []string{"virtual-machines", "deleted/virtual-machines"}) {
properties = append(properties, "volmode=none")
}
datasetPath := filepath.Join(d.config["zfs.pool_name"], dataset)
exists, err := d.datasetExists(datasetPath)
if err != nil {
return err
}
if exists {
properties, err = d.filterRedundantOptions(datasetPath, properties...)
if err != nil {
return err
}
if len(properties) > 0 {
err = d.setDatasetProperties(datasetPath, properties...)
if err != nil {
if !warnOnExistingPolicyApplyError {
return fmt.Errorf("Failed applying policy to existing dataset %q: %w", datasetPath, err)
}
d.logger.Warn("Failed applying policy to existing dataset", logger.Ctx{"dataset": datasetPath, "err": err})
}
}
} else {
err = d.createDataset(datasetPath, properties...)
if err != nil {
return fmt.Errorf("Failed creating dataset %q: %w", datasetPath, err)
}
}
}
return nil
}
// FillConfig populates the storage pool's configuration file with the default values.
func (d *zfs) FillConfig() error {
loopPath := loopFilePath(d.name)
if d.config["source"] == "" || d.config["source"] == loopPath {
// Create a loop based pool.
d.config["source"] = loopPath
// Set default pool_name.
if d.config["zfs.pool_name"] == "" {
d.config["zfs.pool_name"] = d.name
}
// Pick a default size of the loop file if not specified.
if d.config["size"] == "" {
defaultSize, err := loopFileSizeDefault()
if err != nil {
return err
}
d.config["size"] = fmt.Sprintf("%dGiB", defaultSize)
}
} else if filepath.IsAbs(d.config["source"]) {
// Set default pool_name.
if d.config["zfs.pool_name"] == "" {
d.config["zfs.pool_name"] = d.name
}
// Unset size property since it's irrelevant.
d.config["size"] = ""
} else {
// Handle an existing zpool.
if d.config["zfs.pool_name"] == "" {
d.config["zfs.pool_name"] = d.config["source"]
}
// Unset size property since it's irrelevant.
d.config["size"] = ""
}
return nil
}
// Create is called during pool creation and is effectively using an empty driver struct.
// WARNING: The Create() function cannot rely on any of the struct attributes being set.
func (d *zfs) Create() error {
// Store the provided source as we are likely to be mangling it.
d.config["volatile.initial_source"] = d.config["source"]
err := d.FillConfig()
if err != nil {
return err
}
loopPath := loopFilePath(d.name)
if d.config["source"] == "" || d.config["source"] == loopPath {
// Validate pool_name.
if strings.Contains(d.config["zfs.pool_name"], "/") {
return fmt.Errorf("zfs.pool_name can't point to a dataset when source isn't set")
}
// Create the loop file itself.
size, err := units.ParseByteSizeString(d.config["size"])
if err != nil {
return err
}
err = ensureSparseFile(loopPath, size)
if err != nil {
return err
}
// Create the zpool.
_, err = shared.RunCommand("zpool", "create", "-m", "none", "-O", "compression=on", d.config["zfs.pool_name"], loopPath)
if err != nil {
return err
}
// Apply auto-trim if supported.
if zfsTrim {
_, err := shared.RunCommand("zpool", "set", "autotrim=on", d.config["zfs.pool_name"])
if err != nil {
return err
}
}
} else if filepath.IsAbs(d.config["source"]) {
// Handle existing block devices.
if !shared.IsBlockdevPath(d.config["source"]) {
return fmt.Errorf("Custom loop file locations are not supported")
}
// Validate pool_name.
if strings.Contains(d.config["zfs.pool_name"], "/") {
return fmt.Errorf("zfs.pool_name can't point to a dataset when source isn't set")
}
// Wipe if requested.
if shared.IsTrue(d.config["source.wipe"]) {
err := wipeBlockHeaders(d.config["source"])
if err != nil {
return fmt.Errorf("Failed to wipe headers from disk %q: %w", d.config["source"], err)
}
d.config["source.wipe"] = ""
// Create the zpool.
_, err = shared.RunCommand("zpool", "create", "-f", "-m", "none", "-O", "compression=on", d.config["zfs.pool_name"], d.config["source"])
if err != nil {
return err
}
} else {
// Create the zpool.
_, err := shared.RunCommand("zpool", "create", "-m", "none", "-O", "compression=on", d.config["zfs.pool_name"], d.config["source"])
if err != nil {
return err
}
}
// Apply auto-trim if supported.
if zfsTrim {
_, err := shared.RunCommand("zpool", "set", "autotrim=on", d.config["zfs.pool_name"])
if err != nil {
return err
}
}
// We don't need to keep the original source path around for import.
d.config["source"] = d.config["zfs.pool_name"]
} else {
// Validate pool_name.
if d.config["zfs.pool_name"] != d.config["source"] {
return fmt.Errorf("The source must match zfs.pool_name if specified")
}
if strings.Contains(d.config["zfs.pool_name"], "/") {
// Handle a dataset.
exists, err := d.datasetExists(d.config["zfs.pool_name"])
if err != nil {
return err
}
if !exists {
err := d.createDataset(d.config["zfs.pool_name"], "mountpoint=legacy")
if err != nil {
return err
}
}
} else {
// Ensure that the pool is available.
_, err := d.importPool()
if err != nil {
return err
}
}
// Confirm that the existing pool/dataset is all empty.
datasets, err := d.getDatasets(d.config["zfs.pool_name"], "all")
if err != nil {
return err
}
if len(datasets) > 0 {
return fmt.Errorf(`Provided ZFS pool (or dataset) isn't empty, run "sudo zfs list -r %s" to see existing entries`, d.config["zfs.pool_name"])
}
}
// Setup revert in case of problems
revert := revert.New()
defer revert.Fail()
revert.Add(func() { _ = d.Delete(nil) })
// Apply our default configuration.
err = d.ensureInitialDatasets(false)
if err != nil {
return err
}
revert.Success()
return nil
}
// Delete removes the storage pool from the storage device.
func (d *zfs) Delete(op *operations.Operation) error {
// Check if the dataset/pool is already gone.
exists, err := d.datasetExists(d.config["zfs.pool_name"])
if err != nil {
return err
}
if !exists {
return nil
}
// Confirm that nothing's been left behind
datasets, err := d.getDatasets(d.config["zfs.pool_name"], "all")
if err != nil {
return err
}
initialDatasets := d.initialDatasets()
for _, dataset := range datasets {
dataset = strings.TrimPrefix(dataset, "/")
if shared.ValueInSlice(dataset, initialDatasets) {
continue
}
fields := strings.Split(dataset, "/")
if len(fields) > 1 {
return fmt.Errorf("ZFS pool has leftover datasets: %s", dataset)
}
}
if strings.Contains(d.config["zfs.pool_name"], "/") {
// Delete the dataset.
_, err := shared.RunCommand("zfs", "destroy", "-r", d.config["zfs.pool_name"])
if err != nil {
return err
}
} else {
// Delete the pool.
_, err := shared.RunCommand("zpool", "destroy", d.config["zfs.pool_name"])
if err != nil {
return err
}
}
// On delete, wipe everything in the directory.
err = wipeDirectory(GetPoolMountPath(d.name))
if err != nil {
return err
}
// Delete any loop file we may have used
loopPath := loopFilePath(d.name)
err = os.Remove(loopPath)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("Failed to remove '%s': %w", loopPath, err)
}
return nil
}
// Validate checks that all provide keys are supported and that no conflicting or missing configuration is present.
func (d *zfs) Validate(config map[string]string) error {
rules := map[string]func(value string) error{
"size": validate.Optional(validate.IsSize),
// lxdmeta:generate(entities=storage-zfs; group=pool-conf; key=zfs.pool_name)
//
// ---
// type: string
// defaultdesc: name of the pool
// shortdesc: Name of the zpool
"zfs.pool_name": validate.IsAny,
// lxdmeta:generate(entities=storage-zfs; group=pool-conf; key=zfs.clone_copy)
// Set this option to `true` or `false` to enable or disable using ZFS lightweight clones rather
// than full dataset copies.
// Set the option to `rebase` to copy based on the initial image.
// ---
// type: string
// defaultdesc: `true`
// shortdesc: Whether to use ZFS lightweight clones
"zfs.clone_copy": validate.Optional(func(value string) error {
if value == "rebase" {
return nil
}
return validate.IsBool(value)
}),
// lxdmeta:generate(entities=storage-zfs; group=pool-conf; key=zfs.export)
//
// ---
// type: bool
// defaultdesc: `true`
// shortdesc: Disable zpool export while an unmount is being performed
"zfs.export": validate.Optional(validate.IsBool),
}
return d.validatePool(config, rules, d.commonVolumeRules())
}
// Update applies any driver changes required from a configuration change.
func (d *zfs) Update(changedConfig map[string]string) error {
_, ok := changedConfig["zfs.pool_name"]
if ok {
return fmt.Errorf("zfs.pool_name cannot be modified")
}
size, ok := changedConfig["size"]
if ok {
// Figure out loop path
loopPath := loopFilePath(d.name)
if d.config["source"] != loopPath {
return fmt.Errorf("Cannot resize non-loopback pools")
}
// Resize loop file
f, err := os.OpenFile(loopPath, os.O_RDWR, 0600)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
sizeBytes, _ := units.ParseByteSizeString(size)
err = f.Truncate(sizeBytes)
if err != nil {
return err
}
_, err = shared.RunCommand("zpool", "online", "-e", d.config["zfs.pool_name"], loopPath)
if err != nil {
return err
}
}
return nil
}
// importPool the storage pool.
func (d *zfs) importPool() (bool, error) {
if d.config["zfs.pool_name"] == "" {
return false, fmt.Errorf("Cannot mount pool as %q is not specified", "zfs.pool_name")
}
// Check if already setup.
exists, err := d.datasetExists(d.config["zfs.pool_name"])
if err != nil {
return false, err
}
if exists {
return false, nil
}
// Check if the pool exists.
poolName := strings.Split(d.config["zfs.pool_name"], "/")[0]
exists, err = d.datasetExists(poolName)
if err != nil {
return false, err
}
if exists {
return false, fmt.Errorf("ZFS zpool exists but dataset is missing")
}
// Import the pool.
if filepath.IsAbs(d.config["source"]) {
disksPath := shared.VarPath("disks")
_, err := shared.RunCommand("zpool", "import", "-f", "-d", disksPath, poolName)
if err != nil {
return false, err
}
} else {
_, err := shared.RunCommand("zpool", "import", poolName)
if err != nil {
return false, err
}
}
// Check that the dataset now exists.
exists, err = d.datasetExists(d.config["zfs.pool_name"])
if err != nil {
return false, err
}
if exists {
return true, nil
}
return false, fmt.Errorf("ZFS zpool exists but dataset is missing")
}
// Mount mounts the storage pool.
func (d *zfs) Mount() (bool, error) {
// Import the pool if not already imported.
imported, err := d.importPool()
if err != nil {
return false, err
}
// Apply our default configuration.
err = d.ensureInitialDatasets(true)
if err != nil {
return false, err
}
return imported, nil
}
// Unmount unmounts the storage pool.
func (d *zfs) Unmount() (bool, error) {
// Skip if zfs.export config is set to false
if shared.IsFalse(d.config["zfs.export"]) {
return false, nil
}
// Skip if using a dataset and not a full pool.
if strings.Contains(d.config["zfs.pool_name"], "/") {
return false, nil
}
// Check if already unmounted.
exists, err := d.datasetExists(d.config["zfs.pool_name"])
if err != nil {
return false, err
}
if !exists {
return false, nil
}
// Export the pool.
poolName := strings.Split(d.config["zfs.pool_name"], "/")[0]
_, err = shared.RunCommand("zpool", "export", poolName)
if err != nil {
return false, err
}
return true, nil
}
func (d *zfs) GetResources() (*api.ResourcesStoragePool, error) {
// Get the total amount of space.
availableStr, err := d.getDatasetProperty(d.config["zfs.pool_name"], "available")
if err != nil {
return nil, err
}
available, err := strconv.ParseUint(strings.TrimSpace(availableStr), 10, 64)
if err != nil {
return nil, err
}
// Get the used amount of space.
usedStr, err := d.getDatasetProperty(d.config["zfs.pool_name"], "used")
if err != nil {
return nil, err
}
used, err := strconv.ParseUint(strings.TrimSpace(usedStr), 10, 64)
if err != nil {
return nil, err
}
// Build the struct.
// Inode allocation is dynamic so no use in reporting them.
res := api.ResourcesStoragePool{}
res.Space.Total = used + available
res.Space.Used = used
return &res, nil
}
// MigrationType returns the type of transfer methods to be used when doing migrations between pools in preference order.
func (d *zfs) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {
var rsyncFeatures []string
// Do not pass compression argument to rsync if the associated
// config key, that is rsync.compression, is set to false.
if shared.IsFalse(d.Config()["rsync.compression"]) {
rsyncFeatures = []string{"xattrs", "delete", "bidirectional"}
} else {
rsyncFeatures = []string{"xattrs", "delete", "compress", "bidirectional"}
}
// Detect ZFS features.
features := []string{migration.ZFSFeatureMigrationHeader, "compress"}
if contentType == ContentTypeFS {
features = append(features, migration.ZFSFeatureZvolFilesystems)
}
if IsContentBlock(contentType) {
return []migration.Type{
{
FSType: migration.MigrationFSType_ZFS,
Features: features,
},
{
FSType: migration.MigrationFSType_BLOCK_AND_RSYNC,
Features: rsyncFeatures,
},
}
}
if refresh && !copySnapshots {
return []migration.Type{
{
FSType: migration.MigrationFSType_RSYNC,
Features: rsyncFeatures,
},
}
}
return []migration.Type{
{
FSType: migration.MigrationFSType_ZFS,
Features: features,
},
{
FSType: migration.MigrationFSType_RSYNC,
Features: rsyncFeatures,
},
}
}
// patchDropBlockVolumeFilesystemExtension removes the filesystem extension (e.g _ext4) from VM image block volumes.
func (d *zfs) patchDropBlockVolumeFilesystemExtension() error {
poolName, ok := d.config["zfs.pool_name"]
if !ok {
poolName = d.name
}
out, err := shared.RunCommand("zfs", "list", "-H", "-r", "-o", "name", "-t", "volume", fmt.Sprintf("%s/images", poolName))
if err != nil {
return fmt.Errorf("Failed listing images: %w", err)
}
for _, volume := range strings.Split(out, "\n") {
fields := strings.SplitN(volume, fmt.Sprintf("%s/images/", poolName), 2)
if len(fields) != 2 || fields[1] == "" {
continue
}
// Ignore non-block images, and images without filesystem extension
if !strings.HasSuffix(fields[1], ".block") || !strings.Contains(fields[1], "_") {
continue
}
// Rename zfs dataset. Snapshots will automatically be renamed.
newName := fmt.Sprintf("%s/images/%s.block", poolName, strings.Split(fields[1], "_")[0])
_, err = shared.RunCommand("zfs", "rename", volume, newName)
if err != nil {
return fmt.Errorf("Failed renaming zfs dataset: %w", err)
}
}
return nil
}