]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage.pm
a4125d5b9f7a00157a7d85c4e5eb56eb539eec9a
[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 File::Basename;
11 use File::Path;
12 use Cwd 'abs_path';
13 use Socket;
14
15 use PVE::Tools qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
16 use PVE::Cluster qw(cfs_read_file cfs_write_file cfs_lock_file);
17 use PVE::Exception qw(raise_param_exc);
18 use PVE::JSONSchema;
19 use PVE::INotify;
20 use PVE::RPCEnvironment;
21
22 use PVE::Storage::Plugin;
23 use PVE::Storage::DirPlugin;
24 use PVE::Storage::LVMPlugin;
25 use PVE::Storage::LvmThinPlugin;
26 use PVE::Storage::NFSPlugin;
27 use PVE::Storage::ISCSIPlugin;
28 use PVE::Storage::RBDPlugin;
29 use PVE::Storage::SheepdogPlugin;
30 use PVE::Storage::ISCSIDirectPlugin;
31 use PVE::Storage::GlusterfsPlugin;
32 use PVE::Storage::ZFSPoolPlugin;
33 use PVE::Storage::ZFSPlugin;
34 use PVE::Storage::DRBDPlugin;
35
36 # Storage API version. Icrement it on changes in storage API interface.
37 use constant APIVER => 1;
38
39 # load standard plugins
40 PVE::Storage::DirPlugin->register();
41 PVE::Storage::LVMPlugin->register();
42 PVE::Storage::LvmThinPlugin->register();
43 PVE::Storage::NFSPlugin->register();
44 PVE::Storage::ISCSIPlugin->register();
45 PVE::Storage::RBDPlugin->register();
46 PVE::Storage::SheepdogPlugin->register();
47 PVE::Storage::ISCSIDirectPlugin->register();
48 PVE::Storage::GlusterfsPlugin->register();
49 PVE::Storage::ZFSPoolPlugin->register();
50 PVE::Storage::ZFSPlugin->register();
51 PVE::Storage::DRBDPlugin->register();
52
53 # load third-party plugins
54 if ( -d '/usr/share/perl5/PVE/Storage/Custom' ) {
55 dir_glob_foreach('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
56 my ($file) = @_;
57 my $modname = 'PVE::Storage::Custom::' . $file;
58 $modname =~ s!\.pm$!!;
59 $file = 'PVE/Storage/Custom/' . $file;
60
61 eval {
62 require $file;
63 };
64 if ($@) {
65 warn $@;
66 # Check storage API version and that file is really storage plugin.
67 } elsif ($modname->isa('PVE::Storage::Plugin') && $modname->can('api') && $modname->api() == APIVER) {
68 eval {
69 import $file;
70 $modname->register();
71 };
72 warn $@ if $@;
73 } else {
74 warn "Error loading storage plugin \"$modname\" because of API version mismatch. Please, update it.\n"
75 }
76 });
77 }
78
79 # initialize all plugins
80 PVE::Storage::Plugin->init();
81
82 my $UDEVADM = '/sbin/udevadm';
83
84 # PVE::Storage utility functions
85
86 sub config {
87 return cfs_read_file("storage.cfg");
88 }
89
90 sub write_config {
91 my ($cfg) = @_;
92
93 cfs_write_file('storage.cfg', $cfg);
94 }
95
96 sub lock_storage_config {
97 my ($code, $errmsg) = @_;
98
99 cfs_lock_file("storage.cfg", undef, $code);
100 my $err = $@;
101 if ($err) {
102 $errmsg ? die "$errmsg: $err" : die $err;
103 }
104 }
105
106 sub storage_config {
107 my ($cfg, $storeid, $noerr) = @_;
108
109 die "no storage ID specified\n" if !$storeid;
110
111 my $scfg = $cfg->{ids}->{$storeid};
112
113 die "storage '$storeid' does not exists\n" if (!$noerr && !$scfg);
114
115 return $scfg;
116 }
117
118 sub storage_check_node {
119 my ($cfg, $storeid, $node, $noerr) = @_;
120
121 my $scfg = storage_config($cfg, $storeid);
122
123 if ($scfg->{nodes}) {
124 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
125 if (!$scfg->{nodes}->{$node}) {
126 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
127 return undef;
128 }
129 }
130
131 return $scfg;
132 }
133
134 sub storage_check_enabled {
135 my ($cfg, $storeid, $node, $noerr) = @_;
136
137 my $scfg = storage_config($cfg, $storeid);
138
139 if ($scfg->{disable}) {
140 die "storage '$storeid' is disabled\n" if !$noerr;
141 return undef;
142 }
143
144 return storage_check_node($cfg, $storeid, $node, $noerr);
145 }
146
147 sub storage_ids {
148 my ($cfg) = @_;
149
150 return keys %{$cfg->{ids}};
151 }
152
153 sub file_size_info {
154 my ($filename, $timeout) = @_;
155
156 return PVE::Storage::Plugin::file_size_info($filename, $timeout);
157 }
158
159 sub volume_size_info {
160 my ($cfg, $volid, $timeout) = @_;
161
162 my ($storeid, $volname) = parse_volume_id($volid, 1);
163 if ($storeid) {
164 my $scfg = storage_config($cfg, $storeid);
165 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
166 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
167 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
168 return file_size_info($volid, $timeout);
169 } else {
170 return 0;
171 }
172 }
173
174 sub volume_resize {
175 my ($cfg, $volid, $size, $running) = @_;
176
177 my ($storeid, $volname) = parse_volume_id($volid, 1);
178 if ($storeid) {
179 my $scfg = storage_config($cfg, $storeid);
180 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
181 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
182 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
183 die "resize file/device '$volid' is not possible\n";
184 } else {
185 die "unable to parse volume ID '$volid'\n";
186 }
187 }
188
189 sub volume_rollback_is_possible {
190 my ($cfg, $volid, $snap) = @_;
191
192 my ($storeid, $volname) = parse_volume_id($volid, 1);
193 if ($storeid) {
194 my $scfg = storage_config($cfg, $storeid);
195 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
196 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
197 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
198 die "snapshot rollback file/device '$volid' is not possible\n";
199 } else {
200 die "unable to parse volume ID '$volid'\n";
201 }
202 }
203
204 sub volume_snapshot {
205 my ($cfg, $volid, $snap) = @_;
206
207 my ($storeid, $volname) = parse_volume_id($volid, 1);
208 if ($storeid) {
209 my $scfg = storage_config($cfg, $storeid);
210 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
211 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
212 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
213 die "snapshot file/device '$volid' is not possible\n";
214 } else {
215 die "unable to parse volume ID '$volid'\n";
216 }
217 }
218
219 sub volume_snapshot_rollback {
220 my ($cfg, $volid, $snap) = @_;
221
222 my ($storeid, $volname) = parse_volume_id($volid, 1);
223 if ($storeid) {
224 my $scfg = storage_config($cfg, $storeid);
225 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
226 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
227 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
228 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
229 die "snapshot rollback file/device '$volid' is not possible\n";
230 } else {
231 die "unable to parse volume ID '$volid'\n";
232 }
233 }
234
235 sub volume_snapshot_delete {
236 my ($cfg, $volid, $snap, $running) = @_;
237
238 my ($storeid, $volname) = parse_volume_id($volid, 1);
239 if ($storeid) {
240 my $scfg = storage_config($cfg, $storeid);
241 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
242 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
243 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
244 die "snapshot delete file/device '$volid' is not possible\n";
245 } else {
246 die "unable to parse volume ID '$volid'\n";
247 }
248 }
249
250 sub volume_has_feature {
251 my ($cfg, $feature, $volid, $snap, $running) = @_;
252
253 my ($storeid, $volname) = parse_volume_id($volid, 1);
254 if ($storeid) {
255 my $scfg = storage_config($cfg, $storeid);
256 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
257 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running);
258 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
259 return undef;
260 } else {
261 return undef;
262 }
263 }
264
265 sub volume_snapshot_list {
266 my ($cfg, $volid, $prefix) = @_;
267
268 my ($storeid, $volname) = parse_volume_id($volid, 1);
269 if ($storeid) {
270 my $scfg = storage_config($cfg, $storeid);
271 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
272 return $plugin->volume_snapshot_list($scfg, $storeid, $volname, $prefix);
273 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
274 die "send file/device '$volid' is not possible\n";
275 } else {
276 die "unable to parse volume ID '$volid'\n";
277 }
278 # return an empty array if dataset does not exist.
279 # youngest snap first
280 }
281
282 sub get_image_dir {
283 my ($cfg, $storeid, $vmid) = @_;
284
285 my $scfg = storage_config($cfg, $storeid);
286 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
287
288 my $path = $plugin->get_subdir($scfg, 'images');
289
290 return $vmid ? "$path/$vmid" : $path;
291 }
292
293 sub get_private_dir {
294 my ($cfg, $storeid, $vmid) = @_;
295
296 my $scfg = storage_config($cfg, $storeid);
297 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
298
299 my $path = $plugin->get_subdir($scfg, 'rootdir');
300
301 return $vmid ? "$path/$vmid" : $path;
302 }
303
304 sub get_iso_dir {
305 my ($cfg, $storeid) = @_;
306
307 my $scfg = storage_config($cfg, $storeid);
308 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
309
310 return $plugin->get_subdir($scfg, 'iso');
311 }
312
313 sub get_vztmpl_dir {
314 my ($cfg, $storeid) = @_;
315
316 my $scfg = storage_config($cfg, $storeid);
317 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
318
319 return $plugin->get_subdir($scfg, 'vztmpl');
320 }
321
322 sub get_backup_dir {
323 my ($cfg, $storeid) = @_;
324
325 my $scfg = storage_config($cfg, $storeid);
326 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
327
328 return $plugin->get_subdir($scfg, 'backup');
329 }
330
331 # library implementation
332
333 sub parse_vmid {
334 my $vmid = shift;
335
336 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
337
338 return int($vmid);
339 }
340
341 # NOTE: basename and basevmid are always undef for LVM-thin, where the
342 # clone -> base reference is not encoded in the volume ID.
343 # see note in PVE::Storage::LvmThinPlugin for details.
344 sub parse_volname {
345 my ($cfg, $volid) = @_;
346
347 my ($storeid, $volname) = parse_volume_id($volid);
348
349 my $scfg = storage_config($cfg, $storeid);
350
351 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
352
353 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
354
355 return $plugin->parse_volname($volname);
356 }
357
358 sub parse_volume_id {
359 my ($volid, $noerr) = @_;
360
361 return PVE::Storage::Plugin::parse_volume_id($volid, $noerr);
362 }
363
364 # test if we have read access to volid
365 sub check_volume_access {
366 my ($rpcenv, $user, $cfg, $vmid, $volid) = @_;
367
368 my ($sid, $volname) = parse_volume_id($volid, 1);
369 if ($sid) {
370 my ($vtype, undef, $ownervm) = parse_volname($cfg, $volid);
371 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
372 # we simply allow access
373 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
374 # we are owner - allow access
375 } elsif ($vtype eq 'backup' && $ownervm) {
376 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
377 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
378 } else {
379 # allow if we are Datastore administrator
380 $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate']);
381 }
382 } else {
383 die "Only root can pass arbitrary filesystem paths."
384 if $user ne 'root@pam';
385 }
386
387 return undef;
388 }
389
390 my $volume_is_base_and_used__no_lock = sub {
391 my ($scfg, $storeid, $plugin, $volname) = @_;
392
393 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
394 $plugin->parse_volname($volname);
395
396 if ($isBase) {
397 my $vollist = $plugin->list_images($storeid, $scfg);
398 foreach my $info (@$vollist) {
399 my (undef, $tmpvolname) = parse_volume_id($info->{volid});
400 my $basename = undef;
401 my $basevmid = undef;
402
403 eval{
404 (undef, undef, undef, $basename, $basevmid) =
405 $plugin->parse_volname($tmpvolname);
406 };
407
408 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
409 return 1;
410 }
411 }
412 }
413 return 0;
414 };
415
416 # NOTE: this check does not work for LVM-thin, where the clone -> base
417 # reference is not encoded in the volume ID.
418 # see note in PVE::Storage::LvmThinPlugin for details.
419 sub volume_is_base_and_used {
420 my ($cfg, $volid) = @_;
421
422 my ($storeid, $volname) = parse_volume_id($volid);
423 my $scfg = storage_config($cfg, $storeid);
424 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
425
426 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
427 return &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
428 });
429 }
430
431 # try to map a filesystem path to a volume identifier
432 sub path_to_volume_id {
433 my ($cfg, $path) = @_;
434
435 my $ids = $cfg->{ids};
436
437 my ($sid, $volname) = parse_volume_id($path, 1);
438 if ($sid) {
439 if (my $scfg = $ids->{$sid}) {
440 if ($scfg->{path}) {
441 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
442 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
443 return ($vtype, $path);
444 }
445 }
446 return ('');
447 }
448
449 # Note: abs_path() return undef if $path doesn not exist
450 # for example when nfs storage is not mounted
451 $path = abs_path($path) || $path;
452
453 foreach my $sid (keys %$ids) {
454 my $scfg = $ids->{$sid};
455 next if !$scfg->{path};
456 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
457 my $imagedir = $plugin->get_subdir($scfg, 'images');
458 my $isodir = $plugin->get_subdir($scfg, 'iso');
459 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
460 my $backupdir = $plugin->get_subdir($scfg, 'backup');
461 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
462
463 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
464 my $vmid = $1;
465 my $name = $2;
466
467 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
468 foreach my $info (@$vollist) {
469 my ($storeid, $volname) = parse_volume_id($info->{volid});
470 my $volpath = $plugin->path($scfg, $volname, $storeid);
471 if ($volpath eq $path) {
472 return ('images', $info->{volid});
473 }
474 }
475 } elsif ($path =~ m!^$isodir/([^/]+\.[Ii][Ss][Oo])$!) {
476 my $name = $1;
477 return ('iso', "$sid:iso/$name");
478 } elsif ($path =~ m!^$tmpldir/([^/]+\.tar\.gz)$!) {
479 my $name = $1;
480 return ('vztmpl', "$sid:vztmpl/$name");
481 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
482 my $vmid = $1;
483 return ('rootdir', "$sid:rootdir/$vmid");
484 } elsif ($path =~ m!^$backupdir/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!) {
485 my $name = $1;
486 return ('iso', "$sid:backup/$name");
487 }
488 }
489
490 # can't map path to volume id
491 return ('');
492 }
493
494 sub path {
495 my ($cfg, $volid, $snapname) = @_;
496
497 my ($storeid, $volname) = parse_volume_id($volid);
498
499 my $scfg = storage_config($cfg, $storeid);
500
501 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
502 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
503 return wantarray ? ($path, $owner, $vtype) : $path;
504 }
505
506 sub abs_filesystem_path {
507 my ($cfg, $volid) = @_;
508
509 my $path;
510 if (PVE::Storage::parse_volume_id ($volid, 1)) {
511 PVE::Storage::activate_volumes($cfg, [ $volid ]);
512 $path = PVE::Storage::path($cfg, $volid);
513 } else {
514 if (-f $volid) {
515 my $abspath = abs_path($volid);
516 if ($abspath && $abspath =~ m|^(/.+)$|) {
517 $path = $1; # untaint any path
518 }
519 }
520 }
521
522 die "can't find file '$volid'\n" if !($path && -f $path);
523
524 return $path;
525 }
526
527 sub storage_migrate {
528 my ($cfg, $volid, $target_host, $target_storeid, $target_volname) = @_;
529
530 my ($storeid, $volname) = parse_volume_id($volid);
531 $target_volname = $volname if !$target_volname;
532
533 my $scfg = storage_config($cfg, $storeid);
534
535 # no need to migrate shared content
536 return if $storeid eq $target_storeid && $scfg->{shared};
537
538 my $tcfg = storage_config($cfg, $target_storeid);
539
540 my $target_volid = "${target_storeid}:${target_volname}";
541
542 my $errstr = "unable to migrate '$volid' to '${target_volid}' on host '$target_host'";
543
544 my $sshoptions = "-o 'BatchMode=yes'";
545 my $ssh = "/usr/bin/ssh $sshoptions";
546
547 local $ENV{RSYNC_RSH} = $ssh;
548
549 # only implemented for file system based storage
550 if ($scfg->{path}) {
551 if ($tcfg->{path}) {
552
553 my $src_plugin = PVE::Storage::Plugin->lookup($scfg->{type});
554 my $dst_plugin = PVE::Storage::Plugin->lookup($tcfg->{type});
555 my $src = $src_plugin->path($scfg, $volname, $storeid);
556 my $dst = $dst_plugin->path($tcfg, $target_volname, $target_storeid);
557
558 my $dirname = dirname($dst);
559
560 if ($tcfg->{shared}) { # we can do a local copy
561
562 run_command(['/bin/mkdir', '-p', $dirname]);
563
564 run_command(['/bin/cp', $src, $dst]);
565
566 } else {
567 run_command(['/usr/bin/ssh', "root\@${target_host}",
568 '/bin/mkdir', '-p', $dirname]);
569
570 # we use rsync with --sparse, so we can't use --inplace,
571 # so we remove file on the target if it already exists to
572 # save space
573 my ($size, $format) = PVE::Storage::Plugin::file_size_info($src);
574 if ($format && ($format eq 'raw') && $size) {
575 run_command(['/usr/bin/ssh', "root\@${target_host}",
576 'rm', '-f', $dst],
577 outfunc => sub {});
578 }
579
580 my $cmd;
581 if ($format eq 'subvol') {
582 $cmd = ['/usr/bin/rsync', '--progress', '-X', '-A', '--numeric-ids',
583 '-aH', '--delete', '--no-whole-file', '--inplace',
584 '--one-file-system', "$src/", "[root\@${target_host}]:$dst"];
585 } else {
586 $cmd = ['/usr/bin/rsync', '--progress', '--sparse', '--whole-file',
587 $src, "[root\@${target_host}]:$dst"];
588 }
589
590 my $percent = -1;
591
592 run_command($cmd, outfunc => sub {
593 my $line = shift;
594
595 if ($line =~ m/^\s*(\d+\s+(\d+)%\s.*)$/) {
596 if ($2 > $percent) {
597 $percent = $2;
598 print "rsync status: $1\n";
599 *STDOUT->flush();
600 }
601 } else {
602 print "$line\n";
603 *STDOUT->flush();
604 }
605 });
606 }
607 } else {
608 die "$errstr - target type '$tcfg->{type}' not implemented\n";
609 }
610
611 } elsif ($scfg->{type} eq 'zfspool') {
612
613 if ($tcfg->{type} eq 'zfspool') {
614
615 die "$errstr - pool on target does not have the same name as on source!"
616 if $tcfg->{pool} ne $scfg->{pool};
617
618 my (undef, $volname) = parse_volname($cfg, $volid);
619
620 my $zfspath = "$scfg->{pool}\/$volname";
621
622 my $snap = ['zfs', 'snapshot', "$zfspath\@__migration__"];
623
624 my $send = [['zfs', 'send', '-Rpv', "$zfspath\@__migration__"], ['ssh', "root\@$target_host",
625 'zfs', 'recv', $zfspath]];
626
627 my $destroy_target = ['ssh', "root\@$target_host", 'zfs', 'destroy', "$zfspath\@__migration__"];
628 run_command($snap);
629 eval{
630 run_command($send);
631 };
632 my $err = $@;
633 warn "zfs send/receive failed, cleaning up snapshot(s)..\n" if $err;
634 eval { run_command(['zfs', 'destroy', "$zfspath\@__migration__"]); };
635 warn "could not remove source snapshot: $@\n" if $@;
636 eval { run_command($destroy_target); };
637 warn "could not remove target snapshot: $@\n" if $@;
638 die $err if $err;
639
640 } else {
641 die "$errstr - target type $tcfg->{type} is not valid\n";
642 }
643
644 } elsif ($scfg->{type} eq 'lvmthin' || $scfg->{type} eq 'lvm') {
645
646 if (($scfg->{type} eq $tcfg->{type}) &&
647 ($tcfg->{type} eq 'lvmthin' || $tcfg->{type} eq 'lvm')) {
648
649 my (undef, $volname, $vmid) = parse_volname($cfg, $volid);
650 my $size = volume_size_info($cfg, $volid, 5);
651 my $src = path($cfg, $volid);
652 my $dst = path($cfg, $target_volid);
653
654 run_command(['/usr/bin/ssh', "root\@${target_host}",
655 'pvesm', 'alloc', $target_storeid, $vmid,
656 $target_volname, int($size/1024)]);
657
658 eval {
659 if ($tcfg->{type} eq 'lvmthin') {
660 run_command([["dd", "if=$src", "bs=4k"],["/usr/bin/ssh", "root\@${target_host}",
661 "dd", 'conv=sparse', "of=$dst", "bs=4k"]]);
662 } else {
663 run_command([["dd", "if=$src", "bs=4k"],["/usr/bin/ssh", "root\@${target_host}",
664 "dd", "of=$dst", "bs=4k"]]);
665 }
666 };
667 if (my $err = $@) {
668 run_command(['/usr/bin/ssh', "root\@${target_host}",
669 'pvesm', 'free', $target_volid]);
670 die $err;
671 }
672 } else {
673 die "$errstr - migrate from source type '$scfg->{type}' to '$tcfg->{type}' not implemented\n";
674 }
675 } else {
676 die "$errstr - source type '$scfg->{type}' not implemented\n";
677 }
678 }
679
680 sub vdisk_clone {
681 my ($cfg, $volid, $vmid, $snap) = @_;
682
683 my ($storeid, $volname) = parse_volume_id($volid);
684
685 my $scfg = storage_config($cfg, $storeid);
686
687 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
688
689 activate_storage($cfg, $storeid);
690
691 # lock shared storage
692 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
693 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
694 return "$storeid:$volname";
695 });
696 }
697
698 sub vdisk_create_base {
699 my ($cfg, $volid) = @_;
700
701 my ($storeid, $volname) = parse_volume_id($volid);
702
703 my $scfg = storage_config($cfg, $storeid);
704
705 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
706
707 activate_storage($cfg, $storeid);
708
709 # lock shared storage
710 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
711 my $volname = $plugin->create_base($storeid, $scfg, $volname);
712 return "$storeid:$volname";
713 });
714 }
715
716 sub vdisk_alloc {
717 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
718
719 die "no storage ID specified\n" if !$storeid;
720
721 PVE::JSONSchema::parse_storage_id($storeid);
722
723 my $scfg = storage_config($cfg, $storeid);
724
725 die "no VMID specified\n" if !$vmid;
726
727 $vmid = parse_vmid($vmid);
728
729 my $defformat = PVE::Storage::Plugin::default_format($scfg);
730
731 $fmt = $defformat if !$fmt;
732
733 activate_storage($cfg, $storeid);
734
735 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
736
737 # lock shared storage
738 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
739 my $old_umask = umask(umask|0037);
740 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
741 my $err = $@;
742 umask $old_umask;
743 die $err if $err;
744 return "$storeid:$volname";
745 });
746 }
747
748 sub vdisk_free {
749 my ($cfg, $volid) = @_;
750
751 my ($storeid, $volname) = parse_volume_id($volid);
752 my $scfg = storage_config($cfg, $storeid);
753 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
754
755 activate_storage($cfg, $storeid);
756
757 my $cleanup_worker;
758
759 # lock shared storage
760 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
761 # LVM-thin allows deletion of still referenced base volumes!
762 die "base volume '$volname' is still in use by linked clones\n"
763 if &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
764
765 my (undef, undef, undef, undef, undef, $isBase, $format) =
766 $plugin->parse_volname($volname);
767 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
768 });
769
770 return if !$cleanup_worker;
771
772 my $rpcenv = PVE::RPCEnvironment::get();
773 my $authuser = $rpcenv->get_user();
774
775 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
776 }
777
778 #list iso or openvz template ($tt = <iso|vztmpl|backup>)
779 sub template_list {
780 my ($cfg, $storeid, $tt) = @_;
781
782 die "unknown template type '$tt'\n"
783 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup');
784
785 my $ids = $cfg->{ids};
786
787 storage_check_enabled($cfg, $storeid) if ($storeid);
788
789 my $res = {};
790
791 # query the storage
792
793 foreach my $sid (keys %$ids) {
794 next if $storeid && $storeid ne $sid;
795
796 my $scfg = $ids->{$sid};
797 my $type = $scfg->{type};
798
799 next if !storage_check_enabled($cfg, $sid, undef, 1);
800
801 next if $tt eq 'iso' && !$scfg->{content}->{iso};
802 next if $tt eq 'vztmpl' && !$scfg->{content}->{vztmpl};
803 next if $tt eq 'backup' && !$scfg->{content}->{backup};
804
805 activate_storage($cfg, $sid);
806
807 if ($scfg->{path}) {
808 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
809
810 my $path = $plugin->get_subdir($scfg, $tt);
811
812 foreach my $fn (<$path/*>) {
813
814 my $info;
815
816 if ($tt eq 'iso') {
817 next if $fn !~ m!/([^/]+\.[Ii][Ss][Oo])$!;
818
819 $info = { volid => "$sid:iso/$1", format => 'iso' };
820
821 } elsif ($tt eq 'vztmpl') {
822 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
823
824 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
825
826 } elsif ($tt eq 'backup') {
827 next if $fn !~ m!/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!;
828
829 $info = { volid => "$sid:backup/$1", format => $2 };
830 }
831
832 $info->{size} = -s $fn;
833
834 push @{$res->{$sid}}, $info;
835 }
836
837 }
838
839 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
840 }
841
842 return $res;
843 }
844
845
846 sub vdisk_list {
847 my ($cfg, $storeid, $vmid, $vollist) = @_;
848
849 my $ids = $cfg->{ids};
850
851 storage_check_enabled($cfg, $storeid) if ($storeid);
852
853 my $res = {};
854
855 # prepare/activate/refresh all storages
856
857 my $storage_list = [];
858 if ($vollist) {
859 foreach my $volid (@$vollist) {
860 my ($sid, undef) = parse_volume_id($volid);
861 next if !defined($ids->{$sid});
862 next if !storage_check_enabled($cfg, $sid, undef, 1);
863 push @$storage_list, $sid;
864 }
865 } else {
866 foreach my $sid (keys %$ids) {
867 next if $storeid && $storeid ne $sid;
868 next if !storage_check_enabled($cfg, $sid, undef, 1);
869 push @$storage_list, $sid;
870 }
871 }
872
873 my $cache = {};
874
875 activate_storage_list($cfg, $storage_list, $cache);
876
877 foreach my $sid (keys %$ids) {
878 next if $storeid && $storeid ne $sid;
879 next if !storage_check_enabled($cfg, $sid, undef, 1);
880
881 my $scfg = $ids->{$sid};
882 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
883 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
884 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
885 }
886
887 return $res;
888 }
889
890 sub volume_list {
891 my ($cfg, $storeid, $vmid, $content) = @_;
892
893 my @ctypes = qw(images vztmpl iso backup);
894
895 my $cts = $content ? [ $content ] : [ @ctypes ];
896
897 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
898
899 my $res = [];
900 foreach my $ct (@$cts) {
901 my $data;
902 if ($ct eq 'images') {
903 $data = vdisk_list($cfg, $storeid, $vmid);
904 } elsif ($ct eq 'iso' && !defined($vmid)) {
905 $data = template_list($cfg, $storeid, 'iso');
906 } elsif ($ct eq 'vztmpl'&& !defined($vmid)) {
907 $data = template_list ($cfg, $storeid, 'vztmpl');
908 } elsif ($ct eq 'backup') {
909 $data = template_list ($cfg, $storeid, 'backup');
910 foreach my $item (@{$data->{$storeid}}) {
911 if (defined($vmid)) {
912 @{$data->{$storeid}} = grep { $_->{volid} =~ m/\S+-$vmid-\S+/ } @{$data->{$storeid}};
913 }
914 }
915 }
916
917 next if !$data || !$data->{$storeid};
918
919 foreach my $item (@{$data->{$storeid}}) {
920 $item->{content} = $ct;
921 push @$res, $item;
922 }
923 }
924
925 return $res;
926 }
927
928 sub uevent_seqnum {
929
930 my $filename = "/sys/kernel/uevent_seqnum";
931
932 my $seqnum = 0;
933 if (my $fh = IO::File->new($filename, "r")) {
934 my $line = <$fh>;
935 if ($line =~ m/^(\d+)$/) {
936 $seqnum = int($1);
937 }
938 close ($fh);
939 }
940 return $seqnum;
941 }
942
943 sub activate_storage {
944 my ($cfg, $storeid, $cache) = @_;
945
946 $cache = {} if !$cache;
947
948 my $scfg = storage_check_enabled($cfg, $storeid);
949
950 return if $cache->{activated}->{$storeid};
951
952 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
953
954 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
955
956 if ($scfg->{base}) {
957 my ($baseid, undef) = parse_volume_id ($scfg->{base});
958 activate_storage($cfg, $baseid, $cache);
959 }
960
961 if (!$plugin->check_connection($storeid, $scfg)) {
962 die "storage '$storeid' is not online\n";
963 }
964
965 $plugin->activate_storage($storeid, $scfg, $cache);
966
967 my $newseq = uevent_seqnum ();
968
969 # only call udevsettle if there are events
970 if ($newseq > $cache->{uevent_seqnum}) {
971 my $timeout = 30;
972 system ("$UDEVADM settle --timeout=$timeout"); # ignore errors
973 $cache->{uevent_seqnum} = $newseq;
974 }
975
976 $cache->{activated}->{$storeid} = 1;
977 }
978
979 sub activate_storage_list {
980 my ($cfg, $storeid_list, $cache) = @_;
981
982 $cache = {} if !$cache;
983
984 foreach my $storeid (@$storeid_list) {
985 activate_storage($cfg, $storeid, $cache);
986 }
987 }
988
989 sub deactivate_storage {
990 my ($cfg, $storeid) = @_;
991
992 my $scfg = storage_config ($cfg, $storeid);
993 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
994
995 my $cache = {};
996 $plugin->deactivate_storage($storeid, $scfg, $cache);
997 }
998
999 sub activate_volumes {
1000 my ($cfg, $vollist, $snapname) = @_;
1001
1002 return if !($vollist && scalar(@$vollist));
1003
1004 my $storagehash = {};
1005 foreach my $volid (@$vollist) {
1006 my ($storeid, undef) = parse_volume_id($volid);
1007 $storagehash->{$storeid} = 1;
1008 }
1009
1010 my $cache = {};
1011
1012 activate_storage_list($cfg, [keys %$storagehash], $cache);
1013
1014 foreach my $volid (@$vollist) {
1015 my ($storeid, $volname) = parse_volume_id($volid);
1016 my $scfg = storage_config($cfg, $storeid);
1017 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1018 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1019 }
1020 }
1021
1022 sub deactivate_volumes {
1023 my ($cfg, $vollist, $snapname) = @_;
1024
1025 return if !($vollist && scalar(@$vollist));
1026
1027 my $cache = {};
1028
1029 my @errlist = ();
1030 foreach my $volid (@$vollist) {
1031 my ($storeid, $volname) = parse_volume_id($volid);
1032
1033 my $scfg = storage_config($cfg, $storeid);
1034 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1035
1036 eval {
1037 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1038 };
1039 if (my $err = $@) {
1040 warn $err;
1041 push @errlist, $volid;
1042 }
1043 }
1044
1045 die "volume deactivation failed: " . join(' ', @errlist)
1046 if scalar(@errlist);
1047 }
1048
1049 sub storage_info {
1050 my ($cfg, $content) = @_;
1051
1052 my $ids = $cfg->{ids};
1053
1054 my $info = {};
1055
1056 my @ctypes = PVE::Tools::split_list($content);
1057
1058 my $slist = [];
1059 foreach my $storeid (keys %$ids) {
1060
1061 next if !storage_check_enabled($cfg, $storeid, undef, 1);
1062
1063 if (defined($content)) {
1064 my $want_ctype = 0;
1065 foreach my $ctype (@ctypes) {
1066 if ($ids->{$storeid}->{content}->{$ctype}) {
1067 $want_ctype = 1;
1068 last;
1069 }
1070 }
1071 next if !$want_ctype;
1072 }
1073
1074 my $type = $ids->{$storeid}->{type};
1075
1076 $info->{$storeid} = {
1077 type => $type,
1078 total => 0,
1079 avail => 0,
1080 used => 0,
1081 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1082 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
1083 active => 0,
1084 };
1085
1086 push @$slist, $storeid;
1087 }
1088
1089 my $cache = {};
1090
1091 foreach my $storeid (keys %$ids) {
1092 my $scfg = $ids->{$storeid};
1093 next if !$info->{$storeid};
1094
1095 eval { activate_storage($cfg, $storeid, $cache); };
1096 if (my $err = $@) {
1097 warn $err;
1098 next;
1099 }
1100
1101 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1102 my ($total, $avail, $used, $active);
1103 eval { ($total, $avail, $used, $active) = $plugin->status($storeid, $scfg, $cache); };
1104 warn $@ if $@;
1105 next if !$active;
1106 $info->{$storeid}->{total} = int($total);
1107 $info->{$storeid}->{avail} = int($avail);
1108 $info->{$storeid}->{used} = int($used);
1109 $info->{$storeid}->{active} = $active;
1110 }
1111
1112 return $info;
1113 }
1114
1115 sub resolv_server {
1116 my ($server) = @_;
1117
1118 my ($packed_ip, $family);
1119 eval {
1120 my @res = PVE::Tools::getaddrinfo_all($server);
1121 $family = $res[0]->{family};
1122 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1123 };
1124 if (defined $packed_ip) {
1125 return Socket::inet_ntop($family, $packed_ip);
1126 }
1127 return undef;
1128 }
1129
1130 sub scan_nfs {
1131 my ($server_in) = @_;
1132
1133 my $server;
1134 if (!($server = resolv_server ($server_in))) {
1135 die "unable to resolve address for server '${server_in}'\n";
1136 }
1137
1138 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1139
1140 my $res = {};
1141 run_command($cmd, outfunc => sub {
1142 my $line = shift;
1143
1144 # note: howto handle white spaces in export path??
1145 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1146 $res->{$1} = $2;
1147 }
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 # bash completion helper
1457
1458 sub complete_storage {
1459 my ($cmdname, $pname, $cvalue) = @_;
1460
1461 my $cfg = PVE::Storage::config();
1462
1463 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
1464 }
1465
1466 sub complete_storage_enabled {
1467 my ($cmdname, $pname, $cvalue) = @_;
1468
1469 my $res = [];
1470
1471 my $cfg = PVE::Storage::config();
1472 foreach my $sid (keys %{$cfg->{ids}}) {
1473 next if !storage_check_enabled($cfg, $sid, undef, 1);
1474 push @$res, $sid;
1475 }
1476 return $res;
1477 }
1478
1479 sub complete_content_type {
1480 my ($cmdname, $pname, $cvalue) = @_;
1481
1482 return [qw(rootdir images vztmpl iso backup)];
1483 }
1484
1485 sub complete_volume {
1486 my ($cmdname, $pname, $cvalue) = @_;
1487
1488 my $cfg = config();
1489
1490 my $storage_list = complete_storage_enabled();
1491
1492 if ($cvalue =~ m/^([^:]+):/) {
1493 $storage_list = [ $1 ];
1494 } else {
1495 if (scalar(@$storage_list) > 1) {
1496 # only list storage IDs to avoid large listings
1497 my $res = [];
1498 foreach my $storeid (@$storage_list) {
1499 # Hack: simply return 2 artificial values, so that
1500 # completions does not finish
1501 push @$res, "$storeid:volname", "$storeid:...";
1502 }
1503 return $res;
1504 }
1505 }
1506
1507 my $res = [];
1508 foreach my $storeid (@$storage_list) {
1509 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
1510
1511 foreach my $item (@$vollist) {
1512 push @$res, $item->{volid};
1513 }
1514 }
1515
1516 return $res;
1517 }
1518
1519 1;