]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage.pm
8d904d74903e8af2d3780d24e6949c8b63e2ccf9
[pve-storage.git] / PVE / Storage.pm
1 package PVE::Storage;
2
3 use strict;
4 use warnings;
5 use Data::Dumper;
6
7 use POSIX;
8 use IO::Select;
9 use IO::File;
10 use IO::Socket::IP;
11 use IPC::Open3;
12 use File::Basename;
13 use File::Path;
14 use Cwd 'abs_path';
15 use Socket;
16 use Time::Local qw(timelocal);
17
18 use PVE::Tools qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
19 use PVE::Cluster qw(cfs_read_file cfs_write_file cfs_lock_file);
20 use PVE::DataCenterConfig;
21 use PVE::Exception qw(raise_param_exc raise);
22 use PVE::JSONSchema;
23 use PVE::INotify;
24 use PVE::RPCEnvironment;
25 use PVE::SSHInfo;
26
27 use PVE::Storage::Plugin;
28 use PVE::Storage::DirPlugin;
29 use PVE::Storage::LVMPlugin;
30 use PVE::Storage::LvmThinPlugin;
31 use PVE::Storage::NFSPlugin;
32 use PVE::Storage::CIFSPlugin;
33 use PVE::Storage::ISCSIPlugin;
34 use PVE::Storage::RBDPlugin;
35 use PVE::Storage::CephFSPlugin;
36 use PVE::Storage::ISCSIDirectPlugin;
37 use PVE::Storage::GlusterfsPlugin;
38 use PVE::Storage::ZFSPoolPlugin;
39 use PVE::Storage::ZFSPlugin;
40 use PVE::Storage::DRBDPlugin;
41 use PVE::Storage::PBSPlugin;
42
43 # Storage API version. Increment it on changes in storage API interface.
44 use constant APIVER => 8;
45 # Age is the number of versions we're backward compatible with.
46 # This is like having 'current=APIVER' and age='APIAGE' in libtool,
47 # see https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
48 use constant APIAGE => 7;
49
50 # load standard plugins
51 PVE::Storage::DirPlugin->register();
52 PVE::Storage::LVMPlugin->register();
53 PVE::Storage::LvmThinPlugin->register();
54 PVE::Storage::NFSPlugin->register();
55 PVE::Storage::CIFSPlugin->register();
56 PVE::Storage::ISCSIPlugin->register();
57 PVE::Storage::RBDPlugin->register();
58 PVE::Storage::CephFSPlugin->register();
59 PVE::Storage::ISCSIDirectPlugin->register();
60 PVE::Storage::GlusterfsPlugin->register();
61 PVE::Storage::ZFSPoolPlugin->register();
62 PVE::Storage::ZFSPlugin->register();
63 PVE::Storage::DRBDPlugin->register();
64 PVE::Storage::PBSPlugin->register();
65
66 # load third-party plugins
67 if ( -d '/usr/share/perl5/PVE/Storage/Custom' ) {
68 dir_glob_foreach('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
69 my ($file) = @_;
70 my $modname = 'PVE::Storage::Custom::' . $file;
71 $modname =~ s!\.pm$!!;
72 $file = 'PVE/Storage/Custom/' . $file;
73
74 eval {
75 require $file;
76
77 # Check perl interface:
78 die "not derived from PVE::Storage::Plugin\n"
79 if !$modname->isa('PVE::Storage::Plugin');
80 die "does not provide an api() method\n"
81 if !$modname->can('api');
82 # Check storage API version and that file is really storage plugin.
83 my $version = $modname->api();
84 die "implements an API version newer than current ($version > " . APIVER . ")\n"
85 if $version > APIVER;
86 my $min_version = (APIVER - APIAGE);
87 die "API version too old, please update the plugin ($version < $min_version)\n"
88 if $version < $min_version;
89 import $file;
90 $modname->register();
91
92 # If we got this far and the API version is not the same, make some
93 # noise:
94 warn "Plugin \"$modname\" is implementing an older storage API, an upgrade is recommended\n"
95 if $version != APIVER;
96 };
97 if ($@) {
98 warn "Error loading storage plugin \"$modname\": $@";
99 }
100 });
101 }
102
103 # initialize all plugins
104 PVE::Storage::Plugin->init();
105
106 my $UDEVADM = '/sbin/udevadm';
107
108 our $iso_extension_re = qr/\.(?:iso|img)/i;
109
110 # PVE::Storage utility functions
111
112 sub config {
113 return cfs_read_file("storage.cfg");
114 }
115
116 sub write_config {
117 my ($cfg) = @_;
118
119 cfs_write_file('storage.cfg', $cfg);
120 }
121
122 sub lock_storage_config {
123 my ($code, $errmsg) = @_;
124
125 cfs_lock_file("storage.cfg", undef, $code);
126 my $err = $@;
127 if ($err) {
128 $errmsg ? die "$errmsg: $err" : die $err;
129 }
130 }
131
132 # FIXME remove maxfiles for PVE 7.0
133 my $convert_maxfiles_to_prune_backups = sub {
134 my ($scfg) = @_;
135
136 return if !$scfg;
137
138 my $maxfiles = delete $scfg->{maxfiles};
139
140 if (!defined($scfg->{'prune-backups'}) && defined($maxfiles)) {
141 my $prune_backups;
142 if ($maxfiles) {
143 $prune_backups = { 'keep-last' => $maxfiles };
144 } else { # maxfiles 0 means no limit
145 $prune_backups = { 'keep-all' => 1 };
146 }
147 $scfg->{'prune-backups'} = PVE::JSONSchema::print_property_string(
148 $prune_backups,
149 'prune-backups'
150 );
151 }
152 };
153
154 sub storage_config {
155 my ($cfg, $storeid, $noerr) = @_;
156
157 die "no storage ID specified\n" if !$storeid;
158
159 my $scfg = $cfg->{ids}->{$storeid};
160
161 die "storage '$storeid' does not exist\n" if (!$noerr && !$scfg);
162
163 $convert_maxfiles_to_prune_backups->($scfg);
164
165 return $scfg;
166 }
167
168 sub storage_check_node {
169 my ($cfg, $storeid, $node, $noerr) = @_;
170
171 my $scfg = storage_config($cfg, $storeid);
172
173 if ($scfg->{nodes}) {
174 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
175 if (!$scfg->{nodes}->{$node}) {
176 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
177 return undef;
178 }
179 }
180
181 return $scfg;
182 }
183
184 sub storage_check_enabled {
185 my ($cfg, $storeid, $node, $noerr) = @_;
186
187 my $scfg = storage_config($cfg, $storeid);
188
189 if ($scfg->{disable}) {
190 die "storage '$storeid' is disabled\n" if !$noerr;
191 return undef;
192 }
193
194 return storage_check_node($cfg, $storeid, $node, $noerr);
195 }
196
197 # storage_can_replicate:
198 # return true if storage supports replication
199 # (volumes alocated with vdisk_alloc() has replication feature)
200 sub storage_can_replicate {
201 my ($cfg, $storeid, $format) = @_;
202
203 my $scfg = storage_config($cfg, $storeid);
204 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
205 return $plugin->storage_can_replicate($scfg, $storeid, $format);
206 }
207
208 sub storage_ids {
209 my ($cfg) = @_;
210
211 return keys %{$cfg->{ids}};
212 }
213
214 sub file_size_info {
215 my ($filename, $timeout) = @_;
216
217 return PVE::Storage::Plugin::file_size_info($filename, $timeout);
218 }
219
220 sub volume_size_info {
221 my ($cfg, $volid, $timeout) = @_;
222
223 my ($storeid, $volname) = parse_volume_id($volid, 1);
224 if ($storeid) {
225 my $scfg = storage_config($cfg, $storeid);
226 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
227 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
228 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
229 return file_size_info($volid, $timeout);
230 } else {
231 return 0;
232 }
233 }
234
235 sub volume_resize {
236 my ($cfg, $volid, $size, $running) = @_;
237
238 my $padding = (1024 - $size % 1024) % 1024;
239 $size = $size + $padding;
240
241 my ($storeid, $volname) = parse_volume_id($volid, 1);
242 if ($storeid) {
243 my $scfg = storage_config($cfg, $storeid);
244 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
245 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
246 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
247 die "resize file/device '$volid' is not possible\n";
248 } else {
249 die "unable to parse volume ID '$volid'\n";
250 }
251 }
252
253 sub volume_rollback_is_possible {
254 my ($cfg, $volid, $snap) = @_;
255
256 my ($storeid, $volname) = parse_volume_id($volid, 1);
257 if ($storeid) {
258 my $scfg = storage_config($cfg, $storeid);
259 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
260 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
261 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
262 die "snapshot rollback file/device '$volid' is not possible\n";
263 } else {
264 die "unable to parse volume ID '$volid'\n";
265 }
266 }
267
268 sub volume_snapshot {
269 my ($cfg, $volid, $snap) = @_;
270
271 my ($storeid, $volname) = parse_volume_id($volid, 1);
272 if ($storeid) {
273 my $scfg = storage_config($cfg, $storeid);
274 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
275 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
276 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
277 die "snapshot file/device '$volid' is not possible\n";
278 } else {
279 die "unable to parse volume ID '$volid'\n";
280 }
281 }
282
283 sub volume_snapshot_rollback {
284 my ($cfg, $volid, $snap) = @_;
285
286 my ($storeid, $volname) = parse_volume_id($volid, 1);
287 if ($storeid) {
288 my $scfg = storage_config($cfg, $storeid);
289 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
290 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
291 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
292 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
293 die "snapshot rollback file/device '$volid' is not possible\n";
294 } else {
295 die "unable to parse volume ID '$volid'\n";
296 }
297 }
298
299 sub volume_snapshot_delete {
300 my ($cfg, $volid, $snap, $running) = @_;
301
302 my ($storeid, $volname) = parse_volume_id($volid, 1);
303 if ($storeid) {
304 my $scfg = storage_config($cfg, $storeid);
305 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
306 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
307 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
308 die "snapshot delete file/device '$volid' is not possible\n";
309 } else {
310 die "unable to parse volume ID '$volid'\n";
311 }
312 }
313
314 # check if a filesystem on top of a volume needs to flush its journal for
315 # consistency (see fsfreeze(8)) before a snapshot is taken - needed for
316 # container mountpoints
317 sub volume_snapshot_needs_fsfreeze {
318 my ($cfg, $volid) = @_;
319
320 my ($storeid, $volname) = parse_volume_id($volid);
321 my $scfg = storage_config($cfg, $storeid);
322 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
323 return $plugin->volume_snapshot_needs_fsfreeze();
324 }
325
326 # check if a volume or snapshot supports a given feature
327 # $feature - one of:
328 # clone - linked clone is possible
329 # copy - full clone is possible
330 # replicate - replication is possible
331 # snapshot - taking a snapshot is possible
332 # sparseinit - volume is sparsely initialized
333 # template - conversion to base image is possible
334 # $snap - check if the feature is supported for a given snapshot
335 # $running - if the guest owning the volume is running
336 # $opts - hash with further options:
337 # valid_target_formats - list of formats for the target of a copy/clone
338 # operation that the caller could work with. The
339 # format of $volid is always considered valid and if
340 # no list is specified, all formats are considered valid.
341 sub volume_has_feature {
342 my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
343
344 my ($storeid, $volname) = parse_volume_id($volid, 1);
345 if ($storeid) {
346 my $scfg = storage_config($cfg, $storeid);
347 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
348 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running, $opts);
349 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
350 return undef;
351 } else {
352 return undef;
353 }
354 }
355
356 sub volume_snapshot_list {
357 my ($cfg, $volid) = @_;
358
359 my ($storeid, $volname) = parse_volume_id($volid, 1);
360 if ($storeid) {
361 my $scfg = storage_config($cfg, $storeid);
362 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
363 return $plugin->volume_snapshot_list($scfg, $storeid, $volname);
364 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
365 die "send file/device '$volid' is not possible\n";
366 } else {
367 die "unable to parse volume ID '$volid'\n";
368 }
369 # return an empty array if dataset does not exist.
370 }
371
372 sub get_image_dir {
373 my ($cfg, $storeid, $vmid) = @_;
374
375 my $scfg = storage_config($cfg, $storeid);
376 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
377
378 my $path = $plugin->get_subdir($scfg, 'images');
379
380 return $vmid ? "$path/$vmid" : $path;
381 }
382
383 sub get_private_dir {
384 my ($cfg, $storeid, $vmid) = @_;
385
386 my $scfg = storage_config($cfg, $storeid);
387 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
388
389 my $path = $plugin->get_subdir($scfg, 'rootdir');
390
391 return $vmid ? "$path/$vmid" : $path;
392 }
393
394 sub get_iso_dir {
395 my ($cfg, $storeid) = @_;
396
397 my $scfg = storage_config($cfg, $storeid);
398 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
399
400 return $plugin->get_subdir($scfg, 'iso');
401 }
402
403 sub get_vztmpl_dir {
404 my ($cfg, $storeid) = @_;
405
406 my $scfg = storage_config($cfg, $storeid);
407 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
408
409 return $plugin->get_subdir($scfg, 'vztmpl');
410 }
411
412 sub get_backup_dir {
413 my ($cfg, $storeid) = @_;
414
415 my $scfg = storage_config($cfg, $storeid);
416 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
417
418 return $plugin->get_subdir($scfg, 'backup');
419 }
420
421 # library implementation
422
423 sub parse_vmid {
424 my $vmid = shift;
425
426 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
427
428 return int($vmid);
429 }
430
431 # NOTE: basename and basevmid are always undef for LVM-thin, where the
432 # clone -> base reference is not encoded in the volume ID.
433 # see note in PVE::Storage::LvmThinPlugin for details.
434 sub parse_volname {
435 my ($cfg, $volid) = @_;
436
437 my ($storeid, $volname) = parse_volume_id($volid);
438
439 my $scfg = storage_config($cfg, $storeid);
440
441 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
442
443 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
444
445 return $plugin->parse_volname($volname);
446 }
447
448 sub parse_volume_id {
449 my ($volid, $noerr) = @_;
450
451 return PVE::Storage::Plugin::parse_volume_id($volid, $noerr);
452 }
453
454 # test if we have read access to volid
455 sub check_volume_access {
456 my ($rpcenv, $user, $cfg, $vmid, $volid) = @_;
457
458 my ($sid, $volname) = parse_volume_id($volid, 1);
459 if ($sid) {
460 my ($vtype, undef, $ownervm) = parse_volname($cfg, $volid);
461 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
462 # require at least read access to storage, (custom) templates/ISOs could be sensitive
463 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
464 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
465 # we are owner - allow access
466 } elsif ($vtype eq 'backup' && $ownervm) {
467 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
468 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
469 } else {
470 # allow if we are Datastore administrator
471 $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate']);
472 }
473 } else {
474 die "Only root can pass arbitrary filesystem paths."
475 if $user ne 'root@pam';
476 }
477
478 return undef;
479 }
480
481 my $volume_is_base_and_used__no_lock = sub {
482 my ($scfg, $storeid, $plugin, $volname) = @_;
483
484 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
485 $plugin->parse_volname($volname);
486
487 if ($isBase) {
488 my $vollist = $plugin->list_images($storeid, $scfg);
489 foreach my $info (@$vollist) {
490 my (undef, $tmpvolname) = parse_volume_id($info->{volid});
491 my $basename = undef;
492 my $basevmid = undef;
493
494 eval{
495 (undef, undef, undef, $basename, $basevmid) =
496 $plugin->parse_volname($tmpvolname);
497 };
498
499 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
500 return 1;
501 }
502 }
503 }
504 return 0;
505 };
506
507 # NOTE: this check does not work for LVM-thin, where the clone -> base
508 # reference is not encoded in the volume ID.
509 # see note in PVE::Storage::LvmThinPlugin for details.
510 sub volume_is_base_and_used {
511 my ($cfg, $volid) = @_;
512
513 my ($storeid, $volname) = parse_volume_id($volid);
514 my $scfg = storage_config($cfg, $storeid);
515 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
516
517 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
518 return &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
519 });
520 }
521
522 # try to map a filesystem path to a volume identifier
523 sub path_to_volume_id {
524 my ($cfg, $path) = @_;
525
526 my $ids = $cfg->{ids};
527
528 my ($sid, $volname) = parse_volume_id($path, 1);
529 if ($sid) {
530 if (my $scfg = $ids->{$sid}) {
531 if ($scfg->{path}) {
532 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
533 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
534 return ($vtype, $path);
535 }
536 }
537 return ('');
538 }
539
540 # Note: abs_path() return undef if $path doesn not exist
541 # for example when nfs storage is not mounted
542 $path = abs_path($path) || $path;
543
544 foreach my $sid (keys %$ids) {
545 my $scfg = $ids->{$sid};
546 next if !$scfg->{path};
547 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
548 my $imagedir = $plugin->get_subdir($scfg, 'images');
549 my $isodir = $plugin->get_subdir($scfg, 'iso');
550 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
551 my $backupdir = $plugin->get_subdir($scfg, 'backup');
552 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
553 my $snippetsdir = $plugin->get_subdir($scfg, 'snippets');
554
555 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
556 my $vmid = $1;
557 my $name = $2;
558
559 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
560 foreach my $info (@$vollist) {
561 my ($storeid, $volname) = parse_volume_id($info->{volid});
562 my $volpath = $plugin->path($scfg, $volname, $storeid);
563 if ($volpath eq $path) {
564 return ('images', $info->{volid});
565 }
566 }
567 } elsif ($path =~ m!^$isodir/([^/]+$iso_extension_re)$!) {
568 my $name = $1;
569 return ('iso', "$sid:iso/$name");
570 } elsif ($path =~ m!^$tmpldir/([^/]+\.tar\.gz)$!) {
571 my $name = $1;
572 return ('vztmpl', "$sid:vztmpl/$name");
573 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
574 my $vmid = $1;
575 return ('rootdir', "$sid:rootdir/$vmid");
576 } elsif ($path =~ m!^$backupdir/([^/]+\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)))$!) {
577 my $name = $1;
578 return ('backup', "$sid:backup/$name");
579 } elsif ($path =~ m!^$snippetsdir/([^/]+)$!) {
580 my $name = $1;
581 return ('snippets', "$sid:snippets/$name");
582 }
583 }
584
585 # can't map path to volume id
586 return ('');
587 }
588
589 sub path {
590 my ($cfg, $volid, $snapname) = @_;
591
592 my ($storeid, $volname) = parse_volume_id($volid);
593
594 my $scfg = storage_config($cfg, $storeid);
595
596 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
597 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
598 return wantarray ? ($path, $owner, $vtype) : $path;
599 }
600
601 sub abs_filesystem_path {
602 my ($cfg, $volid) = @_;
603
604 my $path;
605 if (parse_volume_id ($volid, 1)) {
606 activate_volumes($cfg, [ $volid ]);
607 $path = PVE::Storage::path($cfg, $volid);
608 } else {
609 if (-f $volid) {
610 my $abspath = abs_path($volid);
611 if ($abspath && $abspath =~ m|^(/.+)$|) {
612 $path = $1; # untaint any path
613 }
614 }
615 }
616
617 die "can't find file '$volid'\n" if !($path && -f $path);
618
619 return $path;
620 }
621
622 my $volname_for_storage = sub {
623 my ($cfg, $volid, $target_storeid) = @_;
624
625 my (undef, $name, $vmid, undef, undef, undef, $format) = parse_volname($cfg, $volid);
626 my $target_scfg = storage_config($cfg, $target_storeid);
627
628 my (undef, $valid_formats) = PVE::Storage::Plugin::default_format($target_scfg);
629 my $format_is_valid = grep { $_ eq $format } @$valid_formats;
630 die "unsupported format '$format' for storage type $target_scfg->{type}\n" if !$format_is_valid;
631
632 (my $name_without_extension = $name) =~ s/\.$format$//;
633
634 if ($target_scfg->{path}) {
635 return "$vmid/$name_without_extension.$format";
636 } else {
637 return "$name_without_extension";
638 }
639 };
640
641 sub storage_migrate {
642 my ($cfg, $volid, $target_sshinfo, $target_storeid, $opts, $logfunc) = @_;
643
644 my $base_snapshot = $opts->{base_snapshot};
645 my $snapshot = $opts->{snapshot};
646 my $ratelimit_bps = $opts->{ratelimit_bps};
647 my $insecure = $opts->{insecure};
648 my $with_snapshots = $opts->{with_snapshots} ? 1 : 0;
649 my $allow_rename = $opts->{allow_rename} ? 1 : 0;
650
651 my ($storeid, $volname) = parse_volume_id($volid);
652
653 my $scfg = storage_config($cfg, $storeid);
654
655 # no need to migrate shared content
656 return $volid if $storeid eq $target_storeid && $scfg->{shared};
657
658 my $tcfg = storage_config($cfg, $target_storeid);
659
660 my $target_volname;
661 if ($opts->{target_volname}) {
662 $target_volname = $opts->{target_volname};
663 } elsif ($scfg->{type} eq $tcfg->{type}) {
664 $target_volname = $volname;
665 } else {
666 $target_volname = $volname_for_storage->($cfg, $volid, $target_storeid);
667 }
668
669 my $target_volid = "${target_storeid}:${target_volname}";
670
671 my $target_ip = $target_sshinfo->{ip};
672
673 my $ssh = PVE::SSHInfo::ssh_info_to_command($target_sshinfo);
674 my $ssh_base = PVE::SSHInfo::ssh_info_to_command_base($target_sshinfo);
675 local $ENV{RSYNC_RSH} = PVE::Tools::cmd2string($ssh_base);
676
677 my @cstream;
678 if (defined($ratelimit_bps)) {
679 @cstream = ([ '/usr/bin/cstream', '-t', $ratelimit_bps ]);
680 $logfunc->("using a bandwidth limit of $ratelimit_bps bps for transferring '$volid'") if $logfunc;
681 }
682
683 my $migration_snapshot;
684 if (!defined($snapshot)) {
685 if ($scfg->{type} eq 'zfspool') {
686 $migration_snapshot = 1;
687 $snapshot = '__migration__';
688 }
689 }
690
691 my @formats = volume_transfer_formats($cfg, $volid, $target_volid, $snapshot, $base_snapshot, $with_snapshots);
692 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
693 my $format = $formats[0];
694
695 my $import_fn = '-'; # let pvesm import read from stdin per default
696 if ($insecure) {
697 my $net = $target_sshinfo->{network} // $target_sshinfo->{ip};
698 $import_fn = "tcp://$net";
699 }
700
701 my $target_apiver = 1; # if there is no apiinfo call, assume 1
702 my $get_api_version = [@$ssh, 'pvesm', 'apiinfo'];
703 my $match_api_version = sub { $target_apiver = $1 if $_[0] =~ m!^APIVER (\d+)$!; };
704 eval { run_command($get_api_version, logfunc => $match_api_version); };
705
706 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
707 my $recv = [@$ssh, '--', 'pvesm', 'import', $target_volid, $format, $import_fn, '-with-snapshots', $with_snapshots];
708 if (defined($snapshot)) {
709 push @$send, '-snapshot', $snapshot
710 }
711 if ($migration_snapshot) {
712 push @$recv, '-delete-snapshot', $snapshot;
713 }
714 push @$recv, '-allow-rename', $allow_rename if $target_apiver >= 5;
715
716 if (defined($base_snapshot)) {
717 # Check if the snapshot exists on the remote side:
718 push @$send, '-base', $base_snapshot;
719 push @$recv, '-base', $base_snapshot;
720 }
721
722 my $new_volid;
723 my $pattern = volume_imported_message(undef, 1);
724 my $match_volid_and_log = sub {
725 my $line = shift;
726
727 $new_volid = $1 if ($line =~ $pattern);
728
729 if ($logfunc) {
730 chomp($line);
731 $logfunc->($line);
732 }
733 };
734
735 volume_snapshot($cfg, $volid, $snapshot) if $migration_snapshot;
736
737 if (defined($snapshot)) {
738 activate_volumes($cfg, [$volid], $snapshot);
739 } else {
740 activate_volumes($cfg, [$volid]);
741 }
742
743 eval {
744 if ($insecure) {
745 my $input = IO::File->new();
746 my $info = IO::File->new();
747 open3($input, $info, $info, @{$recv})
748 or die "receive command failed: $!\n";
749 close($input);
750
751 my ($ip) = <$info> =~ /^($PVE::Tools::IPRE)$/ or die "no tunnel IP received\n";
752 my ($port) = <$info> =~ /^(\d+)$/ or die "no tunnel port received\n";
753 my $socket = IO::Socket::IP->new(PeerHost => $ip, PeerPort => $port, Type => SOCK_STREAM)
754 or die "failed to connect to tunnel at $ip:$port\n";
755 # we won't be reading from the socket
756 shutdown($socket, 0);
757
758 eval { run_command([$send, @cstream], output => '>&'.fileno($socket), errfunc => $logfunc); };
759 my $send_error = $@;
760
761 # don't close the connection entirely otherwise the receiving end
762 # might not get all buffered data (and fails with 'connection reset by peer')
763 shutdown($socket, 1);
764
765 # wait for the remote process to finish
766 while (my $line = <$info>) {
767 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
768 }
769
770 # now close the socket
771 close($socket);
772 if (!close($info)) { # does waitpid()
773 die "import failed: $!\n" if $!;
774 die "import failed: exit code ".($?>>8)."\n";
775 }
776
777 die $send_error if $send_error;
778 } else {
779 run_command([$send, @cstream, $recv], logfunc => $match_volid_and_log);
780 }
781
782 die "unable to get ID of the migrated volume\n"
783 if !defined($new_volid) && $target_apiver >= 5;
784 };
785 my $err = $@;
786 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
787 if ($migration_snapshot) {
788 eval { volume_snapshot_delete($cfg, $volid, $snapshot, 0) };
789 warn "could not remove source snapshot: $@\n" if $@;
790 }
791 die $err if $err;
792
793 return $new_volid // $target_volid;
794 }
795
796 sub vdisk_clone {
797 my ($cfg, $volid, $vmid, $snap) = @_;
798
799 my ($storeid, $volname) = parse_volume_id($volid);
800
801 my $scfg = storage_config($cfg, $storeid);
802
803 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
804
805 activate_storage($cfg, $storeid);
806
807 # lock shared storage
808 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
809 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
810 return "$storeid:$volname";
811 });
812 }
813
814 sub vdisk_create_base {
815 my ($cfg, $volid) = @_;
816
817 my ($storeid, $volname) = parse_volume_id($volid);
818
819 my $scfg = storage_config($cfg, $storeid);
820
821 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
822
823 activate_storage($cfg, $storeid);
824
825 # lock shared storage
826 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
827 my $volname = $plugin->create_base($storeid, $scfg, $volname);
828 return "$storeid:$volname";
829 });
830 }
831
832 sub map_volume {
833 my ($cfg, $volid, $snapname) = @_;
834
835 my ($storeid, $volname) = parse_volume_id($volid);
836
837 my $scfg = storage_config($cfg, $storeid);
838
839 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
840
841 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
842 }
843
844 sub unmap_volume {
845 my ($cfg, $volid, $snapname) = @_;
846
847 my ($storeid, $volname) = parse_volume_id($volid);
848
849 my $scfg = storage_config($cfg, $storeid);
850
851 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
852
853 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
854 }
855
856 sub vdisk_alloc {
857 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
858
859 die "no storage ID specified\n" if !$storeid;
860
861 PVE::JSONSchema::parse_storage_id($storeid);
862
863 my $scfg = storage_config($cfg, $storeid);
864
865 die "no VMID specified\n" if !$vmid;
866
867 $vmid = parse_vmid($vmid);
868
869 my $defformat = PVE::Storage::Plugin::default_format($scfg);
870
871 $fmt = $defformat if !$fmt;
872
873 activate_storage($cfg, $storeid);
874
875 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
876
877 # lock shared storage
878 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
879 my $old_umask = umask(umask|0037);
880 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
881 my $err = $@;
882 umask $old_umask;
883 die $err if $err;
884 return "$storeid:$volname";
885 });
886 }
887
888 sub vdisk_free {
889 my ($cfg, $volid) = @_;
890
891 my ($storeid, $volname) = parse_volume_id($volid);
892 my $scfg = storage_config($cfg, $storeid);
893 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
894
895 activate_storage($cfg, $storeid);
896
897 my $cleanup_worker;
898
899 # lock shared storage
900 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
901 # LVM-thin allows deletion of still referenced base volumes!
902 die "base volume '$volname' is still in use by linked clones\n"
903 if &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
904
905 my (undef, undef, undef, undef, undef, $isBase, $format) =
906 $plugin->parse_volname($volname);
907 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
908 });
909
910 return if !$cleanup_worker;
911
912 my $rpcenv = PVE::RPCEnvironment::get();
913 my $authuser = $rpcenv->get_user();
914
915 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
916 }
917
918 sub vdisk_list {
919 my ($cfg, $storeid, $vmid, $vollist) = @_;
920
921 my $ids = $cfg->{ids};
922
923 storage_check_enabled($cfg, $storeid) if ($storeid);
924
925 my $res = {};
926
927 # prepare/activate/refresh all storages
928
929 my $storage_list = [];
930 if ($vollist) {
931 foreach my $volid (@$vollist) {
932 my ($sid, undef) = parse_volume_id($volid);
933 next if !defined($ids->{$sid});
934 next if !storage_check_enabled($cfg, $sid, undef, 1);
935 push @$storage_list, $sid;
936 }
937 } else {
938 foreach my $sid (keys %$ids) {
939 next if $storeid && $storeid ne $sid;
940 next if !storage_check_enabled($cfg, $sid, undef, 1);
941 my $content = $ids->{$sid}->{content};
942 next if !($content->{rootdir} || $content->{images});
943 push @$storage_list, $sid;
944 }
945 }
946
947 my $cache = {};
948
949 activate_storage_list($cfg, $storage_list, $cache);
950
951 foreach my $sid (keys %$ids) {
952 next if $storeid && $storeid ne $sid;
953 next if !storage_check_enabled($cfg, $sid, undef, 1);
954
955 my $scfg = $ids->{$sid};
956 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
957 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
958 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
959 }
960
961 return $res;
962 }
963
964 sub template_list {
965 my ($cfg, $storeid, $tt) = @_;
966
967 die "unknown template type '$tt'\n"
968 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
969
970 my $ids = $cfg->{ids};
971
972 storage_check_enabled($cfg, $storeid) if ($storeid);
973
974 my $res = {};
975
976 # query the storage
977 foreach my $sid (keys %$ids) {
978 next if $storeid && $storeid ne $sid;
979
980 my $scfg = $ids->{$sid};
981 my $type = $scfg->{type};
982
983 next if !$scfg->{content}->{$tt};
984
985 next if !storage_check_enabled($cfg, $sid, undef, 1);
986
987 $res->{$sid} = volume_list($cfg, $sid, undef, $tt);
988 }
989
990 return $res;
991 }
992
993 sub volume_list {
994 my ($cfg, $storeid, $vmid, $content) = @_;
995
996 my @ctypes = qw(rootdir images vztmpl iso backup snippets);
997
998 my $cts = $content ? [ $content ] : [ @ctypes ];
999
1000 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
1001
1002 $cts = [ grep { defined($scfg->{content}->{$_}) } @$cts ];
1003
1004 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1005
1006 activate_storage($cfg, $storeid);
1007
1008 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1009
1010 @$res = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @$res;
1011
1012 return $res;
1013 }
1014
1015 sub uevent_seqnum {
1016
1017 my $filename = "/sys/kernel/uevent_seqnum";
1018
1019 my $seqnum = 0;
1020 if (my $fh = IO::File->new($filename, "r")) {
1021 my $line = <$fh>;
1022 if ($line =~ m/^(\d+)$/) {
1023 $seqnum = int($1);
1024 }
1025 close ($fh);
1026 }
1027 return $seqnum;
1028 }
1029
1030 sub activate_storage {
1031 my ($cfg, $storeid, $cache) = @_;
1032
1033 $cache = {} if !$cache;
1034
1035 my $scfg = storage_check_enabled($cfg, $storeid);
1036
1037 return if $cache->{activated}->{$storeid};
1038
1039 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
1040
1041 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1042
1043 if ($scfg->{base}) {
1044 my ($baseid, undef) = parse_volume_id ($scfg->{base});
1045 activate_storage($cfg, $baseid, $cache);
1046 }
1047
1048 if (!$plugin->check_connection($storeid, $scfg)) {
1049 die "storage '$storeid' is not online\n";
1050 }
1051
1052 $plugin->activate_storage($storeid, $scfg, $cache);
1053
1054 my $newseq = uevent_seqnum ();
1055
1056 # only call udevsettle if there are events
1057 if ($newseq > $cache->{uevent_seqnum}) {
1058 my $timeout = 30;
1059 system ("$UDEVADM settle --timeout=$timeout"); # ignore errors
1060 $cache->{uevent_seqnum} = $newseq;
1061 }
1062
1063 $cache->{activated}->{$storeid} = 1;
1064 }
1065
1066 sub activate_storage_list {
1067 my ($cfg, $storeid_list, $cache) = @_;
1068
1069 $cache = {} if !$cache;
1070
1071 foreach my $storeid (@$storeid_list) {
1072 activate_storage($cfg, $storeid, $cache);
1073 }
1074 }
1075
1076 sub deactivate_storage {
1077 my ($cfg, $storeid) = @_;
1078
1079 my $scfg = storage_config ($cfg, $storeid);
1080 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1081
1082 my $cache = {};
1083 $plugin->deactivate_storage($storeid, $scfg, $cache);
1084 }
1085
1086 sub activate_volumes {
1087 my ($cfg, $vollist, $snapname) = @_;
1088
1089 return if !($vollist && scalar(@$vollist));
1090
1091 my $storagehash = {};
1092 foreach my $volid (@$vollist) {
1093 my ($storeid, undef) = parse_volume_id($volid);
1094 $storagehash->{$storeid} = 1;
1095 }
1096
1097 my $cache = {};
1098
1099 activate_storage_list($cfg, [keys %$storagehash], $cache);
1100
1101 foreach my $volid (@$vollist) {
1102 my ($storeid, $volname) = parse_volume_id($volid);
1103 my $scfg = storage_config($cfg, $storeid);
1104 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1105 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1106 }
1107 }
1108
1109 sub deactivate_volumes {
1110 my ($cfg, $vollist, $snapname) = @_;
1111
1112 return if !($vollist && scalar(@$vollist));
1113
1114 my $cache = {};
1115
1116 my @errlist = ();
1117 foreach my $volid (@$vollist) {
1118 my ($storeid, $volname) = parse_volume_id($volid);
1119
1120 my $scfg = storage_config($cfg, $storeid);
1121 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1122
1123 eval {
1124 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1125 };
1126 if (my $err = $@) {
1127 warn $err;
1128 push @errlist, $volid;
1129 }
1130 }
1131
1132 die "volume deactivation failed: " . join(' ', @errlist)
1133 if scalar(@errlist);
1134 }
1135
1136 sub storage_info {
1137 my ($cfg, $content, $includeformat) = @_;
1138
1139 my $ids = $cfg->{ids};
1140
1141 my $info = {};
1142
1143 my @ctypes = PVE::Tools::split_list($content);
1144
1145 my $slist = [];
1146 foreach my $storeid (keys %$ids) {
1147 my $storage_enabled = defined(storage_check_enabled($cfg, $storeid, undef, 1));
1148
1149 if (defined($content)) {
1150 my $want_ctype = 0;
1151 foreach my $ctype (@ctypes) {
1152 if ($ids->{$storeid}->{content}->{$ctype}) {
1153 $want_ctype = 1;
1154 last;
1155 }
1156 }
1157 next if !$want_ctype || !$storage_enabled;
1158 }
1159
1160 my $type = $ids->{$storeid}->{type};
1161
1162 $info->{$storeid} = {
1163 type => $type,
1164 total => 0,
1165 avail => 0,
1166 used => 0,
1167 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1168 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
1169 active => 0,
1170 enabled => $storage_enabled ? 1 : 0,
1171 };
1172
1173 push @$slist, $storeid;
1174 }
1175
1176 my $cache = {};
1177
1178 foreach my $storeid (keys %$ids) {
1179 my $scfg = $ids->{$storeid};
1180
1181 next if !$info->{$storeid};
1182 next if !$info->{$storeid}->{enabled};
1183
1184 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1185 if ($includeformat) {
1186 my $pd = $plugin->plugindata();
1187 $info->{$storeid}->{format} = $pd->{format}
1188 if $pd->{format};
1189 $info->{$storeid}->{select_existing} = $pd->{select_existing}
1190 if $pd->{select_existing};
1191 }
1192
1193 eval { activate_storage($cfg, $storeid, $cache); };
1194 if (my $err = $@) {
1195 warn $err;
1196 next;
1197 }
1198
1199 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
1200 warn $@ if $@;
1201 next if !$active;
1202 $info->{$storeid}->{total} = int($total);
1203 $info->{$storeid}->{avail} = int($avail);
1204 $info->{$storeid}->{used} = int($used);
1205 $info->{$storeid}->{active} = $active;
1206 }
1207
1208 return $info;
1209 }
1210
1211 sub resolv_server {
1212 my ($server) = @_;
1213
1214 my ($packed_ip, $family);
1215 eval {
1216 my @res = PVE::Tools::getaddrinfo_all($server);
1217 $family = $res[0]->{family};
1218 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1219 };
1220 if (defined $packed_ip) {
1221 return Socket::inet_ntop($family, $packed_ip);
1222 }
1223 return undef;
1224 }
1225
1226 sub scan_nfs {
1227 my ($server_in) = @_;
1228
1229 my $server;
1230 if (!($server = resolv_server ($server_in))) {
1231 die "unable to resolve address for server '${server_in}'\n";
1232 }
1233
1234 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1235
1236 my $res = {};
1237 run_command($cmd, outfunc => sub {
1238 my $line = shift;
1239
1240 # note: howto handle white spaces in export path??
1241 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1242 $res->{$1} = $2;
1243 }
1244 });
1245
1246 return $res;
1247 }
1248
1249 sub scan_cifs {
1250 my ($server_in, $user, $password, $domain) = @_;
1251
1252 my $server = resolv_server($server_in);
1253 die "unable to resolve address for server '${server_in}'\n" if !$server;
1254
1255 # we only support Windows 2012 and newer, so just use smb3
1256 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1257 push @$cmd, '-W', $domain if defined($domain);
1258
1259 push @$cmd, '-N' if !defined($password);
1260 local $ENV{USER} = $user if defined($user);
1261 local $ENV{PASSWD} = $password if defined($password);
1262
1263 my $res = {};
1264 my $err = '';
1265 run_command($cmd,
1266 noerr => 1,
1267 errfunc => sub {
1268 $err .= "$_[0]\n"
1269 },
1270 outfunc => sub {
1271 my $line = shift;
1272 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1273 $res->{$1} = $2;
1274 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1275 my $status = $1;
1276 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
1277 }
1278 },
1279 );
1280 # only die if we got no share, else it's just some followup check error
1281 # (like workgroup querying)
1282 raise($err) if $err && !%$res;
1283
1284 return $res;
1285 }
1286
1287 sub scan_zfs {
1288
1289 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
1290
1291 my $res = [];
1292 run_command($cmd, outfunc => sub {
1293 my $line = shift;
1294
1295 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1296 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1297 my $size = $size_str + 0;
1298 my $used = $used_str + 0;
1299 # ignore subvolumes generated by our ZFSPoolPlugin
1300 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1301 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1302 push @$res, { pool => $pool, size => $size, free => $size-$used };
1303 }
1304 });
1305
1306 return $res;
1307 }
1308
1309 sub resolv_portal {
1310 my ($portal, $noerr) = @_;
1311
1312 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1313 if ($server) {
1314 if (my $ip = resolv_server($server)) {
1315 $server = $ip;
1316 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1317 return $port ? "$server:$port" : $server;
1318 }
1319 }
1320 return undef if $noerr;
1321
1322 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1323 }
1324
1325
1326 sub scan_iscsi {
1327 my ($portal_in) = @_;
1328
1329 my $portal;
1330 if (!($portal = resolv_portal($portal_in))) {
1331 die "unable to parse/resolve portal address '${portal_in}'\n";
1332 }
1333
1334 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
1335 }
1336
1337 sub storage_default_format {
1338 my ($cfg, $storeid) = @_;
1339
1340 my $scfg = storage_config ($cfg, $storeid);
1341
1342 return PVE::Storage::Plugin::default_format($scfg);
1343 }
1344
1345 sub vgroup_is_used {
1346 my ($cfg, $vgname) = @_;
1347
1348 foreach my $storeid (keys %{$cfg->{ids}}) {
1349 my $scfg = storage_config($cfg, $storeid);
1350 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1351 return 1;
1352 }
1353 }
1354
1355 return undef;
1356 }
1357
1358 sub target_is_used {
1359 my ($cfg, $target) = @_;
1360
1361 foreach my $storeid (keys %{$cfg->{ids}}) {
1362 my $scfg = storage_config($cfg, $storeid);
1363 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1364 return 1;
1365 }
1366 }
1367
1368 return undef;
1369 }
1370
1371 sub volume_is_used {
1372 my ($cfg, $volid) = @_;
1373
1374 foreach my $storeid (keys %{$cfg->{ids}}) {
1375 my $scfg = storage_config($cfg, $storeid);
1376 if ($scfg->{base} && $scfg->{base} eq $volid) {
1377 return 1;
1378 }
1379 }
1380
1381 return undef;
1382 }
1383
1384 sub storage_is_used {
1385 my ($cfg, $storeid) = @_;
1386
1387 foreach my $sid (keys %{$cfg->{ids}}) {
1388 my $scfg = storage_config($cfg, $sid);
1389 next if !$scfg->{base};
1390 my ($st) = parse_volume_id($scfg->{base});
1391 return 1 if $st && $st eq $storeid;
1392 }
1393
1394 return undef;
1395 }
1396
1397 sub foreach_volid {
1398 my ($list, $func) = @_;
1399
1400 return if !$list;
1401
1402 foreach my $sid (keys %$list) {
1403 foreach my $info (@{$list->{$sid}}) {
1404 my $volid = $info->{volid};
1405 my ($sid1, $volname) = parse_volume_id($volid, 1);
1406 if ($sid1 && $sid1 eq $sid) {
1407 &$func ($volid, $sid, $info);
1408 } else {
1409 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1410 }
1411 }
1412 }
1413 }
1414
1415 sub decompressor_info {
1416 my ($format, $comp) = @_;
1417
1418 if ($format eq 'tgz' && !defined($comp)) {
1419 ($format, $comp) = ('tar', 'gz');
1420 }
1421
1422 my $decompressor = {
1423 tar => {
1424 gz => ['tar', '-z'],
1425 lzo => ['tar', '--lzop'],
1426 zst => ['tar', '--zstd'],
1427 },
1428 vma => {
1429 gz => ['zcat'],
1430 lzo => ['lzop', '-d', '-c'],
1431 zst => ['zstd', '-q', '-d', '-c'],
1432 },
1433 };
1434
1435 die "ERROR: archive format not defined\n"
1436 if !defined($decompressor->{$format});
1437
1438 my $decomp;
1439 $decomp = $decompressor->{$format}->{$comp} if $comp;
1440
1441 my $info = {
1442 format => $format,
1443 compression => $comp,
1444 decompressor => $decomp,
1445 };
1446
1447 return $info;
1448 }
1449
1450 sub archive_info {
1451 my ($archive) = shift;
1452 my $info;
1453
1454 my $volid = basename($archive);
1455 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+\.(tgz$|tar|vma)(?:\.(${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)$/) {
1456 my $filename = "$1"; # untaint
1457 my ($type, $format, $comp) = ($2, $3, $4);
1458 my $format_re = defined($comp) ? "$format.$comp" : "$format";
1459 $info = decompressor_info($format, $comp);
1460 $info->{filename} = $filename;
1461 $info->{type} = $type;
1462
1463 if ($volid =~ /^(vzdump-${type}-([1-9][0-9]{2,8})-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2}))\.${format_re}$/) {
1464 $info->{logfilename} = "$1.log";
1465 $info->{vmid} = int($2);
1466 $info->{ctime} = timelocal($8, $7, $6, $5, $4 - 1, $3);
1467 $info->{is_std_name} = 1;
1468 } else {
1469 $info->{is_std_name} = 0;
1470 }
1471 } else {
1472 die "ERROR: couldn't determine archive info from '$archive'\n";
1473 }
1474
1475 return $info;
1476 }
1477
1478 sub archive_remove {
1479 my ($archive_path) = @_;
1480
1481 my $dirname = dirname($archive_path);
1482 my $archive_info = eval { archive_info($archive_path) } // {};
1483 my $logfn = $archive_info->{logfilename};
1484
1485 unlink $archive_path or die "removing archive $archive_path failed: $!\n";
1486
1487 if (defined($logfn)) {
1488 my $logpath = "$dirname/$logfn";
1489 if (-e $logpath) {
1490 unlink $logpath or warn "removing log file $logpath failed: $!\n";
1491 }
1492 }
1493 }
1494
1495 sub extract_vzdump_config_tar {
1496 my ($archive, $conf_re) = @_;
1497
1498 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1499
1500 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1501 die "unable to open file '$archive'\n";
1502
1503 my $file;
1504 while (defined($file = <$fh>)) {
1505 if ($file =~ $conf_re) {
1506 $file = $1; # untaint
1507 last;
1508 }
1509 }
1510
1511 kill 15, $pid;
1512 waitpid $pid, 0;
1513 close $fh;
1514
1515 die "ERROR: archive contains no configuration file\n" if !$file;
1516 chomp $file;
1517
1518 my $raw = '';
1519 my $out = sub {
1520 my $output = shift;
1521 $raw .= "$output\n";
1522 };
1523
1524 run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
1525
1526 return wantarray ? ($raw, $file) : $raw;
1527 }
1528
1529 sub extract_vzdump_config_vma {
1530 my ($archive, $comp) = @_;
1531
1532 my $raw = '';
1533 my $out = sub { $raw .= "$_[0]\n"; };
1534
1535 my $info = archive_info($archive);
1536 $comp //= $info->{compression};
1537 my $decompressor = $info->{decompressor};
1538
1539 if ($comp) {
1540 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
1541
1542 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
1543 my $broken_pipe;
1544 my $errstring;
1545 my $err = sub {
1546 my $output = shift;
1547 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error : Broken pipe/) {
1548 $broken_pipe = 1;
1549 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1550 $errstring = "Failed to extract config from VMA archive: $output\n";
1551 }
1552 };
1553
1554 my $rc = eval { run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1) };
1555 my $rerr = $@;
1556
1557 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1558
1559 if (!$errstring && !$broken_pipe && $rc != 0) {
1560 die "$rerr\n" if $rerr;
1561 die "config extraction failed with exit code $rc\n";
1562 }
1563 die "$errstring\n" if $errstring;
1564 } else {
1565 run_command(["vma", "config", $archive], outfunc => $out);
1566 }
1567
1568 return wantarray ? ($raw, undef) : $raw;
1569 }
1570
1571 sub extract_vzdump_config {
1572 my ($cfg, $volid) = @_;
1573
1574 my ($storeid, $volname) = parse_volume_id($volid);
1575 if (defined($storeid)) {
1576 my $scfg = storage_config($cfg, $storeid);
1577 if ($scfg->{type} eq 'pbs') {
1578 storage_check_enabled($cfg, $storeid);
1579 return PVE::Storage::PBSPlugin->extract_vzdump_config($scfg, $volname, $storeid);
1580 }
1581 }
1582
1583 my $archive = abs_filesystem_path($cfg, $volid);
1584 my $info = archive_info($archive);
1585 my $format = $info->{format};
1586 my $comp = $info->{compression};
1587 my $type = $info->{type};
1588
1589 if ($type eq 'lxc' || $type eq 'openvz') {
1590 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1591 } elsif ($type eq 'qemu') {
1592 if ($format eq 'tar') {
1593 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1594 } else {
1595 return extract_vzdump_config_vma($archive, $comp);
1596 }
1597 } else {
1598 die "cannot determine backup guest type for backup archive '$volid'\n";
1599 }
1600 }
1601
1602 sub prune_backups {
1603 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1604
1605 my $scfg = storage_config($cfg, $storeid);
1606 die "storage '$storeid' does not support backups\n" if !$scfg->{content}->{backup};
1607
1608 if (!defined($keep)) {
1609 die "no prune-backups options configured for storage '$storeid'\n"
1610 if !defined($scfg->{'prune-backups'});
1611 $keep = PVE::JSONSchema::parse_property_string('prune-backups', $scfg->{'prune-backups'});
1612 }
1613
1614 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1615 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1616 }
1617
1618 my $prune_mark = sub {
1619 my ($prune_entries, $keep_count, $id_func) = @_;
1620
1621 return if !$keep_count;
1622
1623 my $already_included = {};
1624 my $newly_included = {};
1625
1626 foreach my $prune_entry (@{$prune_entries}) {
1627 my $mark = $prune_entry->{mark};
1628 my $id = $id_func->($prune_entry->{ctime});
1629
1630 next if $already_included->{$id};
1631
1632 if (defined($mark)) {
1633 $already_included->{$id} = 1 if $mark eq 'keep';
1634 next;
1635 }
1636
1637 if (!$newly_included->{$id}) {
1638 last if scalar(keys %{$newly_included}) >= $keep_count;
1639 $newly_included->{$id} = 1;
1640 $prune_entry->{mark} = 'keep';
1641 } else {
1642 $prune_entry->{mark} = 'remove';
1643 }
1644 }
1645 };
1646
1647 sub prune_mark_backup_group {
1648 my ($backup_group, $keep) = @_;
1649
1650 my $keep_all = delete $keep->{'keep-all'};
1651
1652 if ($keep_all || !scalar(grep {$_ > 0} values %{$keep})) {
1653 $keep = { 'keep-all' => 1 } if $keep_all;
1654 foreach my $prune_entry (@{$backup_group}) {
1655 $prune_entry->{mark} = 'keep';
1656 }
1657 return;
1658 }
1659
1660 my $prune_list = [ sort { $b->{ctime} <=> $a->{ctime} } @{$backup_group} ];
1661
1662 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1663 my ($ctime) = @_;
1664 return $ctime;
1665 });
1666 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1667 my ($ctime) = @_;
1668 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1669 return "$hour/$day/$month/$year";
1670 });
1671 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1672 my ($ctime) = @_;
1673 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1674 return "$day/$month/$year";
1675 });
1676 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1677 my ($ctime) = @_;
1678 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
1679 my $iso_week = int(strftime("%V", $sec, $min, $hour, $day, $month - 1, $year - 1900));
1680 my $iso_week_year = int(strftime("%G", $sec, $min, $hour, $day, $month - 1, $year - 1900));
1681 return "$iso_week/$iso_week_year";
1682 });
1683 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1684 my ($ctime) = @_;
1685 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1686 return "$month/$year";
1687 });
1688 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1689 my ($ctime) = @_;
1690 my $year = (localtime($ctime))[5];
1691 return "$year";
1692 });
1693
1694 foreach my $prune_entry (@{$prune_list}) {
1695 $prune_entry->{mark} //= 'remove';
1696 }
1697 }
1698
1699 sub volume_export {
1700 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1701
1702 my ($storeid, $volname) = parse_volume_id($volid, 1);
1703 die "cannot export volume '$volid'\n" if !$storeid;
1704 my $scfg = storage_config($cfg, $storeid);
1705 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1706 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1707 $snapshot, $base_snapshot, $with_snapshots);
1708 }
1709
1710 sub volume_import {
1711 my ($cfg, $fh, $volid, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1712
1713 my ($storeid, $volname) = parse_volume_id($volid, 1);
1714 die "cannot import into volume '$volid'\n" if !$storeid;
1715 my $scfg = storage_config($cfg, $storeid);
1716 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1717 return $plugin->volume_import($scfg, $storeid, $fh, $volname, $format,
1718 $base_snapshot, $with_snapshots, $allow_rename) // $volid;
1719 }
1720
1721 sub volume_export_formats {
1722 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1723
1724 my ($storeid, $volname) = parse_volume_id($volid, 1);
1725 return if !$storeid;
1726 my $scfg = storage_config($cfg, $storeid);
1727 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1728 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1729 $snapshot, $base_snapshot,
1730 $with_snapshots);
1731 }
1732
1733 sub volume_import_formats {
1734 my ($cfg, $volid, $base_snapshot, $with_snapshots) = @_;
1735
1736 my ($storeid, $volname) = parse_volume_id($volid, 1);
1737 return if !$storeid;
1738 my $scfg = storage_config($cfg, $storeid);
1739 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1740 return $plugin->volume_import_formats($scfg, $storeid, $volname,
1741 $base_snapshot, $with_snapshots);
1742 }
1743
1744 sub volume_transfer_formats {
1745 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1746 my @export_formats = volume_export_formats($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1747 my @import_formats = volume_import_formats($cfg, $dst_volid, $base_snapshot, $with_snapshots);
1748 my %import_hash = map { $_ => 1 } @import_formats;
1749 my @common = grep { $import_hash{$_} } @export_formats;
1750 return @common;
1751 }
1752
1753 sub volume_imported_message {
1754 my ($volid, $want_pattern) = @_;
1755
1756 if ($want_pattern) {
1757 return qr/successfully imported '([^']*)'$/;
1758 } else {
1759 return "successfully imported '$volid'\n";
1760 }
1761 }
1762
1763 # bash completion helper
1764
1765 sub complete_storage {
1766 my ($cmdname, $pname, $cvalue) = @_;
1767
1768 my $cfg = PVE::Storage::config();
1769
1770 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
1771 }
1772
1773 sub complete_storage_enabled {
1774 my ($cmdname, $pname, $cvalue) = @_;
1775
1776 my $res = [];
1777
1778 my $cfg = PVE::Storage::config();
1779 foreach my $sid (keys %{$cfg->{ids}}) {
1780 next if !storage_check_enabled($cfg, $sid, undef, 1);
1781 push @$res, $sid;
1782 }
1783 return $res;
1784 }
1785
1786 sub complete_content_type {
1787 my ($cmdname, $pname, $cvalue) = @_;
1788
1789 return [qw(rootdir images vztmpl iso backup snippets)];
1790 }
1791
1792 sub complete_volume {
1793 my ($cmdname, $pname, $cvalue) = @_;
1794
1795 my $cfg = config();
1796
1797 my $storage_list = complete_storage_enabled();
1798
1799 if ($cvalue =~ m/^([^:]+):/) {
1800 $storage_list = [ $1 ];
1801 } else {
1802 if (scalar(@$storage_list) > 1) {
1803 # only list storage IDs to avoid large listings
1804 my $res = [];
1805 foreach my $storeid (@$storage_list) {
1806 # Hack: simply return 2 artificial values, so that
1807 # completions does not finish
1808 push @$res, "$storeid:volname", "$storeid:...";
1809 }
1810 return $res;
1811 }
1812 }
1813
1814 my $res = [];
1815 foreach my $storeid (@$storage_list) {
1816 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
1817
1818 foreach my $item (@$vollist) {
1819 push @$res, $item->{volid};
1820 }
1821 }
1822
1823 return $res;
1824 }
1825
1826 # Various io-heavy operations require io/bandwidth limits which can be
1827 # configured on multiple levels: The global defaults in datacenter.cfg, and
1828 # per-storage overrides. When we want to do a restore from storage A to storage
1829 # B, we should take the smaller limit defined for storages A and B, and if no
1830 # such limit was specified, use the one from datacenter.cfg.
1831 sub get_bandwidth_limit {
1832 my ($operation, $storage_list, $override) = @_;
1833
1834 # called for each limit (global, per-storage) with the 'default' and the
1835 # $operation limit and should udpate $override for every limit affecting
1836 # us.
1837 my $use_global_limits = 0;
1838 my $apply_limit = sub {
1839 my ($bwlimit) = @_;
1840 if (defined($bwlimit)) {
1841 my $limits = PVE::JSONSchema::parse_property_string('bwlimit', $bwlimit);
1842 my $limit = $limits->{$operation} // $limits->{default};
1843 if (defined($limit)) {
1844 if (!$override || $limit < $override) {
1845 $override = $limit;
1846 }
1847 return;
1848 }
1849 }
1850 # If there was no applicable limit, try to apply the global ones.
1851 $use_global_limits = 1;
1852 };
1853
1854 my ($rpcenv, $authuser);
1855 if (defined($override)) {
1856 $rpcenv = PVE::RPCEnvironment->get();
1857 $authuser = $rpcenv->get_user();
1858 }
1859
1860 # Apply per-storage limits - if there are storages involved.
1861 if (defined($storage_list) && @$storage_list) {
1862 my $config = config();
1863
1864 # The Datastore.Allocate permission allows us to modify the per-storage
1865 # limits, therefore it also allows us to override them.
1866 # Since we have most likely multiple storages to check, do a quick check on
1867 # the general '/storage' path to see if we can skip the checks entirely:
1868 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
1869
1870 my %done;
1871 foreach my $storage (@$storage_list) {
1872 next if !defined($storage);
1873 # Avoid duplicate checks:
1874 next if $done{$storage};
1875 $done{$storage} = 1;
1876
1877 # Otherwise we may still have individual /storage/$ID permissions:
1878 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
1879 # And if not: apply the limits.
1880 my $storecfg = storage_config($config, $storage);
1881 $apply_limit->($storecfg->{bwlimit});
1882 }
1883 }
1884
1885 # Storage limits take precedence over the datacenter defaults, so if
1886 # a limit was applied:
1887 return $override if !$use_global_limits;
1888 }
1889
1890 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
1891 # global default limits.
1892 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
1893 # So if we cannot modify global limits, apply them to our currently
1894 # requested override.
1895 my $dc = cfs_read_file('datacenter.cfg');
1896 $apply_limit->($dc->{bwlimit});
1897 }
1898
1899 return $override;
1900 }
1901
1902 # checks if the storage id is available and dies if not
1903 sub assert_sid_unused {
1904 my ($sid) = @_;
1905
1906 my $cfg = config();
1907 if (my $scfg = storage_config($cfg, $sid, 1)) {
1908 die "storage ID '$sid' already defined\n";
1909 }
1910
1911 return undef;
1912 }
1913
1914 1;