]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage/Plugin.pm
pbs: allow setting up a master key
[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 unlimted.",
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 additon 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 definintion 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 definintion 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', '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 warn "could not parse qemu-img info command output for '$filename'\n" if $@;
825
826 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
827
828 return wantarray ? ($size, $format, $used, $parent, $st->ctime) : $size;
829 }
830
831 sub get_volume_notes {
832 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
833
834 die "volume notes are not supported for $class";
835 }
836
837 sub update_volume_notes {
838 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
839
840 die "volume notes are not supported for $class";
841 }
842
843 sub volume_size_info {
844 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
845 my $path = $class->filesystem_path($scfg, $volname);
846 return file_size_info($path, $timeout);
847
848 }
849
850 sub volume_resize {
851 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
852
853 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
854
855 return 1 if $running;
856
857 my $path = $class->filesystem_path($scfg, $volname);
858
859 my $format = ($class->parse_volname($volname))[6];
860
861 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
862
863 run_command($cmd, timeout => 10);
864
865 return undef;
866 }
867
868 sub volume_snapshot {
869 my ($class, $scfg, $storeid, $volname, $snap) = @_;
870
871 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
872
873 my $path = $class->filesystem_path($scfg, $volname);
874
875 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
876
877 run_command($cmd);
878
879 return undef;
880 }
881
882 sub volume_rollback_is_possible {
883 my ($class, $scfg, $storeid, $volname, $snap) = @_;
884
885 return 1;
886 }
887
888 sub volume_snapshot_rollback {
889 my ($class, $scfg, $storeid, $volname, $snap) = @_;
890
891 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
892
893 my $path = $class->filesystem_path($scfg, $volname);
894
895 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
896
897 run_command($cmd);
898
899 return undef;
900 }
901
902 sub volume_snapshot_delete {
903 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
904
905 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
906
907 return 1 if $running;
908
909 my $path = $class->filesystem_path($scfg, $volname);
910
911 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
912
913 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
914
915 run_command($cmd);
916
917 return undef;
918 }
919
920 sub volume_snapshot_needs_fsfreeze {
921
922 return 0;
923 }
924 sub storage_can_replicate {
925 my ($class, $scfg, $storeid, $format) = @_;
926
927 return 0;
928 }
929
930 sub volume_has_feature {
931 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
932
933 my $features = {
934 snapshot => { current => { qcow2 => 1}, snap => { qcow2 => 1} },
935 clone => { base => {qcow2 => 1, raw => 1, vmdk => 1} },
936 template => { current => {qcow2 => 1, raw => 1, vmdk => 1, subvol => 1} },
937 copy => { base => {qcow2 => 1, raw => 1, vmdk => 1},
938 current => {qcow2 => 1, raw => 1, vmdk => 1},
939 snap => {qcow2 => 1} },
940 sparseinit => { base => {qcow2 => 1, raw => 1, vmdk => 1},
941 current => {qcow2 => 1, raw => 1, vmdk => 1} },
942 };
943
944 # clone_image creates a qcow2 volume
945 return 0 if $feature eq 'clone' &&
946 defined($opts->{valid_target_formats}) &&
947 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats}});
948
949 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
950 $class->parse_volname($volname);
951
952 my $key = undef;
953 if($snapname){
954 $key = 'snap';
955 }else{
956 $key = $isBase ? 'base' : 'current';
957 }
958
959 return 1 if defined($features->{$feature}->{$key}->{$format});
960
961 return undef;
962 }
963
964 sub list_images {
965 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
966
967 my $imagedir = $class->get_subdir($scfg, 'images');
968
969 my ($defFmt, $vaidFmts) = default_format($scfg);
970 my $fmts = join ('|', @$vaidFmts);
971
972 my $res = [];
973
974 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
975
976 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
977 $fn = $1; # untaint
978
979 my $owner = $2;
980 my $name = $3;
981
982 next if !$vollist && defined($vmid) && ($owner ne $vmid);
983
984 my ($size, $format, $used, $parent, $ctime) = file_size_info($fn);
985 next if !($format && defined($size));
986
987 my $volid;
988 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
989 my ($basevmid, $basename) = ($1, $2);
990 $volid = "$storeid:$basevmid/$basename/$owner/$name";
991 } else {
992 $volid = "$storeid:$owner/$name";
993 }
994
995 if ($vollist) {
996 my $found = grep { $_ eq $volid } @$vollist;
997 next if !$found;
998 }
999
1000 my $info = {
1001 volid => $volid, format => $format,
1002 size => $size, vmid => $owner, used => $used, parent => $parent
1003 };
1004
1005 $info->{ctime} = $ctime if $ctime;
1006
1007 push @$res, $info;
1008 }
1009
1010 return $res;
1011 }
1012
1013 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1014 my $get_subdir_files = sub {
1015 my ($sid, $path, $tt, $vmid) = @_;
1016
1017 my $res = [];
1018
1019 foreach my $fn (<$path/*>) {
1020 my $st = File::stat::stat($fn);
1021
1022 next if (!$st || S_ISDIR($st->mode));
1023
1024 my $info;
1025
1026 if ($tt eq 'iso') {
1027 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
1028
1029 $info = { volid => "$sid:iso/$1", format => 'iso' };
1030
1031 } elsif ($tt eq 'vztmpl') {
1032 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
1033
1034 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
1035
1036 } elsif ($tt eq 'backup') {
1037 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
1038 my $original = $fn;
1039 my $format = $2;
1040 $fn = $1;
1041
1042 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1043 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1044
1045 $info = { volid => "$sid:backup/$fn", format => $format };
1046
1047 my $archive_info = eval { PVE::Storage::archive_info($fn) } // {};
1048
1049 $info->{ctime} = $archive_info->{ctime} if defined($archive_info->{ctime});
1050
1051 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1052 $info->{vmid} = $vmid // $1;
1053 }
1054
1055 my $notes_fn = $original.NOTES_EXT;
1056 if (-f $notes_fn) {
1057 my $notes = PVE::Tools::file_read_firstline($notes_fn);
1058 $info->{notes} = $notes if defined($notes);
1059 }
1060
1061 } elsif ($tt eq 'snippets') {
1062
1063 $info = {
1064 volid => "$sid:snippets/". basename($fn),
1065 format => 'snippet',
1066 };
1067 }
1068
1069 $info->{size} = $st->size;
1070 $info->{ctime} //= $st->ctime;
1071
1072 push @$res, $info;
1073 }
1074
1075 return $res;
1076 };
1077
1078 sub list_volumes {
1079 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1080
1081 my $res = [];
1082 my $vmlist = PVE::Cluster::get_vmlist();
1083 foreach my $type (@$content_types) {
1084 my $data;
1085
1086 if ($type eq 'images' || $type eq 'rootdir') {
1087 $data = $class->list_images($storeid, $scfg, $vmid);
1088 } elsif ($scfg->{path}) {
1089 my $path = $class->get_subdir($scfg, $type);
1090
1091 if ($type eq 'iso' && !defined($vmid)) {
1092 $data = $get_subdir_files->($storeid, $path, 'iso');
1093 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1094 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1095 } elsif ($type eq 'backup') {
1096 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1097 } elsif ($type eq 'snippets') {
1098 $data = $get_subdir_files->($storeid, $path, 'snippets');
1099 }
1100 }
1101
1102 next if !$data;
1103
1104 foreach my $item (@$data) {
1105 if ($type eq 'images' || $type eq 'rootdir') {
1106 my $vminfo = $vmlist->{ids}->{$item->{vmid}};
1107 my $vmtype;
1108 if (defined($vminfo)) {
1109 $vmtype = $vminfo->{type};
1110 }
1111 if (defined($vmtype) && $vmtype eq 'lxc') {
1112 $item->{content} = 'rootdir';
1113 } else {
1114 $item->{content} = 'images';
1115 }
1116 next if $type ne $item->{content};
1117 } else {
1118 $item->{content} = $type;
1119 }
1120
1121 push @$res, $item;
1122 }
1123 }
1124
1125 return $res;
1126 }
1127
1128 sub status {
1129 my ($class, $storeid, $scfg, $cache) = @_;
1130
1131 my $path = $scfg->{path};
1132
1133 die "storage definintion has no path\n" if !$path;
1134
1135 my $timeout = 2;
1136 my $res = PVE::Tools::df($path, $timeout);
1137
1138 return undef if !$res || !$res->{total};
1139
1140 return ($res->{total}, $res->{avail}, $res->{used}, 1);
1141 }
1142
1143 sub volume_snapshot_list {
1144 my ($class, $scfg, $storeid, $volname) = @_;
1145
1146 # implement in subclass
1147 die "Volume_snapshot_list is not implemented for $class";
1148
1149 # return an empty array if dataset does not exist.
1150 }
1151
1152 sub activate_storage {
1153 my ($class, $storeid, $scfg, $cache) = @_;
1154
1155 my $path = $scfg->{path};
1156
1157 die "storage definintion has no path\n" if !$path;
1158
1159 # this path test may hang indefinitely on unresponsive mounts
1160 my $timeout = 2;
1161 if (! PVE::Tools::run_fork_with_timeout($timeout, sub {-d $path})) {
1162 die "unable to activate storage '$storeid' - " .
1163 "directory '$path' does not exist or is unreachable\n";
1164 }
1165
1166
1167 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1168
1169 if (defined($scfg->{content})) {
1170 foreach my $vtype (keys %$vtype_subdirs) {
1171 # OpenVZMigrate uses backup (dump) dir
1172 if (defined($scfg->{content}->{$vtype}) ||
1173 ($vtype eq 'backup' && defined($scfg->{content}->{'rootdir'}))) {
1174 my $subdir = $class->get_subdir($scfg, $vtype);
1175 mkpath $subdir if $subdir ne $path;
1176 }
1177 }
1178 }
1179 }
1180
1181 sub deactivate_storage {
1182 my ($class, $storeid, $scfg, $cache) = @_;
1183
1184 # do nothing by default
1185 }
1186
1187 sub map_volume {
1188 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1189
1190 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1191 return $path;
1192 }
1193
1194 sub unmap_volume {
1195 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1196
1197 return 1;
1198 }
1199
1200 sub activate_volume {
1201 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1202
1203 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1204
1205 # check is volume exists
1206 if ($scfg->{path}) {
1207 die "volume '$storeid:$volname' does not exist\n" if ! -e $path;
1208 } else {
1209 die "volume '$storeid:$volname' does not exist\n" if ! -b $path;
1210 }
1211 }
1212
1213 sub deactivate_volume {
1214 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1215
1216 # do nothing by default
1217 }
1218
1219 sub check_connection {
1220 my ($class, $storeid, $scfg) = @_;
1221 # do nothing by default
1222 return 1;
1223 }
1224
1225 sub prune_backups {
1226 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1227
1228 $logfunc //= sub { print "$_[1]\n" };
1229
1230 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1231
1232 my $backup_groups = {};
1233 my $prune_list = [];
1234
1235 foreach my $backup (@{$backups}) {
1236 my $volid = $backup->{volid};
1237 my $archive_info = eval { PVE::Storage::archive_info($volid) } // {};
1238 my $backup_type = $archive_info->{type} // 'unknown';
1239 my $backup_vmid = $archive_info->{vmid} // $backup->{vmid};
1240
1241 next if defined($type) && $type ne $backup_type;
1242
1243 my $prune_entry = {
1244 ctime => $backup->{ctime},
1245 type => $backup_type,
1246 volid => $volid,
1247 };
1248
1249 $prune_entry->{vmid} = $backup_vmid if defined($backup_vmid);
1250
1251 if ($archive_info->{is_std_name}) {
1252 die "internal error - got no VMID\n" if !defined($backup_vmid);
1253 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1254 if defined($vmid) && $backup_vmid ne $vmid;
1255
1256 $prune_entry->{ctime} = $archive_info->{ctime};
1257 my $group = "$backup_type/$backup_vmid";
1258 push @{$backup_groups->{$group}}, $prune_entry;
1259 } else {
1260 # ignore backups that don't use the standard naming scheme
1261 $prune_entry->{mark} = 'protected';
1262 }
1263
1264 push @{$prune_list}, $prune_entry;
1265 }
1266
1267 foreach my $backup_group (values %{$backup_groups}) {
1268 PVE::Storage::prune_mark_backup_group($backup_group, $keep);
1269 }
1270
1271 my $failed;
1272 if (!$dryrun) {
1273 foreach my $prune_entry (@{$prune_list}) {
1274 next if $prune_entry->{mark} ne 'remove';
1275
1276 my $volid = $prune_entry->{volid};
1277 $logfunc->('info', "removing backup '$volid'");
1278 eval {
1279 my (undef, $volname) = parse_volume_id($volid);
1280 my $archive_path = $class->filesystem_path($scfg, $volname);
1281 PVE::Storage::archive_remove($archive_path);
1282 };
1283 if (my $err = $@) {
1284 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1285 $failed = 1;
1286 }
1287 }
1288 }
1289 die "error pruning backups - check log\n" if $failed;
1290
1291 return $prune_list;
1292 }
1293
1294 # Import/Export interface:
1295 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1296 # the default implementations will return this if $scfg->{path} is set,
1297 # mimicking the old PVE::Storage::storage_migrate() function.
1298 #
1299 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1300 # functions in case the format doesn't match their specialized
1301 # implementations to reuse the raw/tar code.
1302 #
1303 # Format specification:
1304 # The following formats are all prefixed with image information in the form
1305 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1306 # to preallocate the image on storages which require it.
1307 #
1308 # raw+size: (image files only)
1309 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1310 # qcow2+size, vmdk: (image files only)
1311 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1312 # files which are already in qcow2 format, or via `qemu-img convert`.
1313 # Note that these formats are only valid with $with_snapshots being true.
1314 # tar+size: (subvolumes only)
1315 # A GNU tar stream containing just the inner contents of the subvolume.
1316 # This does not distinguish between the contents of a privileged or
1317 # unprivileged container. In other words, this is from the root user
1318 # namespace's point of view with no uid-mapping in effect.
1319 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1320
1321 # Plugins may reuse these helpers. Changes to the header format should be
1322 # reflected by changes to the function prototypes.
1323 sub write_common_header($$) {
1324 my ($fh, $image_size_in_bytes) = @_;
1325 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1326 }
1327
1328 sub read_common_header($) {
1329 my ($fh) = @_;
1330 sysread($fh, my $size, 8);
1331 $size = unpack('Q<', $size);
1332 die "import: no size found in export header, aborting.\n" if !defined($size);
1333 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
1334 # Size is in bytes!
1335 return $size;
1336 }
1337
1338 # Export a volume into a file handle as a stream of desired format.
1339 sub volume_export {
1340 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1341 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1342 my $file = $class->path($scfg, $volname, $storeid)
1343 or goto unsupported;
1344 my ($size, $file_format) = file_size_info($file);
1345
1346 if ($format eq 'raw+size') {
1347 goto unsupported if $with_snapshots || $file_format eq 'subvol';
1348 write_common_header($fh, $size);
1349 if ($file_format eq 'raw') {
1350 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1351 } else {
1352 run_command(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1353 output => '>&'.fileno($fh));
1354 }
1355 return;
1356 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1357 my $data_format = $1;
1358 goto unsupported if !$with_snapshots || $file_format ne $data_format;
1359 write_common_header($fh, $size);
1360 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1361 return;
1362 } elsif ($format eq 'tar+size') {
1363 goto unsupported if $file_format ne 'subvol';
1364 write_common_header($fh, $size);
1365 run_command(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1366 output => '>&'.fileno($fh));
1367 return;
1368 }
1369 }
1370 unsupported:
1371 die "volume export format $format not available for $class";
1372 }
1373
1374 sub volume_export_formats {
1375 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1376 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1377 my $file = $class->path($scfg, $volname, $storeid)
1378 or return;
1379 my ($size, $format) = file_size_info($file);
1380
1381 if ($with_snapshots) {
1382 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1383 return ();
1384 }
1385 return ('tar+size') if $format eq 'subvol';
1386 return ('raw+size');
1387 }
1388 return ();
1389 }
1390
1391 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1392 sub volume_import {
1393 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1394
1395 die "volume import format '$format' not available for $class\n"
1396 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1397 my $data_format = $1;
1398
1399 die "format $format cannot be imported without snapshots\n"
1400 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1401 die "format $format cannot be imported with snapshots\n"
1402 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1403
1404 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1405 $class->parse_volname($volname);
1406
1407 # XXX: Should we bother with conversion routines at this level? This won't
1408 # happen without manual CLI usage, so for now we just error out...
1409 die "cannot import format $format into a file of format $file_format\n"
1410 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1411
1412 # Check for an existing file first since interrupting alloc_image doesn't
1413 # free it.
1414 my $file = $class->path($scfg, $volname, $storeid);
1415 if (-e $file) {
1416 die "file '$file' already exists\n" if !$allow_rename;
1417 warn "file '$file' already exists - importing with a different name\n";
1418 $name = undef;
1419 }
1420
1421 my ($size) = read_common_header($fh);
1422 $size = int($size/1024);
1423
1424 eval {
1425 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1426 my $oldname = $volname;
1427 $volname = $allocname;
1428 if (defined($name) && $allocname ne $oldname) {
1429 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1430 }
1431 my $file = $class->path($scfg, $volname, $storeid)
1432 or die "internal error: failed to get path to newly allocated volume $volname\n";
1433 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1434 run_command(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1435 input => '<&'.fileno($fh));
1436 } elsif ($data_format eq 'tar') {
1437 run_command(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1438 input => '<&'.fileno($fh));
1439 } else {
1440 die "volume import format '$format' not available for $class";
1441 }
1442 };
1443 if (my $err = $@) {
1444 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1445 warn $@ if $@;
1446 die $err;
1447 }
1448
1449 return "$storeid:$volname";
1450 }
1451
1452 sub volume_import_formats {
1453 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
1454 if ($scfg->{path} && !defined($base_snapshot)) {
1455 my $format = ($class->parse_volname($volname))[6];
1456 if ($with_snapshots) {
1457 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1458 return ();
1459 }
1460 return ('tar+size') if $format eq 'subvol';
1461 return ('raw+size');
1462 }
1463 return ();
1464 }
1465
1466 1;