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