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