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