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