]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage.pm
drop un-maintained sheepdog 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::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::ISCSIDirectPlugin;
33 use PVE::Storage::GlusterfsPlugin;
34 use PVE::Storage::ZFSPoolPlugin;
35 use PVE::Storage::ZFSPlugin;
36 use PVE::Storage::DRBDPlugin;
37
38 # Storage API version. Icrement it on changes in storage API interface.
39 use constant APIVER => 2;
40 # Age is the number of versions we're backward compatible with.
41 # This is like having 'current=APIVER' and age='APIAGE' in libtool,
42 # see https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
43 use constant APIAGE => 1;
44
45 # load standard plugins
46 PVE::Storage::DirPlugin->register();
47 PVE::Storage::LVMPlugin->register();
48 PVE::Storage::LvmThinPlugin->register();
49 PVE::Storage::NFSPlugin->register();
50 PVE::Storage::CIFSPlugin->register();
51 PVE::Storage::ISCSIPlugin->register();
52 PVE::Storage::RBDPlugin->register();
53 PVE::Storage::CephFSPlugin->register();
54 PVE::Storage::ISCSIDirectPlugin->register();
55 PVE::Storage::GlusterfsPlugin->register();
56 PVE::Storage::ZFSPoolPlugin->register();
57 PVE::Storage::ZFSPlugin->register();
58 PVE::Storage::DRBDPlugin->register();
59
60 # load third-party plugins
61 if ( -d '/usr/share/perl5/PVE/Storage/Custom' ) {
62 dir_glob_foreach('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
63 my ($file) = @_;
64 my $modname = 'PVE::Storage::Custom::' . $file;
65 $modname =~ s!\.pm$!!;
66 $file = 'PVE/Storage/Custom/' . $file;
67
68 eval {
69 require $file;
70
71 # Check perl interface:
72 die "not derived from PVE::Storage::Plugin\n"
73 if !$modname->isa('PVE::Storage::Plugin');
74 die "does not provide an api() method\n"
75 if !$modname->can('api');
76 # Check storage API version and that file is really storage plugin.
77 my $version = $modname->api();
78 die "implements an API version newer than current ($version > " . APIVER . ")\n"
79 if $version > APIVER;
80 my $min_version = (APIVER - APIAGE);
81 die "API version too old, please update the plugin ($version < $min_version)\n"
82 if $version < $min_version;
83 import $file;
84 $modname->register();
85
86 # If we got this far and the API version is not the same, make some
87 # noise:
88 warn "Plugin \"$modname\" is implementing an older storage API, an upgrade is recommended\n"
89 if $version != APIVER;
90 };
91 if ($@) {
92 warn "Error loading storage plugin \"$modname\": $@";
93 }
94 });
95 }
96
97 # initialize all plugins
98 PVE::Storage::Plugin->init();
99
100 my $UDEVADM = '/sbin/udevadm';
101
102 # PVE::Storage utility functions
103
104 sub config {
105 return cfs_read_file("storage.cfg");
106 }
107
108 sub write_config {
109 my ($cfg) = @_;
110
111 cfs_write_file('storage.cfg', $cfg);
112 }
113
114 sub lock_storage_config {
115 my ($code, $errmsg) = @_;
116
117 cfs_lock_file("storage.cfg", undef, $code);
118 my $err = $@;
119 if ($err) {
120 $errmsg ? die "$errmsg: $err" : die $err;
121 }
122 }
123
124 sub storage_config {
125 my ($cfg, $storeid, $noerr) = @_;
126
127 die "no storage ID specified\n" if !$storeid;
128
129 my $scfg = $cfg->{ids}->{$storeid};
130
131 die "storage '$storeid' does not exists\n" if (!$noerr && !$scfg);
132
133 return $scfg;
134 }
135
136 sub storage_check_node {
137 my ($cfg, $storeid, $node, $noerr) = @_;
138
139 my $scfg = storage_config($cfg, $storeid);
140
141 if ($scfg->{nodes}) {
142 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
143 if (!$scfg->{nodes}->{$node}) {
144 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
145 return undef;
146 }
147 }
148
149 return $scfg;
150 }
151
152 sub storage_check_enabled {
153 my ($cfg, $storeid, $node, $noerr) = @_;
154
155 my $scfg = storage_config($cfg, $storeid);
156
157 if ($scfg->{disable}) {
158 die "storage '$storeid' is disabled\n" if !$noerr;
159 return undef;
160 }
161
162 return storage_check_node($cfg, $storeid, $node, $noerr);
163 }
164
165 # storage_can_replicate:
166 # return true if storage supports replication
167 # (volumes alocated with vdisk_alloc() has replication feature)
168 sub storage_can_replicate {
169 my ($cfg, $storeid, $format) = @_;
170
171 my $scfg = storage_config($cfg, $storeid);
172 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
173 return $plugin->storage_can_replicate($scfg, $storeid, $format);
174 }
175
176 sub storage_ids {
177 my ($cfg) = @_;
178
179 return keys %{$cfg->{ids}};
180 }
181
182 sub file_size_info {
183 my ($filename, $timeout) = @_;
184
185 return PVE::Storage::Plugin::file_size_info($filename, $timeout);
186 }
187
188 sub volume_size_info {
189 my ($cfg, $volid, $timeout) = @_;
190
191 my ($storeid, $volname) = parse_volume_id($volid, 1);
192 if ($storeid) {
193 my $scfg = storage_config($cfg, $storeid);
194 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
195 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
196 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
197 return file_size_info($volid, $timeout);
198 } else {
199 return 0;
200 }
201 }
202
203 sub volume_resize {
204 my ($cfg, $volid, $size, $running) = @_;
205
206 my ($storeid, $volname) = parse_volume_id($volid, 1);
207 if ($storeid) {
208 my $scfg = storage_config($cfg, $storeid);
209 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
210 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
211 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
212 die "resize file/device '$volid' is not possible\n";
213 } else {
214 die "unable to parse volume ID '$volid'\n";
215 }
216 }
217
218 sub volume_rollback_is_possible {
219 my ($cfg, $volid, $snap) = @_;
220
221 my ($storeid, $volname) = parse_volume_id($volid, 1);
222 if ($storeid) {
223 my $scfg = storage_config($cfg, $storeid);
224 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
225 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
226 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
227 die "snapshot rollback file/device '$volid' is not possible\n";
228 } else {
229 die "unable to parse volume ID '$volid'\n";
230 }
231 }
232
233 sub volume_snapshot {
234 my ($cfg, $volid, $snap) = @_;
235
236 my ($storeid, $volname) = parse_volume_id($volid, 1);
237 if ($storeid) {
238 my $scfg = storage_config($cfg, $storeid);
239 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
240 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
241 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
242 die "snapshot file/device '$volid' is not possible\n";
243 } else {
244 die "unable to parse volume ID '$volid'\n";
245 }
246 }
247
248 sub volume_snapshot_rollback {
249 my ($cfg, $volid, $snap) = @_;
250
251 my ($storeid, $volname) = parse_volume_id($volid, 1);
252 if ($storeid) {
253 my $scfg = storage_config($cfg, $storeid);
254 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
255 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
256 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
257 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
258 die "snapshot rollback file/device '$volid' is not possible\n";
259 } else {
260 die "unable to parse volume ID '$volid'\n";
261 }
262 }
263
264 sub volume_snapshot_delete {
265 my ($cfg, $volid, $snap, $running) = @_;
266
267 my ($storeid, $volname) = parse_volume_id($volid, 1);
268 if ($storeid) {
269 my $scfg = storage_config($cfg, $storeid);
270 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
271 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
272 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
273 die "snapshot delete file/device '$volid' is not possible\n";
274 } else {
275 die "unable to parse volume ID '$volid'\n";
276 }
277 }
278
279 sub volume_has_feature {
280 my ($cfg, $feature, $volid, $snap, $running) = @_;
281
282 my ($storeid, $volname) = parse_volume_id($volid, 1);
283 if ($storeid) {
284 my $scfg = storage_config($cfg, $storeid);
285 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
286 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running);
287 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
288 return undef;
289 } else {
290 return undef;
291 }
292 }
293
294 sub volume_snapshot_list {
295 my ($cfg, $volid) = @_;
296
297 my ($storeid, $volname) = parse_volume_id($volid, 1);
298 if ($storeid) {
299 my $scfg = storage_config($cfg, $storeid);
300 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
301 return $plugin->volume_snapshot_list($scfg, $storeid, $volname);
302 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
303 die "send file/device '$volid' is not possible\n";
304 } else {
305 die "unable to parse volume ID '$volid'\n";
306 }
307 # return an empty array if dataset does not exist.
308 }
309
310 sub get_image_dir {
311 my ($cfg, $storeid, $vmid) = @_;
312
313 my $scfg = storage_config($cfg, $storeid);
314 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
315
316 my $path = $plugin->get_subdir($scfg, 'images');
317
318 return $vmid ? "$path/$vmid" : $path;
319 }
320
321 sub get_private_dir {
322 my ($cfg, $storeid, $vmid) = @_;
323
324 my $scfg = storage_config($cfg, $storeid);
325 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
326
327 my $path = $plugin->get_subdir($scfg, 'rootdir');
328
329 return $vmid ? "$path/$vmid" : $path;
330 }
331
332 sub get_iso_dir {
333 my ($cfg, $storeid) = @_;
334
335 my $scfg = storage_config($cfg, $storeid);
336 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
337
338 return $plugin->get_subdir($scfg, 'iso');
339 }
340
341 sub get_vztmpl_dir {
342 my ($cfg, $storeid) = @_;
343
344 my $scfg = storage_config($cfg, $storeid);
345 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
346
347 return $plugin->get_subdir($scfg, 'vztmpl');
348 }
349
350 sub get_backup_dir {
351 my ($cfg, $storeid) = @_;
352
353 my $scfg = storage_config($cfg, $storeid);
354 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
355
356 return $plugin->get_subdir($scfg, 'backup');
357 }
358
359 # library implementation
360
361 sub parse_vmid {
362 my $vmid = shift;
363
364 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
365
366 return int($vmid);
367 }
368
369 # NOTE: basename and basevmid are always undef for LVM-thin, where the
370 # clone -> base reference is not encoded in the volume ID.
371 # see note in PVE::Storage::LvmThinPlugin for details.
372 sub parse_volname {
373 my ($cfg, $volid) = @_;
374
375 my ($storeid, $volname) = parse_volume_id($volid);
376
377 my $scfg = storage_config($cfg, $storeid);
378
379 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
380
381 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
382
383 return $plugin->parse_volname($volname);
384 }
385
386 sub parse_volume_id {
387 my ($volid, $noerr) = @_;
388
389 return PVE::Storage::Plugin::parse_volume_id($volid, $noerr);
390 }
391
392 # test if we have read access to volid
393 sub check_volume_access {
394 my ($rpcenv, $user, $cfg, $vmid, $volid) = @_;
395
396 my ($sid, $volname) = parse_volume_id($volid, 1);
397 if ($sid) {
398 my ($vtype, undef, $ownervm) = parse_volname($cfg, $volid);
399 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
400 # require at least read access to storage, (custom) templates/ISOs could be sensitive
401 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
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 # lists all files in the snippets directory
775 sub snippets_list {
776 my ($cfg, $storeid) = @_;
777
778 my $ids = $cfg->{ids};
779
780 storage_check_enabled($cfg, $storeid) if ($storeid);
781
782 my $res = {};
783
784 foreach my $sid (keys %$ids) {
785 next if $storeid && $storeid ne $sid;
786 next if !storage_check_enabled($cfg, $sid, undef, 1);
787
788 my $scfg = $ids->{$sid};
789 next if !$scfg->{content}->{snippets};
790
791 activate_storage($cfg, $sid);
792
793 if ($scfg->{path}) {
794 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
795 my $path = $plugin->get_subdir($scfg, 'snippets');
796
797 foreach my $fn (<$path/*>) {
798 next if -d $fn;
799
800 push @{$res->{$sid}}, {
801 volid => "$sid:snippets/". basename($fn),
802 format => 'snippet',
803 size => -s $fn,
804 };
805 }
806 }
807
808 if ($res->{$sid}) {
809 @{$res->{$sid}} = sort {$a->{volid} cmp $b->{volid} } @{$res->{$sid}};
810 }
811 }
812
813 return $res;
814 }
815
816 #list iso or openvz template ($tt = <iso|vztmpl|backup>)
817 sub template_list {
818 my ($cfg, $storeid, $tt) = @_;
819
820 die "unknown template type '$tt'\n"
821 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup');
822
823 my $ids = $cfg->{ids};
824
825 storage_check_enabled($cfg, $storeid) if ($storeid);
826
827 my $res = {};
828
829 # query the storage
830
831 foreach my $sid (keys %$ids) {
832 next if $storeid && $storeid ne $sid;
833
834 my $scfg = $ids->{$sid};
835 my $type = $scfg->{type};
836
837 next if !storage_check_enabled($cfg, $sid, undef, 1);
838
839 next if $tt eq 'iso' && !$scfg->{content}->{iso};
840 next if $tt eq 'vztmpl' && !$scfg->{content}->{vztmpl};
841 next if $tt eq 'backup' && !$scfg->{content}->{backup};
842
843 activate_storage($cfg, $sid);
844
845 if ($scfg->{path}) {
846 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
847
848 my $path = $plugin->get_subdir($scfg, $tt);
849
850 foreach my $fn (<$path/*>) {
851
852 my $info;
853
854 if ($tt eq 'iso') {
855 next if $fn !~ m!/([^/]+\.[Ii][Ss][Oo])$!;
856
857 $info = { volid => "$sid:iso/$1", format => 'iso' };
858
859 } elsif ($tt eq 'vztmpl') {
860 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
861
862 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
863
864 } elsif ($tt eq 'backup') {
865 next if $fn !~ m!/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!;
866
867 $info = { volid => "$sid:backup/$1", format => $2 };
868 }
869
870 $info->{size} = -s $fn;
871
872 push @{$res->{$sid}}, $info;
873 }
874
875 }
876
877 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
878 }
879
880 return $res;
881 }
882
883
884 sub vdisk_list {
885 my ($cfg, $storeid, $vmid, $vollist) = @_;
886
887 my $ids = $cfg->{ids};
888
889 storage_check_enabled($cfg, $storeid) if ($storeid);
890
891 my $res = {};
892
893 # prepare/activate/refresh all storages
894
895 my $storage_list = [];
896 if ($vollist) {
897 foreach my $volid (@$vollist) {
898 my ($sid, undef) = parse_volume_id($volid);
899 next if !defined($ids->{$sid});
900 next if !storage_check_enabled($cfg, $sid, undef, 1);
901 push @$storage_list, $sid;
902 }
903 } else {
904 foreach my $sid (keys %$ids) {
905 next if $storeid && $storeid ne $sid;
906 next if !storage_check_enabled($cfg, $sid, undef, 1);
907 push @$storage_list, $sid;
908 }
909 }
910
911 my $cache = {};
912
913 activate_storage_list($cfg, $storage_list, $cache);
914
915 foreach my $sid (keys %$ids) {
916 next if $storeid && $storeid ne $sid;
917 next if !storage_check_enabled($cfg, $sid, undef, 1);
918
919 my $scfg = $ids->{$sid};
920 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
921 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
922 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
923 }
924
925 return $res;
926 }
927
928 sub volume_list {
929 my ($cfg, $storeid, $vmid, $content) = @_;
930
931 my @ctypes = qw(images vztmpl iso backup snippets);
932
933 my $cts = $content ? [ $content ] : [ @ctypes ];
934
935 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
936
937 my $res = [];
938 foreach my $ct (@$cts) {
939 my $data;
940 if ($ct eq 'images') {
941 $data = vdisk_list($cfg, $storeid, $vmid);
942 } elsif ($ct eq 'iso' && !defined($vmid)) {
943 $data = template_list($cfg, $storeid, 'iso');
944 } elsif ($ct eq 'vztmpl'&& !defined($vmid)) {
945 $data = template_list ($cfg, $storeid, 'vztmpl');
946 } elsif ($ct eq 'backup') {
947 $data = template_list ($cfg, $storeid, 'backup');
948 foreach my $item (@{$data->{$storeid}}) {
949 if (defined($vmid)) {
950 @{$data->{$storeid}} = grep { $_->{volid} =~ m/\S+-$vmid-\S+/ } @{$data->{$storeid}};
951 }
952 }
953 } elsif ($ct eq 'snippets') {
954 $data = snippets_list($cfg, $storeid);
955 }
956
957 next if !$data || !$data->{$storeid};
958
959 foreach my $item (@{$data->{$storeid}}) {
960 $item->{content} = $ct;
961 push @$res, $item;
962 }
963 }
964
965 return $res;
966 }
967
968 sub uevent_seqnum {
969
970 my $filename = "/sys/kernel/uevent_seqnum";
971
972 my $seqnum = 0;
973 if (my $fh = IO::File->new($filename, "r")) {
974 my $line = <$fh>;
975 if ($line =~ m/^(\d+)$/) {
976 $seqnum = int($1);
977 }
978 close ($fh);
979 }
980 return $seqnum;
981 }
982
983 sub activate_storage {
984 my ($cfg, $storeid, $cache) = @_;
985
986 $cache = {} if !$cache;
987
988 my $scfg = storage_check_enabled($cfg, $storeid);
989
990 return if $cache->{activated}->{$storeid};
991
992 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
993
994 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
995
996 if ($scfg->{base}) {
997 my ($baseid, undef) = parse_volume_id ($scfg->{base});
998 activate_storage($cfg, $baseid, $cache);
999 }
1000
1001 if (!$plugin->check_connection($storeid, $scfg)) {
1002 die "storage '$storeid' is not online\n";
1003 }
1004
1005 $plugin->activate_storage($storeid, $scfg, $cache);
1006
1007 my $newseq = uevent_seqnum ();
1008
1009 # only call udevsettle if there are events
1010 if ($newseq > $cache->{uevent_seqnum}) {
1011 my $timeout = 30;
1012 system ("$UDEVADM settle --timeout=$timeout"); # ignore errors
1013 $cache->{uevent_seqnum} = $newseq;
1014 }
1015
1016 $cache->{activated}->{$storeid} = 1;
1017 }
1018
1019 sub activate_storage_list {
1020 my ($cfg, $storeid_list, $cache) = @_;
1021
1022 $cache = {} if !$cache;
1023
1024 foreach my $storeid (@$storeid_list) {
1025 activate_storage($cfg, $storeid, $cache);
1026 }
1027 }
1028
1029 sub deactivate_storage {
1030 my ($cfg, $storeid) = @_;
1031
1032 my $scfg = storage_config ($cfg, $storeid);
1033 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1034
1035 my $cache = {};
1036 $plugin->deactivate_storage($storeid, $scfg, $cache);
1037 }
1038
1039 sub activate_volumes {
1040 my ($cfg, $vollist, $snapname) = @_;
1041
1042 return if !($vollist && scalar(@$vollist));
1043
1044 my $storagehash = {};
1045 foreach my $volid (@$vollist) {
1046 my ($storeid, undef) = parse_volume_id($volid);
1047 $storagehash->{$storeid} = 1;
1048 }
1049
1050 my $cache = {};
1051
1052 activate_storage_list($cfg, [keys %$storagehash], $cache);
1053
1054 foreach my $volid (@$vollist) {
1055 my ($storeid, $volname) = parse_volume_id($volid);
1056 my $scfg = storage_config($cfg, $storeid);
1057 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1058 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1059 }
1060 }
1061
1062 sub deactivate_volumes {
1063 my ($cfg, $vollist, $snapname) = @_;
1064
1065 return if !($vollist && scalar(@$vollist));
1066
1067 my $cache = {};
1068
1069 my @errlist = ();
1070 foreach my $volid (@$vollist) {
1071 my ($storeid, $volname) = parse_volume_id($volid);
1072
1073 my $scfg = storage_config($cfg, $storeid);
1074 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1075
1076 eval {
1077 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1078 };
1079 if (my $err = $@) {
1080 warn $err;
1081 push @errlist, $volid;
1082 }
1083 }
1084
1085 die "volume deactivation failed: " . join(' ', @errlist)
1086 if scalar(@errlist);
1087 }
1088
1089 sub storage_info {
1090 my ($cfg, $content, $includeformat) = @_;
1091
1092 my $ids = $cfg->{ids};
1093
1094 my $info = {};
1095
1096 my @ctypes = PVE::Tools::split_list($content);
1097
1098 my $slist = [];
1099 foreach my $storeid (keys %$ids) {
1100 my $storage_enabled = defined(storage_check_enabled($cfg, $storeid, undef, 1));
1101
1102 if (defined($content)) {
1103 my $want_ctype = 0;
1104 foreach my $ctype (@ctypes) {
1105 if ($ids->{$storeid}->{content}->{$ctype}) {
1106 $want_ctype = 1;
1107 last;
1108 }
1109 }
1110 next if !$want_ctype || !$storage_enabled;
1111 }
1112
1113 my $type = $ids->{$storeid}->{type};
1114
1115 $info->{$storeid} = {
1116 type => $type,
1117 total => 0,
1118 avail => 0,
1119 used => 0,
1120 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1121 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
1122 active => 0,
1123 enabled => $storage_enabled ? 1 : 0,
1124 };
1125
1126 push @$slist, $storeid;
1127 }
1128
1129 my $cache = {};
1130
1131 foreach my $storeid (keys %$ids) {
1132 my $scfg = $ids->{$storeid};
1133
1134 next if !$info->{$storeid};
1135 next if !$info->{$storeid}->{enabled};
1136
1137 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1138 if ($includeformat) {
1139 my $pd = $plugin->plugindata();
1140 $info->{$storeid}->{format} = $pd->{format}
1141 if $pd->{format};
1142 $info->{$storeid}->{select_existing} = $pd->{select_existing}
1143 if $pd->{select_existing};
1144 }
1145
1146 eval { activate_storage($cfg, $storeid, $cache); };
1147 if (my $err = $@) {
1148 warn $err;
1149 next;
1150 }
1151
1152 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
1153 warn $@ if $@;
1154 next if !$active;
1155 $info->{$storeid}->{total} = int($total);
1156 $info->{$storeid}->{avail} = int($avail);
1157 $info->{$storeid}->{used} = int($used);
1158 $info->{$storeid}->{active} = $active;
1159 }
1160
1161 return $info;
1162 }
1163
1164 sub resolv_server {
1165 my ($server) = @_;
1166
1167 my ($packed_ip, $family);
1168 eval {
1169 my @res = PVE::Tools::getaddrinfo_all($server);
1170 $family = $res[0]->{family};
1171 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1172 };
1173 if (defined $packed_ip) {
1174 return Socket::inet_ntop($family, $packed_ip);
1175 }
1176 return undef;
1177 }
1178
1179 sub scan_nfs {
1180 my ($server_in) = @_;
1181
1182 my $server;
1183 if (!($server = resolv_server ($server_in))) {
1184 die "unable to resolve address for server '${server_in}'\n";
1185 }
1186
1187 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1188
1189 my $res = {};
1190 run_command($cmd, outfunc => sub {
1191 my $line = shift;
1192
1193 # note: howto handle white spaces in export path??
1194 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1195 $res->{$1} = $2;
1196 }
1197 });
1198
1199 return $res;
1200 }
1201
1202 sub scan_cifs {
1203 my ($server_in, $user, $password, $domain) = @_;
1204
1205 my $server;
1206 if (!($server = resolv_server ($server_in))) {
1207 die "unable to resolve address for server '${server_in}'\n";
1208 }
1209
1210 # we support only Windows grater than 2012 cifsscan so use smb3
1211 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1212 if (defined($user)) {
1213 die "password is required" if !defined($password);
1214 push @$cmd, '-U', "$user\%$password";
1215 push @$cmd, '-W', $domain if defined($domain);
1216 } else {
1217 push @$cmd, '-N';
1218 }
1219
1220 my $res = {};
1221 run_command($cmd,
1222 outfunc => sub {
1223 my $line = shift;
1224 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1225 $res->{$1} = $2;
1226 } elsif ($line =~ m/(NT_STATUS_(\S*))/) {
1227 $res->{$1} = '';
1228 }
1229 },
1230 errfunc => sub {},
1231 noerr => 1
1232 );
1233
1234 return $res;
1235 }
1236
1237 sub scan_zfs {
1238
1239 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-H', '-o', 'name,avail,used'];
1240
1241 my $res = [];
1242 run_command($cmd, outfunc => sub {
1243 my $line = shift;
1244
1245 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1246 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1247 my $size = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($size_str);
1248 my $used = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($used_str);
1249 # ignore subvolumes generated by our ZFSPoolPlugin
1250 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1251 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1252 push @$res, { pool => $pool, size => $size, free => $size-$used };
1253 }
1254 });
1255
1256 return $res;
1257 }
1258
1259 sub resolv_portal {
1260 my ($portal, $noerr) = @_;
1261
1262 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1263 if ($server) {
1264 if (my $ip = resolv_server($server)) {
1265 $server = $ip;
1266 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1267 return $port ? "$server:$port" : $server;
1268 }
1269 }
1270 return undef if $noerr;
1271
1272 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1273 }
1274
1275
1276 sub scan_iscsi {
1277 my ($portal_in) = @_;
1278
1279 my $portal;
1280 if (!($portal = resolv_portal($portal_in))) {
1281 die "unable to parse/resolve portal address '${portal_in}'\n";
1282 }
1283
1284 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
1285 }
1286
1287 sub storage_default_format {
1288 my ($cfg, $storeid) = @_;
1289
1290 my $scfg = storage_config ($cfg, $storeid);
1291
1292 return PVE::Storage::Plugin::default_format($scfg);
1293 }
1294
1295 sub vgroup_is_used {
1296 my ($cfg, $vgname) = @_;
1297
1298 foreach my $storeid (keys %{$cfg->{ids}}) {
1299 my $scfg = storage_config($cfg, $storeid);
1300 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1301 return 1;
1302 }
1303 }
1304
1305 return undef;
1306 }
1307
1308 sub target_is_used {
1309 my ($cfg, $target) = @_;
1310
1311 foreach my $storeid (keys %{$cfg->{ids}}) {
1312 my $scfg = storage_config($cfg, $storeid);
1313 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1314 return 1;
1315 }
1316 }
1317
1318 return undef;
1319 }
1320
1321 sub volume_is_used {
1322 my ($cfg, $volid) = @_;
1323
1324 foreach my $storeid (keys %{$cfg->{ids}}) {
1325 my $scfg = storage_config($cfg, $storeid);
1326 if ($scfg->{base} && $scfg->{base} eq $volid) {
1327 return 1;
1328 }
1329 }
1330
1331 return undef;
1332 }
1333
1334 sub storage_is_used {
1335 my ($cfg, $storeid) = @_;
1336
1337 foreach my $sid (keys %{$cfg->{ids}}) {
1338 my $scfg = storage_config($cfg, $sid);
1339 next if !$scfg->{base};
1340 my ($st) = parse_volume_id($scfg->{base});
1341 return 1 if $st && $st eq $storeid;
1342 }
1343
1344 return undef;
1345 }
1346
1347 sub foreach_volid {
1348 my ($list, $func) = @_;
1349
1350 return if !$list;
1351
1352 foreach my $sid (keys %$list) {
1353 foreach my $info (@{$list->{$sid}}) {
1354 my $volid = $info->{volid};
1355 my ($sid1, $volname) = parse_volume_id($volid, 1);
1356 if ($sid1 && $sid1 eq $sid) {
1357 &$func ($volid, $sid, $info);
1358 } else {
1359 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1360 }
1361 }
1362 }
1363 }
1364
1365 sub extract_vzdump_config_tar {
1366 my ($archive, $conf_re) = @_;
1367
1368 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1369
1370 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1371 die "unable to open file '$archive'\n";
1372
1373 my $file;
1374 while (defined($file = <$fh>)) {
1375 if ($file =~ $conf_re) {
1376 $file = $1; # untaint
1377 last;
1378 }
1379 }
1380
1381 kill 15, $pid;
1382 waitpid $pid, 0;
1383 close $fh;
1384
1385 die "ERROR: archive contains no configuration file\n" if !$file;
1386 chomp $file;
1387
1388 my $raw = '';
1389 my $out = sub {
1390 my $output = shift;
1391 $raw .= "$output\n";
1392 };
1393
1394 PVE::Tools::run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
1395
1396 return wantarray ? ($raw, $file) : $raw;
1397 }
1398
1399 sub extract_vzdump_config_vma {
1400 my ($archive, $comp) = @_;
1401
1402 my $cmd;
1403 my $raw = '';
1404 my $out = sub {
1405 my $output = shift;
1406 $raw .= "$output\n";
1407 };
1408
1409
1410 if ($comp) {
1411 my $uncomp;
1412 if ($comp eq 'gz') {
1413 $uncomp = ["zcat", $archive];
1414 } elsif ($comp eq 'lzo') {
1415 $uncomp = ["lzop", "-d", "-c", $archive];
1416 } else {
1417 die "unknown compression method '$comp'\n";
1418 }
1419 $cmd = [$uncomp, ["vma", "config", "-"]];
1420
1421 # in some cases, lzop/zcat exits with 1 when its stdout pipe is
1422 # closed early by vma, detect this and ignore the exit code later
1423 my $broken_pipe;
1424 my $errstring;
1425 my $err = sub {
1426 my $output = shift;
1427 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/) {
1428 $broken_pipe = 1;
1429 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1430 $errstring = "Failed to extract config from VMA archive: $output\n";
1431 }
1432 };
1433
1434 # in other cases, the pipeline will exit with exit code 141
1435 # because of the broken pipe, handle / ignore this as well
1436 my $rc;
1437 eval {
1438 $rc = PVE::Tools::run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1);
1439 };
1440 my $rerr = $@;
1441
1442 # use exit code if no stderr output and not just broken pipe
1443 if (!$errstring && !$broken_pipe && $rc != 0 && $rc != 141) {
1444 die "$rerr\n" if $rerr;
1445 die "config extraction failed with exit code $rc\n";
1446 }
1447 die "$errstring\n" if $errstring;
1448 } else {
1449 # simple case without compression and weird piping behaviour
1450 PVE::Tools::run_command(["vma", "config", $archive], outfunc => $out);
1451 }
1452
1453 return wantarray ? ($raw, undef) : $raw;
1454 }
1455
1456 sub extract_vzdump_config {
1457 my ($cfg, $volid) = @_;
1458
1459 my $archive = abs_filesystem_path($cfg, $volid);
1460
1461 if ($volid =~ /vzdump-(lxc|openvz)-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|(tar(\.(gz|lzo))?))$/) {
1462 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1463 } elsif ($volid =~ /vzdump-qemu-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?))$/) {
1464 my $format;
1465 my $comp;
1466 if ($7 eq 'tgz') {
1467 $format = 'tar';
1468 $comp = 'gz';
1469 } else {
1470 $format = $9;
1471 $comp = $11 if defined($11);
1472 }
1473
1474 if ($format eq 'tar') {
1475 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1476 } else {
1477 return extract_vzdump_config_vma($archive, $comp);
1478 }
1479 } else {
1480 die "cannot determine backup guest type for backup archive '$volid'\n";
1481 }
1482 }
1483
1484 sub volume_export {
1485 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1486
1487 my ($storeid, $volname) = parse_volume_id($volid, 1);
1488 die "cannot export volume '$volid'\n" if !$storeid;
1489 my $scfg = storage_config($cfg, $storeid);
1490 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1491 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1492 $snapshot, $base_snapshot, $with_snapshots);
1493 }
1494
1495 sub volume_import {
1496 my ($cfg, $fh, $volid, $format, $base_snapshot, $with_snapshots) = @_;
1497
1498 my ($storeid, $volname) = parse_volume_id($volid, 1);
1499 die "cannot import into volume '$volid'\n" if !$storeid;
1500 my $scfg = storage_config($cfg, $storeid);
1501 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1502 return $plugin->volume_import($scfg, $storeid, $fh, $volname, $format,
1503 $base_snapshot, $with_snapshots);
1504 }
1505
1506 sub volume_export_formats {
1507 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1508
1509 my ($storeid, $volname) = parse_volume_id($volid, 1);
1510 return if !$storeid;
1511 my $scfg = storage_config($cfg, $storeid);
1512 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1513 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1514 $snapshot, $base_snapshot,
1515 $with_snapshots);
1516 }
1517
1518 sub volume_import_formats {
1519 my ($cfg, $volid, $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_import_formats($scfg, $storeid, $volname,
1526 $base_snapshot, $with_snapshots);
1527 }
1528
1529 sub volume_transfer_formats {
1530 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1531 my @export_formats = volume_export_formats($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1532 my @import_formats = volume_import_formats($cfg, $dst_volid, $base_snapshot, $with_snapshots);
1533 my %import_hash = map { $_ => 1 } @import_formats;
1534 my @common = grep { $import_hash{$_} } @export_formats;
1535 return @common;
1536 }
1537
1538 # bash completion helper
1539
1540 sub complete_storage {
1541 my ($cmdname, $pname, $cvalue) = @_;
1542
1543 my $cfg = PVE::Storage::config();
1544
1545 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
1546 }
1547
1548 sub complete_storage_enabled {
1549 my ($cmdname, $pname, $cvalue) = @_;
1550
1551 my $res = [];
1552
1553 my $cfg = PVE::Storage::config();
1554 foreach my $sid (keys %{$cfg->{ids}}) {
1555 next if !storage_check_enabled($cfg, $sid, undef, 1);
1556 push @$res, $sid;
1557 }
1558 return $res;
1559 }
1560
1561 sub complete_content_type {
1562 my ($cmdname, $pname, $cvalue) = @_;
1563
1564 return [qw(rootdir images vztmpl iso backup snippets)];
1565 }
1566
1567 sub complete_volume {
1568 my ($cmdname, $pname, $cvalue) = @_;
1569
1570 my $cfg = config();
1571
1572 my $storage_list = complete_storage_enabled();
1573
1574 if ($cvalue =~ m/^([^:]+):/) {
1575 $storage_list = [ $1 ];
1576 } else {
1577 if (scalar(@$storage_list) > 1) {
1578 # only list storage IDs to avoid large listings
1579 my $res = [];
1580 foreach my $storeid (@$storage_list) {
1581 # Hack: simply return 2 artificial values, so that
1582 # completions does not finish
1583 push @$res, "$storeid:volname", "$storeid:...";
1584 }
1585 return $res;
1586 }
1587 }
1588
1589 my $res = [];
1590 foreach my $storeid (@$storage_list) {
1591 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
1592
1593 foreach my $item (@$vollist) {
1594 push @$res, $item->{volid};
1595 }
1596 }
1597
1598 return $res;
1599 }
1600
1601 # Various io-heavy operations require io/bandwidth limits which can be
1602 # configured on multiple levels: The global defaults in datacenter.cfg, and
1603 # per-storage overrides. When we want to do a restore from storage A to storage
1604 # B, we should take the smaller limit defined for storages A and B, and if no
1605 # such limit was specified, use the one from datacenter.cfg.
1606 sub get_bandwidth_limit {
1607 my ($operation, $storage_list, $override) = @_;
1608
1609 # called for each limit (global, per-storage) with the 'default' and the
1610 # $operation limit and should udpate $override for every limit affecting
1611 # us.
1612 my $use_global_limits = 0;
1613 my $apply_limit = sub {
1614 my ($bwlimit) = @_;
1615 if (defined($bwlimit)) {
1616 my $limits = PVE::JSONSchema::parse_property_string('bwlimit', $bwlimit);
1617 my $limit = $limits->{$operation} // $limits->{default};
1618 if (defined($limit)) {
1619 if (!$override || $limit < $override) {
1620 $override = $limit;
1621 }
1622 return;
1623 }
1624 }
1625 # If there was no applicable limit, try to apply the global ones.
1626 $use_global_limits = 1;
1627 };
1628
1629 my ($rpcenv, $authuser);
1630 if (defined($override)) {
1631 $rpcenv = PVE::RPCEnvironment->get();
1632 $authuser = $rpcenv->get_user();
1633 }
1634
1635 # Apply per-storage limits - if there are storages involved.
1636 if (defined($storage_list) && @$storage_list) {
1637 my $config = config();
1638
1639 # The Datastore.Allocate permission allows us to modify the per-storage
1640 # limits, therefore it also allows us to override them.
1641 # Since we have most likely multiple storages to check, do a quick check on
1642 # the general '/storage' path to see if we can skip the checks entirely:
1643 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
1644
1645 my %done;
1646 foreach my $storage (@$storage_list) {
1647 next if !defined($storage);
1648 # Avoid duplicate checks:
1649 next if $done{$storage};
1650 $done{$storage} = 1;
1651
1652 # Otherwise we may still have individual /storage/$ID permissions:
1653 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
1654 # And if not: apply the limits.
1655 my $storecfg = storage_config($config, $storage);
1656 $apply_limit->($storecfg->{bwlimit});
1657 }
1658 }
1659
1660 # Storage limits take precedence over the datacenter defaults, so if
1661 # a limit was applied:
1662 return $override if !$use_global_limits;
1663 }
1664
1665 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
1666 # global default limits.
1667 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
1668 # So if we cannot modify global limits, apply them to our currently
1669 # requested override.
1670 my $dc = cfs_read_file('datacenter.cfg');
1671 $apply_limit->($dc->{bwlimit});
1672 }
1673
1674 return $override;
1675 }
1676
1677 # checks if the storage id is available and dies if not
1678 sub assert_sid_unused {
1679 my ($sid) = @_;
1680
1681 my $cfg = config();
1682 if (my $scfg = storage_config($cfg, $sid, 1)) {
1683 die "storage ID '$sid' already defined\n";
1684 }
1685
1686 return undef;
1687 }
1688
1689 1;