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