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