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