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