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