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