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