]> git.proxmox.com Git - pve-storage.git/blame - PVE/Storage/Plugin.pm
config: mention that maxfiles is deprecated
[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',
d1eb35ea 407 content => { images => 1, rootdir => 1, vztmpl => 1, iso => 1, snippets => 1},
1dc01b9f
DM
408 };
409 }
045ae0a7 410
1dc01b9f
DM
411 # make sure we have a path
412 $ids->{local}->{path} = '/var/lib/vz' if !$ids->{local}->{path};
413
414 # remove node restrictions for local storage
415 delete($ids->{local}->{nodes});
416
417 foreach my $storeid (keys %$ids) {
418 my $d = $ids->{$storeid};
419 my $type = $d->{type};
420
421 my $def = $defaultData->{plugindata}->{$type};
422
423 if ($def->{content}) {
424 $d->{content} = $def->{content}->[1] if !$d->{content};
425 }
d7875239 426 if (grep { $_ eq $type } @SHARED_STORAGE) {
1dc01b9f
DM
427 $d->{shared} = 1;
428 }
429 }
430
431 return $cfg;
432}
433
434# Storage implementation
435
3932ca0d
TL
436# called during addition of storage (before the new storage config got written)
437# die to abort additon if there are (grave) problems
438# NOTE: runs in a storage config *locked* context
439sub on_add_hook {
440 my ($class, $storeid, $scfg, %param) = @_;
441
442 # do nothing by default
afeda182 443 return undef;
3932ca0d
TL
444}
445
0ff4cfea
DM
446# called during storage configuration update (before the updated storage config got written)
447# die to abort the update if there are (grave) problems
448# NOTE: runs in a storage config *locked* context
449sub on_update_hook {
450 my ($class, $storeid, $scfg, %param) = @_;
451
452 # do nothing by default
afeda182 453 return undef;
0ff4cfea
DM
454}
455
3932ca0d
TL
456# called during deletion of storage (before the new storage config got written)
457# and if the activate check on addition fails, to cleanup all storage traces
458# which on_add_hook may have created.
459# die to abort deletion if there are (very grave) problems
460# NOTE: runs in a storage config *locked* context
461sub on_delete_hook {
462 my ($class, $storeid, $scfg) = @_;
463
464 # do nothing by default
afeda182 465 return undef;
3932ca0d
TL
466}
467
1dc01b9f
DM
468sub cluster_lock_storage {
469 my ($class, $storeid, $shared, $timeout, $func, @param) = @_;
470
471 my $res;
472 if (!$shared) {
473 my $lockid = "pve-storage-$storeid";
474 my $lockdir = "/var/lock/pve-manager";
475 mkdir $lockdir;
045ae0a7 476 $res = PVE::Tools::lock_file("$lockdir/$lockid", $timeout, $func, @param);
1dc01b9f
DM
477 die $@ if $@;
478 } else {
479 $res = PVE::Cluster::cfs_lock_storage($storeid, $timeout, $func, @param);
480 die $@ if $@;
045ae0a7 481 }
1dc01b9f
DM
482 return $res;
483}
484
485sub parse_name_dir {
486 my $name = shift;
487
35533c68
DM
488 if ($name =~ m!^((base-)?[^/\s]+\.(raw|qcow2|vmdk|subvol))$!) {
489 return ($1, $3, $2); # (name, format, isBase)
1dc01b9f
DM
490 }
491
492 die "unable to parse volume filename '$name'\n";
493}
494
495sub parse_volname {
496 my ($class, $volname) = @_;
497
2502b33b
DM
498 if ($volname =~ m!^(\d+)/(\S+)/(\d+)/(\S+)$!) {
499 my ($basedvmid, $basename) = ($1, $2);
500 parse_name_dir($basename);
501 my ($vmid, $name) = ($3, $4);
35533c68
DM
502 my (undef, $format, $isBase) = parse_name_dir($name);
503 return ('images', $name, $vmid, $basename, $basedvmid, $isBase, $format);
2502b33b 504 } elsif ($volname =~ m!^(\d+)/(\S+)$!) {
1dc01b9f 505 my ($vmid, $name) = ($1, $2);
35533c68
DM
506 my (undef, $format, $isBase) = parse_name_dir($name);
507 return ('images', $name, $vmid, undef, undef, $isBase, $format);
4c693491 508 } elsif ($volname =~ m!^iso/([^/]+$PVE::Storage::iso_extension_re)$!) {
1dc01b9f 509 return ('iso', $1);
13d2cb79 510 } elsif ($volname =~ m!^vztmpl/([^/]+\.tar\.[gx]z)$!) {
1dc01b9f
DM
511 return ('vztmpl', $1);
512 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
513 return ('rootdir', $1, $1);
277cafc0 514 } elsif ($volname =~ m!^backup/([^/]+(?:\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\COMPRESSOR_RE}))?))))$!) {
1dc01b9f 515 my $fn = $1;
4cb6e060 516 if ($fn =~ m/^vzdump-(openvz|lxc|qemu)-(\d+)-.+/) {
1dc01b9f
DM
517 return ('backup', $fn, $2);
518 }
519 return ('backup', $fn);
7c7ae12f
DC
520 } elsif ($volname =~ m!^snippets/([^/]+)$!) {
521 return ('snippets', $1);
1dc01b9f
DM
522 }
523
524 die "unable to parse directory volume name '$volname'\n";
525}
526
045ae0a7 527my $vtype_subdirs = {
1dc01b9f
DM
528 images => 'images',
529 rootdir => 'private',
530 iso => 'template/iso',
531 vztmpl => 'template/cache',
532 backup => 'dump',
7c7ae12f 533 snippets => 'snippets',
1dc01b9f
DM
534};
535
c48801b5
AA
536sub get_vtype_subdirs {
537 return $vtype_subdirs;
538}
539
1dc01b9f
DM
540sub get_subdir {
541 my ($class, $scfg, $vtype) = @_;
542
543 my $path = $scfg->{path};
544
545 die "storage definintion has no path\n" if !$path;
546
547 my $subdir = $vtype_subdirs->{$vtype};
548
549 die "unknown vtype '$vtype'\n" if !defined($subdir);
550
045ae0a7 551 return "$path/$subdir";
1dc01b9f
DM
552}
553
08480ce7 554sub filesystem_path {
e67069eb 555 my ($class, $scfg, $volname, $snapname) = @_;
1dc01b9f 556
e67069eb
DM
557 my ($vtype, $name, $vmid, undef, undef, $isBase, $format) =
558 $class->parse_volname($volname);
559
560 # Note: qcow2/qed has internal snapshot, so path is always
561 # the same (with or without snapshot => same file).
562 die "can't snapshot this image format\n"
563 if defined($snapname) && $format !~ m/^(qcow2|qed)$/;
1dc01b9f
DM
564
565 my $dir = $class->get_subdir($scfg, $vtype);
566
567 $dir .= "/$vmid" if $vtype eq 'images';
568
569 my $path = "$dir/$name";
570
571 return wantarray ? ($path, $vmid, $vtype) : $path;
572}
573
08480ce7 574sub path {
e67069eb 575 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
08480ce7 576
e67069eb 577 return $class->filesystem_path($scfg, $volname, $snapname);
08480ce7
DM
578}
579
2502b33b
DM
580sub create_base {
581 my ($class, $storeid, $scfg, $volname) = @_;
582
583 # this only works for file based storage types
5510f5c9 584 die "storage definition has no path\n" if !$scfg->{path};
2502b33b 585
35533c68 586 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
2502b33b
DM
587 $class->parse_volname($volname);
588
589 die "create_base on wrong vtype '$vtype'\n" if $vtype ne 'images';
590
591 die "create_base not possible with base image\n" if $isBase;
592
08480ce7 593 my $path = $class->filesystem_path($scfg, $volname);
2502b33b 594
35533c68
DM
595 my ($size, undef, $used, $parent) = file_size_info($path);
596 die "file_size_info on '$volname' failed\n" if !($format && defined($size));
2502b33b
DM
597
598 die "volname '$volname' contains wrong information about parent\n"
599 if $basename && (!$parent || $parent ne "../$basevmid/$basename");
600
601 my $newname = $name;
602 $newname =~ s/^vm-/base-/;
603
604 my $newvolname = $basename ? "$basevmid/$basename/$vmid/$newname" :
605 "$vmid/$newname";
606
08480ce7 607 my $newpath = $class->filesystem_path($scfg, $newvolname);
2502b33b
DM
608
609 die "file '$newpath' already exists\n" if -f $newpath;
610
1a3459ac 611 rename($path, $newpath) ||
2502b33b
DM
612 die "rename '$path' to '$newpath' failed - $!\n";
613
c803c396 614 # We try to protect base volume
2502b33b 615
c803c396
DM
616 chmod(0444, $newpath); # nobody should write anything
617
618 # also try to set immutable flag
619 eval { run_command(['/usr/bin/chattr', '+i', $newpath]); };
620 warn $@ if $@;
1a3459ac 621
2502b33b
DM
622 return $newvolname;
623}
624
83a40b8d
TL
625my $get_vm_disk_number = sub {
626 my ($disk_name, $scfg, $vmid, $suffix) = @_;
345f8981 627
dd1fa860
TL
628 my $disk_regex = qr/(vm|base)-$vmid-disk-(\d+)$suffix/;
629
345f8981 630 my $type = $scfg->{type};
f4cc2c4a 631 my $def = { %{$defaultData->{plugindata}->{$type}} };
345f8981 632
dd1fa860
TL
633 my $valid = $def->{format}[0];
634 if ($valid->{subvol}) {
635 $disk_regex = qr/(vm|base|subvol|basevol)-$vmid-disk-(\d+)/;
636 }
345f8981 637
83a40b8d
TL
638 if ($disk_name =~ m/$disk_regex/) {
639 return $2;
345f8981 640 }
83a40b8d
TL
641
642 return undef;
643};
345f8981
SI
644
645sub get_next_vm_diskname {
646 my ($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix) = @_;
647
345f8981
SI
648 $fmt //= '';
649 my $prefix = ($fmt eq 'subvol') ? 'subvol' : 'vm';
650 my $suffix = $add_fmt_suffix ? ".$fmt" : '';
651
83a40b8d
TL
652 my $disk_ids = {};
653 foreach my $disk (@$disk_list) {
654 my $disknum = $get_vm_disk_number->($disk, $scfg, $vmid, $suffix);
655 $disk_ids->{$disknum} = 1 if defined($disknum);
656 }
657
59fa9fd6 658 for (my $i = 0; $i < $MAX_VOLUMES_PER_GUEST; $i++) {
345f8981
SI
659 if (!$disk_ids->{$i}) {
660 return "$prefix-$vmid-disk-$i$suffix";
661 }
662 }
663
664 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
665}
666
a44c0147
FE
667sub find_free_diskname {
668 my ($class, $storeid, $scfg, $vmid, $fmt, $add_fmt_suffix) = @_;
669
670 my $disks = $class->list_images($storeid, $scfg, $vmid);
2502b33b 671
01e872db 672 my $disk_list = [ map { $_->{volid} } @$disks ];
2502b33b 673
a44c0147
FE
674 return get_next_vm_diskname($disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix);
675}
2502b33b
DM
676
677sub clone_image {
f236eaf8 678 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
2502b33b
DM
679
680 # this only works for file based storage types
681 die "storage definintion has no path\n" if !$scfg->{path};
682
35533c68 683 my ($vtype, $basename, $basevmid, undef, undef, $isBase, $format) =
2502b33b
DM
684 $class->parse_volname($volname);
685
686 die "clone_image on wrong vtype '$vtype'\n" if $vtype ne 'images';
687
f236eaf8
SP
688 die "this storage type does not support clone_image on snapshot\n" if $snap;
689
35533c68
DM
690 die "this storage type does not support clone_image on subvolumes\n" if $format eq 'subvol';
691
f236eaf8 692 die "clone_image only works on base images\n" if !$isBase;
1dc01b9f
DM
693
694 my $imagedir = $class->get_subdir($scfg, 'images');
695 $imagedir .= "/$vmid";
696
697 mkpath $imagedir;
698
d7f6f85e 699 my $name = $class->find_free_diskname($storeid, $scfg, $vmid, "qcow2", 1);
2502b33b
DM
700
701 warn "clone $volname: $vtype, $name, $vmid to $name (base=../$basevmid/$basename)\n";
702
703 my $newvol = "$basevmid/$basename/$vmid/$name";
704
08480ce7 705 my $path = $class->filesystem_path($scfg, $newvol);
2502b33b 706
1a3459ac 707 # Note: we use relative paths, so we need to call chdir before qemu-img
2502b33b 708 eval {
7fc619d5 709 local $CWD = $imagedir;
2502b33b 710
1a3459ac 711 my $cmd = ['/usr/bin/qemu-img', 'create', '-b', "../$basevmid/$basename",
9177cc2e 712 '-F', $format, '-f', 'qcow2', $path];
1a3459ac 713
2502b33b
DM
714 run_command($cmd);
715 };
716 my $err = $@;
1dc01b9f 717
2502b33b
DM
718 die $err if $err;
719
720 return $newvol;
721}
722
723sub alloc_image {
724 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
725
726 my $imagedir = $class->get_subdir($scfg, 'images');
727 $imagedir .= "/$vmid";
728
729 mkpath $imagedir;
730
d7f6f85e 731 $name = $class->find_free_diskname($storeid, $scfg, $vmid, $fmt, 1) if !$name;
1a3459ac 732
1dc01b9f
DM
733 my (undef, $tmpfmt) = parse_name_dir($name);
734
045ae0a7 735 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
1dc01b9f
DM
736 if $tmpfmt ne $fmt;
737
738 my $path = "$imagedir/$name";
739
740 die "disk image '$path' already exists\n" if -e $path;
741
35533c68
DM
742 if ($fmt eq 'subvol') {
743 # only allow this if size = 0, so that user knows what he is doing
744 die "storage does not support subvol quotas\n" if $size != 0;
3918b96a 745
1f5734bb
WB
746 my $old_umask = umask(0022);
747 my $err;
748 mkdir($path) or $err = "unable to create subvol '$path' - $!\n";
749 umask $old_umask;
750 die $err if $err;
35533c68
DM
751 } else {
752 my $cmd = ['/usr/bin/qemu-img', 'create'];
045ae0a7 753
35533c68 754 push @$cmd, '-o', 'preallocation=metadata' if $fmt eq 'qcow2';
3918b96a 755
35533c68 756 push @$cmd, '-f', $fmt, $path, "${size}K";
1dc01b9f 757
a8ec2f02
CE
758 eval { run_command($cmd, errmsg => "unable to create image"); };
759 if ($@) {
760 unlink $path;
761 rmdir $imagedir;
762 die "$@";
763 }
35533c68 764 }
3918b96a 765
1dc01b9f
DM
766 return "$vmid/$name";
767}
768
769sub free_image {
35533c68 770 my ($class, $storeid, $scfg, $volname, $isBase, $format) = @_;
1dc01b9f 771
08480ce7 772 my $path = $class->filesystem_path($scfg, $volname);
1dc01b9f 773
f5451f28
DC
774 if ($isBase) {
775 # try to remove immutable flag
776 eval { run_command(['/usr/bin/chattr', '-i', $path]); };
777 warn $@ if $@;
778 }
779
4a7d2222 780 if (defined($format) && ($format eq 'subvol')) {
35533c68
DM
781 File::Path::remove_tree($path);
782 } else {
de0cd0c2 783 if (!(-f $path || -l $path)) {
481f6177 784 warn "disk image '$path' does not exist\n";
35533c68
DM
785 return undef;
786 }
1dc01b9f 787
35533c68
DM
788 unlink($path) || die "unlink '$path' failed - $!\n";
789 }
712e27f1
CE
790
791 # try to cleanup directory to not clutter storage with empty $vmid dirs if
792 # all images from a guest got deleted
793 my $dir = dirname($path);
794 rmdir($dir);
3918b96a 795
1dc01b9f
DM
796 return undef;
797}
798
799sub file_size_info {
800 my ($filename, $timeout) = @_;
801
92ae59df 802 my $st = File::stat::stat($filename);
51eee96d 803
d1f47000
FG
804 if (!defined($st)) {
805 my $extramsg = -l $filename ? ' - dangling symlink?' : '';
806 warn "failed to stat '$filename'$extramsg\n";
807 return undef;
808 }
809
92ae59df
AA
810 if (S_ISDIR($st->mode)) {
811 return wantarray ? (0, 'subvol', 0, undef, $st->ctime) : 1;
35533c68 812 }
3918b96a 813
af0335e8 814 my $json = '';
1dbbd5ab 815 eval {
80699b1d
TL
816 run_command(['/usr/bin/qemu-img', 'info', '--output=json', $filename],
817 timeout => $timeout,
818 outfunc => sub { $json .= shift },
819 errfunc => sub { warn "$_[0]\n" }
820 );
1dbbd5ab 821 };
aa4594b1
TM
822 warn $@ if $@;
823
80699b1d
TL
824 my $info = eval { decode_json($json) };
825 warn "could not parse qemu-img info command output for '$filename'\n" if $@;
af0335e8 826
80699b1d 827 my ($size, $format, $used, $parent) = $info->@{qw(virtual-size format actual-size backing-filename)};
af0335e8 828
92ae59df 829 return wantarray ? ($size, $format, $used, $parent, $st->ctime) : $size;
1dc01b9f
DM
830}
831
e9991d26
DC
832sub get_volume_notes {
833 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
834
835 die "volume notes are not supported for $class";
836}
837
838sub update_volume_notes {
839 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
840
841 die "volume notes are not supported for $class";
842}
843
e47e548e
AD
844sub volume_size_info {
845 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
08480ce7 846 my $path = $class->filesystem_path($scfg, $volname);
e47e548e
AD
847 return file_size_info($path, $timeout);
848
849}
850
81f5058c
AD
851sub volume_resize {
852 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
853
6d788031 854 die "can't resize this image format\n" if $volname !~ m/\.(raw|qcow2)$/;
81f5058c
AD
855
856 return 1 if $running;
857
08480ce7 858 my $path = $class->filesystem_path($scfg, $volname);
81f5058c 859
0589e5f9
WL
860 my $format = ($class->parse_volname($volname))[6];
861
862 my $cmd = ['/usr/bin/qemu-img', 'resize', '-f', $format, $path , $size];
81f5058c 863
1059cc99 864 run_command($cmd, timeout => 10);
81f5058c
AD
865
866 return undef;
867}
868
7dcb0697 869sub volume_snapshot {
f5640e7d 870 my ($class, $scfg, $storeid, $volname, $snap) = @_;
7dcb0697 871
6d788031 872 die "can't snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
7dcb0697 873
08480ce7 874 my $path = $class->filesystem_path($scfg, $volname);
7dcb0697
AD
875
876 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-c', $snap, $path];
877
3f13fd7d 878 run_command($cmd);
7dcb0697
AD
879
880 return undef;
881}
882
1597f1f9 883sub volume_rollback_is_possible {
3918b96a 884 my ($class, $scfg, $storeid, $volname, $snap) = @_;
1597f1f9 885
3918b96a 886 return 1;
1597f1f9
WL
887}
888
41dffa85
AD
889sub volume_snapshot_rollback {
890 my ($class, $scfg, $storeid, $volname, $snap) = @_;
891
6d788031 892 die "can't rollback snapshot this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
41dffa85 893
08480ce7 894 my $path = $class->filesystem_path($scfg, $volname);
41dffa85
AD
895
896 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-a', $snap, $path];
897
3f13fd7d 898 run_command($cmd);
41dffa85
AD
899
900 return undef;
901}
902
6000a061
AD
903sub volume_snapshot_delete {
904 my ($class, $scfg, $storeid, $volname, $snap, $running) = @_;
905
6d788031 906 die "can't delete snapshot for this image format\n" if $volname !~ m/\.(qcow2|qed)$/;
6000a061
AD
907
908 return 1 if $running;
909
08480ce7 910 my $path = $class->filesystem_path($scfg, $volname);
6000a061 911
399581a2
WB
912 $class->deactivate_volume($storeid, $scfg, $volname, $snap, {});
913
6000a061
AD
914 my $cmd = ['/usr/bin/qemu-img', 'snapshot','-d', $snap, $path];
915
3f13fd7d 916 run_command($cmd);
6000a061
AD
917
918 return undef;
919}
920
2c036838
SI
921sub volume_snapshot_needs_fsfreeze {
922
923 return 0;
924}
7118dd91
DM
925sub storage_can_replicate {
926 my ($class, $scfg, $storeid, $format) = @_;
927
928 return 0;
929}
930
f884fe11 931sub volume_has_feature {
e6f4eed4 932 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
f884fe11
AD
933
934 my $features = {
5649ccfe
AD
935 snapshot => { current => { qcow2 => 1}, snap => { qcow2 => 1} },
936 clone => { base => {qcow2 => 1, raw => 1, vmdk => 1} },
35533c68 937 template => { current => {qcow2 => 1, raw => 1, vmdk => 1, subvol => 1} },
5649ccfe 938 copy => { base => {qcow2 => 1, raw => 1, vmdk => 1},
22b8cf97
AD
939 current => {qcow2 => 1, raw => 1, vmdk => 1},
940 snap => {qcow2 => 1} },
baafddbd
DC
941 sparseinit => { base => {qcow2 => 1, raw => 1, vmdk => 1},
942 current => {qcow2 => 1, raw => 1, vmdk => 1} },
f884fe11
AD
943 };
944
e6f4eed4
FE
945 # clone_image creates a qcow2 volume
946 return 0 if $feature eq 'clone' &&
947 defined($opts->{valid_target_formats}) &&
948 !(grep { $_ eq 'qcow2' } @{$opts->{valid_target_formats}});
949
35533c68 950 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
dc4f2cb3
AD
951 $class->parse_volname($volname);
952
dc4f2cb3
AD
953 my $key = undef;
954 if($snapname){
2c5a7097 955 $key = 'snap';
dc4f2cb3
AD
956 }else{
957 $key = $isBase ? 'base' : 'current';
f884fe11 958 }
dc4f2cb3
AD
959
960 return 1 if defined($features->{$feature}->{$key}->{$format});
961
f884fe11
AD
962 return undef;
963}
964
1dc01b9f
DM
965sub list_images {
966 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
967
968 my $imagedir = $class->get_subdir($scfg, 'images');
969
970 my ($defFmt, $vaidFmts) = default_format($scfg);
045ae0a7 971 my $fmts = join ('|', @$vaidFmts);
1dc01b9f
DM
972
973 my $res = [];
974
975 foreach my $fn (<$imagedir/[0-9][0-9]*/*>) {
976
977 next if $fn !~ m!^(/.+/(\d+)/([^/]+\.($fmts)))$!;
978 $fn = $1; # untaint
979
980 my $owner = $2;
981 my $name = $3;
1dc01b9f 982
2502b33b 983 next if !$vollist && defined($vmid) && ($owner ne $vmid);
1dc01b9f 984
51eee96d 985 my ($size, $format, $used, $parent, $ctime) = file_size_info($fn);
35533c68 986 next if !($format && defined($size));
2502b33b
DM
987
988 my $volid;
989 if ($parent && $parent =~ m!^../(\d+)/([^/]+\.($fmts))$!) {
990 my ($basevmid, $basename) = ($1, $2);
991 $volid = "$storeid:$basevmid/$basename/$owner/$name";
992 } else {
993 $volid = "$storeid:$owner/$name";
994 }
1dc01b9f 995
2502b33b
DM
996 if ($vollist) {
997 my $found = grep { $_ eq $volid } @$vollist;
998 next if !$found;
1dc01b9f
DM
999 }
1000
51eee96d 1001 my $info = {
2502b33b 1002 volid => $volid, format => $format,
1a3459ac 1003 size => $size, vmid => $owner, used => $used, parent => $parent
2502b33b 1004 };
51eee96d
DM
1005
1006 $info->{ctime} = $ctime if $ctime;
1007
1008 push @$res, $info;
1dc01b9f
DM
1009 }
1010
1011 return $res;
1012}
1013
c2fc9fbe
DM
1014# list templates ($tt = <iso|vztmpl|backup|snippets>)
1015my $get_subdir_files = sub {
1016 my ($sid, $path, $tt, $vmid) = @_;
1017
1018 my $res = [];
1019
1020 foreach my $fn (<$path/*>) {
92ae59df
AA
1021 my $st = File::stat::stat($fn);
1022
3d10acf8 1023 next if (!$st || S_ISDIR($st->mode));
c2fc9fbe
DM
1024
1025 my $info;
1026
1027 if ($tt eq 'iso') {
4c693491 1028 next if $fn !~ m!/([^/]+$PVE::Storage::iso_extension_re)$!i;
c2fc9fbe
DM
1029
1030 $info = { volid => "$sid:iso/$1", format => 'iso' };
1031
1032 } elsif ($tt eq 'vztmpl') {
1033 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
1034
1035 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
1036
1037 } elsif ($tt eq 'backup') {
277cafc0 1038 next if $fn !~ m!/([^/]+\.(tgz|(?:(?:tar|vma)(?:\.(${\COMPRESSOR_RE}))?)))$!;
d260b9f3 1039 my $original = $fn;
1b396425 1040 my $format = $2;
40c795e7 1041 $fn = $1;
edb92f70 1042
4b702ac3 1043 # only match for VMID now, to avoid false positives (VMID in parent directory name)
edb92f70
FE
1044 next if defined($vmid) && $fn !~ m/\S+-$vmid-\S+/;
1045
40c795e7 1046 $info = { volid => "$sid:backup/$fn", format => $format };
1b396425 1047
e9667b34 1048 my $archive_info = eval { PVE::Storage::archive_info($fn) } // {};
fb821c18 1049
e9667b34 1050 $info->{ctime} = $archive_info->{ctime} if defined($archive_info->{ctime});
9c629b3e 1051
93afc379 1052 if (defined($vmid) || $fn =~ m!\-([1-9][0-9]{2,8})\-[^/]+\.${format}$!) {
1b396425
DC
1053 $info->{vmid} = $vmid // $1;
1054 }
1055
6fef456c
DC
1056 my $notes_fn = $original.NOTES_EXT;
1057 if (-f $notes_fn) {
1058 my $notes = PVE::Tools::file_read_firstline($notes_fn);
1059 $info->{notes} = $notes if defined($notes);
d260b9f3
DC
1060 }
1061
c2fc9fbe
DM
1062 } elsif ($tt eq 'snippets') {
1063
1064 $info = {
1065 volid => "$sid:snippets/". basename($fn),
1066 format => 'snippet',
1067 };
1068 }
1069
92ae59df
AA
1070 $info->{size} = $st->size;
1071 $info->{ctime} //= $st->ctime;
c2fc9fbe
DM
1072
1073 push @$res, $info;
1074 }
1075
1076 return $res;
1077};
1078
1079sub list_volumes {
1080 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
1081
1082 my $res = [];
5dae1a31 1083 my $vmlist = PVE::Cluster::get_vmlist();
a4e41b0b 1084 foreach my $type (@$content_types) {
c2fc9fbe
DM
1085 my $data;
1086
a4e41b0b 1087 if ($type eq 'images' || $type eq 'rootdir') {
c2fc9fbe 1088 $data = $class->list_images($storeid, $scfg, $vmid);
a14e0a5e 1089 } elsif ($scfg->{path}) {
a4e41b0b 1090 my $path = $class->get_subdir($scfg, $type);
a14e0a5e 1091
a4e41b0b 1092 if ($type eq 'iso' && !defined($vmid)) {
a14e0a5e 1093 $data = $get_subdir_files->($storeid, $path, 'iso');
a4e41b0b 1094 } elsif ($type eq 'vztmpl'&& !defined($vmid)) {
a14e0a5e 1095 $data = $get_subdir_files->($storeid, $path, 'vztmpl');
a4e41b0b 1096 } elsif ($type eq 'backup') {
a14e0a5e 1097 $data = $get_subdir_files->($storeid, $path, 'backup', $vmid);
a4e41b0b 1098 } elsif ($type eq 'snippets') {
a14e0a5e
FG
1099 $data = $get_subdir_files->($storeid, $path, 'snippets');
1100 }
c2fc9fbe
DM
1101 }
1102
1103 next if !$data;
1104
1105 foreach my $item (@$data) {
a4e41b0b 1106 if ($type eq 'images' || $type eq 'rootdir') {
a420842d
FG
1107 my $vminfo = $vmlist->{ids}->{$item->{vmid}};
1108 my $vmtype;
1109 if (defined($vminfo)) {
1110 $vmtype = $vminfo->{type};
1111 }
5dae1a31
TM
1112 if (defined($vmtype) && $vmtype eq 'lxc') {
1113 $item->{content} = 'rootdir';
1114 } else {
1115 $item->{content} = 'images';
1116 }
0877df04 1117 next if $type ne $item->{content};
5dae1a31 1118 } else {
a4e41b0b 1119 $item->{content} = $type;
5dae1a31
TM
1120 }
1121
c2fc9fbe
DM
1122 push @$res, $item;
1123 }
1124 }
1125
1126 return $res;
1127}
1128
1dc01b9f
DM
1129sub status {
1130 my ($class, $storeid, $scfg, $cache) = @_;
1131
1132 my $path = $scfg->{path};
1133
1134 die "storage definintion has no path\n" if !$path;
045ae0a7 1135
1dc01b9f
DM
1136 my $timeout = 2;
1137 my $res = PVE::Tools::df($path, $timeout);
1138
1139 return undef if !$res || !$res->{total};
1140
1141 return ($res->{total}, $res->{avail}, $res->{used}, 1);
1142}
1143
aefe82ea 1144sub volume_snapshot_list {
8b622c2d 1145 my ($class, $scfg, $storeid, $volname) = @_;
aefe82ea
WL
1146
1147 # implement in subclass
1148 die "Volume_snapshot_list is not implemented for $class";
1149
636ac5b8 1150 # return an empty array if dataset does not exist.
aefe82ea
WL
1151}
1152
1dc01b9f
DM
1153sub activate_storage {
1154 my ($class, $storeid, $scfg, $cache) = @_;
1155
1156 my $path = $scfg->{path};
1157
1158 die "storage definintion has no path\n" if !$path;
1159
e53050ed
EK
1160 # this path test may hang indefinitely on unresponsive mounts
1161 my $timeout = 2;
1162 if (! PVE::Tools::run_fork_with_timeout($timeout, sub {-d $path})) {
1163 die "unable to activate storage '$storeid' - " .
1164 "directory '$path' does not exist or is unreachable\n";
1165 }
1166
1dc01b9f 1167
c7616abc
WB
1168 return if defined($scfg->{mkdir}) && !$scfg->{mkdir};
1169
1dc01b9f
DM
1170 if (defined($scfg->{content})) {
1171 foreach my $vtype (keys %$vtype_subdirs) {
6bcc16d7
DM
1172 # OpenVZMigrate uses backup (dump) dir
1173 if (defined($scfg->{content}->{$vtype}) ||
1174 ($vtype eq 'backup' && defined($scfg->{content}->{'rootdir'}))) {
1175 my $subdir = $class->get_subdir($scfg, $vtype);
1176 mkpath $subdir if $subdir ne $path;
1177 }
1dc01b9f
DM
1178 }
1179 }
1180}
1181
1182sub deactivate_storage {
1183 my ($class, $storeid, $scfg, $cache) = @_;
1184
1185 # do nothing by default
1186}
1187
40d69893
DM
1188sub map_volume {
1189 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1190
d560ec28
ML
1191 my ($path) = $class->path($scfg, $volname, $storeid, $snapname);
1192 return $path;
40d69893
DM
1193}
1194
1195sub unmap_volume {
1196 my ($class, $storeid, $scfg, $volname, $snapname) = @_;
1197
1198 return 1;
1199}
1200
1dc01b9f 1201sub activate_volume {
02e797b8 1202 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1dc01b9f 1203
02e797b8 1204 my $path = $class->filesystem_path($scfg, $volname, $snapname);
1dc01b9f
DM
1205
1206 # check is volume exists
1207 if ($scfg->{path}) {
1208 die "volume '$storeid:$volname' does not exist\n" if ! -e $path;
1209 } else {
1210 die "volume '$storeid:$volname' does not exist\n" if ! -b $path;
1211 }
1212}
1213
1214sub deactivate_volume {
02e797b8 1215 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
1dc01b9f
DM
1216
1217 # do nothing by default
1218}
1219
c9eeac01
AD
1220sub check_connection {
1221 my ($class, $storeid, $scfg) = @_;
1222 # do nothing by default
1223 return 1;
1224}
1225
8f26b391
FE
1226sub prune_backups {
1227 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1228
1229 $logfunc //= sub { print "$_[1]\n" };
1230
1231 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
1232
1233 my $backup_groups = {};
1234 my $prune_list = [];
1235
1236 foreach my $backup (@{$backups}) {
1237 my $volid = $backup->{volid};
8f26b391
FE
1238 my $archive_info = eval { PVE::Storage::archive_info($volid) } // {};
1239 my $backup_type = $archive_info->{type} // 'unknown';
68ce0b31 1240 my $backup_vmid = $archive_info->{vmid} // $backup->{vmid};
8f26b391
FE
1241
1242 next if defined($type) && $type ne $backup_type;
1243
1244 my $prune_entry = {
1245 ctime => $backup->{ctime},
1246 type => $backup_type,
1247 volid => $volid,
1248 };
1249
1250 $prune_entry->{vmid} = $backup_vmid if defined($backup_vmid);
1251
1252 if ($archive_info->{is_std_name}) {
cba2b7c1
TL
1253 die "internal error - got no VMID\n" if !defined($backup_vmid);
1254 die "internal error - got wrong VMID '$backup_vmid' != '$vmid'\n"
1255 if defined($vmid) && $backup_vmid ne $vmid;
68ce0b31 1256
8f26b391
FE
1257 $prune_entry->{ctime} = $archive_info->{ctime};
1258 my $group = "$backup_type/$backup_vmid";
1259 push @{$backup_groups->{$group}}, $prune_entry;
1260 } else {
1261 # ignore backups that don't use the standard naming scheme
1262 $prune_entry->{mark} = 'protected';
1263 }
1264
1265 push @{$prune_list}, $prune_entry;
1266 }
1267
1268 foreach my $backup_group (values %{$backup_groups}) {
1269 PVE::Storage::prune_mark_backup_group($backup_group, $keep);
1270 }
1271
1272 my $failed;
1273 if (!$dryrun) {
1274 foreach my $prune_entry (@{$prune_list}) {
1275 next if $prune_entry->{mark} ne 'remove';
1276
1277 my $volid = $prune_entry->{volid};
1278 $logfunc->('info', "removing backup '$volid'");
1279 eval {
1280 my (undef, $volname) = parse_volume_id($volid);
1281 my $archive_path = $class->filesystem_path($scfg, $volname);
1282 PVE::Storage::archive_remove($archive_path);
1283 };
1284 if (my $err = $@) {
1285 $logfunc->('err', "error when removing backup '$volid' - $err\n");
1286 $failed = 1;
1287 }
1288 }
1289 }
1290 die "error pruning backups - check log\n" if $failed;
1291
1292 return $prune_list;
1293}
1294
e1f6cb39
DM
1295# Import/Export interface:
1296# Any path based storage is assumed to support 'raw' and 'tar' streams, so
1297# the default implementations will return this if $scfg->{path} is set,
1298# mimicking the old PVE::Storage::storage_migrate() function.
1299#
1300# Plugins may fall back to PVE::Storage::Plugin::volume_{export,import}...
1301# functions in case the format doesn't match their specialized
1302# implementations to reuse the raw/tar code.
1303#
1304# Format specification:
1305# The following formats are all prefixed with image information in the form
1306# of a 64 bit little endian unsigned integer (pack('Q<')) in order to be able
1307# to preallocate the image on storages which require it.
1308#
1309# raw+size: (image files only)
1310# A raw binary data stream such as produced via `dd if=TheImageFile`.
1311# qcow2+size, vmdk: (image files only)
1312# A raw qcow2/vmdk/... file such as produced via `dd if=some.qcow2` for
1313# files which are already in qcow2 format, or via `qemu-img convert`.
1314# Note that these formats are only valid with $with_snapshots being true.
1315# tar+size: (subvolumes only)
6b3a4a25
WB
1316# A GNU tar stream containing just the inner contents of the subvolume.
1317# This does not distinguish between the contents of a privileged or
1318# unprivileged container. In other words, this is from the root user
1319# namespace's point of view with no uid-mapping in effect.
1320# As produced via `tar -C vm-100-disk-1.subvol -cpf TheOutputFile.dat .`
e1f6cb39
DM
1321
1322# Plugins may reuse these helpers. Changes to the header format should be
1323# reflected by changes to the function prototypes.
1324sub write_common_header($$) {
1325 my ($fh, $image_size_in_bytes) = @_;
1326 syswrite($fh, pack("Q<", $image_size_in_bytes), 8);
1327}
1328
1329sub read_common_header($) {
1330 my ($fh) = @_;
1331 sysread($fh, my $size, 8);
1332 $size = unpack('Q<', $size);
f105c176 1333 die "import: no size found in export header, aborting.\n" if !defined($size);
b5eff97d 1334 die "import: got a bad size (not a multiple of 1K), aborting.\n" if ($size&1023);
e1f6cb39
DM
1335 # Size is in bytes!
1336 return $size;
1337}
1338
47f37b53
WB
1339# Export a volume into a file handle as a stream of desired format.
1340sub volume_export {
1341 my ($class, $scfg, $storeid, $fh, $volname, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
e1f6cb39
DM
1342 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1343 my $file = $class->path($scfg, $volname, $storeid)
1344 or goto unsupported;
1345 my ($size, $file_format) = file_size_info($file);
1346
1347 if ($format eq 'raw+size') {
1348 goto unsupported if $with_snapshots || $file_format eq 'subvol';
1349 write_common_header($fh, $size);
1350 if ($file_format eq 'raw') {
1351 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1352 } else {
1353 run_command(['qemu-img', 'convert', '-f', $file_format, '-O', 'raw', $file, '/dev/stdout'],
1354 output => '>&'.fileno($fh));
1355 }
1356 return;
1357 } elsif ($format =~ /^(qcow2|vmdk)\+size$/) {
1358 my $data_format = $1;
1359 goto unsupported if !$with_snapshots || $file_format ne $data_format;
1360 write_common_header($fh, $size);
1361 run_command(['dd', "if=$file", "bs=4k"], output => '>&'.fileno($fh));
1362 return;
1363 } elsif ($format eq 'tar+size') {
1364 goto unsupported if $file_format ne 'subvol';
1365 write_common_header($fh, $size);
6b3a4a25 1366 run_command(['tar', @COMMON_TAR_FLAGS, '-cf', '-', '-C', $file, '.'],
e1f6cb39
DM
1367 output => '>&'.fileno($fh));
1368 return;
1369 }
1370 }
1371 unsupported:
1372 die "volume export format $format not available for $class";
47f37b53
WB
1373}
1374
d390328b
WB
1375sub volume_export_formats {
1376 my ($class, $scfg, $storeid, $volname, $snapshot, $base_snapshot, $with_snapshots) = @_;
e1f6cb39
DM
1377 if ($scfg->{path} && !defined($snapshot) && !defined($base_snapshot)) {
1378 my $file = $class->path($scfg, $volname, $storeid)
1379 or return;
1380 my ($size, $format) = file_size_info($file);
1381
1382 if ($with_snapshots) {
1383 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1384 return ();
1385 }
1386 return ('tar+size') if $format eq 'subvol';
1387 return ('raw+size');
1388 }
1389 return ();
d390328b
WB
1390}
1391
47f37b53
WB
1392# Import data from a stream, creating a new or replacing or adding to an existing volume.
1393sub volume_import {
a97d3ee4 1394 my ($class, $scfg, $storeid, $fh, $volname, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
e1f6cb39
DM
1395
1396 die "volume import format '$format' not available for $class\n"
1397 if $format !~ /^(raw|tar|qcow2|vmdk)\+size$/;
1398 my $data_format = $1;
1399
1400 die "format $format cannot be imported without snapshots\n"
1401 if !$with_snapshots && ($data_format eq 'qcow2' || $data_format eq 'vmdk');
1402 die "format $format cannot be imported with snapshots\n"
1403 if $with_snapshots && ($data_format eq 'raw' || $data_format eq 'tar');
1404
1405 my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $file_format) =
1406 $class->parse_volname($volname);
1407
1408 # XXX: Should we bother with conversion routines at this level? This won't
1409 # happen without manual CLI usage, so for now we just error out...
1410 die "cannot import format $format into a file of format $file_format\n"
1411 if $data_format ne $file_format && !($data_format eq 'tar' && $file_format eq 'subvol');
1412
1413 # Check for an existing file first since interrupting alloc_image doesn't
1414 # free it.
1415 my $file = $class->path($scfg, $volname, $storeid);
a97d3ee4
FE
1416 if (-e $file) {
1417 die "file '$file' already exists\n" if !$allow_rename;
1418 warn "file '$file' already exists - importing with a different name\n";
1419 $name = undef;
1420 }
e1f6cb39
DM
1421
1422 my ($size) = read_common_header($fh);
1423 $size = int($size/1024);
1424
1425 eval {
1426 my $allocname = $class->alloc_image($storeid, $scfg, $vmid, $file_format, $name, $size);
a97d3ee4
FE
1427 my $oldname = $volname;
1428 $volname = $allocname;
1429 if (defined($name) && $allocname ne $oldname) {
e1f6cb39
DM
1430 die "internal error: unexpected allocated name: '$allocname' != '$oldname'\n";
1431 }
1432 my $file = $class->path($scfg, $volname, $storeid)
1433 or die "internal error: failed to get path to newly allocated volume $volname\n";
1434 if ($data_format eq 'raw' || $data_format eq 'qcow2' || $data_format eq 'vmdk') {
1435 run_command(['dd', "of=$file", 'conv=sparse', 'bs=64k'],
1436 input => '<&'.fileno($fh));
1437 } elsif ($data_format eq 'tar') {
6b3a4a25 1438 run_command(['tar', @COMMON_TAR_FLAGS, '-C', $file, '-xf', '-'],
e1f6cb39
DM
1439 input => '<&'.fileno($fh));
1440 } else {
1441 die "volume import format '$format' not available for $class";
1442 }
1443 };
1444 if (my $err = $@) {
1445 eval { $class->free_image($storeid, $scfg, $volname, 0, $file_format) };
1446 warn $@ if $@;
1447 die $err;
1448 }
a97d3ee4
FE
1449
1450 return "$storeid:$volname";
47f37b53 1451}
e47e548e 1452
d390328b
WB
1453sub volume_import_formats {
1454 my ($class, $scfg, $storeid, $volname, $base_snapshot, $with_snapshots) = @_;
e1f6cb39
DM
1455 if ($scfg->{path} && !defined($base_snapshot)) {
1456 my $format = ($class->parse_volname($volname))[6];
1457 if ($with_snapshots) {
1458 return ($format.'+size') if ($format eq 'qcow2' || $format eq 'vmdk');
1459 return ();
1460 }
1461 return ('tar+size') if $format eq 'subvol';
1462 return ('raw+size');
1463 }
1464 return ();
d390328b
WB
1465}
1466
1dc01b9f 14671;