]> git.proxmox.com Git - pve-storage.git/blob - src/PVE/Storage/Plugin.pm
b5a54c100e8c1b35b340633acd6e0966eb05e3ee
[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+)$/); # untaint
978 die "size '$size' not an integer\n" if !defined($size);
979 # coerce back from string
980 $size = int($size);
981 ($used) = ($used =~ /^(\d+)$/); # untaint
982 die "used '$used' not an integer\n" if !defined($used);
983 # coerce back from string
984 $used = int($used);
985 ($format) = ($format =~ /^(\S+)$/); # untaint
986 die "format '$format' includes whitespace\n" if !defined($format);
987 if (defined($parent)) {
988 ($parent) = ($parent =~ /^(\S+)$/); # untaint
989 }
990 return wantarray ? ($size, $format, $used, $parent, $st->ctime) : $size;
991 }
992
993 # FIXME remove on the next APIAGE reset.
994 # Deprecated, use get_volume_attribute instead.
995 sub get_volume_notes {
996 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
997
998 die "volume notes are not supported for $class";
999 }
1000
1001 # FIXME remove on the next APIAGE reset.
1002 # Deprecated, use update_volume_attribute instead.
1003 sub update_volume_notes {
1004 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
1005
1006 die "volume notes are not supported for $class";
1007 }
1008
1009 # Returns undef if the attribute is not supported for the volume.
1010 # Should die if there is an error fetching the attribute.
1011 # Possible attributes:
1012 # notes - user-provided comments/notes.
1013 # protected - not to be removed by free_image, and for backups, ignored when pruning.
1014 sub get_volume_attribute {
1015 my ($class, $scfg, $storeid, $volname, $attribute) = @_;
1016
1017 if ($attribute eq 'notes') {
1018 my $notes = eval { $class->get_volume_notes($scfg, $storeid, $volname); };
1019 if (my $err = $@) {
1020 return if $err =~ m/^volume notes are not supported/;
1021 die $err;
1022 }
1023 return $notes;
1024 }
1025
1026 return;
1027 }
1028
1029 # Dies if the attribute is not supported for the volume.
1030 sub update_volume_attribute {
1031 my ($class, $scfg, $storeid, $volname, $attribute, $value) = @_;
1032
1033 if ($attribute eq 'notes') {
1034 $class->update_volume_notes($scfg, $storeid, $volname, $value);
1035 }
1036
1037 die "attribute '$attribute' is not supported for storage type '$scfg->{type}'\n";
1038 }
1039
1040 sub volume_size_info {
1041 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
1042 my $path = $class->filesystem_path($scfg, $volname);
1043 return file_size_info($path, $timeout);
1044
1045 }
1046
1047 sub volume_resize {
1048 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
1049
1050 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
1051
1052 return 1 if $running;
1053
1054 my $path = $class->filesystem_path($scfg, $volname);
1055
1056 my $format = ($class->parse_volname($volname))[6];
1057
1058 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
1059
1060 run_command($cmd, timeout => 10);
1061
1062 return undef;
1063 }
1064
1065 sub volume_snapshot {
1066 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1067
1068 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1069
1070 my $path = $class->filesystem_path($scfg, $volname);
1071
1072 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
1073
1074 run_command($cmd);
1075
1076 return undef;
1077 }
1078
1079 # Asserts that a rollback to $snap on $volname is possible.
1080 # If certain snapshots are preventing the rollback and $blockers is an array
1081 # reference, the snapshot names can be pushed onto $blockers prior to dying.
1082 sub volume_rollback_is_possible {
1083 my ($class, $scfg, $storeid, $volname, $snap, $blockers) = @_;
1084
1085 return 1;
1086 }
1087
1088 sub volume_snapshot_rollback {
1089 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1090
1091 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1092
1093 my $path = $class->filesystem_path($scfg, $volname);
1094
1095 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
1096
1097 run_command($cmd);
1098
1099 return undef;
1100 }
1101
1102 sub volume_snapshot_delete {
1103 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
1104
1105 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
1106
1107 return 1 if $running;
1108
1109 my $path = $class->filesystem_path($scfg, $volname);
1110
1111 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
1112
1113 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
1114
1115 run_command($cmd);
1116
1117 return undef;
1118 }
1119
1120 sub volume_snapshot_needs_fsfreeze {
1121
1122 return 0;
1123 }
1124 sub storage_can_replicate {
1125 my ($class, $scfg, $storeid, $format) = @_;
1126
1127 return 0;
1128 }
1129
1130 sub volume_has_feature {
1131 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
1132
1133 my $features = {
1134 snapshot => {
1135 current => { qcow2 => 1 },
1136 snap => { qcow2 => 1 },
1137 },
1138 clone => {
1139 base => { qcow2 => 1, raw => 1, vmdk => 1 },
1140 },
1141 template => {
1142 current => { qcow2 => 1, raw => 1, vmdk => 1, subvol => 1 },
1143 },
1144 copy => {
1145 base => { qcow2 => 1, raw => 1, vmdk => 1 },
1146 current => { qcow2 => 1, raw => 1, vmdk => 1 },
1147 snap => { qcow2 => 1 },
1148 },
1149 sparseinit => {
1150 base => { qcow2 => 1, raw => 1, vmdk => 1 },
1151 current => { qcow2 => 1, raw => 1, vmdk => 1 },
1152 },
1153 rename => {
1154 current => {qcow2 => 1, raw => 1, vmdk => 1},
1155 },
1156 };
1157
1158 if ($feature eq 'clone') {
1159 if (
1160 defined($opts->{valid_target_formats})
1161 && !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats}})
1162 ) {
1163 return 0; # clone_image creates a qcow2 volume
1164 }
1165 } elsif ($feature eq 'rename') {
1166 return 0 if $class->can('api') && $class->api() < 10;
1167 }
1168
1169
1170 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) = $class->parse_volname($volname);
1171
1172 my $key = undef;
1173 if($snapname){
1174 $key = 'snap';
1175 }else{
1176 $key = $isBase ? 'base' : 'current';
1177 }
1178
1179 return 1 if defined($features->{$feature}->{$key}->{$format});
1180
1181 return undef;
1182 }
1183
1184 sub list_images {
1185 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
1186
1187 my $imagedir = $class->get_subdir($scfg, 'images');
1188
1189 my ($defFmt, $vaidFmts) = default_format($scfg);
1190 my $fmts = join ('|', @$vaidFmts);
1191
1192 my $res = [];
1193
1194 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
1195
1196 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
1197 $fn = $1; # untaint
1198
1199 my $owner = $2;
1200 my $name = $3;
1201
1202 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1203
1204 my ($size, $format, $used, $parent, $ctime) = file_size_info($fn);
1205 next if !($format && defined($size));
1206
1207 my $volid;
1208 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
1209 my ($basevmid, $basename) = ($1, $2);
1210 $volid = "$storeid:$basevmid/$basename/$owner/$name";
1211 } else {
1212 $volid = "$storeid:$owner/$name";
1213 }
1214
1215 if ($vollist) {
1216 my $found = grep { $_ eq $volid } @$vollist;
1217 next if !$found;
1218 }
1219
1220 my $info = {
1221 volid => $volid, format => $format,
1222 size => $size, vmid => $owner, used => $used, parent => $parent
1223 };
1224
1225 $info->{ctime} = $ctime if $ctime;
1226
1227 push @$res, $info;
1228 }
1229
1230 return $res;
1231 }
1232
1233 # list templates ($tt = <iso|vztmpl|backup|snippets>)
1234 my $get_subdir_files = sub {
1235 my ($sid, $path, $tt, $vmid) = @_;
1236
1237 my $res = [];
1238
1239 foreach my $fn (<$path/*>) {
1240 my $st = File::stat::stat($fn);
1241
1242 next if (!$st || S_ISDIR($st->mode));
1243
1244 my $info;
1245
1246 if ($tt eq 'iso') {
1247 next if $fn !~ m!/([^/]+$PVE::Storage::ISO_EXT_RE_0)$!i;
1248
1249 $info = { volid => "$sid:iso/$1", format => 'iso' };
1250
1251 } elsif ($tt eq 'vztmpl') {
1252 next if $fn !~ m!/([^/]+$PVE::Storage::VZTMPL_EXT_RE_1)$!;
1253
1254 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
1255
1256 } elsif ($tt eq 'backup') {
1257 next if $fn !~ m!/([^/]+$PVE::Storage::BACKUP_EXT_RE_2)$!;
1258 my $original = $fn;
1259 my $format = $2;
1260 $fn = $1;
1261
1262 # only match for VMID now, to avoid false positives (VMID in parent directory name)
1263 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1264
1265 $info = { volid => "$sid:backup/$fn", format => $format };
1266
1267 my $archive_info = eval { PVE::Storage::archive_info($fn) } // {};
1268
1269 $info->{ctime} = $archive_info->{ctime} if defined($archive_info->{ctime});
1270 $info->{subtype} = $archive_info->{type} // 'unknown';
1271
1272 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1273 $info->{vmid} = $vmid // $1;
1274 }
1275
1276 my $notes_fn = $original.NOTES_EXT;
1277 if (-f $notes_fn) {
1278 my $notes = PVE::Tools::file_read_firstline($notes_fn);
1279 $info->{notes} = eval { decode('UTF-8', $notes, 1) } // $notes if defined($notes);
1280 }
1281
1282 $info->{protected} = 1 if -e PVE::Storage::protection_file_path($original);
1283 } elsif ($tt eq 'snippets') {
1284
1285 $info = {
1286 volid => "$sid:snippets/". basename($fn),
1287 format => 'snippet',
1288 };
1289 }
1290
1291 $info->{size} = $st->size;
1292 $info->{ctime} //= $st->ctime;
1293
1294 push @$res, $info;
1295 }
1296
1297 return $res;
1298 };
1299
1300 # If attributes are set on a volume, they should be included in the result.
1301 # See get_volume_attribute for a list of possible attributes.
1302 sub list_volumes {
1303 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1304
1305 my $res = [];
1306 my $vmlist = PVE::Cluster::get_vmlist();
1307 foreach my $type (@$content_types) {
1308 my $data;
1309
1310 if ($type eq 'images' || $type eq 'rootdir') {
1311 $data = $class->list_images($storeid, $scfg, $vmid);
1312 } elsif ($scfg->{path}) {
1313 my $path = $class->get_subdir($scfg, $type);
1314
1315 if ($type eq 'iso' && !defined($vmid)) {
1316 $data = $get_subdir_files->($storeid, $path, 'iso');
1317 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
1318 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
1319 } elsif ($type eq 'backup') {
1320 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
1321 } elsif ($type eq 'snippets') {
1322 $data = $get_subdir_files->($storeid, $path, 'snippets');
1323 }
1324 }
1325
1326 next if !$data;
1327
1328 foreach my $item (@$data) {
1329 if ($type eq 'images' || $type eq 'rootdir') {
1330 my $vminfo = $vmlist->{ids}->{$item->{vmid}};
1331 my $vmtype;
1332 if (defined($vminfo)) {
1333 $vmtype = $vminfo->{type};
1334 }
1335 if (defined($vmtype) && $vmtype eq 'lxc') {
1336 $item->{content} = 'rootdir';
1337 } else {
1338 $item->{content} = 'images';
1339 }
1340 next if $type ne $item->{content};
1341 } else {
1342 $item->{content} = $type;
1343 }
1344
1345 push @$res, $item;
1346 }
1347 }
1348
1349 return $res;
1350 }
1351
1352 sub status {
1353 my ($class, $storeid, $scfg, $cache) = @_;
1354
1355 my $path = $scfg->{path};
1356
1357 die "storage definition has no path\n" if !$path;
1358
1359 my $timeout = 2;
1360 my $res = PVE::Tools::df($path, $timeout);
1361
1362 return undef if !$res || !$res->{total};
1363
1364 return ($res->{total}, $res->{avail}, $res->{used}, 1);
1365 }
1366
1367 # Returns a hash with the snapshot names as keys and the following data:
1368 # id - Unique id to distinguish different snapshots even if the have the same name.
1369 # timestamp - Creation time of the snapshot (seconds since epoch).
1370 # Returns an empty hash if the volume does not exist.
1371 sub volume_snapshot_info {
1372 my ($class, $scfg, $storeid, $volname) = @_;
1373
1374 die "volume_snapshot_info is not implemented for $class";
1375 }
1376
1377 sub activate_storage {
1378 my ($class, $storeid, $scfg, $cache) = @_;
1379
1380 my $path = $scfg->{path};
1381
1382 die "storage definition has no path\n" if !$path;
1383
1384 # this path test may hang indefinitely on unresponsive mounts
1385 my $timeout = 2;
1386 if (! PVE::Tools::run_fork_with_timeout($timeout, sub {-d $path})) {
1387 die "unable to activate storage '$storeid' - " .
1388 "directory '$path' does not exist or is unreachable\n";
1389 }
1390
1391 # TODO: mkdir is basically deprecated since 8.0, but we don't warn here until 8.4 or 9.0, as we
1392 # only got the replacement in 8.0, so no real replacement window, and its really noisy.
1393
1394 if (defined($scfg->{content})) {
1395 # (opt-out) create content dirs and check validity
1396 if (
1397 (!defined($scfg->{'create-subdirs'}) || $scfg->{'create-subdirs'})
1398 # FIXME The mkdir option is deprecated. Remove with PVE 9?
1399 && (!defined($scfg->{mkdir}) || $scfg->{mkdir})
1400 ) {
1401 for my $vtype (sort keys %$vtype_subdirs) {
1402 # OpenVZMigrate uses backup (dump) dir
1403 if (
1404 defined($scfg->{content}->{$vtype})
1405 || ($vtype eq 'backup' && defined($scfg->{content}->{'rootdir'}))
1406 ) {
1407 my $subdir = $class->get_subdir($scfg, $vtype);
1408 mkpath $subdir if $subdir ne $path;
1409 }
1410 }
1411 }
1412
1413 # check that content dirs are pairwise inequal
1414 my $resolved_subdirs = {};
1415 for my $vtype (sort keys $scfg->{content}->%*) {
1416 my $subdir = $class->get_subdir($scfg, $vtype);
1417 my $abs_subdir = abs_path($subdir);
1418 next if !defined($abs_subdir);
1419
1420 die "storage '$storeid' uses directory $abs_subdir for multiple content types\n"
1421 if defined($abs_subdir) && defined($resolved_subdirs->{$abs_subdir});
1422
1423 $resolved_subdirs->{$abs_subdir} = 1;
1424 }
1425 }
1426 }
1427
1428 sub deactivate_storage {
1429 my ($class, $storeid, $scfg, $cache) = @_;
1430
1431 # do nothing by default
1432 }
1433
1434 sub map_volume {
1435 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1436
1437 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1438 return $path;
1439 }
1440
1441 sub unmap_volume {
1442 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1443
1444 return 1;
1445 }
1446
1447 sub activate_volume {
1448 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1449
1450 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1451
1452 # check is volume exists
1453 if ($scfg->{path}) {
1454 die "volume '$storeid:$volname' does not exist\n" if ! -e $path;
1455 } else {
1456 die "volume '$storeid:$volname' does not exist\n" if ! -b $path;
1457 }
1458 }
1459
1460 sub deactivate_volume {
1461 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1462
1463 # do nothing by default
1464 }
1465
1466 sub check_connection {
1467 my ($class, $storeid, $scfg) = @_;
1468 # do nothing by default
1469 return 1;
1470 }
1471
1472 sub prune_backups {
1473 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1474
1475 $logfunc //= sub { print "$_[1]\n" };
1476
1477 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1478
1479 my $backup_groups = {};
1480 my $prune_list = [];
1481
1482 foreach my $backup (@{$backups}) {
1483 my $volid = $backup->{volid};
1484 my $archive_info = eval { PVE::Storage::archive_info($volid) } // {};
1485 my $backup_type = $archive_info->{type} // 'unknown';
1486 my $backup_vmid = $archive_info->{vmid} // $backup->{vmid};
1487
1488 next if defined($type) && $type ne $backup_type;
1489
1490 my $prune_entry = {
1491 ctime => $backup->{ctime},
1492 type => $backup_type,
1493 volid => $volid,
1494 };
1495
1496 $prune_entry->{vmid} = $backup_vmid if defined($backup_vmid);
1497
1498 if ($archive_info->{is_std_name}) {
1499 die "internal error - got no VMID\n" if !defined($backup_vmid);
1500 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1501 if defined($vmid) && $backup_vmid ne $vmid;
1502
1503 $prune_entry->{ctime} = $archive_info->{ctime};
1504 my $group = "$backup_type/$backup_vmid";
1505 push @{$backup_groups->{$group}}, $prune_entry;
1506 } else {
1507 # ignore backups that don't use the standard naming scheme
1508 $prune_entry->{mark} = 'renamed';
1509 }
1510
1511 $prune_entry->{mark} = 'protected' if $backup->{protected};
1512
1513 push @{$prune_list}, $prune_entry;
1514 }
1515
1516 foreach my $backup_group (values %{$backup_groups}) {
1517 PVE::Storage::prune_mark_backup_group($backup_group, $keep);
1518 }
1519
1520 my $failed;
1521 if (!$dryrun) {
1522 foreach my $prune_entry (@{$prune_list}) {
1523 next if $prune_entry->{mark} ne 'remove';
1524
1525 my $volid = $prune_entry->{volid};
1526 $logfunc->('info', "removing backup '$volid'");
1527 eval {
1528 my (undef, $volname) = parse_volume_id($volid);
1529 my $archive_path = $class->filesystem_path($scfg, $volname);
1530 PVE::Storage::archive_remove($archive_path);
1531 };
1532 if (my $err = $@) {
1533 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1534 $failed = 1;
1535 }
1536 }
1537 }
1538 die "error pruning backups - check log\n" if $failed;
1539
1540 return $prune_list;
1541 }
1542
1543 # Import/Export interface:
1544 # Any path based storage is assumed to support 'raw' and 'tar' streams, so
1545 # the default implementations will return this if $scfg->{path} is set,
1546 # mimicking the old PVE::Storage::storage_migrate() function.
1547 #
1548 # Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1549 # functions in case the format doesn't match their specialized
1550 # implementations to reuse the raw/tar code.
1551 #
1552 # Format specification:
1553 # The following formats are all prefixed with image information in the form
1554 # of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1555 # to preallocate the image on storages which require it.
1556 #
1557 # raw+size: (image files only)
1558 # A raw binary data stream such as produced via `dd if=TheImageFile`.
1559 # qcow2+size, vmdk: (image files only)
1560 # A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1561 # files which are already in qcow2 format, or via `qemu-img convert`.
1562 # Note that these formats are only valid with $with_snapshots being true.
1563 # tar+size: (subvolumes only)
1564 # A GNU tar stream containing just the inner contents of the subvolume.
1565 # This does not distinguish between the contents of a privileged or
1566 # unprivileged container. In other words, this is from the root user
1567 # namespace's point of view with no uid-mapping in effect.
1568 # As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
1569
1570 # Plugins may reuse these helpers. Changes to the header format should be
1571 # reflected by changes to the function prototypes.
1572 sub write_common_header($$) {
1573 my ($fh, $image_size_in_bytes) = @_;
1574 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1575 }
1576
1577 sub read_common_header($) {
1578 my ($fh) = @_;
1579 sysread($fh, my $size, 8);
1580 $size = unpack('Q<', $size);
1581 die "import: no size found in export header, aborting.\n" if !defined($size);
1582 # Size is in bytes!
1583 return $size;
1584 }
1585
1586 # Export a volume into a file handle as a stream of desired format.
1587 sub volume_export {
1588 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1589 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1590 my $file = $class->path($scfg, $volname, $storeid)
1591 or goto unsupported;
1592 my ($size, $file_format) = file_size_info($file);
1593
1594 if ($format eq 'raw+size') {
1595 goto unsupported if $with_snapshots || $file_format eq 'subvol';
1596 write_common_header($fh, $size);
1597 if ($file_format eq 'raw') {
1598 run_command(['dd', "if=$file", "bs=4k", "status=progress"], output => '>&'.fileno($fh));
1599 } else {
1600 run_command(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1601 output => '>&'.fileno($fh));
1602 }
1603 return;
1604 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1605 my $data_format = $1;
1606 goto unsupported if !$with_snapshots || $file_format ne $data_format;
1607 write_common_header($fh, $size);
1608 run_command(['dd', "if=$file", "bs=4k", "status=progress"], output => '>&'.fileno($fh));
1609 return;
1610 } elsif ($format eq 'tar+size') {
1611 goto unsupported if $file_format ne 'subvol';
1612 write_common_header($fh, $size);
1613 run_command(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
1614 output => '>&'.fileno($fh));
1615 return;
1616 }
1617 }
1618 unsupported:
1619 die "volume export format $format not available for $class";
1620 }
1621
1622 sub volume_export_formats {
1623 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1624 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1625 my $file = $class->path($scfg, $volname, $storeid)
1626 or return;
1627 my ($size, $format) = file_size_info($file);
1628
1629 if ($with_snapshots) {
1630 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1631 return ();
1632 }
1633 return ('tar+size') if $format eq 'subvol';
1634 return ('raw+size');
1635 }
1636 return ();
1637 }
1638
1639 # Import data from a stream, creating a new or replacing or adding to an existing volume.
1640 sub volume_import {
1641 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1642
1643 die "volume import format '$format' not available for $class\n"
1644 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1645 my $data_format = $1;
1646
1647 die "format $format cannot be imported without snapshots\n"
1648 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1649 die "format $format cannot be imported with snapshots\n"
1650 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1651
1652 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1653 $class->parse_volname($volname);
1654
1655 # XXX: Should we bother with conversion routines at this level? This won't
1656 # happen without manual CLI usage, so for now we just error out...
1657 die "cannot import format $format into a file of format $file_format\n"
1658 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1659
1660 # Check for an existing file first since interrupting alloc_image doesn't
1661 # free it.
1662 my $file = $class->path($scfg, $volname, $storeid);
1663 if (-e $file) {
1664 die "file '$file' already exists\n" if !$allow_rename;
1665 warn "file '$file' already exists - importing with a different name\n";
1666 $name = undef;
1667 }
1668
1669 my ($size) = read_common_header($fh);
1670 $size = int($size/1024);
1671
1672 eval {
1673 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
1674 my $oldname = $volname;
1675 $volname = $allocname;
1676 if (defined($name) && $allocname ne $oldname) {
1677 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1678 }
1679 my $file = $class->path($scfg, $volname, $storeid)
1680 or die "internal error: failed to get path to newly allocated volume $volname\n";
1681 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1682 run_command(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1683 input => '<&'.fileno($fh));
1684 } elsif ($data_format eq 'tar') {
1685 run_command(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
1686 input => '<&'.fileno($fh));
1687 } else {
1688 die "volume import format '$format' not available for $class";
1689 }
1690 };
1691 if (my $err = $@) {
1692 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1693 warn $@ if $@;
1694 die $err;
1695 }
1696
1697 return "$storeid:$volname";
1698 }
1699
1700 sub volume_import_formats {
1701 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
1702 if ($scfg->{path} && !defined($base_snapshot)) {
1703 my $format = ($class->parse_volname($volname))[6];
1704 if ($with_snapshots) {
1705 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1706 return ();
1707 }
1708 return ('tar+size') if $format eq 'subvol';
1709 return ('raw+size');
1710 }
1711 return ();
1712 }
1713
1714 sub rename_volume {
1715 my ($class, $scfg, $storeid, $source_volname, $target_vmid, $target_volname) = @_;
1716 die "not implemented in storage plugin '$class'\n" if $class->can('api') && $class->api() < 10;
1717 die "no path found\n" if !$scfg->{path};
1718
1719 my (
1720 undef,
1721 $source_image,
1722 $source_vmid,
1723 $base_name,
1724 $base_vmid,
1725 undef,
1726 $format
1727 ) = $class->parse_volname($source_volname);
1728
1729 $target_volname = $class->find_free_diskname($storeid, $scfg, $target_vmid, $format, 1)
1730 if !$target_volname;
1731
1732 my $basedir = $class->get_subdir($scfg, 'images');
1733
1734 mkpath "${basedir}/${target_vmid}";
1735
1736 my $old_path = "${basedir}/${source_vmid}/${source_image}";
1737 my $new_path = "${basedir}/${target_vmid}/${target_volname}";
1738
1739 die "target volume '${target_volname}' already exists\n" if -e $new_path;
1740
1741 my $base = $base_name ? "${base_vmid}/${base_name}/" : '';
1742
1743 rename($old_path, $new_path) ||
1744 die "rename '$old_path' to '$new_path' failed - $!\n";
1745
1746 return "${storeid}:${base}${target_vmid}/${target_volname}";
1747 }
1748
1749 sub config_aware_base_mkdir {
1750 my ($class, $scfg, $path) = @_;
1751
1752 # FIXME the mkdir parameter is deprecated and create-base-path should be used
1753 if ($scfg->{'create-base-path'} // $scfg->{mkdir} // 1) {
1754 mkpath($path);
1755 }
1756 }
1757
1758 1;