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