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