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