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