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