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