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