]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage/Plugin.pm
list volumes: also return backup type for backups
[pve-storage.git] / PVE / Storage / Plugin.pm
1 package PVE::Storage::Plugin;
2
3 use strict;
4 use warnings;
5
6 use Fcntl ':mode';
7 use File::chdir;
8 use File::Path;
9 use File::Basename;
10 use File::stat qw();
11
12 use PVE::Tools qw(run_command);
13 use PVE::JSONSchema qw(get_standard_option register_standard_option);
14 use PVE::Cluster qw(cfs_register_file);
15
16 use JSON;
17
18 use base qw(PVE::SectionConfig);
19
20 use constant COMPRESSOR_RE => 'gz|lzo|zst';
21
22 use constant NOTES_EXT => ".notes";
23
24 our @COMMON_TAR_FLAGS = qw(
25 --one-file-system
26 -p --sparse --numeric-owner --acls
27 --xattrs --xattrs-include=user.* --xattrs-include=security.capability
28 --warning=no-file-ignored --warning=no-xattr-write
29 );
30
31 our @SHARED_STORAGE = (
32 'iscsi',
33 'nfs',
34 'cifs',
35 'rbd',
36 'cephfs',
37 'iscsidirect',
38 'glusterfs',
39 'zfs',
40 'drbd',
41 'pbs',
42 );
43
44 our $QCOW2_PREALLOCATION = {
45 off => 1,
46 metadata => 1,
47 falloc => 1,
48 full => 1,
49 };
50
51 our $RAW_PREALLOCATION = {
52 off => 1,
53 falloc => 1,
54 full => 1,
55 };
56
57 our $MAX_VOLUMES_PER_GUEST = 1024;
58
59 cfs_register_file ('storage.cfg',
60 sub { __PACKAGE__->parse_config(@_); },
61 sub { __PACKAGE__->write_config(@_); });
62
63 my %prune_option = (
64 optional => 1,
65 type => 'integer', minimum => '0',
66 format_description => 'N',
67 );
68
69 our $prune_backups_format = {
70 'keep-all' => {
71 type => 'boolean',
72 description => 'Keep all backups. Conflicts with the other options when true.',
73 optional => 1,
74 },
75 'keep-last' => {
76 %prune_option,
77 description => 'Keep the last <N> backups.',
78 },
79 'keep-hourly' => {
80 %prune_option,
81 description => 'Keep backups for the last <N> different hours. If there is more' .
82 'than one backup for a single hour, only the latest one is kept.'
83 },
84 'keep-daily' => {
85 %prune_option,
86 description => 'Keep backups for the last <N> different days. If there is more' .
87 'than one backup for a single day, only the latest one is kept.'
88 },
89 'keep-weekly' => {
90 %prune_option,
91 description => 'Keep backups for the last <N> different weeks. If there is more' .
92 'than one backup for a single week, only the latest one is kept.'
93 },
94 'keep-monthly' => {
95 %prune_option,
96 description => 'Keep backups for the last <N> different months. If there is more' .
97 'than one backup for a single month, only the latest one is kept.'
98 },
99 'keep-yearly' => {
100 %prune_option,
101 description => 'Keep backups for the last <N> different years. If there is more' .
102 'than one backup for a single year, only the latest one is kept.'
103 },
104 };
105 PVE::JSONSchema::register_format('prune-backups', $prune_backups_format, \&validate_prune_backups);
106 sub validate_prune_backups {
107 my ($prune_backups) = @_;
108
109 my $res = { $prune_backups->%* };
110
111 my $keep_all = delete $res->{'keep-all'};
112
113 if (scalar(grep { $_ > 0 } values %{$res}) == 0) {
114 $res = { 'keep-all' => 1 };
115 } elsif ($keep_all) {
116 die "keep-all cannot be set together with other options.\n";
117 }
118
119 return $res;
120 }
121 register_standard_option('prune-backups', {
122 description => "The retention options with shorter intervals are processed first " .
123 "with --keep-last being the very first one. Each option covers a " .
124 "specific period of time. We say that backups within this period " .
125 "are covered by this option. The next option does not take care " .
126 "of already covered backups and only considers older backups.",
127 optional => 1,
128 type => 'string',
129 format => 'prune-backups',
130 });
131
132 my $defaultData = {
133 propertyList => {
134 type => { description => "Storage type." },
135 storage => get_standard_option('pve-storage-id',
136 { completion => \&PVE::Storage::complete_storage }),
137 nodes => get_standard_option('pve-node-list', { optional => 1 }),
138 content => {
139 description => "Allowed content types.\n\nNOTE: the value " .
140 "'rootdir' is used for Containers, and value 'images' for VMs.\n",
141 type => 'string', format => 'pve-storage-content-list',
142 optional => 1,
143 completion => \&PVE::Storage::complete_content_type,
144 },
145 disable => {
146 description => "Flag to disable the storage.",
147 type => 'boolean',
148 optional => 1,
149 },
150 maxfiles => {
151 description => "Deprecated: use 'prune-backups' instead. " .
152 "Maximal number of backup files per VM. Use '0' for unlimited.",
153 type => 'integer',
154 minimum => 0,
155 optional => 1,
156 },
157 'prune-backups' => get_standard_option('prune-backups'),
158 shared => {
159 description => "Mark storage as shared.",
160 type => 'boolean',
161 optional => 1,
162 },
163 'format' => {
164 description => "Default image format.",
165 type => 'string', format => 'pve-storage-format',
166 optional => 1,
167 },
168 preallocation => {
169 description => "Preallocation mode for raw and qcow2 images. " .
170 "Using 'metadata' on raw images results in preallocation=off.",
171 type => 'string', enum => ['off', 'metadata', 'falloc', 'full'],
172 default => 'metadata',
173 optional => 1,
174 },
175 },
176 };
177
178 sub content_hash_to_string {
179 my $hash = shift;
180
181 my @cta;
182 foreach my $ct (keys %$hash) {
183 push @cta, $ct if $hash->{$ct};
184 }
185
186 return join(',', @cta);
187 }
188
189 sub valid_content_types {
190 my ($type) = @_;
191
192 my $def = $defaultData->{plugindata}->{$type};
193
194 return {} if !$def;
195
196 return $def->{content}->[0];
197 }
198
199 sub default_format {
200 my ($scfg) = @_;
201
202 my $type = $scfg->{type};
203 my $def = $defaultData->{plugindata}->{$type};
204
205 my $def_format = 'raw';
206 my $valid_formats = [ $def_format ];
207
208 if (defined($def->{format})) {
209 $def_format = $scfg->{format} || $def->{format}->[1];
210 $valid_formats = [ sort keys %{$def->{format}->[0]} ];
211 }
212
213 return wantarray ? ($def_format, $valid_formats) : $def_format;
214 }
215
216 PVE::JSONSchema::register_format('pve-storage-path', \&verify_path);
217 sub verify_path {
218 my ($path, $noerr) = @_;
219
220 # fixme: exclude more shell meta characters?
221 # we need absolute paths
222 if ($path !~ m|^/[^;\(\)]+|) {
223 return undef if $noerr;
224 die "value does not look like a valid absolute path\n";
225 }
226 return $path;
227 }
228
229 PVE::JSONSchema::register_format('pve-storage-server', \&verify_server);
230 sub verify_server {
231 my ($server, $noerr) = @_;
232
233 if (!(PVE::JSONSchema::pve_verify_ip($server, 1) ||
234 PVE::JSONSchema::pve_verify_dns_name($server, 1)))
235 {
236 return undef if $noerr;
237 die "value does not look like a valid server name or IP address\n";
238 }
239 return $server;
240 }
241
242 PVE::JSONSchema::register_format('pve-storage-vgname', \&parse_lvm_name);
243 sub parse_lvm_name {
244 my ($name, $noerr) = @_;
245
246 if ($name !~ m/^[a-z0-9][a-z0-9\-\_\.]*[a-z0-9]$/i) {
247 return undef if $noerr;
248 die "lvm name '$name' contains illegal characters\n";
249 }
250
251 return $name;
252 }
253
254 # fixme: do we need this
255 #PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
256 #sub verify_portal {
257 # my ($portal, $noerr) = @_;
258 #
259 # # IP with optional port
260 # if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
261 # return undef if $noerr;
262 # die "value does not look like a valid portal address\n";
263 # }
264 # return $portal;
265 #}
266
267 PVE::JSONSchema::register_format('pve-storage-portal-dns', \&verify_portal_dns);
268 sub verify_portal_dns {
269 my ($portal, $noerr) = @_;
270
271 # IP or DNS name with optional port
272 if (!PVE::Tools::parse_host_and_port($portal)) {
273 return undef if $noerr;
274 die "value does not look like a valid portal address\n";
275 }
276 return $portal;
277 }
278
279 PVE::JSONSchema::register_format('pve-storage-content', \&verify_content);
280 sub verify_content {
281 my ($ct, $noerr) = @_;
282
283 my $valid_content = valid_content_types('dir'); # dir includes all types
284
285 if (!$valid_content->{$ct}) {
286 return undef if $noerr;
287 die "invalid content type '$ct'\n";
288 }
289
290 return $ct;
291 }
292
293 PVE::JSONSchema::register_format('pve-storage-format', \&verify_format);
294 sub verify_format {
295 my ($fmt, $noerr) = @_;
296
297 if ($fmt !~ m/(raw|qcow2|vmdk|subvol)/) {
298 return undef if $noerr;
299 die "invalid format '$fmt'\n";
300 }
301
302 return $fmt;
303 }
304
305 PVE::JSONSchema::register_format('pve-storage-options', \&verify_options);
306 sub verify_options {
307 my ($value, $noerr) = @_;
308
309 # mount options (see man fstab)
310 if ($value !~ m/^\S+$/) {
311 return undef if $noerr;
312 die "invalid options '$value'\n";
313 }
314
315 return $value;
316 }
317
318 PVE::JSONSchema::register_format('pve-volume-id', \&parse_volume_id);
319 sub parse_volume_id {
320 my ($volid, $noerr) = @_;
321
322 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
323 return wantarray ? ($1, $2) : $1;
324 }
325 return undef if $noerr;
326 die "unable to parse volume ID '$volid'\n";
327 }
328
329
330 sub private {
331 return $defaultData;
332 }
333
334 sub parse_section_header {
335 my ($class, $line) = @_;
336
337 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
338 my ($type, $storeid) = (lc($1), $2);
339 my $errmsg = undef; # set if you want to skip whole section
340 eval { PVE::JSONSchema::parse_storage_id($storeid); };
341 $errmsg = $@ if $@;
342 my $config = {}; # to return additional attributes
343 return ($type, $storeid, $errmsg, $config);
344 }
345 return undef;
346 }
347
348 sub decode_value {
349 my ($class, $type, $key, $value) = @_;
350
351 my $def = $defaultData->{plugindata}->{$type};
352
353 if ($key eq 'content') {
354 my $valid_content = $def->{content}->[0];
355
356 my $res = {};
357
358 foreach my $c (PVE::Tools::split_list($value)) {
359 if (!$valid_content->{$c}) {
360 warn "storage does not support content type '$c'\n";
361 next;
362 }
363 $res->{$c} = 1;
364 }
365
366 if ($res->{none} && scalar (keys %$res) > 1) {
367 die "unable to combine 'none' with other content types\n";
368 }
369
370 if (scalar(keys $res->%*) == 0 && !$valid_content->{none}) {
371 die "storage does not support content type 'none'\n";
372 }
373
374 return $res;
375 } elsif ($key eq 'format') {
376 my $valid_formats = $def->{format}->[0];
377
378 if (!$valid_formats->{$value}) {
379 warn "storage does not support format '$value'\n";
380 next;
381 }
382
383 return $value;
384 } elsif ($key eq 'nodes') {
385 my $res = {};
386
387 foreach my $node (PVE::Tools::split_list($value)) {
388 if (PVE::JSONSchema::pve_verify_node_name($node)) {
389 $res->{$node} = 1;
390 }
391 }
392
393 # fixme:
394 # no node restrictions for local storage
395 #if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
396 # die "storage '$storeid' does not allow node restrictions\n";
397 #}
398
399 return $res;
400 }
401
402 return $value;
403 }
404
405 sub encode_value {
406 my ($class, $type, $key, $value) = @_;
407
408 if ($key eq 'nodes') {
409 return join(',', keys(%$value));
410 } elsif ($key eq 'content') {
411 my $res = content_hash_to_string($value) || 'none';
412 return $res;
413 }
414
415 return $value;
416 }
417
418 sub parse_config {
419 my ($class, $filename, $raw) = @_;
420
421 my $cfg = $class->SUPER::parse_config($filename, $raw);
422 my $ids = $cfg->{ids};
423
424 # make sure we have a reasonable 'local:' storage
425 # we want 'local' to be always the same 'type' (on all cluster nodes)
426 if (!$ids->{local} || $ids->{local}->{type} ne 'dir' ||
427 ($ids->{local}->{path} && $ids->{local}->{path} ne '/var/lib/vz')) {
428 $ids->{local} = {
429 type => 'dir',
430 priority => 0, # force first entry
431 path => '/var/lib/vz',
432 'prune-backups' => 'keep-all=1',
433 content => {
434 backup => 1,
435 images => 1,
436 iso => 1,
437 rootdir => 1,
438 snippets => 1,
439 vztmpl => 1,
440 },
441 };
442 }
443
444 # make sure we have a path
445 $ids->{local}->{path} = '/var/lib/vz' if !$ids->{local}->{path};
446
447 # remove node restrictions for local storage
448 delete($ids->{local}->{nodes});
449
450 foreach my $storeid (keys %$ids) {
451 my $d = $ids->{$storeid};
452 my $type = $d->{type};
453
454 my $def = $defaultData->{plugindata}->{$type};
455
456 if ($def->{content}) {
457 $d->{content} = $def->{content}->[1] if !$d->{content};
458 }
459 if (grep { $_ eq $type } @SHARED_STORAGE) {
460 $d->{shared} = 1;
461 }
462 }
463
464 return $cfg;
465 }
466
467 sub preallocation_cmd_option {
468 my ($scfg, $fmt) = @_;
469
470 my $prealloc = $scfg->{preallocation};
471
472 if ($fmt eq 'qcow2') {
473 $prealloc = $prealloc // 'metadata';
474
475 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
476 if !$QCOW2_PREALLOCATION->{$prealloc};
477
478 return "preallocation=$prealloc";
479 } elsif ($fmt eq 'raw') {
480 $prealloc = $prealloc // 'off';
481 $prealloc = 'off' if $prealloc eq 'metadata';
482
483 die "preallocation mode '$prealloc' not supported by format '$fmt'\n"
484 if !$RAW_PREALLOCATION->{$prealloc};
485
486 return "preallocation=$prealloc";
487 }
488
489 return;
490 }
491
492 # Storage implementation
493
494 # called during addition of storage (before the new storage config got written)
495 # die to abort addition if there are (grave) problems
496 # NOTE: runs in a storage config *locked* context
497 sub on_add_hook {
498 my ($class, $storeid, $scfg, %param) = @_;
499
500 # do nothing by default
501 return undef;
502 }
503
504 # called during storage configuration update (before the updated storage config got written)
505 # die to abort the update if there are (grave) problems
506 # NOTE: runs in a storage config *locked* context
507 sub on_update_hook {
508 my ($class, $storeid, $scfg, %param) = @_;
509
510 # do nothing by default
511 return undef;
512 }
513
514 # called during deletion of storage (before the new storage config got written)
515 # and if the activate check on addition fails, to cleanup all storage traces
516 # which on_add_hook may have created.
517 # die to abort deletion if there are (very grave) problems
518 # NOTE: runs in a storage config *locked* context
519 sub on_delete_hook {
520 my ($class, $storeid, $scfg) = @_;
521
522 # do nothing by default
523 return undef;
524 }
525
526 sub cluster_lock_storage {
527 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
528
529 my $res;
530 if (!$shared) {
531 my $lockid = "pve-storage-$storeid";
532 my $lockdir = "/var/lock/pve-manager";
533 mkdir $lockdir;
534 $res = PVE::Tools::lock_file("$lockdir/$lockid", $timeout, $func, @param);
535 die $@ if $@;
536 } else {
537 $res = PVE::Cluster::cfs_lock_storage($storeid, $timeout, $func, @param);
538 die $@ if $@;
539 }
540 return $res;
541 }
542
543 sub parse_name_dir {
544 my $name = shift;
545
546 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
547 return ($1, $3, $2); # (name, format, isBase)
548 }
549
550 die "unable to parse volume filename '$name'\n";
551 }
552
553 sub parse_volname {
554 my ($class, $volname) = @_;
555
556 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
557 my ($basedvmid, $basename) = ($1, $2);
558 parse_name_dir($basename);
559 my ($vmid, $name) = ($3, $4);
560 my (undef, $format, $isBase) = parse_name_dir($name);
561 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
562 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
563 my ($vmid, $name) = ($1, $2);
564 my (undef, $format, $isBase) = parse_name_dir($name);
565 return ('images', $name, $vmid, undef, undef, $isBase, $format);
566 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!) {
567 return ('iso', $1);
568 } elsif ($volname =~ m!^vztmpl/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!) {
569 return ('vztmpl', $1);
570 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
571 return ('rootdir', $1, $1);
572 } elsif ($volname =~ m!^backup/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!) {
573 my $fn = $1;
574 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
575 return ('backup', $fn, $2);
576 }
577 return ('backup', $fn);
578 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
579 return ('snippets', $1);
580 }
581
582 die "unable to parse directory volume name '$volname'\n";
583 }
584
585 my $vtype_subdirs = {
586 images => 'images',
587 rootdir => 'private',
588 iso => 'template/iso',
589 vztmpl => 'template/cache',
590 backup => 'dump',
591 snippets => 'snippets',
592 };
593
594 sub get_vtype_subdirs {
595 return $vtype_subdirs;
596 }
597
598 sub get_subdir {
599 my ($class, $scfg, $vtype) = @_;
600
601 my $path = $scfg->{path};
602
603 die "storage definition has no path\n" if !$path;
604
605 my $subdir = $vtype_subdirs->{$vtype};
606
607 die "unknown vtype '$vtype'\n" if !defined($subdir);
608
609 return "$path/$subdir";
610 }
611
612 sub filesystem_path {
613 my ($class, $scfg, $volname, $snapname) = @_;
614
615 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
616 $class->parse_volname($volname);
617
618 # Note: qcow2/qed has internal snapshot, so path is always
619 # the same (with or without snapshot => same file).
620 die "can't snapshot this image format\n"
621 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
622
623 my $dir = $class->get_subdir($scfg, $vtype);
624
625 $dir .= "/$vmid" if $vtype eq 'images';
626
627 my $path = "$dir/$name";
628
629 return wantarray ? ($path, $vmid, $vtype) : $path;
630 }
631
632 sub path {
633 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
634
635 return $class->filesystem_path($scfg, $volname, $snapname);
636 }
637
638 sub create_base {
639 my ($class, $storeid, $scfg, $volname) = @_;
640
641 # this only works for file based storage types
642 die "storage definition has no path\n" if !$scfg->{path};
643
644 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
645 $class->parse_volname($volname);
646
647 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
648
649 die "create_base not possible with base image\n" if $isBase;
650
651 my $path = $class->filesystem_path($scfg, $volname);
652
653 my ($size, undef, $used, $parent) = file_size_info($path);
654 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
655
656 die "volname '$volname' contains wrong information about parent\n"
657 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
658
659 my $newname = $name;
660 $newname =~ s/^vm-/base-/;
661
662 my $newvolname = $basename ? "$basevmid/$basename/$vmid/$newname" :
663 "$vmid/$newname";
664
665 my $newpath = $class->filesystem_path($scfg, $newvolname);
666
667 die "file '$newpath' already exists\n" if -f $newpath;
668
669 rename($path, $newpath) ||
670 die "rename '$path' to '$newpath' failed - $!\n";
671
672 # We try to protect base volume
673
674 chmod(0444, $newpath); # nobody should write anything
675
676 # also try to set immutable flag
677 eval { run_command(['/usr/bin/chattr', '+i', $newpath]); };
678 warn $@ if $@;
679
680 return $newvolname;
681 }
682
683 my $get_vm_disk_number = sub {
684 my ($disk_name, $scfg, $vmid, $suffix) = @_;
685
686 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
687
688 my $type = $scfg->{type};
689 my $def = { %{$defaultData->{plugindata}->{$type}} };
690
691 my $valid = $def->{format}[0];
692 if ($valid->{subvol}) {
693 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
694 }
695
696 if ($disk_name =~ m/$disk_regex/) {
697 return $2;
698 }
699
700 return undef;
701 };
702
703 sub get_next_vm_diskname {
704 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
705
706 $fmt //= '';
707 my $prefix = ($fmt eq 'subvol') ? 'subvol' : 'vm';
708 my $suffix = $add_fmt_suffix ? ".$fmt" : '';
709
710 my $disk_ids = {};
711 foreach my $disk (@$disk_list) {
712 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
713 $disk_ids->{$disknum} = 1 if defined($disknum);
714 }
715
716 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
717 if (!$disk_ids->{$i}) {
718 return "$prefix-$vmid-disk-$i$suffix";
719 }
720 }
721
722 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
723 }
724
725 sub find_free_diskname {
726 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
727
728 my $disks = $class->list_images($storeid, $scfg, $vmid);
729
730 my $disk_list = [ map { $_->{volid} } @$disks ];
731
732 return get_next_vm_diskname($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
733 }
734
735 sub clone_image {
736 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
737
738 # this only works for file based storage types
739 die "storage definition has no path\n" if !$scfg->{path};
740
741 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
742 $class->parse_volname($volname);
743
744 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
745
746 die "this storage type does not support clone_image on snapshot\n" if $snap;
747
748 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
749
750 die "clone_image only works on base images\n" if !$isBase;
751
752 my $imagedir = $class->get_subdir($scfg, 'images');
753 $imagedir .= "/$vmid";
754
755 mkpath $imagedir;
756
757 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
758
759 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
760
761 my $newvol = "$basevmid/$basename/$vmid/$name";
762
763 my $path = $class->filesystem_path($scfg, $newvol);
764
765 # Note: we use relative paths, so we need to call chdir before qemu-img
766 eval {
767 local $CWD = $imagedir;
768
769 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
770 '-F', $format, '-f', 'qcow2', $path];
771
772 run_command($cmd);
773 };
774 my $err = $@;
775
776 die $err if $err;
777
778 return $newvol;
779 }
780
781 sub alloc_image {
782 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
783
784 my $imagedir = $class->get_subdir($scfg, 'images');
785 $imagedir .= "/$vmid";
786
787 mkpath $imagedir;
788
789 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
790
791 my (undef, $tmpfmt) = parse_name_dir($name);
792
793 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
794 if $tmpfmt ne $fmt;
795
796 my $path = "$imagedir/$name";
797
798 die "disk image '$path' already exists\n" if -e $path;
799
800 if ($fmt eq 'subvol') {
801 # only allow this if size = 0, so that user knows what he is doing
802 die "storage does not support subvol quotas\n" if $size != 0;
803
804 my $old_umask = umask(0022);
805 my $err;
806 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
807 umask $old_umask;
808 die $err if $err;
809 } else {
810 my $cmd = ['/usr/bin/qemu-img', 'create'];
811
812 my $prealloc_opt = preallocation_cmd_option($scfg, $fmt);
813 push @$cmd, '-o', $prealloc_opt if defined($prealloc_opt);
814
815 push @$cmd, '-f', $fmt, $path, "${size}K";
816
817 eval { run_command($cmd, errmsg => "unable to create image"); };
818 if ($@) {
819 unlink $path;
820 rmdir $imagedir;
821 die "$@";
822 }
823 }
824
825 return "$vmid/$name";
826 }
827
828 sub free_image {
829 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
830
831 die "cannot remove protected volume '$volname' on '$storeid'\n"
832 if $class->get_volume_attribute($scfg, $storeid, $volname, 'protected');
833
834 my $path = $class->filesystem_path($scfg, $volname);
835
836 if ($isBase) {
837 # try to remove immutable flag
838 eval { run_command(['/usr/bin/chattr', '-i', $path]); };
839 warn $@ if $@;
840 }
841
842 if (defined($format) && ($format eq 'subvol')) {
843 File::Path::remove_tree($path);
844 } else {
845 if (!(-f $path || -l $path)) {
846 warn "disk image '$path' does not exist\n";
847 return undef;
848 }
849
850 unlink($path) || die "unlink '$path' failed - $!\n";
851 }
852
853 # try to cleanup directory to not clutter storage with empty $vmid dirs if
854 # all images from a guest got deleted
855 my $dir = dirname($path);
856 rmdir($dir);
857
858 return undef;
859 }
860
861 sub file_size_info {
862 my ($filename, $timeout) = @_;
863
864 my $st = File::stat::stat($filename);
865
866 if (!defined($st)) {
867 my $extramsg = -l $filename ? ' - dangling symlink?' : '';
868 warn "failed to stat '$filename'$extramsg\n";
869 return undef;
870 }
871
872 if (S_ISDIR($st->mode)) {
873 return wantarray ? (0, 'subvol', 0, undef, $st->ctime) : 1;
874 }
875
876 my $json = '';
877 eval {
878 run_command(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
879 timeout => $timeout,
880 outfunc => sub { $json .= shift },
881 errfunc => sub { warn "$_[0]\n" }
882 );
883 };
884 warn $@ if $@;
885
886 my $info = eval { decode_json($json) };
887 if (my $err = $@) {
888 warn "could not parse qemu-img info command output for '$filename' - $err\n";
889 return wantarray ? (undef, undef, undef, undef, $st->ctime) : undef;
890 }
891
892 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
893
894 ($size) = ($size =~ /^(\d+)$/) or die "size '$size' not an integer\n"; # untaint
895 # coerce back from string
896 $size = int($size);
897 ($used) = ($used =~ /^(\d+)$/) or die "used '$used' not an integer\n"; # untaint
898 # coerce back from string
899 $used = int($used);
900 ($format) = ($format =~ /^(\S+)$/) or die "format '$format' includes whitespace\n"; # untaint
901 if (defined($parent)) {
902 ($parent) = ($parent =~ /^(\S+)$/) or die "parent '$parent' includes whitespace\n"; # untaint
903 }
904 return wantarray ? ($size, $format, $used, $parent, $st->ctime) : $size;
905 }
906
907 # FIXME remove on the next APIAGE reset.
908 # Deprecated, use get_volume_attribute instead.
909 sub get_volume_notes {
910 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
911
912 die "volume notes are not supported for $class";
913 }
914
915 # FIXME remove on the next APIAGE reset.
916 # Deprecated, use update_volume_attribute instead.
917 sub update_volume_notes {
918 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
919
920 die "volume notes are not supported for $class";
921 }
922
923 # Returns undef if the attribute is not supported for the volume.
924 # Should die if there is an error fetching the attribute.
925 # Possible attributes:
926 # notes - user-provided comments/notes.
927 # protected - not to be removed by free_image, and for backups, ignored when pruning.
928 sub get_volume_attribute {
929 my ($class, $scfg, $storeid, $volname, $attribute) = @_;
930
931 if ($attribute eq 'notes') {
932 my $notes = eval { $class->get_volume_notes($scfg, $storeid, $volname); };
933 if (my $err = $@) {
934 return if $err =~ m/^volume notes are not supported/;
935 die $err;
936 }
937 return $notes;
938 }
939
940 return;
941 }
942
943 # Dies if the attribute is not supported for the volume.
944 sub update_volume_attribute {
945 my ($class, $scfg, $storeid, $volname, $attribute, $value) = @_;
946
947 if ($attribute eq 'notes') {
948 $class->update_volume_notes($scfg, $storeid, $volname, $value);
949 }
950
951 die "attribute '$attribute' is not supported for storage type '$scfg->{type}'\n";
952 }
953
954 sub volume_size_info {
955 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
956 my $path = $class->filesystem_path($scfg, $volname);
957 return file_size_info($path, $timeout);
958
959 }
960
961 sub volume_resize {
962 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
963
964 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
965
966 return 1 if $running;
967
968 my $path = $class->filesystem_path($scfg, $volname);
969
970 my $format = ($class->parse_volname($volname))[6];
971
972 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
973
974 run_command($cmd, timeout => 10);
975
976 return undef;
977 }
978
979 sub volume_snapshot {
980 my ($class, $scfg, $storeid, $volname, $snap) = @_;
981
982 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
983
984 my $path = $class->filesystem_path($scfg, $volname);
985
986 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
987
988 run_command($cmd);
989
990 return undef;
991 }
992
993 # Asserts that a rollback to $snap on $volname is possible.
994 # If certain snapshots are preventing the rollback and $blockers is an array
995 # reference, the snapshot names can be pushed onto $blockers prior to dying.
996 sub volume_rollback_is_possible {
997 my ($class, $scfg, $storeid, $volname, $snap, $blockers) = @_;
998
999 return 1;
1000 }
1001
1002 sub volume_snapshot_rollback {
1003 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1004
1005 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1006
1007 my $path = $class->filesystem_path($scfg, $volname);
1008
1009 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
1010
1011 run_command($cmd);
1012
1013 return undef;
1014 }
1015
1016 sub volume_snapshot_delete {
1017 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
1018
1019 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1020
1021 return 1 if $running;
1022
1023 my $path = $class->filesystem_path($scfg, $volname);
1024
1025 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
1026
1027 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
1028
1029 run_command($cmd);
1030
1031 return undef;
1032 }
1033
1034 sub volume_snapshot_needs_fsfreeze {
1035
1036 return 0;
1037 }
1038 sub storage_can_replicate {
1039 my ($class, $scfg, $storeid, $format) = @_;
1040
1041 return 0;
1042 }
1043
1044 sub volume_has_feature {
1045 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
1046
1047 my $features = {
1048 snapshot => { current => { qcow2 => 1}, snap => { qcow2 => 1} },
1049 clone => { base => {qcow2 => 1, raw => 1, vmdk => 1} },
1050 template => { current => {qcow2 => 1, raw => 1, vmdk => 1, subvol => 1} },
1051 copy => { base => {qcow2 => 1, raw => 1, vmdk => 1},
1052 current => {qcow2 => 1, raw => 1, vmdk => 1},
1053 snap => {qcow2 => 1} },
1054 sparseinit => { base => {qcow2 => 1, raw => 1, vmdk => 1},
1055 current => {qcow2 => 1, raw => 1, vmdk => 1} },
1056 rename => { current => {qcow2 => 1, raw => 1, vmdk => 1} },
1057 };
1058
1059 # clone_image creates a qcow2 volume
1060 return 0 if $feature eq 'clone' &&
1061 defined($opts->{valid_target_formats}) &&
1062 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats}});
1063
1064 return 0 if $feature eq 'rename' && $class->can('api') && $class->api() < 10;
1065
1066 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
1067 $class->parse_volname($volname);
1068
1069 my $key = undef;
1070 if($snapname){
1071 $key = 'snap';
1072 }else{
1073 $key = $isBase ? 'base' : 'current';
1074 }
1075
1076 return 1 if defined($features->{$feature}->{$key}->{$format});
1077
1078 return undef;
1079 }
1080
1081 sub list_images {
1082 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
1083
1084 my $imagedir = $class->get_subdir($scfg, 'images');
1085
1086 my ($defFmt, $vaidFmts) = default_format($scfg);
1087 my $fmts = join ('|', @$vaidFmts);
1088
1089 my $res = [];
1090
1091 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
1092
1093 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1094 $fn = $1; # untaint
1095
1096 my $owner = $2;
1097 my $name = $3;
1098
1099 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1100
1101 my ($size, $format, $used, $parent, $ctime) = file_size_info($fn);
1102 next if !($format && defined($size));
1103
1104 my $volid;
1105 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1106 my ($basevmid, $basename) = ($1, $2);
1107 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1108 } else {
1109 $volid = "$storeid:$owner/$name";
1110 }
1111
1112 if ($vollist) {
1113 my $found = grep { $_ eq $volid } @$vollist;
1114 next if !$found;
1115 }
1116
1117 my $info = {
1118 volid => $volid, format => $format,
1119 size => $size, vmid => $owner, used => $used, parent => $parent
1120 };
1121
1122 $info->{ctime} = $ctime if $ctime;
1123
1124 push @$res, $info;
1125 }
1126
1127 return $res;
1128 }
1129
1130 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1131 my $get_subdir_files = sub {
1132 my ($sid, $path, $tt, $vmid) = @_;
1133
1134 my $res = [];
1135
1136 foreach my $fn (<$path/*>) {
1137 my $st = File::stat::stat($fn);
1138
1139 next if (!$st || S_ISDIR($st->mode));
1140
1141 my $info;
1142
1143 if ($tt eq 'iso') {
1144 next if $fn !~ m!/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!i;
1145
1146 $info = { volid => "$sid:iso/$1", format => 'iso' };
1147
1148 } elsif ($tt eq 'vztmpl') {
1149 next if $fn !~ m!/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!;
1150
1151 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
1152
1153 } elsif ($tt eq 'backup') {
1154 next if $fn !~ m!/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!;
1155 my $original = $fn;
1156 my $format = $2;
1157 $fn = $1;
1158
1159 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1160 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1161
1162 $info = { volid => "$sid:backup/$fn", format => $format };
1163
1164 my $archive_info = eval { PVE::Storage::archive_info($fn) } // {};
1165
1166 $info->{ctime} = $archive_info->{ctime} if defined($archive_info->{ctime});
1167 $info->{subtype} = $archive_info->{type} // 'unknown';
1168
1169 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1170 $info->{vmid} = $vmid // $1;
1171 }
1172
1173 my $notes_fn = $original.NOTES_EXT;
1174 if (-f $notes_fn) {
1175 my $notes = PVE::Tools::file_read_firstline($notes_fn);
1176 $info->{notes} = $notes if defined($notes);
1177 }
1178
1179 $info->{protected} = 1 if -e PVE::Storage::protection_file_path($original);
1180 } elsif ($tt eq 'snippets') {
1181
1182 $info = {
1183 volid => "$sid:snippets/". basename($fn),
1184 format => 'snippet',
1185 };
1186 }
1187
1188 $info->{size} = $st->size;
1189 $info->{ctime} //= $st->ctime;
1190
1191 push @$res, $info;
1192 }
1193
1194 return $res;
1195 };
1196
1197 # If attributes are set on a volume, they should be included in the result.
1198 # See get_volume_attribute for a list of possible attributes.
1199 sub list_volumes {
1200 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1201
1202 my $res = [];
1203 my $vmlist = PVE::Cluster::get_vmlist();
1204 foreach my $type (@$content_types) {
1205 my $data;
1206
1207 if ($type eq 'images' || $type eq 'rootdir') {
1208 $data = $class->list_images($storeid, $scfg, $vmid);
1209 } elsif ($scfg->{path}) {
1210 my $path = $class->get_subdir($scfg, $type);
1211
1212 if ($type eq 'iso' && !defined($vmid)) {
1213 $data = $get_subdir_files->($storeid, $path, 'iso');
1214 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1215 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1216 } elsif ($type eq 'backup') {
1217 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1218 } elsif ($type eq 'snippets') {
1219 $data = $get_subdir_files->($storeid, $path, 'snippets');
1220 }
1221 }
1222
1223 next if !$data;
1224
1225 foreach my $item (@$data) {
1226 if ($type eq 'images' || $type eq 'rootdir') {
1227 my $vminfo = $vmlist->{ids}->{$item->{vmid}};
1228 my $vmtype;
1229 if (defined($vminfo)) {
1230 $vmtype = $vminfo->{type};
1231 }
1232 if (defined($vmtype) && $vmtype eq 'lxc') {
1233 $item->{content} = 'rootdir';
1234 } else {
1235 $item->{content} = 'images';
1236 }
1237 next if $type ne $item->{content};
1238 } else {
1239 $item->{content} = $type;
1240 }
1241
1242 push @$res, $item;
1243 }
1244 }
1245
1246 return $res;
1247 }
1248
1249 sub status {
1250 my ($class, $storeid, $scfg, $cache) = @_;
1251
1252 my $path = $scfg->{path};
1253
1254 die "storage definition has no path\n" if !$path;
1255
1256 my $timeout = 2;
1257 my $res = PVE::Tools::df($path, $timeout);
1258
1259 return undef if !$res || !$res->{total};
1260
1261 return ($res->{total}, $res->{avail}, $res->{used}, 1);
1262 }
1263
1264 # Returns a hash with the snapshot names as keys and the following data:
1265 # id - Unique id to distinguish different snapshots even if the have the same name.
1266 # timestamp - Creation time of the snapshot (seconds since epoch).
1267 # Returns an empty hash if the volume does not exist.
1268 sub volume_snapshot_info {
1269 my ($class, $scfg, $storeid, $volname) = @_;
1270
1271 die "volume_snapshot_info is not implemented for $class";
1272 }
1273
1274 sub activate_storage {
1275 my ($class, $storeid, $scfg, $cache) = @_;
1276
1277 my $path = $scfg->{path};
1278
1279 die "storage definition has no path\n" if !$path;
1280
1281 # this path test may hang indefinitely on unresponsive mounts
1282 my $timeout = 2;
1283 if (! PVE::Tools::run_fork_with_timeout($timeout, sub {-d $path})) {
1284 die "unable to activate storage '$storeid' - " .
1285 "directory '$path' does not exist or is unreachable\n";
1286 }
1287
1288
1289 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1290
1291 if (defined($scfg->{content})) {
1292 foreach my $vtype (keys %$vtype_subdirs) {
1293 # OpenVZMigrate uses backup (dump) dir
1294 if (defined($scfg->{content}->{$vtype}) ||
1295 ($vtype eq 'backup' && defined($scfg->{content}->{'rootdir'}))) {
1296 my $subdir = $class->get_subdir($scfg, $vtype);
1297 mkpath $subdir if $subdir ne $path;
1298 }
1299 }
1300 }
1301 }
1302
1303 sub deactivate_storage {
1304 my ($class, $storeid, $scfg, $cache) = @_;
1305
1306 # do nothing by default
1307 }
1308
1309 sub map_volume {
1310 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1311
1312 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1313 return $path;
1314 }
1315
1316 sub unmap_volume {
1317 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1318
1319 return 1;
1320 }
1321
1322 sub activate_volume {
1323 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1324
1325 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1326
1327 # check is volume exists
1328 if ($scfg->{path}) {
1329 die "volume '$storeid:$volname' does not exist\n" if ! -e $path;
1330 } else {
1331 die "volume '$storeid:$volname' does not exist\n" if ! -b $path;
1332 }
1333 }
1334
1335 sub deactivate_volume {
1336 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1337
1338 # do nothing by default
1339 }
1340
1341 sub check_connection {
1342 my ($class, $storeid, $scfg) = @_;
1343 # do nothing by default
1344 return 1;
1345 }
1346
1347 sub prune_backups {
1348 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1349
1350 $logfunc //= sub { print "$_[1]\n" };
1351
1352 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1353
1354 my $backup_groups = {};
1355 my $prune_list = [];
1356
1357 foreach my $backup (@{$backups}) {
1358 my $volid = $backup->{volid};
1359 my $archive_info = eval { PVE::Storage::archive_info($volid) } // {};
1360 my $backup_type = $archive_info->{type} // 'unknown';
1361 my $backup_vmid = $archive_info->{vmid} // $backup->{vmid};
1362
1363 next if defined($type) && $type ne $backup_type;
1364
1365 my $prune_entry = {
1366 ctime => $backup->{ctime},
1367 type => $backup_type,
1368 volid => $volid,
1369 };
1370
1371 $prune_entry->{vmid} = $backup_vmid if defined($backup_vmid);
1372
1373 if ($archive_info->{is_std_name}) {
1374 die "internal error - got no VMID\n" if !defined($backup_vmid);
1375 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1376 if defined($vmid) && $backup_vmid ne $vmid;
1377
1378 $prune_entry->{ctime} = $archive_info->{ctime};
1379 my $group = "$backup_type/$backup_vmid";
1380 push @{$backup_groups->{$group}}, $prune_entry;
1381 } else {
1382 # ignore backups that don't use the standard naming scheme
1383 $prune_entry->{mark} = 'renamed';
1384 }
1385
1386 $prune_entry->{mark} = 'protected' if $backup->{protected};
1387
1388 push @{$prune_list}, $prune_entry;
1389 }
1390
1391 foreach my $backup_group (values %{$backup_groups}) {
1392 PVE::Storage::prune_mark_backup_group($backup_group, $keep);
1393 }
1394
1395 my $failed;
1396 if (!$dryrun) {
1397 foreach my $prune_entry (@{$prune_list}) {
1398 next if $prune_entry->{mark} ne 'remove';
1399
1400 my $volid = $prune_entry->{volid};
1401 $logfunc->('info', "removing backup '$volid'");
1402 eval {
1403 my (undef, $volname) = parse_volume_id($volid);
1404 my $archive_path = $class->filesystem_path($scfg, $volname);
1405 PVE::Storage::archive_remove($archive_path);
1406 };
1407 if (my $err = $@) {
1408 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1409 $failed = 1;
1410 }
1411 }
1412 }
1413 die "error pruning backups - check log\n" if $failed;
1414
1415 return $prune_list;
1416 }
1417
1418 # Import/Export interface:
1419 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1420 # the default implementations will return this if $scfg->{path} is set,
1421 # mimicking the old PVE::Storage::storage_migrate() function.
1422 #
1423 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1424 # functions in case the format doesn't match their specialized
1425 # implementations to reuse the raw/tar code.
1426 #
1427 # Format specification:
1428 # The following formats are all prefixed with image information in the form
1429 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1430 # to preallocate the image on storages which require it.
1431 #
1432 # raw+size: (image files only)
1433 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1434 # qcow2+size, vmdk: (image files only)
1435 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1436 # files which are already in qcow2 format, or via `qemu-img convert`.
1437 # Note that these formats are only valid with $with_snapshots being true.
1438 # tar+size: (subvolumes only)
1439 # A GNU tar stream containing just the inner contents of the subvolume.
1440 # This does not distinguish between the contents of a privileged or
1441 # unprivileged container. In other words, this is from the root user
1442 # namespace's point of view with no uid-mapping in effect.
1443 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1444
1445 # Plugins may reuse these helpers. Changes to the header format should be
1446 # reflected by changes to the function prototypes.
1447 sub write_common_header($$) {
1448 my ($fh, $image_size_in_bytes) = @_;
1449 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1450 }
1451
1452 sub read_common_header($) {
1453 my ($fh) = @_;
1454 sysread($fh, my $size, 8);
1455 $size = unpack('Q<', $size);
1456 die "import: no size found in export header, aborting.\n" if !defined($size);
1457 # Size is in bytes!
1458 return $size;
1459 }
1460
1461 # Export a volume into a file handle as a stream of desired format.
1462 sub volume_export {
1463 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1464 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1465 my $file = $class->path($scfg, $volname, $storeid)
1466 or goto unsupported;
1467 my ($size, $file_format) = file_size_info($file);
1468
1469 if ($format eq 'raw+size') {
1470 goto unsupported if $with_snapshots || $file_format eq 'subvol';
1471 write_common_header($fh, $size);
1472 if ($file_format eq 'raw') {
1473 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1474 } else {
1475 run_command(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1476 output => '>&'.fileno($fh));
1477 }
1478 return;
1479 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1480 my $data_format = $1;
1481 goto unsupported if !$with_snapshots || $file_format ne $data_format;
1482 write_common_header($fh, $size);
1483 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1484 return;
1485 } elsif ($format eq 'tar+size') {
1486 goto unsupported if $file_format ne 'subvol';
1487 write_common_header($fh, $size);
1488 run_command(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1489 output => '>&'.fileno($fh));
1490 return;
1491 }
1492 }
1493 unsupported:
1494 die "volume export format $format not available for $class";
1495 }
1496
1497 sub volume_export_formats {
1498 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1499 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1500 my $file = $class->path($scfg, $volname, $storeid)
1501 or return;
1502 my ($size, $format) = file_size_info($file);
1503
1504 if ($with_snapshots) {
1505 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1506 return ();
1507 }
1508 return ('tar+size') if $format eq 'subvol';
1509 return ('raw+size');
1510 }
1511 return ();
1512 }
1513
1514 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1515 sub volume_import {
1516 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1517
1518 die "volume import format '$format' not available for $class\n"
1519 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1520 my $data_format = $1;
1521
1522 die "format $format cannot be imported without snapshots\n"
1523 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1524 die "format $format cannot be imported with snapshots\n"
1525 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1526
1527 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1528 $class->parse_volname($volname);
1529
1530 # XXX: Should we bother with conversion routines at this level? This won't
1531 # happen without manual CLI usage, so for now we just error out...
1532 die "cannot import format $format into a file of format $file_format\n"
1533 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1534
1535 # Check for an existing file first since interrupting alloc_image doesn't
1536 # free it.
1537 my $file = $class->path($scfg, $volname, $storeid);
1538 if (-e $file) {
1539 die "file '$file' already exists\n" if !$allow_rename;
1540 warn "file '$file' already exists - importing with a different name\n";
1541 $name = undef;
1542 }
1543
1544 my ($size) = read_common_header($fh);
1545 $size = int($size/1024);
1546
1547 eval {
1548 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1549 my $oldname = $volname;
1550 $volname = $allocname;
1551 if (defined($name) && $allocname ne $oldname) {
1552 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1553 }
1554 my $file = $class->path($scfg, $volname, $storeid)
1555 or die "internal error: failed to get path to newly allocated volume $volname\n";
1556 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1557 run_command(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1558 input => '<&'.fileno($fh));
1559 } elsif ($data_format eq 'tar') {
1560 run_command(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1561 input => '<&'.fileno($fh));
1562 } else {
1563 die "volume import format '$format' not available for $class";
1564 }
1565 };
1566 if (my $err = $@) {
1567 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1568 warn $@ if $@;
1569 die $err;
1570 }
1571
1572 return "$storeid:$volname";
1573 }
1574
1575 sub volume_import_formats {
1576 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1577 if ($scfg->{path} && !defined($base_snapshot)) {
1578 my $format = ($class->parse_volname($volname))[6];
1579 if ($with_snapshots) {
1580 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1581 return ();
1582 }
1583 return ('tar+size') if $format eq 'subvol';
1584 return ('raw+size');
1585 }
1586 return ();
1587 }
1588
1589 sub rename_volume {
1590 my ($class, $scfg, $storeid, $source_volname, $target_vmid, $target_volname) = @_;
1591 die "not implemented in storage plugin '$class'\n" if $class->can('api') && $class->api() < 10;
1592 die "no path found\n" if !$scfg->{path};
1593
1594 my (
1595 undef,
1596 $source_image,
1597 $source_vmid,
1598 $base_name,
1599 $base_vmid,
1600 undef,
1601 $format
1602 ) = $class->parse_volname($source_volname);
1603
1604 $target_volname = $class->find_free_diskname($storeid, $scfg, $target_vmid, $format, 1)
1605 if !$target_volname;
1606
1607 my $basedir = $class->get_subdir($scfg, 'images');
1608
1609 mkpath "${basedir}/${target_vmid}";
1610
1611 my $old_path = "${basedir}/${source_vmid}/${source_image}";
1612 my $new_path = "${basedir}/${target_vmid}/${target_volname}";
1613
1614 die "target volume '${target_volname}' already exists\n" if -e $new_path;
1615
1616 my $base = $base_name ? "${base_vmid}/${base_name}/" : '';
1617
1618 rename($old_path, $new_path) ||
1619 die "rename '$old_path' to '$new_path' failed - $!\n";
1620
1621 return "${storeid}:${base}${target_vmid}/${target_volname}";
1622 }
1623
1624 1;