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