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