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