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