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