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