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