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