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