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