-
-
Notifications
You must be signed in to change notification settings - Fork 165
/
driver_btrfs_utils.go
597 lines (475 loc) · 15.8 KB
/
driver_btrfs_utils.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
package drivers
import (
"bufio"
"context"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"unsafe"
"github.com/pborman/uuid"
"golang.org/x/sys/unix"
"gopkg.in/yaml.v2"
"github.com/lxc/lxd/lxd/backup"
"github.com/lxc/lxd/lxd/revert"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/ioprogress"
"github.com/lxc/lxd/shared/logger"
)
// Errors.
var errBtrfsNoQuota = fmt.Errorf("Quotas disabled on filesystem")
var errBtrfsNoQGroup = fmt.Errorf("Unable to find quota group")
// setReceivedUUID sets the "Received UUID" field on a subvolume with the given path using ioctl.
func setReceivedUUID(path string, UUID string) error {
type btrfsIoctlReceivedSubvolArgs struct {
uuid [16]byte
_ [22]uint64 // padding
}
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("Failed opening %s: %w", path, err)
}
defer func() { _ = f.Close() }()
args := btrfsIoctlReceivedSubvolArgs{}
binUUID, err := uuid.Parse(UUID).MarshalBinary()
if err != nil {
return fmt.Errorf("Failed coverting UUID: %w", err)
}
copy(args.uuid[:], binUUID)
// 0xC0C09425 = _IOWR(BTRFS_IOCTL_MAGIC, 37, struct btrfs_ioctl_received_subvol_args)
_, _, errno := unix.Syscall(unix.SYS_IOCTL, f.Fd(), 0xC0C09425, uintptr(unsafe.Pointer(&args)))
if errno != 0 {
return fmt.Errorf("Failed setting received UUID: %w", unix.Errno(errno))
}
return nil
}
func (d *btrfs) getMountOptions() string {
// Allow overriding the default options.
if d.config["btrfs.mount_options"] != "" {
return d.config["btrfs.mount_options"]
}
return "user_subvol_rm_allowed"
}
func (d *btrfs) isSubvolume(path string) bool {
// Stat the path.
fs := unix.Stat_t{}
err := unix.Lstat(path, &fs)
if err != nil {
return false
}
// Check if BTRFS_FIRST_FREE_OBJECTID is the inode number.
if fs.Ino != 256 {
return false
}
return true
}
func (d *btrfs) getSubvolumes(path string) ([]string, error) {
result := []string{}
// Make sure the path has a trailing slash.
if !strings.HasSuffix(path, "/") {
path = path + "/"
}
// Walk through the entire tree looking for subvolumes.
err := filepath.WalkDir(path, func(fpath string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
// Ignore the base path.
if strings.TrimRight(fpath, "/") == strings.TrimRight(path, "/") {
return nil
}
// Subvolumes can only be directories.
if !entry.IsDir() {
return nil
}
// Check if a subvolume.
if d.isSubvolume(fpath) {
result = append(result, strings.TrimPrefix(fpath, path))
}
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
// snapshotSubvolume creates a snapshot of the specified path at the dest supplied. If recursion is true and
// sub volumes are found below the path then they are created at the relative location in dest.
func (d *btrfs) snapshotSubvolume(path string, dest string, recursion bool) (revert.Hook, error) {
revert := revert.New()
defer revert.Fail()
// Single subvolume creation.
snapshot := func(path string, dest string) error {
_, err := shared.RunCommand("btrfs", "subvolume", "snapshot", path, dest)
if err != nil {
return err
}
revert.Add(func() {
// Don't delete recursive since there already is a revert hook
// for each subvolume that got created.
_ = d.deleteSubvolume(dest, false)
})
return nil
}
// First snapshot the root.
err := snapshot(path, dest)
if err != nil {
return nil, err
}
// Now snapshot all subvolumes of the root.
if recursion {
// Get the subvolumes list.
subSubVols, err := d.getSubvolumes(path)
if err != nil {
return nil, err
}
sort.Strings(subSubVols)
for _, subSubVol := range subSubVols {
subSubVolSnapPath := filepath.Join(dest, subSubVol)
// Clear the target for the subvol to use.
_ = os.Remove(subSubVolSnapPath)
err := snapshot(filepath.Join(path, subSubVol), subSubVolSnapPath)
if err != nil {
return nil, err
}
}
}
cleanup := revert.Clone().Fail
revert.Success()
return cleanup, nil
}
func (d *btrfs) deleteSubvolume(rootPath string, recursion bool) error {
// Single subvolume deletion.
destroy := func(path string) error {
// Attempt (but don't fail on) to delete any qgroup on the subvolume.
qgroup, _, err := d.getQGroup(path)
if err == nil {
_, _ = shared.RunCommand("btrfs", "qgroup", "destroy", qgroup, path)
}
// Temporarily change ownership & mode to help with nesting.
_ = os.Chmod(path, 0700)
_ = os.Chown(path, 0, 0)
// Delete the subvolume itself.
_, err = shared.RunCommand("btrfs", "subvolume", "delete", path)
return err
}
// Try and ensure volume is writable to possibility of destroy failing.
err := d.setSubvolumeReadonlyProperty(rootPath, false)
if err != nil {
d.logger.Warn("Failed setting subvolume writable", logger.Ctx{"path": rootPath, "err": err})
}
// Attempt to delete the root subvol itself (short path).
err = destroy(rootPath)
if err == nil {
return nil
} else if !recursion {
return fmt.Errorf("Failed deleting subvolume %q: %w", rootPath, err)
}
// Delete subsubvols as recursion enabled.
// Get the subvolumes list.
subSubVols, err := d.getSubvolumes(rootPath)
if err != nil {
return err
}
// Perform a first pass and ensure all sub volumes are writable.
sort.Sort(sort.StringSlice(subSubVols))
for _, subSubVol := range subSubVols {
subSubVolPath := filepath.Join(rootPath, subSubVol)
err = d.setSubvolumeReadonlyProperty(subSubVolPath, false)
if err != nil {
d.logger.Warn("Failed setting subvolume writable", logger.Ctx{"path": subSubVolPath, "err": err})
}
}
// Perform a second pass to delete subvolumes.
sort.Sort(sort.Reverse(sort.StringSlice(subSubVols)))
for _, subSubVol := range subSubVols {
subSubVolPath := filepath.Join(rootPath, subSubVol)
err := destroy(subSubVolPath)
if err != nil {
return fmt.Errorf("Failed deleting subvolume %q: %w", subSubVolPath, err)
}
}
// Delete the root subvol itself.
err = destroy(rootPath)
if err != nil {
return fmt.Errorf("Failed deleting subvolume %q: %w", rootPath, err)
}
return nil
}
func (d *btrfs) getQGroup(path string) (string, int64, error) {
// Try to get the qgroup details.
output, err := shared.RunCommand("btrfs", "qgroup", "show", "-e", "-f", "--raw", path)
if err != nil {
return "", -1, errBtrfsNoQuota
}
// Parse to extract the qgroup identifier.
var qgroup string
usage := int64(-1)
for _, line := range strings.Split(output, "\n") {
// Use case-insensitive field title match because BTRFS tooling changed casing between versions.
if line == "" || strings.HasPrefix(strings.ToLower(line), "qgroupid") || strings.HasPrefix(line, "-") {
continue
}
fields := strings.Fields(line)
// The BTRFS tooling changed the number of columns between versions so we only check for minimum.
if len(fields) < 3 {
continue
}
qgroup = fields[0]
val, err := strconv.ParseInt(fields[2], 10, 64)
if err == nil {
usage = val
}
break
}
if qgroup == "" {
return "", -1, errBtrfsNoQGroup
}
return qgroup, usage, nil
}
func (d *btrfs) sendSubvolume(path string, parent string, conn io.ReadWriteCloser, tracker *ioprogress.ProgressTracker) error {
defer func() { _ = conn.Close() }()
// Assemble btrfs send command.
args := []string{"send"}
if parent != "" {
args = append(args, "-p", parent)
}
args = append(args, path)
cmd := exec.Command("btrfs", args...)
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
// Setup progress tracker.
var stdout io.WriteCloser = conn
if tracker != nil {
stdout = &ioprogress.ProgressWriter{
WriteCloser: conn,
Tracker: tracker,
}
}
cmd.Stdout = stdout
// Run the command.
err = cmd.Start()
if err != nil {
return err
}
// Read any error.
output, err := io.ReadAll(stderr)
if err != nil {
logger.Errorf("Problem reading btrfs send stderr: %s", err)
}
err = cmd.Wait()
if err != nil {
return fmt.Errorf("Btrfs send failed: %w (%s)", err, string(output))
}
return nil
}
// setSubvolumeReadonlyProperty sets the readonly property on the subvolume to true or false.
func (d *btrfs) setSubvolumeReadonlyProperty(path string, readonly bool) error {
// Silently ignore requests to set subvolume readonly property if running in a user namespace as we won't
// be able to change it if it is readonly already, and making it readonly will mean we cannot undo it.
if d.state.OS.RunningInUserNS {
return nil
}
args := []string{"property", "set"}
if btrfsPropertyForce {
args = append(args, "-f")
}
args = append(args, "-ts", path, "ro", fmt.Sprintf("%t", readonly))
_, err := shared.RunCommand("btrfs", args...)
return err
}
// BTRFSSubVolume is the structure used to store information about a subvolume.
// Note: This is used by both migration and backup subsystems so do not modify without considering both!
type BTRFSSubVolume struct {
Path string `json:"path" yaml:"path"` // Path inside the volume where the subvolume belongs (so / is the top of the volume tree).
Snapshot string `json:"snapshot" yaml:"snapshot"` // Snapshot name the subvolume belongs to.
Readonly bool `json:"readonly" yaml:"readonly"` // Is the sub volume read only or not.
UUID string `json:"uuid" yaml:"uuid"` // The subvolume UUID.
}
// getSubvolumesMetaData retrieves subvolume meta data with paths relative to the root volume.
// The first item in the returned list is the root subvolume itself.
func (d *btrfs) getSubvolumesMetaData(vol Volume) ([]BTRFSSubVolume, error) {
var subVols []BTRFSSubVolume
snapName := ""
if vol.IsSnapshot() {
_, snapName, _ = api.GetParentAndSnapshotName(vol.name)
}
// Add main root volume to subvolumes list first.
subVols = append(subVols, BTRFSSubVolume{
Snapshot: snapName,
Path: string(filepath.Separator),
Readonly: BTRFSSubVolumeIsRo(vol.MountPath()),
})
// Find any subvolumes in volume.
subVolPaths, err := d.getSubvolumes(vol.MountPath())
if err != nil {
return nil, err
}
sort.Strings(subVolPaths)
// Add any subvolumes under the root subvolume with relative path to root.
for _, subVolPath := range subVolPaths {
subVols = append(subVols, BTRFSSubVolume{
Snapshot: snapName,
Path: fmt.Sprintf("%s%s", string(filepath.Separator), subVolPath),
Readonly: BTRFSSubVolumeIsRo(filepath.Join(vol.MountPath(), subVolPath)),
})
}
stdout := strings.Builder{}
poolMountPath := GetPoolMountPath(vol.pool)
if !d.state.OS.RunningInUserNS {
// List all subvolumes in the given filesystem with their UUIDs and received UUIDs.
err = shared.RunCommandWithFds(context.TODO(), nil, &stdout, "btrfs", "subvolume", "list", "-u", "-R", poolMountPath)
if err != nil {
return nil, err
}
uuidMap := make(map[string]string)
receivedUUIDMap := make(map[string]string)
scanner := bufio.NewScanner(strings.NewReader(stdout.String()))
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) != 13 {
continue
}
uuidMap[filepath.Join(poolMountPath, fields[12])] = fields[10]
if fields[8] != "-" {
receivedUUIDMap[filepath.Join(poolMountPath, fields[12])] = fields[8]
}
}
for i, subVol := range subVols {
subVols[i].UUID = uuidMap[filepath.Join(vol.MountPath(), subVol.Path)]
}
}
return subVols, nil
}
func (d *btrfs) getSubVolumeReceivedUUID(vol Volume) (string, error) {
stdout := strings.Builder{}
poolMountPath := GetPoolMountPath(vol.pool)
// List all subvolumes in the given filesystem with their UUIDs.
err := shared.RunCommandWithFds(context.TODO(), nil, &stdout, "btrfs", "subvolume", "list", "-R", poolMountPath)
if err != nil {
return "", err
}
scanner := bufio.NewScanner(strings.NewReader(stdout.String()))
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) != 11 {
continue
}
if vol.MountPath() == filepath.Join(poolMountPath, fields[10]) && fields[8] != "-" {
return fields[8], nil
}
}
return "", nil
}
// BTRFSMetaDataHeader is the meta data header about the volumes being sent/stored.
// Note: This is used by both migration and backup subsystems so do not modify without considering both!
type BTRFSMetaDataHeader struct {
Subvolumes []BTRFSSubVolume `json:"subvolumes" yaml:"subvolumes"` // Sub volumes inside the volume (including the top level ones).
}
// restorationHeader scans the volume and any specified snapshots, returning a header containing subvolume metadata
// for use in restoring a volume and its snapshots onto another system. The metadata returned represents how the
// subvolumes should be restored, not necessarily how they are on disk now. Most of the time this is the same,
// however in circumstances where the volume being scanned is itself a snapshot, the returned metadata will
// not report the volume as readonly or as being a snapshot, as the expectation is that this volume will be
// restored on the target system as a normal volume and not a snapshot.
func (d *btrfs) restorationHeader(vol Volume, snapshots []string) (*BTRFSMetaDataHeader, error) {
var migrationHeader BTRFSMetaDataHeader
// Add snapshots to volumes list.
for _, snapName := range snapshots {
snapVol, _ := vol.NewSnapshot(snapName)
// Add snapshot root volume to volumes list.
subVols, err := d.getSubvolumesMetaData(snapVol)
if err != nil {
return nil, err
}
migrationHeader.Subvolumes = append(migrationHeader.Subvolumes, subVols...)
}
// Add main root volume to volumes list.
subVols, err := d.getSubvolumesMetaData(vol)
if err != nil {
return nil, err
}
// If vol is a snapshot itself, we force the volume as writable (even if it isn't on disk) and remove the
// snapshot name indicator as the expectation is that this volume is going to be restored on the target
// system as a normal (non-snapshot) writable volume.
if vol.IsSnapshot() {
subVols[0].Readonly = false
for i := range subVols {
subVols[i].Snapshot = ""
}
}
migrationHeader.Subvolumes = append(migrationHeader.Subvolumes, subVols...)
return &migrationHeader, nil
}
// loadOptimizedBackupHeader extracts optimized backup header from a given ReadSeeker.
func (d *btrfs) loadOptimizedBackupHeader(r io.ReadSeeker, mountPath string) (*BTRFSMetaDataHeader, error) {
header := BTRFSMetaDataHeader{}
// Extract.
tr, cancelFunc, err := backup.TarReader(r, d.state.OS, mountPath)
if err != nil {
return nil, err
}
defer cancelFunc()
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive.
}
if err != nil {
return nil, fmt.Errorf("Error reading backup file for optimized backup header file: %w", err)
}
if hdr.Name == "backup/optimized_header.yaml" {
err = yaml.NewDecoder(tr).Decode(&header)
if err != nil {
return nil, fmt.Errorf("Error parsing optimized backup header file: %w", err)
}
cancelFunc()
return &header, nil
}
}
return nil, fmt.Errorf("Optimized backup header file not found")
}
// receiveSubVolume receives a subvolume from an io.Reader into the receivePath and returns the path to the received subvolume.
func (d *btrfs) receiveSubVolume(r io.Reader, receivePath string) (string, error) {
files, err := os.ReadDir(receivePath)
if err != nil {
return "", fmt.Errorf("Failed listing contents of %q: %w", receivePath, err)
}
err = shared.RunCommandWithFds(context.TODO(), r, nil, "btrfs", "receive", "-e", receivePath)
if err != nil {
return "", err
}
// Check contents of target path is expected after receive.
newFiles, err := os.ReadDir(receivePath)
if err != nil {
return "", fmt.Errorf("Failed listing contents of %q: %w", receivePath, err)
}
filename := ""
// Identify the latest received path.
for _, a := range newFiles {
found := false
for _, b := range files {
if a.Name() == b.Name() {
found = true
break
}
}
if !found {
filename = a.Name()
break
}
}
if filename == "" {
return "", fmt.Errorf("Failed to determine received subvolume")
}
subVolPath := filepath.Join(receivePath, filename)
return subVolPath, nil
}