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