]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage/Plugin.pm
e20acb3517f2e580a8c6884f25c59a7e1eff990d
[pve-storage.git] / PVE / Storage / Plugin.pm
1 package PVE::Storage::Plugin;
2
3 use strict;
4 use warnings;
5
6 use File::chdir;
7 use File::Path;
8 use File::Basename;
9
10 use PVE::Tools qw(run_command);
11 use PVE::JSONSchema qw(get_standard_option);
12 use PVE::Cluster qw(cfs_register_file);
13
14 use base qw(PVE::SectionConfig);
15
16 our @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
23 our @SHARED_STORAGE = (
24 'iscsi',
25 'nfs',
26 'cifs',
27 'rbd',
28 'cephfs',
29 'iscsidirect',
30 'glusterfs',
31 'zfs',
32 'drbd');
33
34 our $MAX_VOLUMES_PER_GUEST = 1024;
35
36 cfs_register_file ('storage.cfg',
37 sub { __PACKAGE__->parse_config(@_); },
38 sub { __PACKAGE__->write_config(@_); });
39
40
41 my $defaultData = {
42 propertyList => {
43 type => { description => "Storage type." },
44 storage => get_standard_option('pve-storage-id',
45 { completion => \&PVE::Storage::complete_storage }),
46 nodes => get_standard_option('pve-node-list', { optional => 1 }),
47 content => {
48 description => "Allowed content types.\n\nNOTE: the value " .
49 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
50 type => 'string', format => 'pve-storage-content-list',
51 optional => 1,
52 completion => \&PVE::Storage::complete_content_type,
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 },
70 'format' => {
71 description => "Default image format.",
72 type => 'string', format => 'pve-storage-format',
73 optional => 1,
74 },
75 },
76 };
77
78 sub 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};
84 }
85
86 return join(',', @cta);
87 }
88
89 sub 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
99 sub default_format {
100 my ($scfg) = @_;
101
102 my $type = $scfg->{type};
103 my $def = $defaultData->{plugindata}->{$type};
104
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 }
112
113 return wantarray ? ($def_format, $valid_formats) : $def_format;
114 }
115
116 PVE::JSONSchema::register_format('pve-storage-path', \&verify_path);
117 sub 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
129 PVE::JSONSchema::register_format('pve-storage-server', \&verify_server);
130 sub verify_server {
131 my ($server, $noerr) = @_;
132
133 if (!(PVE::JSONSchema::pve_verify_ip($server, 1) ||
134 PVE::JSONSchema::pve_verify_dns_name($server, 1)))
135 {
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
142 PVE::JSONSchema::register_format('pve-storage-vgname', \&parse_lvm_name);
143 sub 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
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
167 PVE::JSONSchema::register_format('pve-storage-portal-dns', \&verify_portal_dns);
168 sub verify_portal_dns {
169 my ($portal, $noerr) = @_;
170
171 # IP or DNS name with optional port
172 if (!PVE::Tools::parse_host_and_port($portal)) {
173 return undef if $noerr;
174 die "value does not look like a valid portal address\n";
175 }
176 return $portal;
177 }
178
179 PVE::JSONSchema::register_format('pve-storage-content', \&verify_content);
180 sub verify_content {
181 my ($ct, $noerr) = @_;
182
183 my $valid_content = valid_content_types('dir'); # dir includes all types
184
185 if (!$valid_content->{$ct}) {
186 return undef if $noerr;
187 die "invalid content type '$ct'\n";
188 }
189
190 return $ct;
191 }
192
193 PVE::JSONSchema::register_format('pve-storage-format', \&verify_format);
194 sub verify_format {
195 my ($fmt, $noerr) = @_;
196
197 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
198 return undef if $noerr;
199 die "invalid format '$fmt'\n";
200 }
201
202 return $fmt;
203 }
204
205 PVE::JSONSchema::register_format('pve-storage-options', \&verify_options);
206 sub 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
218 PVE::JSONSchema::register_format('pve-volume-id', \&parse_volume_id);
219 sub 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
229
230 sub private {
231 return $defaultData;
232 }
233
234 sub 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
248 sub 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];
255
256 my $res = {};
257
258 foreach my $c (PVE::Tools::split_list($value)) {
259 if (!$valid_content->{$c}) {
260 warn "storage does not support content type '$c'\n";
261 next;
262 }
263 $res->{$c} = 1;
264 }
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}) {
275 warn "storage does not support format '$value'\n";
276 next;
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
301 sub 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
314 sub 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
321 # we want 'local' to be always the same 'type' (on all cluster nodes)
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, snippets => 1},
330 };
331 }
332
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 }
348 if (grep { $_ eq $type } @SHARED_STORAGE) {
349 $d->{shared} = 1;
350 }
351 }
352
353 return $cfg;
354 }
355
356 # Storage implementation
357
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
361 sub 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
372 sub on_delete_hook {
373 my ($class, $storeid, $scfg) = @_;
374
375 # do nothing by default
376 }
377
378 sub 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;
386 $res = PVE::Tools::lock_file("$lockdir/$lockid", $timeout, $func, @param);
387 die $@ if $@;
388 } else {
389 $res = PVE::Cluster::cfs_lock_storage($storeid, $timeout, $func, @param);
390 die $@ if $@;
391 }
392 return $res;
393 }
394
395 sub parse_name_dir {
396 my $name = shift;
397
398 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
399 return ($1, $3, $2); # (name, format, isBase)
400 }
401
402 die "unable to parse volume filename '$name'\n";
403 }
404
405 sub parse_volname {
406 my ($class, $volname) = @_;
407
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);
412 my (undef, $format, $isBase) = parse_name_dir($name);
413 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
414 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
415 my ($vmid, $name) = ($1, $2);
416 my (undef, $format, $isBase) = parse_name_dir($name);
417 return ('images', $name, $vmid, undef, undef, $isBase, $format);
418 } elsif ($volname =~ m!^iso/([^/]+\.[Ii][Ss][Oo])$!) {
419 return ('iso', $1);
420 } elsif ($volname =~ m!^vztmpl/([^/]+\.tar\.[gx]z)$!) {
421 return ('vztmpl', $1);
422 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
423 return ('rootdir', $1, $1);
424 } elsif ($volname =~ m!^backup/([^/]+(\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo)))$!) {
425 my $fn = $1;
426 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
427 return ('backup', $fn, $2);
428 }
429 return ('backup', $fn);
430 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
431 return ('snippets', $1);
432 }
433
434 die "unable to parse directory volume name '$volname'\n";
435 }
436
437 my $vtype_subdirs = {
438 images => 'images',
439 rootdir => 'private',
440 iso => 'template/iso',
441 vztmpl => 'template/cache',
442 backup => 'dump',
443 snippets => 'snippets',
444 };
445
446 sub get_subdir {
447 my ($class, $scfg, $vtype) = @_;
448
449 my $path = $scfg->{path};
450
451 die "storage definintion has no path\n" if !$path;
452
453 my $subdir = $vtype_subdirs->{$vtype};
454
455 die "unknown vtype '$vtype'\n" if !defined($subdir);
456
457 return "$path/$subdir";
458 }
459
460 sub filesystem_path {
461 my ($class, $scfg, $volname, $snapname) = @_;
462
463 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
464 $class->parse_volname($volname);
465
466 # Note: qcow2/qed has internal snapshot, so path is always
467 # the same (with or without snapshot => same file).
468 die "can't snapshot this image format\n"
469 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
470
471 my $dir = $class->get_subdir($scfg, $vtype);
472
473 $dir .= "/$vmid" if $vtype eq 'images';
474
475 my $path = "$dir/$name";
476
477 return wantarray ? ($path, $vmid, $vtype) : $path;
478 }
479
480 sub path {
481 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
482
483 return $class->filesystem_path($scfg, $volname, $snapname);
484 }
485
486 sub create_base {
487 my ($class, $storeid, $scfg, $volname) = @_;
488
489 # this only works for file based storage types
490 die "storage definition has no path\n" if !$scfg->{path};
491
492 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
493 $class->parse_volname($volname);
494
495 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
496
497 die "create_base not possible with base image\n" if $isBase;
498
499 my $path = $class->filesystem_path($scfg, $volname);
500
501 my ($size, undef, $used, $parent) = file_size_info($path);
502 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
503
504 die "volname '$volname' contains wrong information about parent\n"
505 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
506
507 my $newname = $name;
508 $newname =~ s/^vm-/base-/;
509
510 my $newvolname = $basename ? "$basevmid/$basename/$vmid/$newname" :
511 "$vmid/$newname";
512
513 my $newpath = $class->filesystem_path($scfg, $newvolname);
514
515 die "file '$newpath' already exists\n" if -f $newpath;
516
517 rename($path, $newpath) ||
518 die "rename '$path' to '$newpath' failed - $!\n";
519
520 # We try to protect base volume
521
522 chmod(0444, $newpath); # nobody should write anything
523
524 # also try to set immutable flag
525 eval { run_command(['/usr/bin/chattr', '+i', $newpath]); };
526 warn $@ if $@;
527
528 return $newvolname;
529 }
530
531 my $get_vm_disk_number = sub {
532 my ($disk_name, $scfg, $vmid, $suffix) = @_;
533
534 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
535
536 my $type = $scfg->{type};
537 my $def = { %{$defaultData->{plugindata}->{$type}} };
538
539 my $valid = $def->{format}[0];
540 if ($valid->{subvol}) {
541 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
542 }
543
544 if ($disk_name =~ m/$disk_regex/) {
545 return $2;
546 }
547
548 return undef;
549 };
550
551 sub get_next_vm_diskname {
552 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
553
554 $fmt //= '';
555 my $prefix = ($fmt eq 'subvol') ? 'subvol' : 'vm';
556 my $suffix = $add_fmt_suffix ? ".$fmt" : '';
557
558 my $disk_ids = {};
559 foreach my $disk (@$disk_list) {
560 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
561 $disk_ids->{$disknum} = 1 if defined($disknum);
562 }
563
564 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
565 if (!$disk_ids->{$i}) {
566 return "$prefix-$vmid-disk-$i$suffix";
567 }
568 }
569
570 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
571 }
572
573 my $find_free_diskname = sub {
574 my ($imgdir, $vmid, $fmt, $scfg) = @_;
575
576 my $disk_list = [];
577
578 if (defined(my $dh = IO::Dir->new($imgdir))) {
579 @$disk_list = $dh->read();
580 $dh->close();
581 }
582
583 return get_next_vm_diskname($disk_list, $imgdir, $vmid, $fmt, $scfg, 1);
584 };
585
586 sub clone_image {
587 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
588
589 # this only works for file based storage types
590 die "storage definintion has no path\n" if !$scfg->{path};
591
592 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
593 $class->parse_volname($volname);
594
595 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
596
597 die "this storage type does not support clone_image on snapshot\n" if $snap;
598
599 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
600
601 die "clone_image only works on base images\n" if !$isBase;
602
603 my $imagedir = $class->get_subdir($scfg, 'images');
604 $imagedir .= "/$vmid";
605
606 mkpath $imagedir;
607
608 my $name = $find_free_diskname->($imagedir, $vmid, "qcow2", $scfg);
609
610 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
611
612 my $newvol = "$basevmid/$basename/$vmid/$name";
613
614 my $path = $class->filesystem_path($scfg, $newvol);
615
616 # Note: we use relative paths, so we need to call chdir before qemu-img
617 eval {
618 local $CWD = $imagedir;
619
620 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
621 '-f', 'qcow2', $path];
622
623 run_command($cmd);
624 };
625 my $err = $@;
626
627 die $err if $err;
628
629 return $newvol;
630 }
631
632 sub alloc_image {
633 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
634
635 my $imagedir = $class->get_subdir($scfg, 'images');
636 $imagedir .= "/$vmid";
637
638 mkpath $imagedir;
639
640 $name = $find_free_diskname->($imagedir, $vmid, $fmt, $scfg) if !$name;
641
642 my (undef, $tmpfmt) = parse_name_dir($name);
643
644 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
645 if $tmpfmt ne $fmt;
646
647 my $path = "$imagedir/$name";
648
649 die "disk image '$path' already exists\n" if -e $path;
650
651 if ($fmt eq 'subvol') {
652 # only allow this if size = 0, so that user knows what he is doing
653 die "storage does not support subvol quotas\n" if $size != 0;
654
655 my $old_umask = umask(0022);
656 my $err;
657 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
658 umask $old_umask;
659 die $err if $err;
660 } else {
661 my $cmd = ['/usr/bin/qemu-img', 'create'];
662
663 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
664
665 push @$cmd, '-f', $fmt, $path, "${size}K";
666
667 eval { run_command($cmd, errmsg => "unable to create image"); };
668 if ($@) {
669 unlink $path;
670 rmdir $imagedir;
671 die "$@";
672 }
673 }
674
675 return "$vmid/$name";
676 }
677
678 sub free_image {
679 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
680
681 my $path = $class->filesystem_path($scfg, $volname);
682
683 if ($isBase) {
684 # try to remove immutable flag
685 eval { run_command(['/usr/bin/chattr', '-i', $path]); };
686 warn $@ if $@;
687 }
688
689 if (defined($format) && ($format eq 'subvol')) {
690 File::Path::remove_tree($path);
691 } else {
692
693 if (! (-f $path || -l $path)) {
694 warn "disk image '$path' does not exists\n";
695 return undef;
696 }
697
698 unlink($path) || die "unlink '$path' failed - $!\n";
699 }
700
701 # try to cleanup directory to not clutter storage with empty $vmid dirs if
702 # all images from a guest got deleted
703 my $dir = dirname($path);
704 rmdir($dir);
705
706 return undef;
707 }
708
709 sub file_size_info {
710 my ($filename, $timeout) = @_;
711
712 if (-d $filename) {
713 return wantarray ? (0, 'subvol', 0, undef) : 1;
714 }
715
716 my $cmd = ['/usr/bin/qemu-img', 'info', $filename];
717
718 my $format;
719 my $parent;
720 my $size = 0;
721 my $used = 0;
722
723 eval {
724 run_command($cmd, timeout => $timeout, outfunc => sub {
725 my $line = shift;
726 if ($line =~ m/^file format:\s+(\S+)\s*$/) {
727 $format = $1;
728 } elsif ($line =~ m/^backing file:\s(\S+)\s/) {
729 $parent = $1;
730 } elsif ($line =~ m/^virtual size:\s\S+\s+\((\d+)\s+bytes\)$/) {
731 $size = int($1);
732 } elsif ($line =~ m/^disk size:\s+(\d+(.\d+)?)([KMGT])\s*$/) {
733 $used = $1;
734 my $u = $3;
735
736 $used *= 1024 if $u eq 'K';
737 $used *= (1024*1024) if $u eq 'M';
738 $used *= (1024*1024*1024) if $u eq 'G';
739 $used *= (1024*1024*1024*1024) if $u eq 'T';
740
741 $used = int($used);
742 }
743 });
744 };
745
746 return wantarray ? ($size, $format, $used, $parent) : $size;
747 }
748
749 sub volume_size_info {
750 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
751 my $path = $class->filesystem_path($scfg, $volname);
752 return file_size_info($path, $timeout);
753
754 }
755
756 sub volume_resize {
757 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
758
759 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
760
761 return 1 if $running;
762
763 my $path = $class->filesystem_path($scfg, $volname);
764
765 my $format = ($class->parse_volname($volname))[6];
766
767 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
768
769 run_command($cmd, timeout => 10);
770
771 return undef;
772 }
773
774 sub volume_snapshot {
775 my ($class, $scfg, $storeid, $volname, $snap) = @_;
776
777 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
778
779 my $path = $class->filesystem_path($scfg, $volname);
780
781 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
782
783 run_command($cmd);
784
785 return undef;
786 }
787
788 sub volume_rollback_is_possible {
789 my ($class, $scfg, $storeid, $volname, $snap) = @_;
790
791 return 1;
792 }
793
794 sub volume_snapshot_rollback {
795 my ($class, $scfg, $storeid, $volname, $snap) = @_;
796
797 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
798
799 my $path = $class->filesystem_path($scfg, $volname);
800
801 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
802
803 run_command($cmd);
804
805 return undef;
806 }
807
808 sub volume_snapshot_delete {
809 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
810
811 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
812
813 return 1 if $running;
814
815 my $path = $class->filesystem_path($scfg, $volname);
816
817 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
818
819 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
820
821 run_command($cmd);
822
823 return undef;
824 }
825
826 sub storage_can_replicate {
827 my ($class, $scfg, $storeid, $format) = @_;
828
829 return 0;
830 }
831
832 sub volume_has_feature {
833 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running) = @_;
834
835 my $features = {
836 snapshot => { current => { qcow2 => 1}, snap => { qcow2 => 1} },
837 clone => { base => {qcow2 => 1, raw => 1, vmdk => 1} },
838 template => { current => {qcow2 => 1, raw => 1, vmdk => 1, subvol => 1} },
839 copy => { base => {qcow2 => 1, raw => 1, vmdk => 1},
840 current => {qcow2 => 1, raw => 1, vmdk => 1},
841 snap => {qcow2 => 1} },
842 sparseinit => { base => {qcow2 => 1, raw => 1, vmdk => 1},
843 current => {qcow2 => 1, raw => 1, vmdk => 1} },
844 };
845
846 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
847 $class->parse_volname($volname);
848
849 my $key = undef;
850 if($snapname){
851 $key = 'snap';
852 }else{
853 $key = $isBase ? 'base' : 'current';
854 }
855
856 return 1 if defined($features->{$feature}->{$key}->{$format});
857
858 return undef;
859 }
860
861 sub list_images {
862 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
863
864 my $imagedir = $class->get_subdir($scfg, 'images');
865
866 my ($defFmt, $vaidFmts) = default_format($scfg);
867 my $fmts = join ('|', @$vaidFmts);
868
869 my $res = [];
870
871 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
872
873 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
874 $fn = $1; # untaint
875
876 my $owner = $2;
877 my $name = $3;
878
879 next if !$vollist && defined($vmid) && ($owner ne $vmid);
880
881 my ($size, $format, $used, $parent) = file_size_info($fn);
882 next if !($format && defined($size));
883
884 my $volid;
885 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
886 my ($basevmid, $basename) = ($1, $2);
887 $volid = "$storeid:$basevmid/$basename/$owner/$name";
888 } else {
889 $volid = "$storeid:$owner/$name";
890 }
891
892 if ($vollist) {
893 my $found = grep { $_ eq $volid } @$vollist;
894 next if !$found;
895 }
896
897 push @$res, {
898 volid => $volid, format => $format,
899 size => $size, vmid => $owner, used => $used, parent => $parent
900 };
901 }
902
903 return $res;
904 }
905
906 sub status {
907 my ($class, $storeid, $scfg, $cache) = @_;
908
909 my $path = $scfg->{path};
910
911 die "storage definintion has no path\n" if !$path;
912
913 my $timeout = 2;
914 my $res = PVE::Tools::df($path, $timeout);
915
916 return undef if !$res || !$res->{total};
917
918 return ($res->{total}, $res->{avail}, $res->{used}, 1);
919 }
920
921 sub volume_snapshot_list {
922 my ($class, $scfg, $storeid, $volname) = @_;
923
924 # implement in subclass
925 die "Volume_snapshot_list is not implemented for $class";
926
927 # return an empty array if dataset does not exist.
928 }
929
930 sub activate_storage {
931 my ($class, $storeid, $scfg, $cache) = @_;
932
933 my $path = $scfg->{path};
934
935 die "storage definintion has no path\n" if !$path;
936
937 # this path test may hang indefinitely on unresponsive mounts
938 my $timeout = 2;
939 if (! PVE::Tools::run_fork_with_timeout($timeout, sub {-d $path})) {
940 die "unable to activate storage '$storeid' - " .
941 "directory '$path' does not exist or is unreachable\n";
942 }
943
944
945 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
946
947 if (defined($scfg->{content})) {
948 foreach my $vtype (keys %$vtype_subdirs) {
949 # OpenVZMigrate uses backup (dump) dir
950 if (defined($scfg->{content}->{$vtype}) ||
951 ($vtype eq 'backup' && defined($scfg->{content}->{'rootdir'}))) {
952 my $subdir = $class->get_subdir($scfg, $vtype);
953 mkpath $subdir if $subdir ne $path;
954 }
955 }
956 }
957 }
958
959 sub deactivate_storage {
960 my ($class, $storeid, $scfg, $cache) = @_;
961
962 # do nothing by default
963 }
964
965 sub map_volume {
966 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
967
968 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
969 return $path;
970 }
971
972 sub unmap_volume {
973 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
974
975 return 1;
976 }
977
978 sub activate_volume {
979 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
980
981 my $path = $class->filesystem_path($scfg, $volname, $snapname);
982
983 # check is volume exists
984 if ($scfg->{path}) {
985 die "volume '$storeid:$volname' does not exist\n" if ! -e $path;
986 } else {
987 die "volume '$storeid:$volname' does not exist\n" if ! -b $path;
988 }
989 }
990
991 sub deactivate_volume {
992 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
993
994 # do nothing by default
995 }
996
997 sub check_connection {
998 my ($class, $storeid, $scfg) = @_;
999 # do nothing by default
1000 return 1;
1001 }
1002
1003 # Import/Export interface:
1004 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1005 # the default implementations will return this if $scfg->{path} is set,
1006 # mimicking the old PVE::Storage::storage_migrate() function.
1007 #
1008 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1009 # functions in case the format doesn't match their specialized
1010 # implementations to reuse the raw/tar code.
1011 #
1012 # Format specification:
1013 # The following formats are all prefixed with image information in the form
1014 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1015 # to preallocate the image on storages which require it.
1016 #
1017 # raw+size: (image files only)
1018 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1019 # qcow2+size, vmdk: (image files only)
1020 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1021 # files which are already in qcow2 format, or via `qemu-img convert`.
1022 # Note that these formats are only valid with $with_snapshots being true.
1023 # tar+size: (subvolumes only)
1024 # A GNU tar stream containing just the inner contents of the subvolume.
1025 # This does not distinguish between the contents of a privileged or
1026 # unprivileged container. In other words, this is from the root user
1027 # namespace's point of view with no uid-mapping in effect.
1028 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1029
1030 # Plugins may reuse these helpers. Changes to the header format should be
1031 # reflected by changes to the function prototypes.
1032 sub write_common_header($$) {
1033 my ($fh, $image_size_in_bytes) = @_;
1034 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1035 }
1036
1037 sub read_common_header($) {
1038 my ($fh) = @_;
1039 sysread($fh, my $size, 8);
1040 $size = unpack('Q<', $size);
1041 die "got a bad size (not a multiple of 1K)\n" if ($size&1023);
1042 # Size is in bytes!
1043 return $size;
1044 }
1045
1046 # Export a volume into a file handle as a stream of desired format.
1047 sub volume_export {
1048 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1049 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1050 my $file = $class->path($scfg, $volname, $storeid)
1051 or goto unsupported;
1052 my ($size, $file_format) = file_size_info($file);
1053
1054 if ($format eq 'raw+size') {
1055 goto unsupported if $with_snapshots || $file_format eq 'subvol';
1056 write_common_header($fh, $size);
1057 if ($file_format eq 'raw') {
1058 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1059 } else {
1060 run_command(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1061 output => '>&'.fileno($fh));
1062 }
1063 return;
1064 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1065 my $data_format = $1;
1066 goto unsupported if !$with_snapshots || $file_format ne $data_format;
1067 write_common_header($fh, $size);
1068 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1069 return;
1070 } elsif ($format eq 'tar+size') {
1071 goto unsupported if $file_format ne 'subvol';
1072 write_common_header($fh, $size);
1073 run_command(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1074 output => '>&'.fileno($fh));
1075 return;
1076 }
1077 }
1078 unsupported:
1079 die "volume export format $format not available for $class";
1080 }
1081
1082 sub volume_export_formats {
1083 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1084 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1085 my $file = $class->path($scfg, $volname, $storeid)
1086 or return;
1087 my ($size, $format) = file_size_info($file);
1088
1089 if ($with_snapshots) {
1090 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1091 return ();
1092 }
1093 return ('tar+size') if $format eq 'subvol';
1094 return ('raw+size');
1095 }
1096 return ();
1097 }
1098
1099 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1100 sub volume_import {
1101 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots) = @_;
1102
1103 die "volume import format '$format' not available for $class\n"
1104 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1105 my $data_format = $1;
1106
1107 die "format $format cannot be imported without snapshots\n"
1108 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1109 die "format $format cannot be imported with snapshots\n"
1110 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1111
1112 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1113 $class->parse_volname($volname);
1114
1115 # XXX: Should we bother with conversion routines at this level? This won't
1116 # happen without manual CLI usage, so for now we just error out...
1117 die "cannot import format $format into a file of format $file_format\n"
1118 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1119
1120 # Check for an existing file first since interrupting alloc_image doesn't
1121 # free it.
1122 my $file = $class->path($scfg, $volname, $storeid);
1123 die "file '$file' already exists\n" if -e $file;
1124
1125 my ($size) = read_common_header($fh);
1126 $size = int($size/1024);
1127
1128 eval {
1129 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1130 if ($allocname ne $volname) {
1131 my $oldname = $volname;
1132 $volname = $allocname; # Let the cleanup code know what to free
1133 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1134 }
1135 my $file = $class->path($scfg, $volname, $storeid)
1136 or die "internal error: failed to get path to newly allocated volume $volname\n";
1137 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1138 run_command(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1139 input => '<&'.fileno($fh));
1140 } elsif ($data_format eq 'tar') {
1141 run_command(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1142 input => '<&'.fileno($fh));
1143 } else {
1144 die "volume import format '$format' not available for $class";
1145 }
1146 };
1147 if (my $err = $@) {
1148 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1149 warn $@ if $@;
1150 die $err;
1151 }
1152 }
1153
1154 sub volume_import_formats {
1155 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
1156 if ($scfg->{path} && !defined($base_snapshot)) {
1157 my $format = ($class->parse_volname($volname))[6];
1158 if ($with_snapshots) {
1159 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1160 return ();
1161 }
1162 return ('tar+size') if $format eq 'subvol';
1163 return ('raw+size');
1164 }
1165 return ();
1166 }
1167
1168 1;