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