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