]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage/BTRFSPlugin.pm
plugins: allow limiting the number of protected backups per guest
[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 => { current => { qcow2 => 1, raw => 1, vmdk => 1, subvol => 1 } },
597 copy => {
598 base => { qcow2 => 1, raw => 1, subvol => 1, vmdk => 1 },
599 current => { qcow2 => 1, raw => 1, subvol => 1, vmdk => 1 },
600 snap => { qcow2 => 1, raw => 1, subvol => 1 },
601 },
602 sparseinit => { base => {qcow2 => 1, raw => 1, vmdk => 1 },
603 current => {qcow2 => 1, raw => 1, vmdk => 1 } },
604 };
605
606 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
607 $class->parse_volname($volname);
608
609 my $key = undef;
610 if ($snapname) {
611 $key = 'snap';
612 } else {
613 $key = $isBase ? 'base' : 'current';
614 }
615
616 return 1 if defined($features->{$feature}->{$key}->{$format});
617
618 return undef;
619 }
620
621 sub list_images {
622 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
623 my $imagedir = $class->get_subdir($scfg, 'images');
624
625 my $res = [];
626
627 # Copied from Plugin.pm, with file_size_info calls adapted:
628 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
629 # different to in Plugin.pm the regex below also excludes '@' as valid file name
630 next if $fn !~ m@^(/.+/(\d+)/([^/\@.]+(?:\.(qcow2|vmdk|subvol))?))$@;
631 $fn = $1; # untaint
632
633 my $owner = $2;
634 my $name = $3;
635 my $ext = $4;
636
637 next if !$vollist && defined($vmid) && ($owner ne $vmid);
638
639 my $volid = "$storeid:$owner/$name";
640 my ($size, $format, $used, $parent, $ctime);
641
642 if (!$ext) { # raw
643 $volid .= '.raw';
644 ($size, $format, $used, $parent, $ctime) = PVE::Storage::Plugin::file_size_info("$fn/disk.raw");
645 } elsif ($ext eq 'subvol') {
646 ($used, $size) = (0, 0);
647 #($used, $size) = btrfs_subvol_quota($class, $fn);
648 $format = 'subvol';
649 } else {
650 ($size, $format, $used, $parent, $ctime) = PVE::Storage::Plugin::file_size_info($fn);
651 }
652 next if !($format && defined($size));
653
654 if ($vollist) {
655 next if ! grep { $_ eq $volid } @$vollist;
656 }
657
658 my $info = {
659 volid => $volid, format => $format,
660 size => $size, vmid => $owner, used => $used, parent => $parent,
661 };
662
663 $info->{ctime} = $ctime if $ctime;
664
665 push @$res, $info;
666 }
667
668 return $res;
669 }
670
671 sub volume_export_formats {
672 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
673
674 # We can do whatever `DirPlugin` can do.
675 my @result = PVE::Storage::Plugin::volume_export_formats(@_);
676
677 # `btrfs send` only works on snapshots:
678 return @result if !defined $snapshot;
679
680 # Incremental stream with snapshots is only supported if the snapshots are listed (new api):
681 return @result if defined($base_snapshot) && $with_snapshots && ref($with_snapshots) ne 'ARRAY';
682
683 # Otherwise we do also support `with_snapshots`.
684
685 # Finally, `btrfs send` only works on formats where we actually use btrfs subvolumes:
686 my $format = ($class->parse_volname($volname))[6];
687 return @result if $format ne 'raw' && $format ne 'subvol';
688
689 return ('btrfs', @result);
690 }
691
692 sub volume_import_formats {
693 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
694
695 # Same as export-formats, beware the parameter order:
696 return volume_export_formats(
697 $class,
698 $scfg,
699 $storeid,
700 $volname,
701 $snapshot,
702 $base_snapshot,
703 $with_snapshots,
704 );
705 }
706
707 sub volume_export {
708 my (
709 $class,
710 $scfg,
711 $storeid,
712 $fh,
713 $volname,
714 $format,
715 $snapshot,
716 $base_snapshot,
717 $with_snapshots,
718 ) = @_;
719
720 if ($format ne 'btrfs') {
721 return PVE::Storage::Plugin::volume_export(@_);
722 }
723
724 die "format 'btrfs' only works on snapshots\n"
725 if !defined $snapshot;
726
727 die "'btrfs' format in incremental mode requires snapshots to be listed explicitly\n"
728 if defined($base_snapshot) && $with_snapshots && ref($with_snapshots) ne 'ARRAY';
729
730 my $volume_format = ($class->parse_volname($volname))[6];
731
732 die "btrfs-sending volumes of type $volume_format ('$volname') is not supported\n"
733 if $volume_format ne 'raw' && $volume_format ne 'subvol';
734
735 my $path = $class->path($scfg, $volname, $storeid);
736
737 if ($volume_format eq 'raw') {
738 $path = raw_file_to_subvol($path);
739 }
740
741 my $cmd = ['btrfs', '-q', 'send', '-e'];
742 if ($base_snapshot) {
743 my $base = $class->path($scfg, $volname, $storeid, $base_snapshot);
744 if ($volume_format eq 'raw') {
745 $base = raw_file_to_subvol($base);
746 }
747 push @$cmd, '-p', $base;
748 }
749 push @$cmd, '--';
750 if (ref($with_snapshots) eq 'ARRAY') {
751 push @$cmd, (map { "$path\@$_" } ($with_snapshots // [])->@*), $path;
752 } else {
753 dir_glob_foreach(dirname($path), $BTRFS_VOL_REGEX, sub {
754 push @$cmd, "$path\@$_[2]" if !(defined($snapshot) && $_[2] eq $snapshot);
755 });
756 }
757 $path .= "\@$snapshot" if defined($snapshot);
758 push @$cmd, $path;
759
760 run_command($cmd, output => '>&'.fileno($fh));
761 return;
762 }
763
764 sub volume_import {
765 my (
766 $class,
767 $scfg,
768 $storeid,
769 $fh,
770 $volname,
771 $format,
772 $snapshot,
773 $base_snapshot,
774 $with_snapshots,
775 $allow_rename,
776 ) = @_;
777
778 if ($format ne 'btrfs') {
779 return PVE::Storage::Plugin::volume_import(@_);
780 }
781
782 die "format 'btrfs' only works on snapshots\n"
783 if !defined $snapshot;
784
785 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $volume_format) =
786 $class->parse_volname($volname);
787
788 die "btrfs-receiving volumes of type $volume_format ('$volname') is not supported\n"
789 if $volume_format ne 'raw' && $volume_format ne 'subvol';
790
791 if (defined($base_snapshot)) {
792 my $path = $class->path($scfg, $volname, $storeid, $base_snapshot);
793 die "base snapshot '$base_snapshot' not found - no such directory '$path'\n"
794 if !path_is_subvolume($path);
795 }
796
797 my $destination = $class->filesystem_path($scfg, $volname);
798 if ($volume_format eq 'raw') {
799 $destination = raw_file_to_subvol($destination);
800 }
801
802 if (!defined($base_snapshot) && -e $destination) {
803 die "volume $volname already exists\n" if !$allow_rename;
804 $volname = $class->find_free_diskname($storeid, $scfg, $vmid, $volume_format, 1);
805 }
806
807 my $imagedir = $class->get_subdir($scfg, $vtype);
808 $imagedir .= "/$vmid" if $vtype eq 'images';
809
810 my $tmppath = "$imagedir/recv.$vmid.tmp";
811 mkdir($imagedir); # FIXME: if $scfg->{mkdir};
812 if (!mkdir($tmppath)) {
813 die "temp receive directory already exists at '$tmppath', incomplete concurrent import?\n"
814 if $! == EEXIST;
815 die "failed to create temporary receive directory at '$tmppath' - $!\n";
816 }
817
818 my $dh = IO::Dir->new($tmppath)
819 or die "failed to open temporary receive directory '$tmppath' - $!\n";
820 eval {
821 run_command(['btrfs', '-q', 'receive', '-e', '--', $tmppath], input => '<&'.fileno($fh));
822
823 # Analyze the received subvolumes;
824 my ($diskname, $found_snapshot, @snapshots);
825 $dh->rewind;
826 while (defined(my $entry = $dh->read)) {
827 next if $entry eq '.' || $entry eq '..';
828 next if $entry !~ /^$BTRFS_VOL_REGEX$/;
829 my ($cur_diskname, $cur_snapshot) = ($1, $2);
830
831 die "send stream included a non-snapshot subvolume\n"
832 if !defined($cur_snapshot);
833
834 if (!defined($diskname)) {
835 $diskname = $cur_diskname;
836 } else {
837 die "multiple disks contained in stream ('$diskname' vs '$cur_diskname')\n"
838 if $diskname ne $cur_diskname;
839 }
840
841 if ($cur_snapshot eq $snapshot) {
842 $found_snapshot = 1;
843 } else {
844 push @snapshots, $cur_snapshot;
845 }
846 }
847
848 die "send stream did not contain the expected current snapshot '$snapshot'\n"
849 if !$found_snapshot;
850
851 # Rotate the disk into place, first the current state:
852 # Note that read-only subvolumes cannot be moved into different directories, but for the
853 # "current" state we also want a writable copy, so start with that:
854 $class->btrfs_cmd(['property', 'set', "$tmppath/$diskname\@$snapshot", 'ro', 'false']);
855 PVE::Tools::renameat2(
856 -1,
857 "$tmppath/$diskname\@$snapshot",
858 -1,
859 $destination,
860 &PVE::Tools::RENAME_NOREPLACE,
861 ) or die "failed to move received snapshot '$tmppath/$diskname\@$snapshot'"
862 . " into place at '$destination' - $!\n";
863
864 # Now recreate the actual snapshot:
865 $class->btrfs_cmd([
866 'subvolume',
867 'snapshot',
868 '-r',
869 '--',
870 $destination,
871 "$destination\@$snapshot",
872 ]);
873
874 # Now go through the remaining snapshots (if any)
875 foreach my $snap (@snapshots) {
876 $class->btrfs_cmd(['property', 'set', "$tmppath/$diskname\@$snap", 'ro', 'false']);
877 PVE::Tools::renameat2(
878 -1,
879 "$tmppath/$diskname\@$snap",
880 -1,
881 "$destination\@$snap",
882 &PVE::Tools::RENAME_NOREPLACE,
883 ) or die "failed to move received snapshot '$tmppath/$diskname\@$snap'"
884 . " into place at '$destination\@$snap' - $!\n";
885 eval { $class->btrfs_cmd(['property', 'set', "$destination\@$snap", 'ro', 'true']) };
886 warn "failed to make $destination\@$snap read-only - $!\n" if $@;
887 }
888 };
889 my $err = $@;
890
891 eval {
892 # Cleanup all the received snapshots we did not move into place, so we can remove the temp
893 # directory.
894 if ($dh) {
895 $dh->rewind;
896 while (defined(my $entry = $dh->read)) {
897 next if $entry eq '.' || $entry eq '..';
898 eval { $class->btrfs_cmd(['subvolume', 'delete', '--', "$tmppath/$entry"]) };
899 warn $@ if $@;
900 }
901 $dh->close; undef $dh;
902 }
903 if (!rmdir($tmppath)) {
904 warn "failed to remove temporary directory '$tmppath' - $!\n"
905 }
906 };
907 warn $@ if $@;
908 if ($err) {
909 # clean up if the directory ended up being empty after an error
910 rmdir($tmppath);
911 die $err;
912 }
913
914 return "$storeid:$volname";
915 }
916
917 1