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