]> git.proxmox.com Git - pve-storage.git/blob - src/PVE/Storage/Plugin.pm
727b7a6b58f79c5c5fab9d93062858af93e12c82
[pve-storage.git] / src / PVE / Storage / Plugin.pm
1 package PVE::Storage::Plugin;
2
3 use strict;
4 use warnings;
5
6 use Cwd qw(abs_path);
7 use Encode qw(decode);
8 use Fcntl ':mode';
9 use File::chdir;
10 use File::Path;
11 use File::Basename;
12 use File::stat qw();
13
14 use PVE::Tools qw(run_command);
15 use PVE::JSONSchema qw(get_standard_option register_standard_option);
16 use PVE::Cluster qw(cfs_register_file);
17
18 use JSON;
19
20 use base qw(PVE::SectionConfig);
21
22 use constant COMPRESSOR_RE => 'gz|lzo|zst';
23
24 use constant LOG_EXT => ".log";
25 use constant NOTES_EXT => ".notes";
26
27 our @COMMON_TAR_FLAGS = qw(
28 --one-file-system
29 -p --sparse --numeric-owner --acls
30 --xattrs --xattrs-include=user.* --xattrs-include=security.capability
31 --warning=no-file-ignored --warning=no-xattr-write
32 );
33
34 our @SHARED_STORAGE = (
35 'iscsi',
36 'nfs',
37 'cifs',
38 'rbd',
39 'cephfs',
40 'iscsidirect',
41 'glusterfs',
42 'zfs',
43 'drbd',
44 'pbs',
45 );
46
47 our $QCOW2_PREALLOCATION = {
48 off => 1,
49 metadata => 1,
50 falloc => 1,
51 full => 1,
52 };
53
54 our $RAW_PREALLOCATION = {
55 off => 1,
56 falloc => 1,
57 full => 1,
58 };
59
60 our $MAX_VOLUMES_PER_GUEST = 1024;
61
62 cfs_register_file ('storage.cfg',
63 sub { __PACKAGE__->parse_config(@_); },
64 sub { __PACKAGE__->write_config(@_); });
65
66 my %prune_option = (
67 optional => 1,
68 type => 'integer', minimum => '0',
69 format_description => 'N',
70 );
71
72 our $prune_backups_format = {
73 'keep-all' => {
74 type => 'boolean',
75 description => 'Keep all backups. Conflicts with the other options when true.',
76 optional => 1,
77 },
78 'keep-last' => {
79 %prune_option,
80 description => 'Keep the last <N> backups.',
81 },
82 'keep-hourly' => {
83 %prune_option,
84 description => 'Keep backups for the last <N> different hours. If there is more' .
85 'than one backup for a single hour, only the latest one is kept.'
86 },
87 'keep-daily' => {
88 %prune_option,
89 description => 'Keep backups for the last <N> different days. If there is more' .
90 'than one backup for a single day, only the latest one is kept.'
91 },
92 'keep-weekly' => {
93 %prune_option,
94 description => 'Keep backups for the last <N> different weeks. If there is more' .
95 'than one backup for a single week, only the latest one is kept.'
96 },
97 'keep-monthly' => {
98 %prune_option,
99 description => 'Keep backups for the last <N> different months. If there is more' .
100 'than one backup for a single month, only the latest one is kept.'
101 },
102 'keep-yearly' => {
103 %prune_option,
104 description => 'Keep backups for the last <N> different years. If there is more' .
105 'than one backup for a single year, only the latest one is kept.'
106 },
107 };
108 PVE::JSONSchema::register_format('prune-backups', $prune_backups_format, \&validate_prune_backups);
109 sub validate_prune_backups {
110 my ($prune_backups) = @_;
111
112 my $res = { $prune_backups->%* };
113
114 my $keep_all = delete $res->{'keep-all'};
115
116 if (scalar(grep { $_ > 0 } values %{$res}) == 0) {
117 $res = { 'keep-all' => 1 };
118 } elsif ($keep_all) {
119 die "keep-all cannot be set together with other options.\n";
120 }
121
122 return $res;
123 }
124 register_standard_option('prune-backups', {
125 description => "The retention options with shorter intervals are processed first " .
126 "with --keep-last being the very first one. Each option covers a " .
127 "specific period of time. We say that backups within this period " .
128 "are covered by this option. The next option does not take care " .
129 "of already covered backups and only considers older backups.",
130 optional => 1,
131 type => 'string',
132 format => 'prune-backups',
133 });
134
135 my $defaultData = {
136 propertyList => {
137 type => { description => "Storage type." },
138 storage => get_standard_option('pve-storage-id',
139 { completion => \&PVE::Storage::complete_storage }),
140 nodes => get_standard_option('pve-node-list', { optional => 1 }),
141 content => {
142 description => "Allowed content types.\n\nNOTE: the value " .
143 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
144 type => 'string', format => 'pve-storage-content-list',
145 optional => 1,
146 completion => \&PVE::Storage::complete_content_type,
147 },
148 disable => {
149 description => "Flag to disable the storage.",
150 type => 'boolean',
151 optional => 1,
152 },
153 maxfiles => {
154 description => "Deprecated: use 'prune-backups' instead. " .
155 "Maximal number of backup files per VM. Use '0' for unlimited.",
156 type => 'integer',
157 minimum => 0,
158 optional => 1,
159 },
160 'prune-backups' => get_standard_option('prune-backups'),
161 'max-protected-backups' => {
162 description => "Maximal number of protected backups per guest. Use '-1' for unlimited.",
163 type => 'integer',
164 minimum => -1,
165 optional => 1,
166 default => "Unlimited for users with Datastore.Allocate privilege, 5 for other users",
167 },
168 shared => {
169 description => "Mark storage as shared.",
170 type => 'boolean',
171 optional => 1,
172 },
173 subdir => {
174 description => "Subdir to mount.",
175 type => 'string', format => 'pve-storage-path',
176 optional => 1,
177 },
178 'format' => {
179 description => "Default image format.",
180 type => 'string', format => 'pve-storage-format',
181 optional => 1,
182 },
183 preallocation => {
184 description => "Preallocation mode for raw and qcow2 images. " .
185 "Using 'metadata' on raw images results in preallocation=off.",
186 type => 'string', enum => ['off', 'metadata', 'falloc', 'full'],
187 default => 'metadata',
188 optional => 1,
189 },
190 'content-dirs' => {
191 description => "Overrides for default content type directories.",
192 type => "string", format => "pve-dir-override-list",
193 optional => 1,
194 },
195 options => {
196 description => "NFS/CIFS mount options (see 'man nfs' or 'man mount.cifs')",
197 type => 'string',
198 format => 'pve-storage-options',
199 optional => 1,
200 },
201 },
202 };
203
204 sub content_hash_to_string {
205 my $hash = shift;
206
207 my @cta;
208 foreach my $ct (keys %$hash) {
209 push @cta, $ct if $hash->{$ct};
210 }
211
212 return join(',', @cta);
213 }
214
215 sub valid_content_types {
216 my ($type) = @_;
217
218 my $def = $defaultData->{plugindata}->{$type};
219
220 return {} if !$def;
221
222 return $def->{content}->[0];
223 }
224
225 sub dirs_hash_to_string {
226 my $hash = shift;
227
228 return join(',', map { "$_=$hash->{$_}" } sort keys %$hash);
229 }
230
231 sub default_format {
232 my ($scfg) = @_;
233
234 my $type = $scfg->{type};
235 my $def = $defaultData->{plugindata}->{$type};
236
237 my $def_format = 'raw';
238 my $valid_formats = [ $def_format ];
239
240 if (defined($def->{format})) {
241 $def_format = $scfg->{format} || $def->{format}->[1];
242 $valid_formats = [ sort keys %{$def->{format}->[0]} ];
243 }
244
245 return wantarray ? ($def_format, $valid_formats) : $def_format;
246 }
247
248 PVE::JSONSchema::register_format('pve-storage-path', \&verify_path);
249 sub verify_path {
250 my ($path, $noerr) = @_;
251
252 # fixme: exclude more shell meta characters?
253 # we need absolute paths
254 if ($path !~ m|^/[^;\(\)]+|) {
255 return undef if $noerr;
256 die "value does not look like a valid absolute path\n";
257 }
258 return $path;
259 }
260
261 PVE::JSONSchema::register_format('pve-storage-server', \&verify_server);
262 sub verify_server {
263 my ($server, $noerr) = @_;
264
265 if (!(PVE::JSONSchema::pve_verify_ip($server, 1) ||
266 PVE::JSONSchema::pve_verify_dns_name($server, 1)))
267 {
268 return undef if $noerr;
269 die "value does not look like a valid server name or IP address\n";
270 }
271 return $server;
272 }
273
274 PVE::JSONSchema::register_format('pve-storage-vgname', \&parse_lvm_name);
275 sub parse_lvm_name {
276 my ($name, $noerr) = @_;
277
278 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
279 return undef if $noerr;
280 die "lvm name '$name' contains illegal characters\n";
281 }
282
283 return $name;
284 }
285
286 # fixme: do we need this
287 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
288 #sub verify_portal {
289 # my ($portal, $noerr) = @_;
290 #
291 # # IP with optional port
292 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
293 # return undef if $noerr;
294 # die "value does not look like a valid portal address\n";
295 # }
296 # return $portal;
297 #}
298
299 PVE::JSONSchema::register_format('pve-storage-portal-dns', \&verify_portal_dns);
300 sub verify_portal_dns {
301 my ($portal, $noerr) = @_;
302
303 # IP or DNS name with optional port
304 if (!PVE::Tools::parse_host_and_port($portal)) {
305 return undef if $noerr;
306 die "value does not look like a valid portal address\n";
307 }
308 return $portal;
309 }
310
311 PVE::JSONSchema::register_format('pve-storage-content', \&verify_content);
312 sub verify_content {
313 my ($ct, $noerr) = @_;
314
315 my $valid_content = valid_content_types('dir'); # dir includes all types
316
317 if (!$valid_content->{$ct}) {
318 return undef if $noerr;
319 die "invalid content type '$ct'\n";
320 }
321
322 return $ct;
323 }
324
325 PVE::JSONSchema::register_format('pve-storage-format', \&verify_format);
326 sub verify_format {
327 my ($fmt, $noerr) = @_;
328
329 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
330 return undef if $noerr;
331 die "invalid format '$fmt'\n";
332 }
333
334 return $fmt;
335 }
336
337 PVE::JSONSchema::register_format('pve-storage-options', \&verify_options);
338 sub verify_options {
339 my ($value, $noerr) = @_;
340
341 # mount options (see man fstab)
342 if ($value !~ m/^\S+$/) {
343 return undef if $noerr;
344 die "invalid options '$value'\n";
345 }
346
347 return $value;
348 }
349
350 PVE::JSONSchema::register_format('pve-volume-id', \&parse_volume_id);
351 sub parse_volume_id {
352 my ($volid, $noerr) = @_;
353
354 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
355 return wantarray ? ($1, $2) : $1;
356 }
357 return undef if $noerr;
358 die "unable to parse volume ID '$volid'\n";
359 }
360
361 PVE::JSONSchema::register_format('pve-dir-override', \&verify_dir_override);
362 sub verify_dir_override {
363 my ($value, $noerr) = @_;
364
365 if ($value =~ m/^([a-z]+)=([^.]*(?:\.?[^.]+)+)$/) {
366 my ($content_type, $relative_path) = ($1, $2);
367 if (verify_content($content_type, $noerr)) {
368 # linux has 4k max-path, but limit total length to lower as its concat'd for full path
369 if (length($relative_path) < 1023 && !(grep { length($_) >= 255 } split('/', $relative_path))) {
370 return $value;
371 }
372 }
373 }
374
375 return undef if $noerr;
376 die "invalid override '$value'\n";
377 }
378
379 sub private {
380 return $defaultData;
381 }
382
383 sub parse_section_header {
384 my ($class, $line) = @_;
385
386 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
387 my ($type, $storeid) = (lc($1), $2);
388 my $errmsg = undef; # set if you want to skip whole section
389 eval { PVE::JSONSchema::parse_storage_id($storeid); };
390 $errmsg = $@ if $@;
391 my $config = {}; # to return additional attributes
392 return ($type, $storeid, $errmsg, $config);
393 }
394 return undef;
395 }
396
397 sub decode_value {
398 my ($class, $type, $key, $value) = @_;
399
400 my $def = $defaultData->{plugindata}->{$type};
401
402 if ($key eq 'content') {
403 my $valid_content = $def->{content}->[0];
404
405 my $res = {};
406
407 foreach my $c (PVE::Tools::split_list($value)) {
408 if (!$valid_content->{$c}) {
409 warn "storage does not support content type '$c'\n";
410 next;
411 }
412 $res->{$c} = 1;
413 }
414
415 if ($res->{none} && scalar (keys %$res) > 1) {
416 die "unable to combine 'none' with other content types\n";
417 }
418
419 if (scalar(keys $res->%*) == 0 && !$valid_content->{none}) {
420 die "storage does not support content type 'none'\n";
421 }
422
423 return $res;
424 } elsif ($key eq 'format') {
425 my $valid_formats = $def->{format}->[0];
426
427 if (!$valid_formats->{$value}) {
428 warn "storage does not support format '$value'\n";
429 next;
430 }
431
432 return $value;
433 } elsif ($key eq 'nodes') {
434 my $res = {};
435
436 foreach my $node (PVE::Tools::split_list($value)) {
437 if (PVE::JSONSchema::pve_verify_node_name($node)) {
438 $res->{$node} = 1;
439 }
440 }
441
442 # fixme:
443 # no node restrictions for local storage
444 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
445 # die "storage '$storeid' does not allow node restrictions\n";
446 #}
447
448 return $res;
449 } elsif ($key eq 'content-dirs') {
450 my $valid_content = $def->{content}->[0];
451 my $res = {};
452
453 foreach my $dir (PVE::Tools::split_list($value)) {
454 my ($content, $path) = split(/=/, $dir, 2);
455
456 if (!$valid_content->{$content}) {
457 warn "storage does not support content type '$content'\n";
458 next;
459 }
460
461 $res->{$content} = $path;
462 }
463
464 return $res;
465 }
466
467 return $value;
468 }
469
470 sub encode_value {
471 my ($class, $type, $key, $value) = @_;
472
473 if ($key eq 'nodes') {
474 return join(',', keys(%$value));
475 } elsif ($key eq 'content') {
476 my $res = content_hash_to_string($value) || 'none';
477 return $res;
478 } elsif ($key eq 'content-dirs') {
479 my $res = dirs_hash_to_string($value);
480 return $res;
481 }
482
483 return $value;
484 }
485
486 sub parse_config {
487 my ($class, $filename, $raw) = @_;
488
489 my $cfg = $class->SUPER::parse_config($filename, $raw);
490 my $ids = $cfg->{ids};
491
492 # make sure we have a reasonable 'local:' storage
493 # we want 'local' to be always the same 'type' (on all cluster nodes)
494 if (!$ids->{local} || $ids->{local}->{type} ne 'dir' ||
495 ($ids->{local}->{path} && $ids->{local}->{path} ne '/var/lib/vz')) {
496 $ids->{local} = {
497 type => 'dir',
498 priority => 0, # force first entry
499 path => '/var/lib/vz',
500 'prune-backups' => 'keep-all=1',
501 content => {
502 backup => 1,
503 images => 1,
504 iso => 1,
505 rootdir => 1,
506 snippets => 1,
507 vztmpl => 1,
508 },
509 };
510 }
511
512 # make sure we have a path
513 $ids->{local}->{path} = '/var/lib/vz' if !$ids->{local}->{path};
514
515 # remove node restrictions for local storage
516 delete($ids->{local}->{nodes});
517
518 foreach my $storeid (keys %$ids) {
519 my $d = $ids->{$storeid};
520 my $type = $d->{type};
521
522 my $def = $defaultData->{plugindata}->{$type};
523
524 if ($def->{content}) {
525 $d->{content} = $def->{content}->[1] if !$d->{content};
526 }
527 if (grep { $_ eq $type } @SHARED_STORAGE) {
528 $d->{shared} = 1;
529 }
530 }
531
532 return $cfg;
533 }
534
535 sub preallocation_cmd_option {
536 my ($scfg, $fmt) = @_;
537
538 my $prealloc = $scfg->{preallocation};
539
540 if ($fmt eq 'qcow2') {
541 $prealloc = $prealloc // 'metadata';
542
543 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
544 if !$QCOW2_PREALLOCATION->{$prealloc};
545
546 return "preallocation=$prealloc";
547 } elsif ($fmt eq 'raw') {
548 $prealloc = $prealloc // 'off';
549 $prealloc = 'off' if $prealloc eq 'metadata';
550
551 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
552 if !$RAW_PREALLOCATION->{$prealloc};
553
554 return "preallocation=$prealloc";
555 }
556
557 return;
558 }
559
560 # Storage implementation
561
562 # called during addition of storage (before the new storage config got written)
563 # die to abort addition if there are (grave) problems
564 # NOTE: runs in a storage config *locked* context
565 sub on_add_hook {
566 my ($class, $storeid, $scfg, %param) = @_;
567
568 # do nothing by default
569 return undef;
570 }
571
572 # called during storage configuration update (before the updated storage config got written)
573 # die to abort the update if there are (grave) problems
574 # NOTE: runs in a storage config *locked* context
575 sub on_update_hook {
576 my ($class, $storeid, $scfg, %param) = @_;
577
578 # do nothing by default
579 return undef;
580 }
581
582 # called during deletion of storage (before the new storage config got written)
583 # and if the activate check on addition fails, to cleanup all storage traces
584 # which on_add_hook may have created.
585 # die to abort deletion if there are (very grave) problems
586 # NOTE: runs in a storage config *locked* context
587 sub on_delete_hook {
588 my ($class, $storeid, $scfg) = @_;
589
590 # do nothing by default
591 return undef;
592 }
593
594 sub cluster_lock_storage {
595 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
596
597 my $res;
598 if (!$shared) {
599 my $lockid = "pve-storage-$storeid";
600 my $lockdir = "/var/lock/pve-manager";
601 mkdir $lockdir;
602 $res = PVE::Tools::lock_file("$lockdir/$lockid", $timeout, $func, @param);
603 die $@ if $@;
604 } else {
605 $res = PVE::Cluster::cfs_lock_storage($storeid, $timeout, $func, @param);
606 die $@ if $@;
607 }
608 return $res;
609 }
610
611 sub parse_name_dir {
612 my $name = shift;
613
614 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
615 return ($1, $3, $2); # (name, format, isBase)
616 }
617
618 die "unable to parse volume filename '$name'\n";
619 }
620
621 sub parse_volname {
622 my ($class, $volname) = @_;
623
624 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
625 my ($basedvmid, $basename) = ($1, $2);
626 parse_name_dir($basename);
627 my ($vmid, $name) = ($3, $4);
628 my (undef, $format, $isBase) = parse_name_dir($name);
629 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
630 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
631 my ($vmid, $name) = ($1, $2);
632 my (undef, $format, $isBase) = parse_name_dir($name);
633 return ('images', $name, $vmid, undef, undef, $isBase, $format);
634 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!) {
635 return ('iso', $1);
636 } elsif ($volname =~ m!^vztmpl/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!) {
637 return ('vztmpl', $1);
638 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
639 return ('rootdir', $1, $1);
640 } elsif ($volname =~ m!^backup/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!) {
641 my $fn = $1;
642 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
643 return ('backup', $fn, $2);
644 }
645 return ('backup', $fn);
646 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
647 return ('snippets', $1);
648 }
649
650 die "unable to parse directory volume name '$volname'\n";
651 }
652
653 my $vtype_subdirs = {
654 images => 'images',
655 rootdir => 'private',
656 iso => 'template/iso',
657 vztmpl => 'template/cache',
658 backup => 'dump',
659 snippets => 'snippets',
660 };
661
662 sub get_vtype_subdirs {
663 return $vtype_subdirs;
664 }
665
666 sub get_subdir {
667 my ($class, $scfg, $vtype) = @_;
668
669 my $path = $scfg->{path};
670
671 die "storage definition has no path\n" if !$path;
672 die "unknown vtype '$vtype'\n" if !exists($vtype_subdirs->{$vtype});
673
674 my $subdir = $scfg->{"content-dirs"}->{$vtype} // $vtype_subdirs->{$vtype};
675
676 return "$path/$subdir";
677 }
678
679 sub filesystem_path {
680 my ($class, $scfg, $volname, $snapname) = @_;
681
682 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
683 $class->parse_volname($volname);
684
685 # Note: qcow2/qed has internal snapshot, so path is always
686 # the same (with or without snapshot => same file).
687 die "can't snapshot this image format\n"
688 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
689
690 my $dir = $class->get_subdir($scfg, $vtype);
691
692 $dir .= "/$vmid" if $vtype eq 'images';
693
694 my $path = "$dir/$name";
695
696 return wantarray ? ($path, $vmid, $vtype) : $path;
697 }
698
699 sub path {
700 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
701
702 return $class->filesystem_path($scfg, $volname, $snapname);
703 }
704
705 sub create_base {
706 my ($class, $storeid, $scfg, $volname) = @_;
707
708 # this only works for file based storage types
709 die "storage definition has no path\n" if !$scfg->{path};
710
711 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
712 $class->parse_volname($volname);
713
714 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
715
716 die "create_base not possible with base image\n" if $isBase;
717
718 my $path = $class->filesystem_path($scfg, $volname);
719
720 my ($size, undef, $used, $parent) = file_size_info($path);
721 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
722
723 die "volname '$volname' contains wrong information about parent\n"
724 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
725
726 my $newname = $name;
727 $newname =~ s/^vm-/base-/;
728
729 my $newvolname = $basename ? "$basevmid/$basename/$vmid/$newname" :
730 "$vmid/$newname";
731
732 my $newpath = $class->filesystem_path($scfg, $newvolname);
733
734 die "file '$newpath' already exists\n" if -f $newpath;
735
736 rename($path, $newpath) ||
737 die "rename '$path' to '$newpath' failed - $!\n";
738
739 # We try to protect base volume
740
741 chmod(0444, $newpath); # nobody should write anything
742
743 # also try to set immutable flag
744 eval { run_command(['/usr/bin/chattr', '+i', $newpath]); };
745 warn $@ if $@;
746
747 return $newvolname;
748 }
749
750 my $get_vm_disk_number = sub {
751 my ($disk_name, $scfg, $vmid, $suffix) = @_;
752
753 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
754
755 my $type = $scfg->{type};
756 my $def = { %{$defaultData->{plugindata}->{$type}} };
757
758 my $valid = $def->{format}[0];
759 if ($valid->{subvol}) {
760 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
761 }
762
763 if ($disk_name =~ m/$disk_regex/) {
764 return $2;
765 }
766
767 return undef;
768 };
769
770 sub get_next_vm_diskname {
771 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
772
773 $fmt //= '';
774 my $prefix = ($fmt eq 'subvol') ? 'subvol' : 'vm';
775 my $suffix = $add_fmt_suffix ? ".$fmt" : '';
776
777 my $disk_ids = {};
778 foreach my $disk (@$disk_list) {
779 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
780 $disk_ids->{$disknum} = 1 if defined($disknum);
781 }
782
783 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
784 if (!$disk_ids->{$i}) {
785 return "$prefix-$vmid-disk-$i$suffix";
786 }
787 }
788
789 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
790 }
791
792 sub find_free_diskname {
793 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
794
795 my $disks = $class->list_images($storeid, $scfg, $vmid);
796
797 my $disk_list = [ map { $_->{volid} } @$disks ];
798
799 return get_next_vm_diskname($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
800 }
801
802 sub clone_image {
803 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
804
805 # this only works for file based storage types
806 die "storage definition has no path\n" if !$scfg->{path};
807
808 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
809 $class->parse_volname($volname);
810
811 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
812
813 die "this storage type does not support clone_image on snapshot\n" if $snap;
814
815 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
816
817 die "clone_image only works on base images\n" if !$isBase;
818
819 my $imagedir = $class->get_subdir($scfg, 'images');
820 $imagedir .= "/$vmid";
821
822 mkpath $imagedir;
823
824 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
825
826 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
827
828 my $newvol = "$basevmid/$basename/$vmid/$name";
829
830 my $path = $class->filesystem_path($scfg, $newvol);
831
832 # Note: we use relative paths, so we need to call chdir before qemu-img
833 eval {
834 local $CWD = $imagedir;
835
836 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
837 '-F', $format, '-f', 'qcow2', $path];
838
839 run_command($cmd);
840 };
841 my $err = $@;
842
843 die $err if $err;
844
845 return $newvol;
846 }
847
848 sub alloc_image {
849 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
850
851 my $imagedir = $class->get_subdir($scfg, 'images');
852 $imagedir .= "/$vmid";
853
854 mkpath $imagedir;
855
856 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
857
858 my (undef, $tmpfmt) = parse_name_dir($name);
859
860 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
861 if $tmpfmt ne $fmt;
862
863 my $path = "$imagedir/$name";
864
865 die "disk image '$path' already exists\n" if -e $path;
866
867 if ($fmt eq 'subvol') {
868 # only allow this if size = 0, so that user knows what he is doing
869 die "storage does not support subvol quotas\n" if $size != 0;
870
871 my $old_umask = umask(0022);
872 my $err;
873 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
874 umask $old_umask;
875 die $err if $err;
876 } else {
877 my $cmd = ['/usr/bin/qemu-img', 'create'];
878
879 my $prealloc_opt = preallocation_cmd_option($scfg, $fmt);
880 push @$cmd, '-o', $prealloc_opt if defined($prealloc_opt);
881
882 push @$cmd, '-f', $fmt, $path, "${size}K";
883
884 eval { run_command($cmd, errmsg => "unable to create image"); };
885 if ($@) {
886 unlink $path;
887 rmdir $imagedir;
888 die "$@";
889 }
890 }
891
892 return "$vmid/$name";
893 }
894
895 sub free_image {
896 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
897
898 die "cannot remove protected volume '$volname' on '$storeid'\n"
899 if $class->get_volume_attribute($scfg, $storeid, $volname, 'protected');
900
901 my $path = $class->filesystem_path($scfg, $volname);
902
903 if ($isBase) {
904 # try to remove immutable flag
905 eval { run_command(['/usr/bin/chattr', '-i', $path]); };
906 warn $@ if $@;
907 }
908
909 if (defined($format) && ($format eq 'subvol')) {
910 File::Path::remove_tree($path);
911 } else {
912 if (!(-f $path || -l $path)) {
913 warn "disk image '$path' does not exist\n";
914 return undef;
915 }
916
917 unlink($path) || die "unlink '$path' failed - $!\n";
918 }
919
920 # try to cleanup directory to not clutter storage with empty $vmid dirs if
921 # all images from a guest got deleted
922 my $dir = dirname($path);
923 rmdir($dir);
924
925 return undef;
926 }
927
928 sub file_size_info {
929 my ($filename, $timeout) = @_;
930
931 my $st = File::stat::stat($filename);
932
933 if (!defined($st)) {
934 my $extramsg = -l $filename ? ' - dangling symlink?' : '';
935 warn "failed to stat '$filename'$extramsg\n";
936 return undef;
937 }
938
939 if (S_ISDIR($st->mode)) {
940 return wantarray ? (0, 'subvol', 0, undef, $st->ctime) : 1;
941 }
942
943 my $json = '';
944 eval {
945 run_command(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
946 timeout => $timeout,
947 outfunc => sub { $json .= shift },
948 errfunc => sub { warn "$_[0]\n" }
949 );
950 };
951 warn $@ if $@;
952
953 my $info = eval { decode_json($json) };
954 if (my $err = $@) {
955 warn "could not parse qemu-img info command output for '$filename' - $err\n";
956 return wantarray ? (undef, undef, undef, undef, $st->ctime) : undef;
957 }
958
959 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
960
961 ($size) = ($size =~ /^(\d+)$/) or die "size '$size' not an integer\n"; # untaint
962 # coerce back from string
963 $size = int($size);
964 ($used) = ($used =~ /^(\d+)$/) or die "used '$used' not an integer\n"; # untaint
965 # coerce back from string
966 $used = int($used);
967 ($format) = ($format =~ /^(\S+)$/) or die "format '$format' includes whitespace\n"; # untaint
968 if (defined($parent)) {
969 ($parent) = ($parent =~ /^(\S+)$/) or die "parent '$parent' includes whitespace\n"; # untaint
970 }
971 return wantarray ? ($size, $format, $used, $parent, $st->ctime) : $size;
972 }
973
974 # FIXME remove on the next APIAGE reset.
975 # Deprecated, use get_volume_attribute instead.
976 sub get_volume_notes {
977 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
978
979 die "volume notes are not supported for $class";
980 }
981
982 # FIXME remove on the next APIAGE reset.
983 # Deprecated, use update_volume_attribute instead.
984 sub update_volume_notes {
985 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
986
987 die "volume notes are not supported for $class";
988 }
989
990 # Returns undef if the attribute is not supported for the volume.
991 # Should die if there is an error fetching the attribute.
992 # Possible attributes:
993 # notes - user-provided comments/notes.
994 # protected - not to be removed by free_image, and for backups, ignored when pruning.
995 sub get_volume_attribute {
996 my ($class, $scfg, $storeid, $volname, $attribute) = @_;
997
998 if ($attribute eq 'notes') {
999 my $notes = eval { $class->get_volume_notes($scfg, $storeid, $volname); };
1000 if (my $err = $@) {
1001 return if $err =~ m/^volume notes are not supported/;
1002 die $err;
1003 }
1004 return $notes;
1005 }
1006
1007 return;
1008 }
1009
1010 # Dies if the attribute is not supported for the volume.
1011 sub update_volume_attribute {
1012 my ($class, $scfg, $storeid, $volname, $attribute, $value) = @_;
1013
1014 if ($attribute eq 'notes') {
1015 $class->update_volume_notes($scfg, $storeid, $volname, $value);
1016 }
1017
1018 die "attribute '$attribute' is not supported for storage type '$scfg->{type}'\n";
1019 }
1020
1021 sub volume_size_info {
1022 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
1023 my $path = $class->filesystem_path($scfg, $volname);
1024 return file_size_info($path, $timeout);
1025
1026 }
1027
1028 sub volume_resize {
1029 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
1030
1031 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
1032
1033 return 1 if $running;
1034
1035 my $path = $class->filesystem_path($scfg, $volname);
1036
1037 my $format = ($class->parse_volname($volname))[6];
1038
1039 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
1040
1041 run_command($cmd, timeout => 10);
1042
1043 return undef;
1044 }
1045
1046 sub volume_snapshot {
1047 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1048
1049 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1050
1051 my $path = $class->filesystem_path($scfg, $volname);
1052
1053 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
1054
1055 run_command($cmd);
1056
1057 return undef;
1058 }
1059
1060 # Asserts that a rollback to $snap on $volname is possible.
1061 # If certain snapshots are preventing the rollback and $blockers is an array
1062 # reference, the snapshot names can be pushed onto $blockers prior to dying.
1063 sub volume_rollback_is_possible {
1064 my ($class, $scfg, $storeid, $volname, $snap, $blockers) = @_;
1065
1066 return 1;
1067 }
1068
1069 sub volume_snapshot_rollback {
1070 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1071
1072 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1073
1074 my $path = $class->filesystem_path($scfg, $volname);
1075
1076 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
1077
1078 run_command($cmd);
1079
1080 return undef;
1081 }
1082
1083 sub volume_snapshot_delete {
1084 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
1085
1086 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1087
1088 return 1 if $running;
1089
1090 my $path = $class->filesystem_path($scfg, $volname);
1091
1092 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
1093
1094 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
1095
1096 run_command($cmd);
1097
1098 return undef;
1099 }
1100
1101 sub volume_snapshot_needs_fsfreeze {
1102
1103 return 0;
1104 }
1105 sub storage_can_replicate {
1106 my ($class, $scfg, $storeid, $format) = @_;
1107
1108 return 0;
1109 }
1110
1111 sub volume_has_feature {
1112 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
1113
1114 my $features = {
1115 snapshot => {
1116 current => { qcow2 => 1 },
1117 snap => { qcow2 => 1 },
1118 },
1119 clone => {
1120 base => { qcow2 => 1, raw => 1, vmdk => 1 },
1121 },
1122 template => {
1123 current => { qcow2 => 1, raw => 1, vmdk => 1, subvol => 1 },
1124 },
1125 copy => {
1126 base => { qcow2 => 1, raw => 1, vmdk => 1 },
1127 current => { qcow2 => 1, raw => 1, vmdk => 1 },
1128 snap => { qcow2 => 1 },
1129 },
1130 sparseinit => {
1131 base => { qcow2 => 1, raw => 1, vmdk => 1 },
1132 current => { qcow2 => 1, raw => 1, vmdk => 1 },
1133 },
1134 rename => {
1135 current => {qcow2 => 1, raw => 1, vmdk => 1},
1136 },
1137 };
1138
1139 if ($feature eq 'clone') {
1140 if (
1141 defined($opts->{valid_target_formats})
1142 && !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats}})
1143 ) {
1144 return 0; # clone_image creates a qcow2 volume
1145 }
1146 } elsif ($feature eq 'rename') {
1147 return 0 if $class->can('api') && $class->api() < 10;
1148 }
1149
1150
1151 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) = $class->parse_volname($volname);
1152
1153 my $key = undef;
1154 if($snapname){
1155 $key = 'snap';
1156 }else{
1157 $key = $isBase ? 'base' : 'current';
1158 }
1159
1160 return 1 if defined($features->{$feature}->{$key}->{$format});
1161
1162 return undef;
1163 }
1164
1165 sub list_images {
1166 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
1167
1168 my $imagedir = $class->get_subdir($scfg, 'images');
1169
1170 my ($defFmt, $vaidFmts) = default_format($scfg);
1171 my $fmts = join ('|', @$vaidFmts);
1172
1173 my $res = [];
1174
1175 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
1176
1177 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1178 $fn = $1; # untaint
1179
1180 my $owner = $2;
1181 my $name = $3;
1182
1183 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1184
1185 my ($size, $format, $used, $parent, $ctime) = file_size_info($fn);
1186 next if !($format && defined($size));
1187
1188 my $volid;
1189 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1190 my ($basevmid, $basename) = ($1, $2);
1191 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1192 } else {
1193 $volid = "$storeid:$owner/$name";
1194 }
1195
1196 if ($vollist) {
1197 my $found = grep { $_ eq $volid } @$vollist;
1198 next if !$found;
1199 }
1200
1201 my $info = {
1202 volid => $volid, format => $format,
1203 size => $size, vmid => $owner, used => $used, parent => $parent
1204 };
1205
1206 $info->{ctime} = $ctime if $ctime;
1207
1208 push @$res, $info;
1209 }
1210
1211 return $res;
1212 }
1213
1214 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1215 my $get_subdir_files = sub {
1216 my ($sid, $path, $tt, $vmid) = @_;
1217
1218 my $res = [];
1219
1220 foreach my $fn (<$path/*>) {
1221 my $st = File::stat::stat($fn);
1222
1223 next if (!$st || S_ISDIR($st->mode));
1224
1225 my $info;
1226
1227 if ($tt eq 'iso') {
1228 next if $fn !~ m!/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!i;
1229
1230 $info = { volid => "$sid:iso/$1", format => 'iso' };
1231
1232 } elsif ($tt eq 'vztmpl') {
1233 next if $fn !~ m!/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!;
1234
1235 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
1236
1237 } elsif ($tt eq 'backup') {
1238 next if $fn !~ m!/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!;
1239 my $original = $fn;
1240 my $format = $2;
1241 $fn = $1;
1242
1243 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1244 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1245
1246 $info = { volid => "$sid:backup/$fn", format => $format };
1247
1248 my $archive_info = eval { PVE::Storage::archive_info($fn) } // {};
1249
1250 $info->{ctime} = $archive_info->{ctime} if defined($archive_info->{ctime});
1251 $info->{subtype} = $archive_info->{type} // 'unknown';
1252
1253 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1254 $info->{vmid} = $vmid // $1;
1255 }
1256
1257 my $notes_fn = $original.NOTES_EXT;
1258 if (-f $notes_fn) {
1259 my $notes = PVE::Tools::file_read_firstline($notes_fn);
1260 $info->{notes} = eval { decode('UTF-8', $notes, 1) } // $notes if defined($notes);
1261 }
1262
1263 $info->{protected} = 1 if -e PVE::Storage::protection_file_path($original);
1264 } elsif ($tt eq 'snippets') {
1265
1266 $info = {
1267 volid => "$sid:snippets/". basename($fn),
1268 format => 'snippet',
1269 };
1270 }
1271
1272 $info->{size} = $st->size;
1273 $info->{ctime} //= $st->ctime;
1274
1275 push @$res, $info;
1276 }
1277
1278 return $res;
1279 };
1280
1281 # If attributes are set on a volume, they should be included in the result.
1282 # See get_volume_attribute for a list of possible attributes.
1283 sub list_volumes {
1284 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1285
1286 my $res = [];
1287 my $vmlist = PVE::Cluster::get_vmlist();
1288 foreach my $type (@$content_types) {
1289 my $data;
1290
1291 if ($type eq 'images' || $type eq 'rootdir') {
1292 $data = $class->list_images($storeid, $scfg, $vmid);
1293 } elsif ($scfg->{path}) {
1294 my $path = $class->get_subdir($scfg, $type);
1295
1296 if ($type eq 'iso' && !defined($vmid)) {
1297 $data = $get_subdir_files->($storeid, $path, 'iso');
1298 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1299 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1300 } elsif ($type eq 'backup') {
1301 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1302 } elsif ($type eq 'snippets') {
1303 $data = $get_subdir_files->($storeid, $path, 'snippets');
1304 }
1305 }
1306
1307 next if !$data;
1308
1309 foreach my $item (@$data) {
1310 if ($type eq 'images' || $type eq 'rootdir') {
1311 my $vminfo = $vmlist->{ids}->{$item->{vmid}};
1312 my $vmtype;
1313 if (defined($vminfo)) {
1314 $vmtype = $vminfo->{type};
1315 }
1316 if (defined($vmtype) && $vmtype eq 'lxc') {
1317 $item->{content} = 'rootdir';
1318 } else {
1319 $item->{content} = 'images';
1320 }
1321 next if $type ne $item->{content};
1322 } else {
1323 $item->{content} = $type;
1324 }
1325
1326 push @$res, $item;
1327 }
1328 }
1329
1330 return $res;
1331 }
1332
1333 sub status {
1334 my ($class, $storeid, $scfg, $cache) = @_;
1335
1336 my $path = $scfg->{path};
1337
1338 die "storage definition has no path\n" if !$path;
1339
1340 my $timeout = 2;
1341 my $res = PVE::Tools::df($path, $timeout);
1342
1343 return undef if !$res || !$res->{total};
1344
1345 return ($res->{total}, $res->{avail}, $res->{used}, 1);
1346 }
1347
1348 # Returns a hash with the snapshot names as keys and the following data:
1349 # id - Unique id to distinguish different snapshots even if the have the same name.
1350 # timestamp - Creation time of the snapshot (seconds since epoch).
1351 # Returns an empty hash if the volume does not exist.
1352 sub volume_snapshot_info {
1353 my ($class, $scfg, $storeid, $volname) = @_;
1354
1355 die "volume_snapshot_info is not implemented for $class";
1356 }
1357
1358 sub activate_storage {
1359 my ($class, $storeid, $scfg, $cache) = @_;
1360
1361 my $path = $scfg->{path};
1362
1363 die "storage definition has no path\n" if !$path;
1364
1365 # this path test may hang indefinitely on unresponsive mounts
1366 my $timeout = 2;
1367 if (! PVE::Tools::run_fork_with_timeout($timeout, sub {-d $path})) {
1368 die "unable to activate storage '$storeid' - " .
1369 "directory '$path' does not exist or is unreachable\n";
1370 }
1371
1372 warn "${storeid}: 'mkdir' option is deprecated. Use 'create-base-path' or 'create-subdirs' instead.\n"
1373 if defined($scfg->{mkdir});
1374
1375 # check that content dirs are pairwise inequal
1376 my $resolved_subdirs = {};
1377 if (defined($scfg->{content})) {
1378 foreach my $vtype (keys $scfg->{content}->%*) {
1379 my $abs_subdir = abs_path($class->get_subdir($scfg, $vtype));
1380 die "storage '$storeid' uses directory $abs_subdir for multiple content types\n"
1381 if defined($resolved_subdirs->{$abs_subdir});
1382 $resolved_subdirs->{$abs_subdir} = 1;
1383 }
1384 }
1385
1386 return if defined($scfg->{'create-subdirs'}) && !$scfg->{'create-subdirs'};
1387
1388 # FIXME The mkdir option is deprecated. Remove with PVE 9?
1389 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1390
1391 if (defined($scfg->{content})) {
1392 foreach my $vtype (keys %$vtype_subdirs) {
1393 # OpenVZMigrate uses backup (dump) dir
1394 if (defined($scfg->{content}->{$vtype}) ||
1395 ($vtype eq 'backup' && defined($scfg->{content}->{'rootdir'}))) {
1396 my $subdir = $class->get_subdir($scfg, $vtype);
1397 mkpath $subdir if $subdir ne $path;
1398 }
1399 }
1400 }
1401 }
1402
1403 sub deactivate_storage {
1404 my ($class, $storeid, $scfg, $cache) = @_;
1405
1406 # do nothing by default
1407 }
1408
1409 sub map_volume {
1410 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1411
1412 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1413 return $path;
1414 }
1415
1416 sub unmap_volume {
1417 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1418
1419 return 1;
1420 }
1421
1422 sub activate_volume {
1423 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1424
1425 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1426
1427 # check is volume exists
1428 if ($scfg->{path}) {
1429 die "volume '$storeid:$volname' does not exist\n" if ! -e $path;
1430 } else {
1431 die "volume '$storeid:$volname' does not exist\n" if ! -b $path;
1432 }
1433 }
1434
1435 sub deactivate_volume {
1436 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1437
1438 # do nothing by default
1439 }
1440
1441 sub check_connection {
1442 my ($class, $storeid, $scfg) = @_;
1443 # do nothing by default
1444 return 1;
1445 }
1446
1447 sub prune_backups {
1448 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1449
1450 $logfunc //= sub { print "$_[1]\n" };
1451
1452 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1453
1454 my $backup_groups = {};
1455 my $prune_list = [];
1456
1457 foreach my $backup (@{$backups}) {
1458 my $volid = $backup->{volid};
1459 my $archive_info = eval { PVE::Storage::archive_info($volid) } // {};
1460 my $backup_type = $archive_info->{type} // 'unknown';
1461 my $backup_vmid = $archive_info->{vmid} // $backup->{vmid};
1462
1463 next if defined($type) && $type ne $backup_type;
1464
1465 my $prune_entry = {
1466 ctime => $backup->{ctime},
1467 type => $backup_type,
1468 volid => $volid,
1469 };
1470
1471 $prune_entry->{vmid} = $backup_vmid if defined($backup_vmid);
1472
1473 if ($archive_info->{is_std_name}) {
1474 die "internal error - got no VMID\n" if !defined($backup_vmid);
1475 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1476 if defined($vmid) && $backup_vmid ne $vmid;
1477
1478 $prune_entry->{ctime} = $archive_info->{ctime};
1479 my $group = "$backup_type/$backup_vmid";
1480 push @{$backup_groups->{$group}}, $prune_entry;
1481 } else {
1482 # ignore backups that don't use the standard naming scheme
1483 $prune_entry->{mark} = 'renamed';
1484 }
1485
1486 $prune_entry->{mark} = 'protected' if $backup->{protected};
1487
1488 push @{$prune_list}, $prune_entry;
1489 }
1490
1491 foreach my $backup_group (values %{$backup_groups}) {
1492 PVE::Storage::prune_mark_backup_group($backup_group, $keep);
1493 }
1494
1495 my $failed;
1496 if (!$dryrun) {
1497 foreach my $prune_entry (@{$prune_list}) {
1498 next if $prune_entry->{mark} ne 'remove';
1499
1500 my $volid = $prune_entry->{volid};
1501 $logfunc->('info', "removing backup '$volid'");
1502 eval {
1503 my (undef, $volname) = parse_volume_id($volid);
1504 my $archive_path = $class->filesystem_path($scfg, $volname);
1505 PVE::Storage::archive_remove($archive_path);
1506 };
1507 if (my $err = $@) {
1508 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1509 $failed = 1;
1510 }
1511 }
1512 }
1513 die "error pruning backups - check log\n" if $failed;
1514
1515 return $prune_list;
1516 }
1517
1518 # Import/Export interface:
1519 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1520 # the default implementations will return this if $scfg->{path} is set,
1521 # mimicking the old PVE::Storage::storage_migrate() function.
1522 #
1523 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1524 # functions in case the format doesn't match their specialized
1525 # implementations to reuse the raw/tar code.
1526 #
1527 # Format specification:
1528 # The following formats are all prefixed with image information in the form
1529 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1530 # to preallocate the image on storages which require it.
1531 #
1532 # raw+size: (image files only)
1533 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1534 # qcow2+size, vmdk: (image files only)
1535 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1536 # files which are already in qcow2 format, or via `qemu-img convert`.
1537 # Note that these formats are only valid with $with_snapshots being true.
1538 # tar+size: (subvolumes only)
1539 # A GNU tar stream containing just the inner contents of the subvolume.
1540 # This does not distinguish between the contents of a privileged or
1541 # unprivileged container. In other words, this is from the root user
1542 # namespace's point of view with no uid-mapping in effect.
1543 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1544
1545 # Plugins may reuse these helpers. Changes to the header format should be
1546 # reflected by changes to the function prototypes.
1547 sub write_common_header($$) {
1548 my ($fh, $image_size_in_bytes) = @_;
1549 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1550 }
1551
1552 sub read_common_header($) {
1553 my ($fh) = @_;
1554 sysread($fh, my $size, 8);
1555 $size = unpack('Q<', $size);
1556 die "import: no size found in export header, aborting.\n" if !defined($size);
1557 # Size is in bytes!
1558 return $size;
1559 }
1560
1561 # Export a volume into a file handle as a stream of desired format.
1562 sub volume_export {
1563 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1564 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1565 my $file = $class->path($scfg, $volname, $storeid)
1566 or goto unsupported;
1567 my ($size, $file_format) = file_size_info($file);
1568
1569 if ($format eq 'raw+size') {
1570 goto unsupported if $with_snapshots || $file_format eq 'subvol';
1571 write_common_header($fh, $size);
1572 if ($file_format eq 'raw') {
1573 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1574 } else {
1575 run_command(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1576 output => '>&'.fileno($fh));
1577 }
1578 return;
1579 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1580 my $data_format = $1;
1581 goto unsupported if !$with_snapshots || $file_format ne $data_format;
1582 write_common_header($fh, $size);
1583 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1584 return;
1585 } elsif ($format eq 'tar+size') {
1586 goto unsupported if $file_format ne 'subvol';
1587 write_common_header($fh, $size);
1588 run_command(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1589 output => '>&'.fileno($fh));
1590 return;
1591 }
1592 }
1593 unsupported:
1594 die "volume export format $format not available for $class";
1595 }
1596
1597 sub volume_export_formats {
1598 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1599 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1600 my $file = $class->path($scfg, $volname, $storeid)
1601 or return;
1602 my ($size, $format) = file_size_info($file);
1603
1604 if ($with_snapshots) {
1605 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1606 return ();
1607 }
1608 return ('tar+size') if $format eq 'subvol';
1609 return ('raw+size');
1610 }
1611 return ();
1612 }
1613
1614 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1615 sub volume_import {
1616 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1617
1618 die "volume import format '$format' not available for $class\n"
1619 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1620 my $data_format = $1;
1621
1622 die "format $format cannot be imported without snapshots\n"
1623 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1624 die "format $format cannot be imported with snapshots\n"
1625 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1626
1627 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1628 $class->parse_volname($volname);
1629
1630 # XXX: Should we bother with conversion routines at this level? This won't
1631 # happen without manual CLI usage, so for now we just error out...
1632 die "cannot import format $format into a file of format $file_format\n"
1633 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1634
1635 # Check for an existing file first since interrupting alloc_image doesn't
1636 # free it.
1637 my $file = $class->path($scfg, $volname, $storeid);
1638 if (-e $file) {
1639 die "file '$file' already exists\n" if !$allow_rename;
1640 warn "file '$file' already exists - importing with a different name\n";
1641 $name = undef;
1642 }
1643
1644 my ($size) = read_common_header($fh);
1645 $size = int($size/1024);
1646
1647 eval {
1648 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1649 my $oldname = $volname;
1650 $volname = $allocname;
1651 if (defined($name) && $allocname ne $oldname) {
1652 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1653 }
1654 my $file = $class->path($scfg, $volname, $storeid)
1655 or die "internal error: failed to get path to newly allocated volume $volname\n";
1656 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1657 run_command(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1658 input => '<&'.fileno($fh));
1659 } elsif ($data_format eq 'tar') {
1660 run_command(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1661 input => '<&'.fileno($fh));
1662 } else {
1663 die "volume import format '$format' not available for $class";
1664 }
1665 };
1666 if (my $err = $@) {
1667 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1668 warn $@ if $@;
1669 die $err;
1670 }
1671
1672 return "$storeid:$volname";
1673 }
1674
1675 sub volume_import_formats {
1676 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1677 if ($scfg->{path} && !defined($base_snapshot)) {
1678 my $format = ($class->parse_volname($volname))[6];
1679 if ($with_snapshots) {
1680 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1681 return ();
1682 }
1683 return ('tar+size') if $format eq 'subvol';
1684 return ('raw+size');
1685 }
1686 return ();
1687 }
1688
1689 sub rename_volume {
1690 my ($class, $scfg, $storeid, $source_volname, $target_vmid, $target_volname) = @_;
1691 die "not implemented in storage plugin '$class'\n" if $class->can('api') && $class->api() < 10;
1692 die "no path found\n" if !$scfg->{path};
1693
1694 my (
1695 undef,
1696 $source_image,
1697 $source_vmid,
1698 $base_name,
1699 $base_vmid,
1700 undef,
1701 $format
1702 ) = $class->parse_volname($source_volname);
1703
1704 $target_volname = $class->find_free_diskname($storeid, $scfg, $target_vmid, $format, 1)
1705 if !$target_volname;
1706
1707 my $basedir = $class->get_subdir($scfg, 'images');
1708
1709 mkpath "${basedir}/${target_vmid}";
1710
1711 my $old_path = "${basedir}/${source_vmid}/${source_image}";
1712 my $new_path = "${basedir}/${target_vmid}/${target_volname}";
1713
1714 die "target volume '${target_volname}' already exists\n" if -e $new_path;
1715
1716 my $base = $base_name ? "${base_vmid}/${base_name}/" : '';
1717
1718 rename($old_path, $new_path) ||
1719 die "rename '$old_path' to '$new_path' failed - $!\n";
1720
1721 return "${storeid}:${base}${target_vmid}/${target_volname}";
1722 }
1723
1724 sub config_aware_base_mkdir {
1725 my ($class, $scfg, $path) = @_;
1726
1727 # FIXME the mkdir parameter is deprecated and create-base-path should be used
1728 if ($scfg->{'create-base-path'} // $scfg->{mkdir} // 1) {
1729 mkpath($path);
1730 }
1731 }
1732
1733 1;