]> git.proxmox.com Git - pve-storage.git/blame - PVE/Storage/Plugin.pm
bump version to 5.0-27
[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;
074b2cb4 8
1dc01b9f
DM
9use PVE::Tools qw(run_command);
10use PVE::JSONSchema qw(get_standard_option);
11use PVE::Cluster qw(cfs_register_file);
12
1dc01b9f
DM
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',
e34ce144 27 'cephfs',
d7875239
WL
28 'sheepdog',
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,
329 content => { images => 1, rootdir => 1, vztmpl => 1, iso => 1},
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);
1dc01b9f
DM
418 } elsif ($volname =~ m!^iso/([^/]+\.[Ii][Ss][Oo])$!) {
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);
430 }
431
432 die "unable to parse directory volume name '$volname'\n";
433}
434
045ae0a7 435my $vtype_subdirs = {
1dc01b9f
DM
436 images => 'images',
437 rootdir => 'private',
438 iso => 'template/iso',
439 vztmpl => 'template/cache',
440 backup => 'dump',
441};
442
443sub get_subdir {
444 my ($class, $scfg, $vtype) = @_;
445
446 my $path = $scfg->{path};
447
448 die "storage definintion has no path\n" if !$path;
449
450 my $subdir = $vtype_subdirs->{$vtype};
451
452 die "unknown vtype '$vtype'\n" if !defined($subdir);
453
045ae0a7 454 return "$path/$subdir";
1dc01b9f
DM
455}
456
08480ce7 457sub filesystem_path {
e67069eb 458 my ($class, $scfg, $volname, $snapname) = @_;
1dc01b9f 459
e67069eb
DM
460 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
461 $class->parse_volname($volname);
462
463 # Note: qcow2/qed has internal snapshot, so path is always
464 # the same (with or without snapshot => same file).
465 die "can't snapshot this image format\n"
466 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
1dc01b9f
DM
467
468 my $dir = $class->get_subdir($scfg, $vtype);
469
470 $dir .= "/$vmid" if $vtype eq 'images';
471
472 my $path = "$dir/$name";
473
474 return wantarray ? ($path, $vmid, $vtype) : $path;
475}
476
08480ce7 477sub path {
e67069eb 478 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
08480ce7 479
e67069eb 480 return $class->filesystem_path($scfg, $volname, $snapname);
08480ce7
DM
481}
482
2502b33b
DM
483sub create_base {
484 my ($class, $storeid, $scfg, $volname) = @_;
485
486 # this only works for file based storage types
5510f5c9 487 die "storage definition has no path\n" if !$scfg->{path};
2502b33b 488
35533c68 489 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
2502b33b
DM
490 $class->parse_volname($volname);
491
492 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
493
494 die "create_base not possible with base image\n" if $isBase;
495
08480ce7 496 my $path = $class->filesystem_path($scfg, $volname);
2502b33b 497
35533c68
DM
498 my ($size, undef, $used, $parent) = file_size_info($path);
499 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
2502b33b
DM
500
501 die "volname '$volname' contains wrong information about parent\n"
502 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
503
504 my $newname = $name;
505 $newname =~ s/^vm-/base-/;
506
507 my $newvolname = $basename ? "$basevmid/$basename/$vmid/$newname" :
508 "$vmid/$newname";
509
08480ce7 510 my $newpath = $class->filesystem_path($scfg, $newvolname);
2502b33b
DM
511
512 die "file '$newpath' already exists\n" if -f $newpath;
513
1a3459ac 514 rename($path, $newpath) ||
2502b33b
DM
515 die "rename '$path' to '$newpath' failed - $!\n";
516
c803c396 517 # We try to protect base volume
2502b33b 518
c803c396
DM
519 chmod(0444, $newpath); # nobody should write anything
520
521 # also try to set immutable flag
522 eval { run_command(['/usr/bin/chattr', '+i', $newpath]); };
523 warn $@ if $@;
1a3459ac 524
2502b33b
DM
525 return $newvolname;
526}
527
83a40b8d
TL
528my $get_vm_disk_number = sub {
529 my ($disk_name, $scfg, $vmid, $suffix) = @_;
345f8981
SI
530
531 my $type = $scfg->{type};
532 my $def = $defaultData->{plugindata}->{$type};
533 my $valid_formats = $def->{format}[0];
534
535 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
536 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/
537 if $valid_formats->{subvol};
538
83a40b8d
TL
539 if ($disk_name =~ m/$disk_regex/) {
540 return $2;
345f8981 541 }
83a40b8d
TL
542
543 return undef;
544};
345f8981
SI
545
546sub get_next_vm_diskname {
547 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
548
345f8981
SI
549 $fmt //= '';
550 my $prefix = ($fmt eq 'subvol') ? 'subvol' : 'vm';
551 my $suffix = $add_fmt_suffix ? ".$fmt" : '';
552
83a40b8d
TL
553 my $disk_ids = {};
554 foreach my $disk (@$disk_list) {
555 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
556 $disk_ids->{$disknum} = 1 if defined($disknum);
557 }
558
59fa9fd6 559 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
345f8981
SI
560 if (!$disk_ids->{$i}) {
561 return "$prefix-$vmid-disk-$i$suffix";
562 }
563 }
564
565 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
566}
567
2502b33b 568my $find_free_diskname = sub {
c4a29df4 569 my ($imgdir, $vmid, $fmt, $scfg) = @_;
2502b33b 570
c4a29df4
SI
571 my $disk_list = [];
572
573 if (defined(my $dh = IO::Dir->new($imgdir))) {
574 @$disk_list = $dh->read();
575 $dh->close();
2502b33b
DM
576 }
577
c4a29df4 578 return get_next_vm_diskname($disk_list, $imgdir, $vmid, $fmt, $scfg, 1);
2502b33b
DM
579};
580
581sub clone_image {
f236eaf8 582 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
2502b33b
DM
583
584 # this only works for file based storage types
585 die "storage definintion has no path\n" if !$scfg->{path};
586
35533c68 587 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
2502b33b
DM
588 $class->parse_volname($volname);
589
590 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
591
f236eaf8
SP
592 die "this storage type does not support clone_image on snapshot\n" if $snap;
593
35533c68
DM
594 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
595
f236eaf8 596 die "clone_image only works on base images\n" if !$isBase;
1dc01b9f
DM
597
598 my $imagedir = $class->get_subdir($scfg, 'images');
599 $imagedir .= "/$vmid";
600
601 mkpath $imagedir;
602
c4a29df4 603 my $name = $find_free_diskname->($imagedir, $vmid, "qcow2", $scfg);
2502b33b
DM
604
605 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
606
607 my $newvol = "$basevmid/$basename/$vmid/$name";
608
08480ce7 609 my $path = $class->filesystem_path($scfg, $newvol);
2502b33b 610
1a3459ac 611 # Note: we use relative paths, so we need to call chdir before qemu-img
2502b33b 612 eval {
7fc619d5 613 local $CWD = $imagedir;
2502b33b 614
1a3459ac 615 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
2502b33b 616 '-f', 'qcow2', $path];
1a3459ac 617
2502b33b
DM
618 run_command($cmd);
619 };
620 my $err = $@;
1dc01b9f 621
2502b33b
DM
622 die $err if $err;
623
624 return $newvol;
625}
626
627sub alloc_image {
628 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
629
630 my $imagedir = $class->get_subdir($scfg, 'images');
631 $imagedir .= "/$vmid";
632
633 mkpath $imagedir;
634
c4a29df4 635 $name = $find_free_diskname->($imagedir, $vmid, $fmt, $scfg) if !$name;
1a3459ac 636
1dc01b9f
DM
637 my (undef, $tmpfmt) = parse_name_dir($name);
638
045ae0a7 639 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
1dc01b9f
DM
640 if $tmpfmt ne $fmt;
641
642 my $path = "$imagedir/$name";
643
644 die "disk image '$path' already exists\n" if -e $path;
645
35533c68
DM
646 if ($fmt eq 'subvol') {
647 # only allow this if size = 0, so that user knows what he is doing
648 die "storage does not support subvol quotas\n" if $size != 0;
649
1f5734bb
WB
650 my $old_umask = umask(0022);
651 my $err;
652 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
653 umask $old_umask;
654 die $err if $err;
35533c68
DM
655 } else {
656 my $cmd = ['/usr/bin/qemu-img', 'create'];
045ae0a7 657
35533c68
DM
658 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
659
660 push @$cmd, '-f', $fmt, $path, "${size}K";
1dc01b9f 661
35533c68
DM
662 run_command($cmd, errmsg => "unable to create image");
663 }
664
1dc01b9f
DM
665 return "$vmid/$name";
666}
667
668sub free_image {
35533c68 669 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
1dc01b9f 670
08480ce7 671 my $path = $class->filesystem_path($scfg, $volname);
1dc01b9f 672
f5451f28
DC
673 if ($isBase) {
674 # try to remove immutable flag
675 eval { run_command(['/usr/bin/chattr', '-i', $path]); };
676 warn $@ if $@;
677 }
678
4a7d2222 679 if (defined($format) && ($format eq 'subvol')) {
35533c68
DM
680 File::Path::remove_tree($path);
681 } else {
682
683 if (! -f $path) {
684 warn "disk image '$path' does not exists\n";
685 return undef;
686 }
1dc01b9f 687
35533c68
DM
688 unlink($path) || die "unlink '$path' failed - $!\n";
689 }
690
1dc01b9f
DM
691 return undef;
692}
693
694sub file_size_info {
695 my ($filename, $timeout) = @_;
696
35533c68
DM
697 if (-d $filename) {
698 return wantarray ? (0, 'subvol', 0, undef) : 1;
699 }
700
1dc01b9f
DM
701 my $cmd = ['/usr/bin/qemu-img', 'info', $filename];
702
703 my $format;
73b7847e 704 my $parent;
1dc01b9f
DM
705 my $size = 0;
706 my $used = 0;
707
708 eval {
709 run_command($cmd, timeout => $timeout, outfunc => sub {
710 my $line = shift;
1dc01b9f
DM
711 if ($line =~ m/^file format:\s+(\S+)\s*$/) {
712 $format = $1;
73b7847e
AD
713 } elsif ($line =~ m/^backing file:\s(\S+)\s/) {
714 $parent = $1;
1dc01b9f
DM
715 } elsif ($line =~ m/^virtual size:\s\S+\s+\((\d+)\s+bytes\)$/) {
716 $size = int($1);
717 } elsif ($line =~ m/^disk size:\s+(\d+(.\d+)?)([KMGT])\s*$/) {
718 $used = $1;
719 my $u = $3;
720
721 $used *= 1024 if $u eq 'K';
722 $used *= (1024*1024) if $u eq 'M';
723 $used *= (1024*1024*1024) if $u eq 'G';
724 $used *= (1024*1024*1024*1024) if $u eq 'T';
725
726 $used = int($used);
727 }
728 });
729 };
730
73b7847e 731 return wantarray ? ($size, $format, $used, $parent) : $size;
1dc01b9f
DM
732}
733
e47e548e
AD
734sub volume_size_info {
735 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
08480ce7 736 my $path = $class->filesystem_path($scfg, $volname);
e47e548e
AD
737 return file_size_info($path, $timeout);
738
739}
740
81f5058c
AD
741sub volume_resize {
742 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
743
6d788031 744 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
81f5058c
AD
745
746 return 1 if $running;
747
08480ce7 748 my $path = $class->filesystem_path($scfg, $volname);
81f5058c 749
0589e5f9
WL
750 my $format = ($class->parse_volname($volname))[6];
751
752 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
81f5058c 753
1059cc99 754 run_command($cmd, timeout => 10);
81f5058c
AD
755
756 return undef;
757}
758
7dcb0697 759sub volume_snapshot {
f5640e7d 760 my ($class, $scfg, $storeid, $volname, $snap) = @_;
7dcb0697 761
6d788031 762 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
7dcb0697 763
08480ce7 764 my $path = $class->filesystem_path($scfg, $volname);
7dcb0697
AD
765
766 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
767
3f13fd7d 768 run_command($cmd);
7dcb0697
AD
769
770 return undef;
771}
772
1597f1f9
WL
773sub volume_rollback_is_possible {
774 my ($class, $scfg, $storeid, $volname, $snap) = @_;
775
776 return 1;
777}
778
41dffa85
AD
779sub volume_snapshot_rollback {
780 my ($class, $scfg, $storeid, $volname, $snap) = @_;
781
6d788031 782 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
41dffa85 783
08480ce7 784 my $path = $class->filesystem_path($scfg, $volname);
41dffa85
AD
785
786 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
787
3f13fd7d 788 run_command($cmd);
41dffa85
AD
789
790 return undef;
791}
792
6000a061
AD
793sub volume_snapshot_delete {
794 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
795
6d788031 796 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
6000a061
AD
797
798 return 1 if $running;
799
08480ce7 800 my $path = $class->filesystem_path($scfg, $volname);
6000a061 801
399581a2
WB
802 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
803
6000a061
AD
804 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
805
3f13fd7d 806 run_command($cmd);
6000a061
AD
807
808 return undef;
809}
810
7118dd91
DM
811sub storage_can_replicate {
812 my ($class, $scfg, $storeid, $format) = @_;
813
814 return 0;
815}
816
f884fe11
AD
817sub volume_has_feature {
818 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running) = @_;
819
820 my $features = {
5649ccfe
AD
821 snapshot => { current => { qcow2 => 1}, snap => { qcow2 => 1} },
822 clone => { base => {qcow2 => 1, raw => 1, vmdk => 1} },
35533c68 823 template => { current => {qcow2 => 1, raw => 1, vmdk => 1, subvol => 1} },
5649ccfe 824 copy => { base => {qcow2 => 1, raw => 1, vmdk => 1},
22b8cf97
AD
825 current => {qcow2 => 1, raw => 1, vmdk => 1},
826 snap => {qcow2 => 1} },
baafddbd
DC
827 sparseinit => { base => {qcow2 => 1, raw => 1, vmdk => 1},
828 current => {qcow2 => 1, raw => 1, vmdk => 1} },
f884fe11
AD
829 };
830
35533c68 831 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
dc4f2cb3
AD
832 $class->parse_volname($volname);
833
dc4f2cb3
AD
834 my $key = undef;
835 if($snapname){
2c5a7097 836 $key = 'snap';
dc4f2cb3
AD
837 }else{
838 $key = $isBase ? 'base' : 'current';
f884fe11 839 }
dc4f2cb3
AD
840
841 return 1 if defined($features->{$feature}->{$key}->{$format});
842
f884fe11
AD
843 return undef;
844}
845
1dc01b9f
DM
846sub list_images {
847 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
848
849 my $imagedir = $class->get_subdir($scfg, 'images');
850
851 my ($defFmt, $vaidFmts) = default_format($scfg);
045ae0a7 852 my $fmts = join ('|', @$vaidFmts);
1dc01b9f
DM
853
854 my $res = [];
855
856 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
857
858 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
859 $fn = $1; # untaint
860
861 my $owner = $2;
862 my $name = $3;
1dc01b9f 863
2502b33b 864 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1dc01b9f 865
73b7847e 866 my ($size, $format, $used, $parent) = file_size_info($fn);
35533c68 867 next if !($format && defined($size));
2502b33b
DM
868
869 my $volid;
870 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
871 my ($basevmid, $basename) = ($1, $2);
872 $volid = "$storeid:$basevmid/$basename/$owner/$name";
873 } else {
874 $volid = "$storeid:$owner/$name";
875 }
1dc01b9f 876
2502b33b
DM
877 if ($vollist) {
878 my $found = grep { $_ eq $volid } @$vollist;
879 next if !$found;
1dc01b9f
DM
880 }
881
2502b33b
DM
882 push @$res, {
883 volid => $volid, format => $format,
1a3459ac 884 size => $size, vmid => $owner, used => $used, parent => $parent
2502b33b 885 };
1dc01b9f
DM
886 }
887
888 return $res;
889}
890
891sub status {
892 my ($class, $storeid, $scfg, $cache) = @_;
893
894 my $path = $scfg->{path};
895
896 die "storage definintion has no path\n" if !$path;
045ae0a7 897
1dc01b9f
DM
898 my $timeout = 2;
899 my $res = PVE::Tools::df($path, $timeout);
900
901 return undef if !$res || !$res->{total};
902
903 return ($res->{total}, $res->{avail}, $res->{used}, 1);
904}
905
aefe82ea 906sub volume_snapshot_list {
8b622c2d 907 my ($class, $scfg, $storeid, $volname) = @_;
aefe82ea
WL
908
909 # implement in subclass
910 die "Volume_snapshot_list is not implemented for $class";
911
636ac5b8 912 # return an empty array if dataset does not exist.
aefe82ea
WL
913}
914
1dc01b9f
DM
915sub activate_storage {
916 my ($class, $storeid, $scfg, $cache) = @_;
917
918 my $path = $scfg->{path};
919
920 die "storage definintion has no path\n" if !$path;
921
e53050ed
EK
922 # this path test may hang indefinitely on unresponsive mounts
923 my $timeout = 2;
924 if (! PVE::Tools::run_fork_with_timeout($timeout, sub {-d $path})) {
925 die "unable to activate storage '$storeid' - " .
926 "directory '$path' does not exist or is unreachable\n";
927 }
928
1dc01b9f 929
c7616abc
WB
930 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
931
1dc01b9f
DM
932 if (defined($scfg->{content})) {
933 foreach my $vtype (keys %$vtype_subdirs) {
6bcc16d7
DM
934 # OpenVZMigrate uses backup (dump) dir
935 if (defined($scfg->{content}->{$vtype}) ||
936 ($vtype eq 'backup' && defined($scfg->{content}->{'rootdir'}))) {
937 my $subdir = $class->get_subdir($scfg, $vtype);
938 mkpath $subdir if $subdir ne $path;
939 }
1dc01b9f
DM
940 }
941 }
942}
943
944sub deactivate_storage {
945 my ($class, $storeid, $scfg, $cache) = @_;
946
947 # do nothing by default
948}
949
950sub activate_volume {
02e797b8 951 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1dc01b9f 952
02e797b8 953 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1dc01b9f
DM
954
955 # check is volume exists
956 if ($scfg->{path}) {
957 die "volume '$storeid:$volname' does not exist\n" if ! -e $path;
958 } else {
959 die "volume '$storeid:$volname' does not exist\n" if ! -b $path;
960 }
961}
962
963sub deactivate_volume {
02e797b8 964 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1dc01b9f
DM
965
966 # do nothing by default
967}
968
c9eeac01
AD
969sub check_connection {
970 my ($class, $storeid, $scfg) = @_;
971 # do nothing by default
972 return 1;
973}
974
e1f6cb39
DM
975# Import/Export interface:
976# Any path based storage is assumed to support 'raw' and 'tar' streams, so
977# the default implementations will return this if $scfg->{path} is set,
978# mimicking the old PVE::Storage::storage_migrate() function.
979#
980# Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
981# functions in case the format doesn't match their specialized
982# implementations to reuse the raw/tar code.
983#
984# Format specification:
985# The following formats are all prefixed with image information in the form
986# of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
987# to preallocate the image on storages which require it.
988#
989# raw+size: (image files only)
990# A raw binary data stream such as produced via `dd if=TheImageFile`.
991# qcow2+size, vmdk: (image files only)
992# A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
993# files which are already in qcow2 format, or via `qemu-img convert`.
994# Note that these formats are only valid with $with_snapshots being true.
995# tar+size: (subvolumes only)
6b3a4a25
WB
996# A GNU tar stream containing just the inner contents of the subvolume.
997# This does not distinguish between the contents of a privileged or
998# unprivileged container. In other words, this is from the root user
999# namespace's point of view with no uid-mapping in effect.
1000# As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
e1f6cb39
DM
1001
1002# Plugins may reuse these helpers. Changes to the header format should be
1003# reflected by changes to the function prototypes.
1004sub write_common_header($$) {
1005 my ($fh, $image_size_in_bytes) = @_;
1006 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1007}
1008
1009sub read_common_header($) {
1010 my ($fh) = @_;
1011 sysread($fh, my $size, 8);
1012 $size = unpack('Q<', $size);
1013 die "got a bad size (not a multiple of 1K)\n" if ($size&1023);
1014 # Size is in bytes!
1015 return $size;
1016}
1017
47f37b53
WB
1018# Export a volume into a file handle as a stream of desired format.
1019sub volume_export {
1020 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
e1f6cb39
DM
1021 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1022 my $file = $class->path($scfg, $volname, $storeid)
1023 or goto unsupported;
1024 my ($size, $file_format) = file_size_info($file);
1025
1026 if ($format eq 'raw+size') {
1027 goto unsupported if $with_snapshots || $file_format eq 'subvol';
1028 write_common_header($fh, $size);
1029 if ($file_format eq 'raw') {
1030 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1031 } else {
1032 run_command(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1033 output => '>&'.fileno($fh));
1034 }
1035 return;
1036 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1037 my $data_format = $1;
1038 goto unsupported if !$with_snapshots || $file_format ne $data_format;
1039 write_common_header($fh, $size);
1040 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1041 return;
1042 } elsif ($format eq 'tar+size') {
1043 goto unsupported if $file_format ne 'subvol';
1044 write_common_header($fh, $size);
6b3a4a25 1045 run_command(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
e1f6cb39
DM
1046 output => '>&'.fileno($fh));
1047 return;
1048 }
1049 }
1050 unsupported:
1051 die "volume export format $format not available for $class";
47f37b53
WB
1052}
1053
d390328b
WB
1054sub volume_export_formats {
1055 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
e1f6cb39
DM
1056 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1057 my $file = $class->path($scfg, $volname, $storeid)
1058 or return;
1059 my ($size, $format) = file_size_info($file);
1060
1061 if ($with_snapshots) {
1062 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1063 return ();
1064 }
1065 return ('tar+size') if $format eq 'subvol';
1066 return ('raw+size');
1067 }
1068 return ();
d390328b
WB
1069}
1070
47f37b53
WB
1071# Import data from a stream, creating a new or replacing or adding to an existing volume.
1072sub volume_import {
1073 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots) = @_;
e1f6cb39
DM
1074
1075 die "volume import format '$format' not available for $class\n"
1076 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1077 my $data_format = $1;
1078
1079 die "format $format cannot be imported without snapshots\n"
1080 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1081 die "format $format cannot be imported with snapshots\n"
1082 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1083
1084 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1085 $class->parse_volname($volname);
1086
1087 # XXX: Should we bother with conversion routines at this level? This won't
1088 # happen without manual CLI usage, so for now we just error out...
1089 die "cannot import format $format into a file of format $file_format\n"
1090 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1091
1092 # Check for an existing file first since interrupting alloc_image doesn't
1093 # free it.
1094 my $file = $class->path($scfg, $volname, $storeid);
1095 die "file '$file' already exists\n" if -e $file;
1096
1097 my ($size) = read_common_header($fh);
1098 $size = int($size/1024);
1099
1100 eval {
1101 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1102 if ($allocname ne $volname) {
1103 my $oldname = $volname;
1104 $volname = $allocname; # Let the cleanup code know what to free
1105 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1106 }
1107 my $file = $class->path($scfg, $volname, $storeid)
1108 or die "internal error: failed to get path to newly allocated volume $volname\n";
1109 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1110 run_command(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1111 input => '<&'.fileno($fh));
1112 } elsif ($data_format eq 'tar') {
6b3a4a25 1113 run_command(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
e1f6cb39
DM
1114 input => '<&'.fileno($fh));
1115 } else {
1116 die "volume import format '$format' not available for $class";
1117 }
1118 };
1119 if (my $err = $@) {
1120 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1121 warn $@ if $@;
1122 die $err;
1123 }
47f37b53 1124}
e47e548e 1125
d390328b
WB
1126sub volume_import_formats {
1127 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
e1f6cb39
DM
1128 if ($scfg->{path} && !defined($base_snapshot)) {
1129 my $format = ($class->parse_volname($volname))[6];
1130 if ($with_snapshots) {
1131 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1132 return ();
1133 }
1134 return ('tar+size') if $format eq 'subvol';
1135 return ('raw+size');
1136 }
1137 return ();
d390328b
WB
1138}
1139
1dc01b9f 11401;