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