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