]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage/BTRFSPlugin.pm
some code style refcatoring/cleanup
[pve-storage.git] / PVE / Storage / BTRFSPlugin.pm
1 package PVE::Storage::BTRFSPlugin;
2
3 use strict;
4 use warnings;
5
6 use base qw(PVE::Storage::Plugin);
7
8 use Fcntl qw(S_ISDIR O_WRONLY O_CREAT O_EXCL);
9 use File::Basename qw(basename dirname);
10 use File::Path qw(mkpath);
11 use IO::Dir;
12 use POSIX qw(EEXIST);
13
14 use PVE::Tools qw(run_command dir_glob_foreach);
15
16 use PVE::Storage::DirPlugin;
17
18 use constant {
19 BTRFS_FIRST_FREE_OBJECTID => 256,
20 FS_NOCOW_FL => 0x00800000,
21 FS_IOC_GETFLAGS => 0x40086602,
22 FS_IOC_SETFLAGS => 0x80086601,
23 BTRFS_MAGIC => 0x9123683e,
24 };
25
26 # Configuration (similar to DirPlugin)
27
28 sub type {
29 return 'btrfs';
30 }
31
32 sub plugindata {
33 return {
34 content => [
35 {
36 images => 1,
37 rootdir => 1,
38 vztmpl => 1,
39 iso => 1,
40 backup => 1,
41 snippets => 1,
42 none => 1,
43 },
44 { images => 1, rootdir => 1 },
45 ],
46 format => [ { raw => 1, subvol => 1 }, 'raw', ],
47 };
48 }
49
50 sub properties {
51 return {
52 nocow => {
53 description => "Set the NOCOW flag on files."
54 . " Disables data checksumming and causes data errors to be unrecoverable from"
55 . " while allowing direct I/O. Only use this if data does not need to be any more"
56 . " safe than on a single ext4 formatted disk with no underlying raid system.",
57 type => 'boolean',
58 default => 0,
59 },
60 };
61 }
62
63 sub options {
64 return {
65 path => { fixed => 1 },
66 nodes => { optional => 1 },
67 shared => { optional => 1 },
68 disable => { optional => 1 },
69 maxfiles => { optional => 1 },
70 'prune-backups' => { optional => 1 },
71 'max-protected-backups' => { optional => 1 },
72 content => { optional => 1 },
73 format => { optional => 1 },
74 is_mountpoint => { optional => 1 },
75 nocow => { optional => 1 },
76 mkdir => { optional => 1 },
77 preallocation => { optional => 1 },
78 # TODO: The new variant of mkdir with `populate` vs `create`...
79 };
80 }
81
82 # Storage implementation
83 #
84 # We use the same volume names are directory plugins, but map *raw* disk image file names into a
85 # subdirectory.
86 #
87 # `vm-VMID-disk-ID.raw`
88 # -> `images/VMID/vm-VMID-disk-ID/disk.raw`
89 # where the `vm-VMID-disk-ID/` subdirectory is a btrfs subvolume
90
91 # Reuse `DirPlugin`'s `check_config`. This simply checks for invalid paths.
92 sub check_config {
93 my ($self, $sectionId, $config, $create, $skipSchemaCheck) = @_;
94 return PVE::Storage::DirPlugin::check_config($self, $sectionId, $config, $create, $skipSchemaCheck);
95 }
96
97 my sub getfsmagic($) {
98 my ($path) = @_;
99 # The field type sizes in `struct statfs` are defined in a rather annoying way, and we only
100 # need the first field, which is a `long` for our supported platforms.
101 # Should be moved to pve-rs, so this can be the problem of the `libc` crate ;-)
102 # Just round up and extract what we need:
103 my $buf = pack('x160');
104 if (0 != syscall(&PVE::Syscall::SYS_statfs, $path, $buf)) {
105 die "statfs on '$path' failed - $!\n";
106 }
107
108 return unpack('L!', $buf);
109 }
110
111 my sub assert_btrfs($) {
112 my ($path) = @_;
113 die "'$path' is not a btrfs file system\n"
114 if getfsmagic($path) != BTRFS_MAGIC;
115 }
116
117 sub activate_storage {
118 my ($class, $storeid, $scfg, $cache) = @_;
119
120 my $path = $scfg->{path};
121 if (!defined($scfg->{mkdir}) || $scfg->{mkdir}) {
122 mkpath $path;
123 }
124
125 my $mp = PVE::Storage::DirPlugin::parse_is_mountpoint($scfg);
126 if (defined($mp) && !PVE::Storage::DirPlugin::path_is_mounted($mp, $cache->{mountdata})) {
127 die "unable to activate storage '$storeid' - directory is expected to be a mount point but"
128 ." is not mounted: '$mp'\n";
129 }
130
131 assert_btrfs($path); # only assert this stuff now, ensures $path is there and better UX
132
133 $class->SUPER::activate_storage($storeid, $scfg, $cache);
134 }
135
136 sub status {
137 my ($class, $storeid, $scfg, $cache) = @_;
138 return PVE::Storage::DirPlugin::status($class, $storeid, $scfg, $cache);
139 }
140
141 # TODO: sub get_volume_attribute {}
142
143 # TODO: sub update_volume_attribute {}
144
145 # croak would not include the caller from within this module
146 sub __error {
147 my ($msg) = @_;
148 my (undef, $f, $n) = caller(1);
149 die "$msg at $f: $n\n";
150 }
151
152 # Given a name (eg. `vm-VMID-disk-ID.raw`), take the part up to the format suffix as the name of
153 # the subdirectory (subvolume).
154 sub raw_name_to_dir($) {
155 my ($raw) = @_;
156
157 # For the subvolume directory Strip the `.<format>` suffix:
158 if ($raw =~ /^(.*)\.raw$/) {
159 return $1;
160 }
161
162 __error "internal error: bad disk name: $raw";
163 }
164
165 sub raw_file_to_subvol($) {
166 my ($file) = @_;
167
168 if ($file =~ m|^(.*)/disk\.raw$|) {
169 return "$1";
170 }
171
172 __error "internal error: bad raw path: $file";
173 }
174
175 sub filesystem_path {
176 my ($class, $scfg, $volname, $snapname) = @_;
177
178 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
179 $class->parse_volname($volname);
180
181 my $path = $class->get_subdir($scfg, $vtype);
182
183 $path .= "/$vmid" if $vtype eq 'images';
184
185 if (defined($format) && $format eq 'raw') {
186 my $dir = raw_name_to_dir($name);
187 if ($snapname) {
188 $dir .= "\@$snapname";
189 }
190 $path .= "/$dir/disk.raw";
191 } elsif (defined($format) && $format eq 'subvol') {
192 $path .= "/$name";
193 if ($snapname) {
194 $path .= "\@$snapname";
195 }
196 } else {
197 $path .= "/$name";
198 }
199
200 return wantarray ? ($path, $vmid, $vtype) : $path;
201 }
202
203 sub btrfs_cmd {
204 my ($class, $cmd, $outfunc) = @_;
205
206 my $msg = '';
207 my $func;
208 if (defined($outfunc)) {
209 $func = sub {
210 my $part = &$outfunc(@_);
211 $msg .= $part if defined($part);
212 };
213 } else {
214 $func = sub { $msg .= "$_[0]\n" };
215 }
216 run_command(['btrfs', '-q', @$cmd], errmsg => 'btrfs error', outfunc => $func);
217
218 return $msg;
219 }
220
221 sub btrfs_get_subvol_id {
222 my ($class, $path) = @_;
223 my $info = $class->btrfs_cmd(['subvolume', 'show', '--', $path]);
224 if ($info !~ /^\s*(?:Object|Subvolume) ID:\s*(\d+)$/m) {
225 die "failed to get btrfs subvolume ID from: $info\n";
226 }
227 return $1;
228 }
229
230 my sub chattr : prototype($$$) {
231 my ($fh, $mask, $xor) = @_;
232
233 my $flags = pack('L!', 0);
234 ioctl($fh, FS_IOC_GETFLAGS, $flags) or die "FS_IOC_GETFLAGS failed - $!\n";
235 $flags = pack('L!', (unpack('L!', $flags) & $mask) ^ $xor);
236 ioctl($fh, FS_IOC_SETFLAGS, $flags) or die "FS_IOC_SETFLAGS failed - $!\n";
237 return 1;
238 }
239
240 sub create_base {
241 my ($class, $storeid, $scfg, $volname) = @_;
242
243 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
244 $class->parse_volname($volname);
245
246 my $newname = $name;
247 $newname =~ s/^vm-/base-/;
248
249 # If we're not working with a 'raw' file, which is the only thing that's "different" for btrfs,
250 # or a subvolume, we forward to the DirPlugin
251 if ($format ne 'raw' && $format ne 'subvol') {
252 return PVE::Storage::DirPlugin::create_base(@_);
253 }
254
255 my $path = $class->filesystem_path($scfg, $volname);
256 my $newvolname = $basename ? "$basevmid/$basename/$vmid/$newname" : "$vmid/$newname";
257 my $newpath = $class->filesystem_path($scfg, $newvolname);
258
259 my $subvol = $path;
260 my $newsubvol = $newpath;
261 if ($format eq 'raw') {
262 $subvol = raw_file_to_subvol($subvol);
263 $newsubvol = raw_file_to_subvol($newsubvol);
264 }
265
266 rename($subvol, $newsubvol)
267 || die "rename '$subvol' to '$newsubvol' failed - $!\n";
268 eval { $class->btrfs_cmd(['property', 'set', $newsubvol, 'ro', 'true']) };
269 warn $@ if $@;
270
271 return $newvolname;
272 }
273
274 sub clone_image {
275 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
276
277 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
278 $class->parse_volname($volname);
279
280 # If we're not working with a 'raw' file, which is the only thing that's "different" for btrfs,
281 # or a subvolume, we forward to the DirPlugin
282 if ($format ne 'raw' && $format ne 'subvol') {
283 return PVE::Storage::DirPlugin::clone_image(@_);
284 }
285
286 my $imagedir = $class->get_subdir($scfg, 'images');
287 $imagedir .= "/$vmid";
288 mkpath $imagedir;
289
290 my $path = $class->filesystem_path($scfg, $volname);
291 my $newname = $class->find_free_diskname($storeid, $scfg, $vmid, $format, 1);
292
293 # For btrfs subvolumes we don't actually need the "link":
294 #my $newvolname = "$basevmid/$basename/$vmid/$newname";
295 my $newvolname = "$vmid/$newname";
296 my $newpath = $class->filesystem_path($scfg, $newvolname);
297
298 my $subvol = $path;
299 my $newsubvol = $newpath;
300 if ($format eq 'raw') {
301 $subvol = raw_file_to_subvol($subvol);
302 $newsubvol = raw_file_to_subvol($newsubvol);
303 }
304
305 $class->btrfs_cmd(['subvolume', 'snapshot', '--', $subvol, $newsubvol]);
306
307 return $newvolname;
308 }
309
310 sub alloc_image {
311 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
312
313 if ($fmt ne 'raw' && $fmt ne 'subvol') {
314 return $class->SUPER::alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size);
315 }
316
317 # From Plugin.pm:
318
319 my $imagedir = $class->get_subdir($scfg, 'images') . "/$vmid";
320
321 mkpath $imagedir;
322
323 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
324
325 my (undef, $tmpfmt) = PVE::Storage::Plugin::parse_name_dir($name);
326
327 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
328 if $tmpfmt ne $fmt;
329
330 # End copy from Plugin.pm
331
332 my $subvol = "$imagedir/$name";
333 # .raw is not part of the directory name
334 $subvol =~ s/\.raw$//;
335
336 die "disk image '$subvol' already exists\n" if -e $subvol;
337
338 my $path;
339 if ($fmt eq 'raw') {
340 $path = "$subvol/disk.raw";
341 }
342
343 if ($fmt eq 'subvol' && !!$size) {
344 # NOTE: `btrfs send/recv` actually drops quota information so supporting subvolumes with
345 # quotas doesn't play nice with send/recv.
346 die "btrfs quotas are currently not supported, use an unsized subvolume or a raw file\n";
347 }
348
349 $class->btrfs_cmd(['subvolume', 'create', '--', $subvol]);
350
351 eval {
352 if ($fmt eq 'subvol') {
353 # Nothing to do for now...
354
355 # This is how we *would* do it:
356 # # Use the subvol's default 0/$id qgroup
357 # eval {
358 # # This call should happen at storage creation instead and therefore governed by a
359 # # configuration option!
360 # # $class->btrfs_cmd(['quota', 'enable', $subvol]);
361 # my $id = $class->btrfs_get_subvol_id($subvol);
362 # $class->btrfs_cmd(['qgroup', 'limit', "${size}k", "0/$id", $subvol]);
363 # };
364 } elsif ($fmt eq 'raw') {
365 sysopen my $fh, $path, O_WRONLY | O_CREAT | O_EXCL
366 or die "failed to create raw file '$path' - $!\n";
367 chattr($fh, ~FS_NOCOW_FL, FS_NOCOW_FL) if $scfg->{nocow};
368 truncate($fh, $size * 1024)
369 or die "failed to set file size for '$path' - $!\n";
370 close($fh);
371 } else {
372 die "internal format error (format = $fmt)\n";
373 }
374 };
375
376 if (my $err = $@) {
377 eval { $class->btrfs_cmd(['subvolume', 'delete', '--', $subvol]); };
378 warn $@ if $@;
379 die $err;
380 }
381
382 return "$vmid/$name";
383 }
384
385 # Same as btrfsprogs does:
386 my sub path_is_subvolume : prototype($) {
387 my ($path) = @_;
388 my @stat = stat($path)
389 or die "stat failed on '$path' - $!\n";
390 my ($ino, $mode) = @stat[1, 2];
391 return S_ISDIR($mode) && $ino == BTRFS_FIRST_FREE_OBJECTID;
392 }
393
394 my $BTRFS_VOL_REGEX = qr/((?:vm|base|subvol)-\d+-disk-\d+(?:\.subvol)?)(?:\@(\S+))$/;
395
396 # Calls `$code->($volume, $name, $snapshot)` for each subvol in a directory matching our volume
397 # regex.
398 my sub foreach_subvol : prototype($$) {
399 my ($dir, $code) = @_;
400
401 dir_glob_foreach($dir, $BTRFS_VOL_REGEX, sub {
402 my ($volume, $name, $snapshot) = ($1, $2, $3);
403 return if !path_is_subvolume("$dir/$volume");
404 $code->($volume, $name, $snapshot);
405 })
406 }
407
408 sub free_image {
409 my ($class, $storeid, $scfg, $volname, $isBase, $_format) = @_;
410
411 my (undef, undef, $vmid, undef, undef, undef, $format) =
412 $class->parse_volname($volname);
413
414 if (!defined($format) || ($format ne 'subvol' && $format ne 'raw')) {
415 return $class->SUPER::free_image($storeid, $scfg, $volname, $isBase, $_format);
416 }
417
418 my $path = $class->filesystem_path($scfg, $volname);
419
420 my $subvol = $path;
421 if ($format eq 'raw') {
422 $subvol = raw_file_to_subvol($path);
423 }
424
425 my $dir = dirname($subvol);
426 my $basename = basename($subvol);
427 my @snapshot_vols;
428 foreach_subvol($dir, sub {
429 my ($volume, $name, $snapshot) = @_;
430 return if $name ne $basename;
431 return if !defined $snapshot;
432 push @snapshot_vols, "$dir/$volume";
433 });
434
435 $class->btrfs_cmd(['subvolume', 'delete', '--', @snapshot_vols, $subvol]);
436 # try to cleanup directory to not clutter storage with empty $vmid dirs if
437 # all images from a guest got deleted
438 rmdir($dir);
439
440 return undef;
441 }
442
443 # Currently not used because quotas clash with send/recv.
444 # my sub btrfs_subvol_quota {
445 # my ($class, $path) = @_;
446 # my $id = '0/' . $class->btrfs_get_subvol_id($path);
447 # my $search = qr/^\Q$id\E\s+(\d)+\s+\d+\s+(\d+)\s*$/;
448 # my ($used, $size);
449 # $class->btrfs_cmd(['qgroup', 'show', '--raw', '-rf', '--', $path], sub {
450 # return if defined($size);
451 # if ($_[0] =~ $search) {
452 # ($used, $size) = ($1, $2);
453 # }
454 # });
455 # if (!defined($size)) {
456 # # syslog should include more information:
457 # syslog('err', "failed to get subvolume size for: $path (id $id)");
458 # # UI should only see the last path component:
459 # $path =~ s|^.*/||;
460 # die "failed to get subvolume size for $path\n";
461 # }
462 # return wantarray ? ($used, $size) : $size;
463 # }
464
465 sub volume_size_info {
466 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
467
468 my $path = $class->filesystem_path($scfg, $volname);
469
470 my $format = ($class->parse_volname($volname))[6];
471
472 if (defined($format) && $format eq 'subvol') {
473 my $ctime = (stat($path))[10];
474 my ($used, $size) = (0, 0);
475 #my ($used, $size) = btrfs_subvol_quota($class, $path); # uses wantarray
476 return wantarray ? ($size, 'subvol', $used, undef, $ctime) : 1;
477 }
478
479 return PVE::Storage::Plugin::file_size_info($path, $timeout);
480 }
481
482 sub volume_resize {
483 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
484
485 my $format = ($class->parse_volname($volname))[6];
486 if ($format eq 'subvol') {
487 my $path = $class->filesystem_path($scfg, $volname);
488 my $id = '0/' . $class->btrfs_get_subvol_id($path);
489 $class->btrfs_cmd(['qgroup', 'limit', '--', "${size}k", "0/$id", $path]);
490 return undef;
491 }
492
493 return PVE::Storage::Plugin::volume_resize(@_);
494 }
495
496 sub volume_snapshot {
497 my ($class, $scfg, $storeid, $volname, $snap) = @_;
498
499 my ($name, $vmid, $format) = ($class->parse_volname($volname))[1,2,6];
500 if ($format ne 'subvol' && $format ne 'raw') {
501 return PVE::Storage::Plugin::volume_snapshot(@_);
502 }
503
504 my $path = $class->filesystem_path($scfg, $volname);
505 my $snap_path = $class->filesystem_path($scfg, $volname, $snap);
506
507 if ($format eq 'raw') {
508 $path = raw_file_to_subvol($path);
509 $snap_path = raw_file_to_subvol($snap_path);
510 }
511
512 my $snapshot_dir = $class->get_subdir($scfg, 'images') . "/$vmid";
513 mkpath $snapshot_dir;
514
515 $class->btrfs_cmd(['subvolume', 'snapshot', '-r', '--', $path, $snap_path]);
516 return undef;
517 }
518
519 sub volume_rollback_is_possible {
520 my ($class, $scfg, $storeid, $volname, $snap, $blockers) = @_;
521
522 return 1;
523 }
524
525 sub volume_snapshot_rollback {
526 my ($class, $scfg, $storeid, $volname, $snap) = @_;
527
528 my ($name, $format) = ($class->parse_volname($volname))[1,6];
529
530 if ($format ne 'subvol' && $format ne 'raw') {
531 return PVE::Storage::Plugin::volume_snapshot_rollback(@_);
532 }
533
534 my $path = $class->filesystem_path($scfg, $volname);
535 my $snap_path = $class->filesystem_path($scfg, $volname, $snap);
536
537 if ($format eq 'raw') {
538 $path = raw_file_to_subvol($path);
539 $snap_path = raw_file_to_subvol($snap_path);
540 }
541
542 # Simple version would be:
543 # rename old to temp
544 # create new
545 # on error rename temp back
546 # But for atomicity in case the rename after create-failure *also* fails, we create the new
547 # subvol first, then use RENAME_EXCHANGE,
548 my $tmp_path = "$path.tmp.$$";
549 $class->btrfs_cmd(['subvolume', 'snapshot', '--', $snap_path, $tmp_path]);
550 # The paths are absolute, so pass -1 as file descriptors.
551 my $ok = PVE::Tools::renameat2(-1, $tmp_path, -1, $path, &PVE::Tools::RENAME_EXCHANGE);
552
553 eval { $class->btrfs_cmd(['subvolume', 'delete', '--', $tmp_path]) };
554 warn "failed to remove '$tmp_path' subvolume: $@" if $@;
555
556 if (!$ok) {
557 die "failed to rotate '$tmp_path' into place at '$path' - $!\n";
558 }
559
560 return undef;
561 }
562
563 sub volume_snapshot_delete {
564 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
565
566 my ($name, $vmid, $format) = ($class->parse_volname($volname))[1,2,6];
567
568 if ($format ne 'subvol' && $format ne 'raw') {
569 return PVE::Storage::Plugin::volume_snapshot_delete(@_);
570 }
571
572 my $path = $class->filesystem_path($scfg, $volname, $snap);
573
574 if ($format eq 'raw') {
575 $path = raw_file_to_subvol($path);
576 }
577
578 $class->btrfs_cmd(['subvolume', 'delete', '--', $path]);
579
580 return undef;
581 }
582
583 sub volume_has_feature {
584 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running) = @_;
585
586 my $features = {
587 snapshot => {
588 current => { qcow2 => 1, raw => 1, subvol => 1 },
589 snap => { qcow2 => 1, raw => 1, subvol => 1 }
590 },
591 clone => {
592 base => { qcow2 => 1, raw => 1, subvol => 1, vmdk => 1 },
593 current => { raw => 1 },
594 snap => { raw => 1 },
595 },
596 template => {
597 current => { qcow2 => 1, raw => 1, vmdk => 1, subvol => 1 },
598 },
599 copy => {
600 base => { qcow2 => 1, raw => 1, subvol => 1, vmdk => 1 },
601 current => { qcow2 => 1, raw => 1, subvol => 1, vmdk => 1 },
602 snap => { qcow2 => 1, raw => 1, subvol => 1 },
603 },
604 sparseinit => {
605 base => { qcow2 => 1, raw => 1, vmdk => 1 },
606 current => { qcow2 => 1, raw => 1, vmdk => 1 },
607 },
608 };
609
610 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) = $class->parse_volname($volname);
611
612 my $key = undef;
613 if ($snapname) {
614 $key = 'snap';
615 } else {
616 $key = $isBase ? 'base' : 'current';
617 }
618
619 return 1 if defined($features->{$feature}->{$key}->{$format});
620
621 return undef;
622 }
623
624 sub list_images {
625 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
626 my $imagedir = $class->get_subdir($scfg, 'images');
627
628 my $res = [];
629
630 # Copied from Plugin.pm, with file_size_info calls adapted:
631 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
632 # different to in Plugin.pm the regex below also excludes '@' as valid file name
633 next if $fn !~ m@^(/.+/(\d+)/([^/\@.]+(?:\.(qcow2|vmdk|subvol))?))$@;
634 $fn = $1; # untaint
635
636 my $owner = $2;
637 my $name = $3;
638 my $ext = $4;
639
640 next if !$vollist && defined($vmid) && ($owner ne $vmid);
641
642 my $volid = "$storeid:$owner/$name";
643 my ($size, $format, $used, $parent, $ctime);
644
645 if (!$ext) { # raw
646 $volid .= '.raw';
647 ($size, $format, $used, $parent, $ctime) = PVE::Storage::Plugin::file_size_info("$fn/disk.raw");
648 } elsif ($ext eq 'subvol') {
649 ($used, $size) = (0, 0);
650 #($used, $size) = btrfs_subvol_quota($class, $fn);
651 $format = 'subvol';
652 } else {
653 ($size, $format, $used, $parent, $ctime) = PVE::Storage::Plugin::file_size_info($fn);
654 }
655 next if !($format && defined($size));
656
657 if ($vollist) {
658 next if ! grep { $_ eq $volid } @$vollist;
659 }
660
661 my $info = {
662 volid => $volid, format => $format,
663 size => $size, vmid => $owner, used => $used, parent => $parent,
664 };
665
666 $info->{ctime} = $ctime if $ctime;
667
668 push @$res, $info;
669 }
670
671 return $res;
672 }
673
674 sub volume_export_formats {
675 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
676
677 # We can do whatever `DirPlugin` can do.
678 my @result = PVE::Storage::Plugin::volume_export_formats(@_);
679
680 # `btrfs send` only works on snapshots:
681 return @result if !defined $snapshot;
682
683 # Incremental stream with snapshots is only supported if the snapshots are listed (new api):
684 return @result if defined($base_snapshot) && $with_snapshots && ref($with_snapshots) ne 'ARRAY';
685
686 # Otherwise we do also support `with_snapshots`.
687
688 # Finally, `btrfs send` only works on formats where we actually use btrfs subvolumes:
689 my $format = ($class->parse_volname($volname))[6];
690 return @result if $format ne 'raw' && $format ne 'subvol';
691
692 return ('btrfs', @result);
693 }
694
695 sub volume_import_formats {
696 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
697
698 # Same as export-formats, beware the parameter order:
699 return volume_export_formats(
700 $class,
701 $scfg,
702 $storeid,
703 $volname,
704 $snapshot,
705 $base_snapshot,
706 $with_snapshots,
707 );
708 }
709
710 sub volume_export {
711 my (
712 $class,
713 $scfg,
714 $storeid,
715 $fh,
716 $volname,
717 $format,
718 $snapshot,
719 $base_snapshot,
720 $with_snapshots,
721 ) = @_;
722
723 if ($format ne 'btrfs') {
724 return PVE::Storage::Plugin::volume_export(@_);
725 }
726
727 die "format 'btrfs' only works on snapshots\n"
728 if !defined $snapshot;
729
730 die "'btrfs' format in incremental mode requires snapshots to be listed explicitly\n"
731 if defined($base_snapshot) && $with_snapshots && ref($with_snapshots) ne 'ARRAY';
732
733 my $volume_format = ($class->parse_volname($volname))[6];
734
735 die "btrfs-sending volumes of type $volume_format ('$volname') is not supported\n"
736 if $volume_format ne 'raw' && $volume_format ne 'subvol';
737
738 my $path = $class->path($scfg, $volname, $storeid);
739
740 if ($volume_format eq 'raw') {
741 $path = raw_file_to_subvol($path);
742 }
743
744 my $cmd = ['btrfs', '-q', 'send', '-e'];
745 if ($base_snapshot) {
746 my $base = $class->path($scfg, $volname, $storeid, $base_snapshot);
747 if ($volume_format eq 'raw') {
748 $base = raw_file_to_subvol($base);
749 }
750 push @$cmd, '-p', $base;
751 }
752 push @$cmd, '--';
753 if (ref($with_snapshots) eq 'ARRAY') {
754 push @$cmd, (map { "$path\@$_" } ($with_snapshots // [])->@*), $path;
755 } else {
756 dir_glob_foreach(dirname($path), $BTRFS_VOL_REGEX, sub {
757 push @$cmd, "$path\@$_[2]" if !(defined($snapshot) && $_[2] eq $snapshot);
758 });
759 }
760 $path .= "\@$snapshot" if defined($snapshot);
761 push @$cmd, $path;
762
763 run_command($cmd, output => '>&'.fileno($fh));
764 return;
765 }
766
767 sub volume_import {
768 my (
769 $class,
770 $scfg,
771 $storeid,
772 $fh,
773 $volname,
774 $format,
775 $snapshot,
776 $base_snapshot,
777 $with_snapshots,
778 $allow_rename,
779 ) = @_;
780
781 if ($format ne 'btrfs') {
782 return PVE::Storage::Plugin::volume_import(@_);
783 }
784
785 die "format 'btrfs' only works on snapshots\n"
786 if !defined $snapshot;
787
788 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $volume_format) =
789 $class->parse_volname($volname);
790
791 die "btrfs-receiving volumes of type $volume_format ('$volname') is not supported\n"
792 if $volume_format ne 'raw' && $volume_format ne 'subvol';
793
794 if (defined($base_snapshot)) {
795 my $path = $class->path($scfg, $volname, $storeid, $base_snapshot);
796 die "base snapshot '$base_snapshot' not found - no such directory '$path'\n"
797 if !path_is_subvolume($path);
798 }
799
800 my $destination = $class->filesystem_path($scfg, $volname);
801 if ($volume_format eq 'raw') {
802 $destination = raw_file_to_subvol($destination);
803 }
804
805 if (!defined($base_snapshot) && -e $destination) {
806 die "volume $volname already exists\n" if !$allow_rename;
807 $volname = $class->find_free_diskname($storeid, $scfg, $vmid, $volume_format, 1);
808 }
809
810 my $imagedir = $class->get_subdir($scfg, $vtype);
811 $imagedir .= "/$vmid" if $vtype eq 'images';
812
813 my $tmppath = "$imagedir/recv.$vmid.tmp";
814 mkdir($imagedir); # FIXME: if $scfg->{mkdir};
815 if (!mkdir($tmppath)) {
816 die "temp receive directory already exists at '$tmppath', incomplete concurrent import?\n"
817 if $! == EEXIST;
818 die "failed to create temporary receive directory at '$tmppath' - $!\n";
819 }
820
821 my $dh = IO::Dir->new($tmppath)
822 or die "failed to open temporary receive directory '$tmppath' - $!\n";
823 eval {
824 run_command(['btrfs', '-q', 'receive', '-e', '--', $tmppath], input => '<&'.fileno($fh));
825
826 # Analyze the received subvolumes;
827 my ($diskname, $found_snapshot, @snapshots);
828 $dh->rewind;
829 while (defined(my $entry = $dh->read)) {
830 next if $entry eq '.' || $entry eq '..';
831 next if $entry !~ /^$BTRFS_VOL_REGEX$/;
832 my ($cur_diskname, $cur_snapshot) = ($1, $2);
833
834 die "send stream included a non-snapshot subvolume\n"
835 if !defined($cur_snapshot);
836
837 if (!defined($diskname)) {
838 $diskname = $cur_diskname;
839 } else {
840 die "multiple disks contained in stream ('$diskname' vs '$cur_diskname')\n"
841 if $diskname ne $cur_diskname;
842 }
843
844 if ($cur_snapshot eq $snapshot) {
845 $found_snapshot = 1;
846 } else {
847 push @snapshots, $cur_snapshot;
848 }
849 }
850
851 die "send stream did not contain the expected current snapshot '$snapshot'\n"
852 if !$found_snapshot;
853
854 # Rotate the disk into place, first the current state:
855 # Note that read-only subvolumes cannot be moved into different directories, but for the
856 # "current" state we also want a writable copy, so start with that:
857 $class->btrfs_cmd(['property', 'set', "$tmppath/$diskname\@$snapshot", 'ro', 'false']);
858 PVE::Tools::renameat2(
859 -1,
860 "$tmppath/$diskname\@$snapshot",
861 -1,
862 $destination,
863 &PVE::Tools::RENAME_NOREPLACE,
864 ) or die "failed to move received snapshot '$tmppath/$diskname\@$snapshot'"
865 . " into place at '$destination' - $!\n";
866
867 # Now recreate the actual snapshot:
868 $class->btrfs_cmd([
869 'subvolume',
870 'snapshot',
871 '-r',
872 '--',
873 $destination,
874 "$destination\@$snapshot",
875 ]);
876
877 # Now go through the remaining snapshots (if any)
878 foreach my $snap (@snapshots) {
879 $class->btrfs_cmd(['property', 'set', "$tmppath/$diskname\@$snap", 'ro', 'false']);
880 PVE::Tools::renameat2(
881 -1,
882 "$tmppath/$diskname\@$snap",
883 -1,
884 "$destination\@$snap",
885 &PVE::Tools::RENAME_NOREPLACE,
886 ) or die "failed to move received snapshot '$tmppath/$diskname\@$snap'"
887 . " into place at '$destination\@$snap' - $!\n";
888 eval { $class->btrfs_cmd(['property', 'set', "$destination\@$snap", 'ro', 'true']) };
889 warn "failed to make $destination\@$snap read-only - $!\n" if $@;
890 }
891 };
892 my $err = $@;
893
894 eval {
895 # Cleanup all the received snapshots we did not move into place, so we can remove the temp
896 # directory.
897 if ($dh) {
898 $dh->rewind;
899 while (defined(my $entry = $dh->read)) {
900 next if $entry eq '.' || $entry eq '..';
901 eval { $class->btrfs_cmd(['subvolume', 'delete', '--', "$tmppath/$entry"]) };
902 warn $@ if $@;
903 }
904 $dh->close; undef $dh;
905 }
906 if (!rmdir($tmppath)) {
907 warn "failed to remove temporary directory '$tmppath' - $!\n"
908 }
909 };
910 warn $@ if $@;
911 if ($err) {
912 # clean up if the directory ended up being empty after an error
913 rmdir($tmppath);
914 die $err;
915 }
916
917 return "$storeid:$volname";
918 }
919
920 1