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