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