]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage.pm
Include new storage function volume_snapshot_list.
[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_send {
220 my ($cfg, $volid, $snap, $ip, $incremental_snap, $verbose, $limit,
221 $target_path) = @_;
222
223 my ($storeid, $volname) = parse_volume_id($volid, 1);
224 if ($storeid) {
225 my $scfg = storage_config($cfg, $storeid);
226 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
227 return $plugin->volume_send($scfg, $storeid, $volname, $ip, $snap,
228 $incremental_snap, $verbose, $limit, $target_path);
229
230 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
231 die "send file/device '$volid' is not possible\n";
232 } else {
233 die "unable to parse volume ID '$volid'\n";
234 }
235 }
236
237 sub volume_snapshot_rollback {
238 my ($cfg, $volid, $snap) = @_;
239
240 my ($storeid, $volname) = parse_volume_id($volid, 1);
241 if ($storeid) {
242 my $scfg = storage_config($cfg, $storeid);
243 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
244 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
245 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
246 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
247 die "snapshot rollback file/device '$volid' is not possible\n";
248 } else {
249 die "unable to parse volume ID '$volid'\n";
250 }
251 }
252
253 sub volume_snapshot_delete {
254 my ($cfg, $volid, $snap, $running) = @_;
255
256 my ($storeid, $volname) = parse_volume_id($volid, 1);
257 if ($storeid) {
258 my $scfg = storage_config($cfg, $storeid);
259 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
260 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
261 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
262 die "snapshot delete file/device '$volid' is not possible\n";
263 } else {
264 die "unable to parse volume ID '$volid'\n";
265 }
266 }
267
268 sub volume_has_feature {
269 my ($cfg, $feature, $volid, $snap, $running) = @_;
270
271 my ($storeid, $volname) = parse_volume_id($volid, 1);
272 if ($storeid) {
273 my $scfg = storage_config($cfg, $storeid);
274 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
275 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running);
276 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
277 return undef;
278 } else {
279 return undef;
280 }
281 }
282
283 sub volume_snapshot_list {
284 my ($cfg, $volid, $prefix, $ip) = @_;
285
286 my ($storeid, $volname) = parse_volume_id($volid, 1);
287 if ($storeid) {
288 my $scfg = storage_config($cfg, $storeid);
289 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
290 return $plugin->volume_snapshot_list($scfg, $storeid, $volname, $prefix, $ip);
291 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
292 die "send file/device '$volid' is not possible\n";
293 } else {
294 die "unable to parse volume ID '$volid'\n";
295 }
296 # return an empty array if dataset does not exist.
297 # youngest snap first
298 }
299
300 sub get_image_dir {
301 my ($cfg, $storeid, $vmid) = @_;
302
303 my $scfg = storage_config($cfg, $storeid);
304 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
305
306 my $path = $plugin->get_subdir($scfg, 'images');
307
308 return $vmid ? "$path/$vmid" : $path;
309 }
310
311 sub get_private_dir {
312 my ($cfg, $storeid, $vmid) = @_;
313
314 my $scfg = storage_config($cfg, $storeid);
315 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
316
317 my $path = $plugin->get_subdir($scfg, 'rootdir');
318
319 return $vmid ? "$path/$vmid" : $path;
320 }
321
322 sub get_iso_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, 'iso');
329 }
330
331 sub get_vztmpl_dir {
332 my ($cfg, $storeid) = @_;
333
334 my $scfg = storage_config($cfg, $storeid);
335 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
336
337 return $plugin->get_subdir($scfg, 'vztmpl');
338 }
339
340 sub get_backup_dir {
341 my ($cfg, $storeid) = @_;
342
343 my $scfg = storage_config($cfg, $storeid);
344 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
345
346 return $plugin->get_subdir($scfg, 'backup');
347 }
348
349 # library implementation
350
351 sub parse_vmid {
352 my $vmid = shift;
353
354 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
355
356 return int($vmid);
357 }
358
359 # NOTE: basename and basevmid are always undef for LVM-thin, where the
360 # clone -> base reference is not encoded in the volume ID.
361 # see note in PVE::Storage::LvmThinPlugin for details.
362 sub parse_volname {
363 my ($cfg, $volid) = @_;
364
365 my ($storeid, $volname) = parse_volume_id($volid);
366
367 my $scfg = storage_config($cfg, $storeid);
368
369 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
370
371 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
372
373 return $plugin->parse_volname($volname);
374 }
375
376 sub parse_volume_id {
377 my ($volid, $noerr) = @_;
378
379 return PVE::Storage::Plugin::parse_volume_id($volid, $noerr);
380 }
381
382 # test if we have read access to volid
383 sub check_volume_access {
384 my ($rpcenv, $user, $cfg, $vmid, $volid) = @_;
385
386 my ($sid, $volname) = parse_volume_id($volid, 1);
387 if ($sid) {
388 my ($vtype, undef, $ownervm) = parse_volname($cfg, $volid);
389 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
390 # we simply allow access
391 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
392 # we are owner - allow access
393 } elsif ($vtype eq 'backup' && $ownervm) {
394 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
395 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
396 } else {
397 # allow if we are Datastore administrator
398 $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate']);
399 }
400 } else {
401 die "Only root can pass arbitrary filesystem paths."
402 if $user ne 'root@pam';
403 }
404
405 return undef;
406 }
407
408 my $volume_is_base_and_used__no_lock = sub {
409 my ($scfg, $storeid, $plugin, $volname) = @_;
410
411 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
412 $plugin->parse_volname($volname);
413
414 if ($isBase) {
415 my $vollist = $plugin->list_images($storeid, $scfg);
416 foreach my $info (@$vollist) {
417 my (undef, $tmpvolname) = parse_volume_id($info->{volid});
418 my $basename = undef;
419 my $basevmid = undef;
420
421 eval{
422 (undef, undef, undef, $basename, $basevmid) =
423 $plugin->parse_volname($tmpvolname);
424 };
425
426 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
427 return 1;
428 }
429 }
430 }
431 return 0;
432 };
433
434 # NOTE: this check does not work for LVM-thin, where the clone -> base
435 # reference is not encoded in the volume ID.
436 # see note in PVE::Storage::LvmThinPlugin for details.
437 sub volume_is_base_and_used {
438 my ($cfg, $volid) = @_;
439
440 my ($storeid, $volname) = parse_volume_id($volid);
441 my $scfg = storage_config($cfg, $storeid);
442 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
443
444 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
445 return &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
446 });
447 }
448
449 # try to map a filesystem path to a volume identifier
450 sub path_to_volume_id {
451 my ($cfg, $path) = @_;
452
453 my $ids = $cfg->{ids};
454
455 my ($sid, $volname) = parse_volume_id($path, 1);
456 if ($sid) {
457 if (my $scfg = $ids->{$sid}) {
458 if ($scfg->{path}) {
459 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
460 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
461 return ($vtype, $path);
462 }
463 }
464 return ('');
465 }
466
467 # Note: abs_path() return undef if $path doesn not exist
468 # for example when nfs storage is not mounted
469 $path = abs_path($path) || $path;
470
471 foreach my $sid (keys %$ids) {
472 my $scfg = $ids->{$sid};
473 next if !$scfg->{path};
474 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
475 my $imagedir = $plugin->get_subdir($scfg, 'images');
476 my $isodir = $plugin->get_subdir($scfg, 'iso');
477 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
478 my $backupdir = $plugin->get_subdir($scfg, 'backup');
479 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
480
481 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
482 my $vmid = $1;
483 my $name = $2;
484
485 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
486 foreach my $info (@$vollist) {
487 my ($storeid, $volname) = parse_volume_id($info->{volid});
488 my $volpath = $plugin->path($scfg, $volname, $storeid);
489 if ($volpath eq $path) {
490 return ('images', $info->{volid});
491 }
492 }
493 } elsif ($path =~ m!^$isodir/([^/]+\.[Ii][Ss][Oo])$!) {
494 my $name = $1;
495 return ('iso', "$sid:iso/$name");
496 } elsif ($path =~ m!^$tmpldir/([^/]+\.tar\.gz)$!) {
497 my $name = $1;
498 return ('vztmpl', "$sid:vztmpl/$name");
499 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
500 my $vmid = $1;
501 return ('rootdir', "$sid:rootdir/$vmid");
502 } elsif ($path =~ m!^$backupdir/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!) {
503 my $name = $1;
504 return ('iso', "$sid:backup/$name");
505 }
506 }
507
508 # can't map path to volume id
509 return ('');
510 }
511
512 sub path {
513 my ($cfg, $volid, $snapname) = @_;
514
515 my ($storeid, $volname) = parse_volume_id($volid);
516
517 my $scfg = storage_config($cfg, $storeid);
518
519 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
520 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
521 return wantarray ? ($path, $owner, $vtype) : $path;
522 }
523
524 sub abs_filesystem_path {
525 my ($cfg, $volid) = @_;
526
527 my $path;
528 if (PVE::Storage::parse_volume_id ($volid, 1)) {
529 PVE::Storage::activate_volumes($cfg, [ $volid ]);
530 $path = PVE::Storage::path($cfg, $volid);
531 } else {
532 if (-f $volid) {
533 my $abspath = abs_path($volid);
534 if ($abspath && $abspath =~ m|^(/.+)$|) {
535 $path = $1; # untaint any path
536 }
537 }
538 }
539
540 die "can't find file '$volid'\n" if !($path && -f $path);
541
542 return $path;
543 }
544
545 sub storage_migrate {
546 my ($cfg, $volid, $target_host, $target_storeid, $target_volname) = @_;
547
548 my ($storeid, $volname) = parse_volume_id($volid);
549 $target_volname = $volname if !$target_volname;
550
551 my $scfg = storage_config($cfg, $storeid);
552
553 # no need to migrate shared content
554 return if $storeid eq $target_storeid && $scfg->{shared};
555
556 my $tcfg = storage_config($cfg, $target_storeid);
557
558 my $target_volid = "${target_storeid}:${target_volname}";
559
560 my $errstr = "unable to migrate '$volid' to '${target_volid}' on host '$target_host'";
561
562 my $sshoptions = "-o 'BatchMode=yes'";
563 my $ssh = "/usr/bin/ssh $sshoptions";
564
565 local $ENV{RSYNC_RSH} = $ssh;
566
567 # only implemented for file system based storage
568 if ($scfg->{path}) {
569 if ($tcfg->{path}) {
570
571 my $src_plugin = PVE::Storage::Plugin->lookup($scfg->{type});
572 my $dst_plugin = PVE::Storage::Plugin->lookup($tcfg->{type});
573 my $src = $src_plugin->path($scfg, $volname, $storeid);
574 my $dst = $dst_plugin->path($tcfg, $target_volname, $target_storeid);
575
576 my $dirname = dirname($dst);
577
578 if ($tcfg->{shared}) { # we can do a local copy
579
580 run_command(['/bin/mkdir', '-p', $dirname]);
581
582 run_command(['/bin/cp', $src, $dst]);
583
584 } else {
585 run_command(['/usr/bin/ssh', "root\@${target_host}",
586 '/bin/mkdir', '-p', $dirname]);
587
588 # we use rsync with --sparse, so we can't use --inplace,
589 # so we remove file on the target if it already exists to
590 # save space
591 my ($size, $format) = PVE::Storage::Plugin::file_size_info($src);
592 if ($format && ($format eq 'raw') && $size) {
593 run_command(['/usr/bin/ssh', "root\@${target_host}",
594 'rm', '-f', $dst],
595 outfunc => sub {});
596 }
597
598 my $cmd;
599 if ($format eq 'subvol') {
600 $cmd = ['/usr/bin/rsync', '--progress', '-X', '-A', '--numeric-ids',
601 '-aH', '--delete', '--no-whole-file', '--inplace',
602 '--one-file-system', "$src/", "[root\@${target_host}]:$dst"];
603 } else {
604 $cmd = ['/usr/bin/rsync', '--progress', '--sparse', '--whole-file',
605 $src, "[root\@${target_host}]:$dst"];
606 }
607
608 my $percent = -1;
609
610 run_command($cmd, outfunc => sub {
611 my $line = shift;
612
613 if ($line =~ m/^\s*(\d+\s+(\d+)%\s.*)$/) {
614 if ($2 > $percent) {
615 $percent = $2;
616 print "rsync status: $1\n";
617 *STDOUT->flush();
618 }
619 } else {
620 print "$line\n";
621 *STDOUT->flush();
622 }
623 });
624 }
625 } else {
626 die "$errstr - target type '$tcfg->{type}' not implemented\n";
627 }
628
629 } elsif ($scfg->{type} eq 'zfspool') {
630
631 if ($tcfg->{type} eq 'zfspool') {
632
633 die "$errstr - pool on target does not have the same name as on source!"
634 if $tcfg->{pool} ne $scfg->{pool};
635
636 my (undef, $volname) = parse_volname($cfg, $volid);
637
638 my $zfspath = "$scfg->{pool}\/$volname";
639
640 my $snap = ['zfs', 'snapshot', "$zfspath\@__migration__"];
641
642 my $send = [['zfs', 'send', '-Rpv', "$zfspath\@__migration__"], ['ssh', "root\@$target_host",
643 'zfs', 'recv', $zfspath]];
644
645 my $destroy_target = ['ssh', "root\@$target_host", 'zfs', 'destroy', "$zfspath\@__migration__"];
646 run_command($snap);
647 eval{
648 run_command($send);
649 };
650 my $err = $@;
651 warn "zfs send/receive failed, cleaning up snapshot(s)..\n" if $err;
652 eval { run_command(['zfs', 'destroy', "$zfspath\@__migration__"]); };
653 warn "could not remove source snapshot: $@\n" if $@;
654 eval { run_command($destroy_target); };
655 warn "could not remove target snapshot: $@\n" if $@;
656 die $err if $err;
657
658 } else {
659 die "$errstr - target type $tcfg->{type} is not valid\n";
660 }
661
662 } elsif ($scfg->{type} eq 'lvmthin' || $scfg->{type} eq 'lvm') {
663
664 if (($scfg->{type} eq $tcfg->{type}) &&
665 ($tcfg->{type} eq 'lvmthin' || $tcfg->{type} eq 'lvm')) {
666
667 my (undef, $volname, $vmid) = parse_volname($cfg, $volid);
668 my $size = volume_size_info($cfg, $volid, 5);
669 my $src = path($cfg, $volid);
670 my $dst = path($cfg, $target_volid);
671
672 run_command(['/usr/bin/ssh', "root\@${target_host}",
673 'pvesm', 'alloc', $target_storeid, $vmid,
674 $target_volname, int($size/1024)]);
675
676 eval {
677 if ($tcfg->{type} eq 'lvmthin') {
678 run_command([["dd", "if=$src", "bs=4k"],["/usr/bin/ssh", "root\@${target_host}",
679 "dd", 'conv=sparse', "of=$dst", "bs=4k"]]);
680 } else {
681 run_command([["dd", "if=$src", "bs=4k"],["/usr/bin/ssh", "root\@${target_host}",
682 "dd", "of=$dst", "bs=4k"]]);
683 }
684 };
685 if (my $err = $@) {
686 run_command(['/usr/bin/ssh', "root\@${target_host}",
687 'pvesm', 'free', $target_volid]);
688 die $err;
689 }
690 } else {
691 die "$errstr - migrate from source type '$scfg->{type}' to '$tcfg->{type}' not implemented\n";
692 }
693 } else {
694 die "$errstr - source type '$scfg->{type}' not implemented\n";
695 }
696 }
697
698 sub vdisk_clone {
699 my ($cfg, $volid, $vmid, $snap) = @_;
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->clone_image($scfg, $storeid, $volname, $vmid, $snap);
712 return "$storeid:$volname";
713 });
714 }
715
716 sub vdisk_create_base {
717 my ($cfg, $volid) = @_;
718
719 my ($storeid, $volname) = parse_volume_id($volid);
720
721 my $scfg = storage_config($cfg, $storeid);
722
723 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
724
725 activate_storage($cfg, $storeid);
726
727 # lock shared storage
728 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
729 my $volname = $plugin->create_base($storeid, $scfg, $volname);
730 return "$storeid:$volname";
731 });
732 }
733
734 sub vdisk_alloc {
735 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
736
737 die "no storage ID specified\n" if !$storeid;
738
739 PVE::JSONSchema::parse_storage_id($storeid);
740
741 my $scfg = storage_config($cfg, $storeid);
742
743 die "no VMID specified\n" if !$vmid;
744
745 $vmid = parse_vmid($vmid);
746
747 my $defformat = PVE::Storage::Plugin::default_format($scfg);
748
749 $fmt = $defformat if !$fmt;
750
751 activate_storage($cfg, $storeid);
752
753 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
754
755 # lock shared storage
756 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
757 my $old_umask = umask(umask|0037);
758 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
759 my $err = $@;
760 umask $old_umask;
761 die $err if $err;
762 return "$storeid:$volname";
763 });
764 }
765
766 sub vdisk_free {
767 my ($cfg, $volid) = @_;
768
769 my ($storeid, $volname) = parse_volume_id($volid);
770 my $scfg = storage_config($cfg, $storeid);
771 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
772
773 activate_storage($cfg, $storeid);
774
775 my $cleanup_worker;
776
777 # lock shared storage
778 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
779 # LVM-thin allows deletion of still referenced base volumes!
780 die "base volume '$volname' is still in use by linked clones\n"
781 if &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
782
783 my (undef, undef, undef, undef, undef, $isBase, $format) =
784 $plugin->parse_volname($volname);
785 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
786 });
787
788 return if !$cleanup_worker;
789
790 my $rpcenv = PVE::RPCEnvironment::get();
791 my $authuser = $rpcenv->get_user();
792
793 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
794 }
795
796 #list iso or openvz template ($tt = <iso|vztmpl|backup>)
797 sub template_list {
798 my ($cfg, $storeid, $tt) = @_;
799
800 die "unknown template type '$tt'\n"
801 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup');
802
803 my $ids = $cfg->{ids};
804
805 storage_check_enabled($cfg, $storeid) if ($storeid);
806
807 my $res = {};
808
809 # query the storage
810
811 foreach my $sid (keys %$ids) {
812 next if $storeid && $storeid ne $sid;
813
814 my $scfg = $ids->{$sid};
815 my $type = $scfg->{type};
816
817 next if !storage_check_enabled($cfg, $sid, undef, 1);
818
819 next if $tt eq 'iso' && !$scfg->{content}->{iso};
820 next if $tt eq 'vztmpl' && !$scfg->{content}->{vztmpl};
821 next if $tt eq 'backup' && !$scfg->{content}->{backup};
822
823 activate_storage($cfg, $sid);
824
825 if ($scfg->{path}) {
826 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
827
828 my $path = $plugin->get_subdir($scfg, $tt);
829
830 foreach my $fn (<$path/*>) {
831
832 my $info;
833
834 if ($tt eq 'iso') {
835 next if $fn !~ m!/([^/]+\.[Ii][Ss][Oo])$!;
836
837 $info = { volid => "$sid:iso/$1", format => 'iso' };
838
839 } elsif ($tt eq 'vztmpl') {
840 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
841
842 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
843
844 } elsif ($tt eq 'backup') {
845 next if $fn !~ m!/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!;
846
847 $info = { volid => "$sid:backup/$1", format => $2 };
848 }
849
850 $info->{size} = -s $fn;
851
852 push @{$res->{$sid}}, $info;
853 }
854
855 }
856
857 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
858 }
859
860 return $res;
861 }
862
863
864 sub vdisk_list {
865 my ($cfg, $storeid, $vmid, $vollist) = @_;
866
867 my $ids = $cfg->{ids};
868
869 storage_check_enabled($cfg, $storeid) if ($storeid);
870
871 my $res = {};
872
873 # prepare/activate/refresh all storages
874
875 my $storage_list = [];
876 if ($vollist) {
877 foreach my $volid (@$vollist) {
878 my ($sid, undef) = parse_volume_id($volid);
879 next if !defined($ids->{$sid});
880 next if !storage_check_enabled($cfg, $sid, undef, 1);
881 push @$storage_list, $sid;
882 }
883 } else {
884 foreach my $sid (keys %$ids) {
885 next if $storeid && $storeid ne $sid;
886 next if !storage_check_enabled($cfg, $sid, undef, 1);
887 push @$storage_list, $sid;
888 }
889 }
890
891 my $cache = {};
892
893 activate_storage_list($cfg, $storage_list, $cache);
894
895 foreach my $sid (keys %$ids) {
896 next if $storeid && $storeid ne $sid;
897 next if !storage_check_enabled($cfg, $sid, undef, 1);
898
899 my $scfg = $ids->{$sid};
900 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
901 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
902 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
903 }
904
905 return $res;
906 }
907
908 sub volume_list {
909 my ($cfg, $storeid, $vmid, $content) = @_;
910
911 my @ctypes = qw(images vztmpl iso backup);
912
913 my $cts = $content ? [ $content ] : [ @ctypes ];
914
915 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
916
917 my $res = [];
918 foreach my $ct (@$cts) {
919 my $data;
920 if ($ct eq 'images') {
921 $data = vdisk_list($cfg, $storeid, $vmid);
922 } elsif ($ct eq 'iso' && !defined($vmid)) {
923 $data = template_list($cfg, $storeid, 'iso');
924 } elsif ($ct eq 'vztmpl'&& !defined($vmid)) {
925 $data = template_list ($cfg, $storeid, 'vztmpl');
926 } elsif ($ct eq 'backup') {
927 $data = template_list ($cfg, $storeid, 'backup');
928 foreach my $item (@{$data->{$storeid}}) {
929 if (defined($vmid)) {
930 @{$data->{$storeid}} = grep { $_->{volid} =~ m/\S+-$vmid-\S+/ } @{$data->{$storeid}};
931 }
932 }
933 }
934
935 next if !$data || !$data->{$storeid};
936
937 foreach my $item (@{$data->{$storeid}}) {
938 $item->{content} = $ct;
939 push @$res, $item;
940 }
941 }
942
943 return $res;
944 }
945
946 sub uevent_seqnum {
947
948 my $filename = "/sys/kernel/uevent_seqnum";
949
950 my $seqnum = 0;
951 if (my $fh = IO::File->new($filename, "r")) {
952 my $line = <$fh>;
953 if ($line =~ m/^(\d+)$/) {
954 $seqnum = int($1);
955 }
956 close ($fh);
957 }
958 return $seqnum;
959 }
960
961 sub activate_storage {
962 my ($cfg, $storeid, $cache) = @_;
963
964 $cache = {} if !$cache;
965
966 my $scfg = storage_check_enabled($cfg, $storeid);
967
968 return if $cache->{activated}->{$storeid};
969
970 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
971
972 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
973
974 if ($scfg->{base}) {
975 my ($baseid, undef) = parse_volume_id ($scfg->{base});
976 activate_storage($cfg, $baseid, $cache);
977 }
978
979 if (!$plugin->check_connection($storeid, $scfg)) {
980 die "storage '$storeid' is not online\n";
981 }
982
983 $plugin->activate_storage($storeid, $scfg, $cache);
984
985 my $newseq = uevent_seqnum ();
986
987 # only call udevsettle if there are events
988 if ($newseq > $cache->{uevent_seqnum}) {
989 my $timeout = 30;
990 system ("$UDEVADM settle --timeout=$timeout"); # ignore errors
991 $cache->{uevent_seqnum} = $newseq;
992 }
993
994 $cache->{activated}->{$storeid} = 1;
995 }
996
997 sub activate_storage_list {
998 my ($cfg, $storeid_list, $cache) = @_;
999
1000 $cache = {} if !$cache;
1001
1002 foreach my $storeid (@$storeid_list) {
1003 activate_storage($cfg, $storeid, $cache);
1004 }
1005 }
1006
1007 sub deactivate_storage {
1008 my ($cfg, $storeid) = @_;
1009
1010 my $scfg = storage_config ($cfg, $storeid);
1011 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1012
1013 my $cache = {};
1014 $plugin->deactivate_storage($storeid, $scfg, $cache);
1015 }
1016
1017 sub activate_volumes {
1018 my ($cfg, $vollist, $snapname) = @_;
1019
1020 return if !($vollist && scalar(@$vollist));
1021
1022 my $storagehash = {};
1023 foreach my $volid (@$vollist) {
1024 my ($storeid, undef) = parse_volume_id($volid);
1025 $storagehash->{$storeid} = 1;
1026 }
1027
1028 my $cache = {};
1029
1030 activate_storage_list($cfg, [keys %$storagehash], $cache);
1031
1032 foreach my $volid (@$vollist) {
1033 my ($storeid, $volname) = parse_volume_id($volid);
1034 my $scfg = storage_config($cfg, $storeid);
1035 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1036 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1037 }
1038 }
1039
1040 sub deactivate_volumes {
1041 my ($cfg, $vollist, $snapname) = @_;
1042
1043 return if !($vollist && scalar(@$vollist));
1044
1045 my $cache = {};
1046
1047 my @errlist = ();
1048 foreach my $volid (@$vollist) {
1049 my ($storeid, $volname) = parse_volume_id($volid);
1050
1051 my $scfg = storage_config($cfg, $storeid);
1052 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1053
1054 eval {
1055 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1056 };
1057 if (my $err = $@) {
1058 warn $err;
1059 push @errlist, $volid;
1060 }
1061 }
1062
1063 die "volume deactivation failed: " . join(' ', @errlist)
1064 if scalar(@errlist);
1065 }
1066
1067 sub storage_info {
1068 my ($cfg, $content) = @_;
1069
1070 my $ids = $cfg->{ids};
1071
1072 my $info = {};
1073
1074 my @ctypes = PVE::Tools::split_list($content);
1075
1076 my $slist = [];
1077 foreach my $storeid (keys %$ids) {
1078
1079 next if !storage_check_enabled($cfg, $storeid, undef, 1);
1080
1081 if (defined($content)) {
1082 my $want_ctype = 0;
1083 foreach my $ctype (@ctypes) {
1084 if ($ids->{$storeid}->{content}->{$ctype}) {
1085 $want_ctype = 1;
1086 last;
1087 }
1088 }
1089 next if !$want_ctype;
1090 }
1091
1092 my $type = $ids->{$storeid}->{type};
1093
1094 $info->{$storeid} = {
1095 type => $type,
1096 total => 0,
1097 avail => 0,
1098 used => 0,
1099 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1100 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
1101 active => 0,
1102 };
1103
1104 push @$slist, $storeid;
1105 }
1106
1107 my $cache = {};
1108
1109 foreach my $storeid (keys %$ids) {
1110 my $scfg = $ids->{$storeid};
1111 next if !$info->{$storeid};
1112
1113 eval { activate_storage($cfg, $storeid, $cache); };
1114 if (my $err = $@) {
1115 warn $err;
1116 next;
1117 }
1118
1119 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1120 my ($total, $avail, $used, $active);
1121 eval { ($total, $avail, $used, $active) = $plugin->status($storeid, $scfg, $cache); };
1122 warn $@ if $@;
1123 next if !$active;
1124 $info->{$storeid}->{total} = int($total);
1125 $info->{$storeid}->{avail} = int($avail);
1126 $info->{$storeid}->{used} = int($used);
1127 $info->{$storeid}->{active} = $active;
1128 }
1129
1130 return $info;
1131 }
1132
1133 sub resolv_server {
1134 my ($server) = @_;
1135
1136 my ($packed_ip, $family);
1137 eval {
1138 my @res = PVE::Tools::getaddrinfo_all($server);
1139 $family = $res[0]->{family};
1140 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1141 };
1142 if (defined $packed_ip) {
1143 return Socket::inet_ntop($family, $packed_ip);
1144 }
1145 return undef;
1146 }
1147
1148 sub scan_nfs {
1149 my ($server_in) = @_;
1150
1151 my $server;
1152 if (!($server = resolv_server ($server_in))) {
1153 die "unable to resolve address for server '${server_in}'\n";
1154 }
1155
1156 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1157
1158 my $res = {};
1159 run_command($cmd, outfunc => sub {
1160 my $line = shift;
1161
1162 # note: howto handle white spaces in export path??
1163 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1164 $res->{$1} = $2;
1165 }
1166 });
1167
1168 return $res;
1169 }
1170
1171 sub scan_zfs {
1172
1173 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-H', '-o', 'name,avail,used'];
1174
1175 my $res = [];
1176 run_command($cmd, outfunc => sub {
1177 my $line = shift;
1178
1179 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1180 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1181 my $size = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($size_str);
1182 my $used = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($used_str);
1183 # ignore subvolumes generated by our ZFSPoolPlugin
1184 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1185 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1186 push @$res, { pool => $pool, size => $size, free => $size-$used };
1187 }
1188 });
1189
1190 return $res;
1191 }
1192
1193 sub resolv_portal {
1194 my ($portal, $noerr) = @_;
1195
1196 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1197 if ($server) {
1198 if (my $ip = resolv_server($server)) {
1199 $server = $ip;
1200 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1201 return $port ? "$server:$port" : $server;
1202 }
1203 }
1204 return undef if $noerr;
1205
1206 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1207 }
1208
1209 # idea is from usbutils package (/usr/bin/usb-devices) script
1210 sub __scan_usb_device {
1211 my ($res, $devpath, $parent, $level) = @_;
1212
1213 return if ! -d $devpath;
1214 return if $level && $devpath !~ m/^.*[-.](\d+)$/;
1215 my $port = $level ? int($1 - 1) : 0;
1216
1217 my $busnum = int(file_read_firstline("$devpath/busnum"));
1218 my $devnum = int(file_read_firstline("$devpath/devnum"));
1219
1220 my $d = {
1221 port => $port,
1222 level => $level,
1223 busnum => $busnum,
1224 devnum => $devnum,
1225 speed => file_read_firstline("$devpath/speed"),
1226 class => hex(file_read_firstline("$devpath/bDeviceClass")),
1227 vendid => file_read_firstline("$devpath/idVendor"),
1228 prodid => file_read_firstline("$devpath/idProduct"),
1229 };
1230
1231 if ($level) {
1232 my $usbpath = $devpath;
1233 $usbpath =~ s|^.*/\d+\-||;
1234 $d->{usbpath} = $usbpath;
1235 }
1236
1237 my $product = file_read_firstline("$devpath/product");
1238 $d->{product} = $product if $product;
1239
1240 my $manu = file_read_firstline("$devpath/manufacturer");
1241 $d->{manufacturer} = $manu if $manu;
1242
1243 my $serial => file_read_firstline("$devpath/serial");
1244 $d->{serial} = $serial if $serial;
1245
1246 push @$res, $d;
1247
1248 foreach my $subdev (<$devpath/$busnum-*>) {
1249 next if $subdev !~ m|/$busnum-[0-9]+(\.[0-9]+)*$|;
1250 __scan_usb_device($res, $subdev, $devnum, $level + 1);
1251 }
1252
1253 };
1254
1255 sub scan_usb {
1256
1257 my $devlist = [];
1258
1259 foreach my $device (</sys/bus/usb/devices/usb*>) {
1260 __scan_usb_device($devlist, $device, 0, 0);
1261 }
1262
1263 return $devlist;
1264 }
1265
1266 sub scan_iscsi {
1267 my ($portal_in) = @_;
1268
1269 my $portal;
1270 if (!($portal = resolv_portal($portal_in))) {
1271 die "unable to parse/resolve portal address '${portal_in}'\n";
1272 }
1273
1274 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
1275 }
1276
1277 sub storage_default_format {
1278 my ($cfg, $storeid) = @_;
1279
1280 my $scfg = storage_config ($cfg, $storeid);
1281
1282 return PVE::Storage::Plugin::default_format($scfg);
1283 }
1284
1285 sub vgroup_is_used {
1286 my ($cfg, $vgname) = @_;
1287
1288 foreach my $storeid (keys %{$cfg->{ids}}) {
1289 my $scfg = storage_config($cfg, $storeid);
1290 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1291 return 1;
1292 }
1293 }
1294
1295 return undef;
1296 }
1297
1298 sub target_is_used {
1299 my ($cfg, $target) = @_;
1300
1301 foreach my $storeid (keys %{$cfg->{ids}}) {
1302 my $scfg = storage_config($cfg, $storeid);
1303 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1304 return 1;
1305 }
1306 }
1307
1308 return undef;
1309 }
1310
1311 sub volume_is_used {
1312 my ($cfg, $volid) = @_;
1313
1314 foreach my $storeid (keys %{$cfg->{ids}}) {
1315 my $scfg = storage_config($cfg, $storeid);
1316 if ($scfg->{base} && $scfg->{base} eq $volid) {
1317 return 1;
1318 }
1319 }
1320
1321 return undef;
1322 }
1323
1324 sub storage_is_used {
1325 my ($cfg, $storeid) = @_;
1326
1327 foreach my $sid (keys %{$cfg->{ids}}) {
1328 my $scfg = storage_config($cfg, $sid);
1329 next if !$scfg->{base};
1330 my ($st) = parse_volume_id($scfg->{base});
1331 return 1 if $st && $st eq $storeid;
1332 }
1333
1334 return undef;
1335 }
1336
1337 sub foreach_volid {
1338 my ($list, $func) = @_;
1339
1340 return if !$list;
1341
1342 foreach my $sid (keys %$list) {
1343 foreach my $info (@{$list->{$sid}}) {
1344 my $volid = $info->{volid};
1345 my ($sid1, $volname) = parse_volume_id($volid, 1);
1346 if ($sid1 && $sid1 eq $sid) {
1347 &$func ($volid, $sid, $info);
1348 } else {
1349 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1350 }
1351 }
1352 }
1353 }
1354
1355 sub extract_vzdump_config_tar {
1356 my ($archive, $conf_re) = @_;
1357
1358 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1359
1360 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1361 die "unable to open file '$archive'\n";
1362
1363 my $file;
1364 while (defined($file = <$fh>)) {
1365 if ($file =~ $conf_re) {
1366 $file = $1; # untaint
1367 last;
1368 }
1369 }
1370
1371 kill 15, $pid;
1372 waitpid $pid, 0;
1373 close $fh;
1374
1375 die "ERROR: archive contains no configuration file\n" if !$file;
1376 chomp $file;
1377
1378 my $raw = '';
1379 my $out = sub {
1380 my $output = shift;
1381 $raw .= "$output\n";
1382 };
1383
1384 PVE::Tools::run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
1385
1386 return wantarray ? ($raw, $file) : $raw;
1387 }
1388
1389 sub extract_vzdump_config_vma {
1390 my ($archive, $comp) = @_;
1391
1392 my $cmd;
1393 my $raw = '';
1394 my $out = sub {
1395 my $output = shift;
1396 $raw .= "$output\n";
1397 };
1398
1399
1400 if ($comp) {
1401 my $uncomp;
1402 if ($comp eq 'gz') {
1403 $uncomp = ["zcat", $archive];
1404 } elsif ($comp eq 'lzo') {
1405 $uncomp = ["lzop", "-d", "-c", $archive];
1406 } else {
1407 die "unknown compression method '$comp'\n";
1408 }
1409 $cmd = [$uncomp, ["vma", "config", "-"]];
1410
1411 # in some cases, lzop/zcat exits with 1 when its stdout pipe is
1412 # closed early by vma, detect this and ignore the exit code later
1413 my $broken_pipe;
1414 my $errstring;
1415 my $err = sub {
1416 my $output = shift;
1417 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/) {
1418 $broken_pipe = 1;
1419 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1420 $errstring = "Failed to extract config from VMA archive: $output\n";
1421 }
1422 };
1423
1424 # in other cases, the pipeline will exit with exit code 141
1425 # because of the broken pipe, handle / ignore this as well
1426 my $rc;
1427 eval {
1428 $rc = PVE::Tools::run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1);
1429 };
1430 my $rerr = $@;
1431
1432 # use exit code if no stderr output and not just broken pipe
1433 if (!$errstring && !$broken_pipe && $rc != 0 && $rc != 141) {
1434 die "$rerr\n" if $rerr;
1435 die "config extraction failed with exit code $rc\n";
1436 }
1437 die "$errstring\n" if $errstring;
1438 } else {
1439 # simple case without compression and weird piping behaviour
1440 PVE::Tools::run_command(["vma", "config", $archive], outfunc => $out);
1441 }
1442
1443 return wantarray ? ($raw, undef) : $raw;
1444 }
1445
1446 sub extract_vzdump_config {
1447 my ($cfg, $volid) = @_;
1448
1449 my $archive = abs_filesystem_path($cfg, $volid);
1450
1451 if ($volid =~ /vzdump-(lxc|openvz)-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|(tar(\.(gz|lzo))?))$/) {
1452 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1453 } elsif ($volid =~ /vzdump-qemu-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?))$/) {
1454 my $format;
1455 my $comp;
1456 if ($7 eq 'tgz') {
1457 $format = 'tar';
1458 $comp = 'gz';
1459 } else {
1460 $format = $9;
1461 $comp = $11 if defined($11);
1462 }
1463
1464 if ($format eq 'tar') {
1465 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1466 } else {
1467 return extract_vzdump_config_vma($archive, $comp);
1468 }
1469 } else {
1470 die "cannot determine backup guest type for backup archive '$volid'\n";
1471 }
1472 }
1473
1474 # bash completion helper
1475
1476 sub complete_storage {
1477 my ($cmdname, $pname, $cvalue) = @_;
1478
1479 my $cfg = PVE::Storage::config();
1480
1481 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
1482 }
1483
1484 sub complete_storage_enabled {
1485 my ($cmdname, $pname, $cvalue) = @_;
1486
1487 my $res = [];
1488
1489 my $cfg = PVE::Storage::config();
1490 foreach my $sid (keys %{$cfg->{ids}}) {
1491 next if !storage_check_enabled($cfg, $sid, undef, 1);
1492 push @$res, $sid;
1493 }
1494 return $res;
1495 }
1496
1497 sub complete_content_type {
1498 my ($cmdname, $pname, $cvalue) = @_;
1499
1500 return [qw(rootdir images vztmpl iso backup)];
1501 }
1502
1503 sub complete_volume {
1504 my ($cmdname, $pname, $cvalue) = @_;
1505
1506 my $cfg = config();
1507
1508 my $storage_list = complete_storage_enabled();
1509
1510 if ($cvalue =~ m/^([^:]+):/) {
1511 $storage_list = [ $1 ];
1512 } else {
1513 if (scalar(@$storage_list) > 1) {
1514 # only list storage IDs to avoid large listings
1515 my $res = [];
1516 foreach my $storeid (@$storage_list) {
1517 # Hack: simply return 2 artificial values, so that
1518 # completions does not finish
1519 push @$res, "$storeid:volname", "$storeid:...";
1520 }
1521 return $res;
1522 }
1523 }
1524
1525 my $res = [];
1526 foreach my $storeid (@$storage_list) {
1527 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
1528
1529 foreach my $item (@$vollist) {
1530 push @$res, $item->{volid};
1531 }
1532 }
1533
1534 return $res;
1535 }
1536
1537 1;