]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage.pm
bump version to 8.2.1
[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);
1069 eval { ($total, $avail, $used, $active) = $plugin->status($storeid, $scfg, $cache); };
1070 warn $@ if $@;
1071 next if !$active;
1072 $info->{$storeid}->{total} = int($total);
1073 $info->{$storeid}->{avail} = int($avail);
1074 $info->{$storeid}->{used} = int($used);
1075 $info->{$storeid}->{active} = $active;
1076 }
1077
1078 return $info;
1079 }
1080
1081 sub resolv_server {
1082 my ($server) = @_;
1083
1084 my ($packed_ip, $family);
1085 eval {
1086 my @res = PVE::Tools::getaddrinfo_all($server);
1087 $family = $res[0]->{family};
1088 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1089 };
1090 if (defined $packed_ip) {
1091 return Socket::inet_ntop($family, $packed_ip);
1092 }
1093 return undef;
1094 }
1095
1096 sub scan_nfs {
1097 my ($server_in) = @_;
1098
1099 my $server;
1100 if (!($server = resolv_server ($server_in))) {
1101 die "unable to resolve address for server '${server_in}'\n";
1102 }
1103
1104 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1105
1106 my $res = {};
1107 run_command($cmd, outfunc => sub {
1108 my $line = shift;
1109
1110 # note: howto handle white spaces in export path??
1111 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1112 $res->{$1} = $2;
1113 }
1114 });
1115
1116 return $res;
1117 }
1118
1119 sub scan_cifs {
1120 my ($server_in, $user, $password, $domain) = @_;
1121
1122 my $server;
1123 if (!($server = resolv_server ($server_in))) {
1124 die "unable to resolve address for server '${server_in}'\n";
1125 }
1126
1127 # we support only Windows grater than 2012 cifsscan so use smb3
1128 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1129 if (defined($user)) {
1130 die "password is required" if !defined($password);
1131 push @$cmd, '-U', "$user\%$password";
1132 push @$cmd, '-W', $domain if defined($domain);
1133 } else {
1134 push @$cmd, '-N';
1135 }
1136
1137 my $res = {};
1138 run_command($cmd,
1139 outfunc => sub {
1140 my $line = shift;
1141 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1142 $res->{$1} = $2;
1143 } elsif ($line =~ m/(NT_STATUS_(\S*))/) {
1144 $res->{$1} = '';
1145 }
1146 },
1147 errfunc => sub {},
1148 noerr => 1
1149 );
1150
1151 return $res;
1152 }
1153
1154 sub scan_zfs {
1155
1156 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-H', '-o', 'name,avail,used'];
1157
1158 my $res = [];
1159 run_command($cmd, outfunc => sub {
1160 my $line = shift;
1161
1162 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1163 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1164 my $size = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($size_str);
1165 my $used = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($used_str);
1166 # ignore subvolumes generated by our ZFSPoolPlugin
1167 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1168 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1169 push @$res, { pool => $pool, size => $size, free => $size-$used };
1170 }
1171 });
1172
1173 return $res;
1174 }
1175
1176 sub resolv_portal {
1177 my ($portal, $noerr) = @_;
1178
1179 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1180 if ($server) {
1181 if (my $ip = resolv_server($server)) {
1182 $server = $ip;
1183 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1184 return $port ? "$server:$port" : $server;
1185 }
1186 }
1187 return undef if $noerr;
1188
1189 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1190 }
1191
1192 # idea is from usbutils package (/usr/bin/usb-devices) script
1193 sub __scan_usb_device {
1194 my ($res, $devpath, $parent, $level) = @_;
1195
1196 return if ! -d $devpath;
1197 return if $level && $devpath !~ m/^.*[-.](\d+)$/;
1198 my $port = $level ? int($1 - 1) : 0;
1199
1200 my $busnum = int(file_read_firstline("$devpath/busnum"));
1201 my $devnum = int(file_read_firstline("$devpath/devnum"));
1202
1203 my $d = {
1204 port => $port,
1205 level => $level,
1206 busnum => $busnum,
1207 devnum => $devnum,
1208 speed => file_read_firstline("$devpath/speed"),
1209 class => hex(file_read_firstline("$devpath/bDeviceClass")),
1210 vendid => file_read_firstline("$devpath/idVendor"),
1211 prodid => file_read_firstline("$devpath/idProduct"),
1212 };
1213
1214 if ($level) {
1215 my $usbpath = $devpath;
1216 $usbpath =~ s|^.*/\d+\-||;
1217 $d->{usbpath} = $usbpath;
1218 }
1219
1220 my $product = file_read_firstline("$devpath/product");
1221 $d->{product} = $product if $product;
1222
1223 my $manu = file_read_firstline("$devpath/manufacturer");
1224 $d->{manufacturer} = $manu if $manu;
1225
1226 my $serial => file_read_firstline("$devpath/serial");
1227 $d->{serial} = $serial if $serial;
1228
1229 push @$res, $d;
1230
1231 foreach my $subdev (<$devpath/$busnum-*>) {
1232 next if $subdev !~ m|/$busnum-[0-9]+(\.[0-9]+)*$|;
1233 __scan_usb_device($res, $subdev, $devnum, $level + 1);
1234 }
1235
1236 };
1237
1238 sub scan_usb {
1239
1240 my $devlist = [];
1241
1242 foreach my $device (</sys/bus/usb/devices/usb*>) {
1243 __scan_usb_device($devlist, $device, 0, 0);
1244 }
1245
1246 return $devlist;
1247 }
1248
1249 sub scan_iscsi {
1250 my ($portal_in) = @_;
1251
1252 my $portal;
1253 if (!($portal = resolv_portal($portal_in))) {
1254 die "unable to parse/resolve portal address '${portal_in}'\n";
1255 }
1256
1257 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
1258 }
1259
1260 sub storage_default_format {
1261 my ($cfg, $storeid) = @_;
1262
1263 my $scfg = storage_config ($cfg, $storeid);
1264
1265 return PVE::Storage::Plugin::default_format($scfg);
1266 }
1267
1268 sub vgroup_is_used {
1269 my ($cfg, $vgname) = @_;
1270
1271 foreach my $storeid (keys %{$cfg->{ids}}) {
1272 my $scfg = storage_config($cfg, $storeid);
1273 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1274 return 1;
1275 }
1276 }
1277
1278 return undef;
1279 }
1280
1281 sub target_is_used {
1282 my ($cfg, $target) = @_;
1283
1284 foreach my $storeid (keys %{$cfg->{ids}}) {
1285 my $scfg = storage_config($cfg, $storeid);
1286 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1287 return 1;
1288 }
1289 }
1290
1291 return undef;
1292 }
1293
1294 sub volume_is_used {
1295 my ($cfg, $volid) = @_;
1296
1297 foreach my $storeid (keys %{$cfg->{ids}}) {
1298 my $scfg = storage_config($cfg, $storeid);
1299 if ($scfg->{base} && $scfg->{base} eq $volid) {
1300 return 1;
1301 }
1302 }
1303
1304 return undef;
1305 }
1306
1307 sub storage_is_used {
1308 my ($cfg, $storeid) = @_;
1309
1310 foreach my $sid (keys %{$cfg->{ids}}) {
1311 my $scfg = storage_config($cfg, $sid);
1312 next if !$scfg->{base};
1313 my ($st) = parse_volume_id($scfg->{base});
1314 return 1 if $st && $st eq $storeid;
1315 }
1316
1317 return undef;
1318 }
1319
1320 sub foreach_volid {
1321 my ($list, $func) = @_;
1322
1323 return if !$list;
1324
1325 foreach my $sid (keys %$list) {
1326 foreach my $info (@{$list->{$sid}}) {
1327 my $volid = $info->{volid};
1328 my ($sid1, $volname) = parse_volume_id($volid, 1);
1329 if ($sid1 && $sid1 eq $sid) {
1330 &$func ($volid, $sid, $info);
1331 } else {
1332 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1333 }
1334 }
1335 }
1336 }
1337
1338 sub extract_vzdump_config_tar {
1339 my ($archive, $conf_re) = @_;
1340
1341 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1342
1343 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1344 die "unable to open file '$archive'\n";
1345
1346 my $file;
1347 while (defined($file = <$fh>)) {
1348 if ($file =~ $conf_re) {
1349 $file = $1; # untaint
1350 last;
1351 }
1352 }
1353
1354 kill 15, $pid;
1355 waitpid $pid, 0;
1356 close $fh;
1357
1358 die "ERROR: archive contains no configuration file\n" if !$file;
1359 chomp $file;
1360
1361 my $raw = '';
1362 my $out = sub {
1363 my $output = shift;
1364 $raw .= "$output\n";
1365 };
1366
1367 PVE::Tools::run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
1368
1369 return wantarray ? ($raw, $file) : $raw;
1370 }
1371
1372 sub extract_vzdump_config_vma {
1373 my ($archive, $comp) = @_;
1374
1375 my $cmd;
1376 my $raw = '';
1377 my $out = sub {
1378 my $output = shift;
1379 $raw .= "$output\n";
1380 };
1381
1382
1383 if ($comp) {
1384 my $uncomp;
1385 if ($comp eq 'gz') {
1386 $uncomp = ["zcat", $archive];
1387 } elsif ($comp eq 'lzo') {
1388 $uncomp = ["lzop", "-d", "-c", $archive];
1389 } else {
1390 die "unknown compression method '$comp'\n";
1391 }
1392 $cmd = [$uncomp, ["vma", "config", "-"]];
1393
1394 # in some cases, lzop/zcat exits with 1 when its stdout pipe is
1395 # closed early by vma, detect this and ignore the exit code later
1396 my $broken_pipe;
1397 my $errstring;
1398 my $err = sub {
1399 my $output = shift;
1400 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/) {
1401 $broken_pipe = 1;
1402 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1403 $errstring = "Failed to extract config from VMA archive: $output\n";
1404 }
1405 };
1406
1407 # in other cases, the pipeline will exit with exit code 141
1408 # because of the broken pipe, handle / ignore this as well
1409 my $rc;
1410 eval {
1411 $rc = PVE::Tools::run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1);
1412 };
1413 my $rerr = $@;
1414
1415 # use exit code if no stderr output and not just broken pipe
1416 if (!$errstring && !$broken_pipe && $rc != 0 && $rc != 141) {
1417 die "$rerr\n" if $rerr;
1418 die "config extraction failed with exit code $rc\n";
1419 }
1420 die "$errstring\n" if $errstring;
1421 } else {
1422 # simple case without compression and weird piping behaviour
1423 PVE::Tools::run_command(["vma", "config", $archive], outfunc => $out);
1424 }
1425
1426 return wantarray ? ($raw, undef) : $raw;
1427 }
1428
1429 sub extract_vzdump_config {
1430 my ($cfg, $volid) = @_;
1431
1432 my $archive = abs_filesystem_path($cfg, $volid);
1433
1434 if ($volid =~ /vzdump-(lxc|openvz)-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|(tar(\.(gz|lzo))?))$/) {
1435 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1436 } elsif ($volid =~ /vzdump-qemu-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?))$/) {
1437 my $format;
1438 my $comp;
1439 if ($7 eq 'tgz') {
1440 $format = 'tar';
1441 $comp = 'gz';
1442 } else {
1443 $format = $9;
1444 $comp = $11 if defined($11);
1445 }
1446
1447 if ($format eq 'tar') {
1448 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1449 } else {
1450 return extract_vzdump_config_vma($archive, $comp);
1451 }
1452 } else {
1453 die "cannot determine backup guest type for backup archive '$volid'\n";
1454 }
1455 }
1456
1457 sub volume_export {
1458 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1459
1460 my ($storeid, $volname) = parse_volume_id($volid, 1);
1461 die "cannot export volume '$volid'\n" if !$storeid;
1462 my $scfg = storage_config($cfg, $storeid);
1463 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1464 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1465 $snapshot, $base_snapshot, $with_snapshots);
1466 }
1467
1468 sub volume_import {
1469 my ($cfg, $fh, $volid, $format, $base_snapshot, $with_snapshots) = @_;
1470
1471 my ($storeid, $volname) = parse_volume_id($volid, 1);
1472 die "cannot import into volume '$volid'\n" if !$storeid;
1473 my $scfg = storage_config($cfg, $storeid);
1474 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1475 return $plugin->volume_import($scfg, $storeid, $fh, $volname, $format,
1476 $base_snapshot, $with_snapshots);
1477 }
1478
1479 sub volume_export_formats {
1480 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1481
1482 my ($storeid, $volname) = parse_volume_id($volid, 1);
1483 return if !$storeid;
1484 my $scfg = storage_config($cfg, $storeid);
1485 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1486 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1487 $snapshot, $base_snapshot,
1488 $with_snapshots);
1489 }
1490
1491 sub volume_import_formats {
1492 my ($cfg, $volid, $base_snapshot, $with_snapshots) = @_;
1493
1494 my ($storeid, $volname) = parse_volume_id($volid, 1);
1495 return if !$storeid;
1496 my $scfg = storage_config($cfg, $storeid);
1497 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1498 return $plugin->volume_import_formats($scfg, $storeid, $volname,
1499 $base_snapshot, $with_snapshots);
1500 }
1501
1502 sub volume_transfer_formats {
1503 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1504 my @export_formats = volume_export_formats($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1505 my @import_formats = volume_import_formats($cfg, $dst_volid, $base_snapshot, $with_snapshots);
1506 my %import_hash = map { $_ => 1 } @import_formats;
1507 my @common = grep { $import_hash{$_} } @export_formats;
1508 return @common;
1509 }
1510
1511 # bash completion helper
1512
1513 sub complete_storage {
1514 my ($cmdname, $pname, $cvalue) = @_;
1515
1516 my $cfg = PVE::Storage::config();
1517
1518 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
1519 }
1520
1521 sub complete_storage_enabled {
1522 my ($cmdname, $pname, $cvalue) = @_;
1523
1524 my $res = [];
1525
1526 my $cfg = PVE::Storage::config();
1527 foreach my $sid (keys %{$cfg->{ids}}) {
1528 next if !storage_check_enabled($cfg, $sid, undef, 1);
1529 push @$res, $sid;
1530 }
1531 return $res;
1532 }
1533
1534 sub complete_content_type {
1535 my ($cmdname, $pname, $cvalue) = @_;
1536
1537 return [qw(rootdir images vztmpl iso backup)];
1538 }
1539
1540 sub complete_volume {
1541 my ($cmdname, $pname, $cvalue) = @_;
1542
1543 my $cfg = config();
1544
1545 my $storage_list = complete_storage_enabled();
1546
1547 if ($cvalue =~ m/^([^:]+):/) {
1548 $storage_list = [ $1 ];
1549 } else {
1550 if (scalar(@$storage_list) > 1) {
1551 # only list storage IDs to avoid large listings
1552 my $res = [];
1553 foreach my $storeid (@$storage_list) {
1554 # Hack: simply return 2 artificial values, so that
1555 # completions does not finish
1556 push @$res, "$storeid:volname", "$storeid:...";
1557 }
1558 return $res;
1559 }
1560 }
1561
1562 my $res = [];
1563 foreach my $storeid (@$storage_list) {
1564 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
1565
1566 foreach my $item (@$vollist) {
1567 push @$res, $item->{volid};
1568 }
1569 }
1570
1571 return $res;
1572 }
1573
1574 # Various io-heavy operations require io/bandwidth limits which can be
1575 # configured on multiple levels: The global defaults in datacenter.cfg, and
1576 # per-storage overrides. When we want to do a restore from storage A to storage
1577 # B, we should take the smaller limit defined for storages A and B, and if no
1578 # such limit was specified, use the one from datacenter.cfg.
1579 sub get_bandwidth_limit {
1580 my ($operation, $storage_list, $override) = @_;
1581
1582 # called for each limit (global, per-storage) with the 'default' and the
1583 # $operation limit and should udpate $override for every limit affecting
1584 # us.
1585 my $use_global_limits = 0;
1586 my $apply_limit = sub {
1587 my ($bwlimit) = @_;
1588 if (defined($bwlimit)) {
1589 my $limits = PVE::JSONSchema::parse_property_string('bwlimit', $bwlimit);
1590 my $limit = $limits->{$operation} // $limits->{default};
1591 if (defined($limit)) {
1592 if (!$override || $limit < $override) {
1593 $override = $limit;
1594 }
1595 return;
1596 }
1597 }
1598 # If there was no applicable limit, try to apply the global ones.
1599 $use_global_limits = 1;
1600 };
1601
1602 my ($rpcenv, $authuser);
1603 if (defined($override)) {
1604 $rpcenv = PVE::RPCEnvironment->get();
1605 $authuser = $rpcenv->get_user();
1606 }
1607
1608 # Apply per-storage limits - if there are storages involved.
1609 if (@$storage_list) {
1610 my $config = config();
1611
1612 # The Datastore.Allocate permission allows us to modify the per-storage
1613 # limits, therefore it also allows us to override them.
1614 # Since we have most likely multiple storages to check, do a quick check on
1615 # the general '/storage' path to see if we can skip the checks entirely:
1616 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
1617
1618 my %done;
1619 foreach my $storage (@$storage_list) {
1620 # Avoid duplicate checks:
1621 next if $done{$storage};
1622 $done{$storage} = 1;
1623
1624 # Otherwise we may still have individual /storage/$ID permissions:
1625 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
1626 # And if not: apply the limits.
1627 my $storecfg = storage_config($config, $storage);
1628 $apply_limit->($storecfg->{bwlimit});
1629 }
1630 }
1631
1632 # Storage limits take precedence over the datacenter defaults, so if
1633 # a limit was applied:
1634 return $override if !$use_global_limits;
1635 }
1636
1637 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
1638 # global default limits.
1639 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
1640 # So if we cannot modify global limits, apply them to our currently
1641 # requested override.
1642 my $dc = cfs_read_file('datacenter.cfg');
1643 $apply_limit->($dc->{bwlimit});
1644 }
1645
1646 return $override;
1647 }
1648
1649 1;