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