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