]> git.proxmox.com Git - pve-storage.git/blame - PVE/Storage.pm
migrate: use pvesm import/export for zfs
[pve-storage.git] / PVE / Storage.pm
CommitLineData
b6cf0a66
DM
1package PVE::Storage;
2
3use strict;
ffd6f2f3 4use warnings;
dec97937 5use Data::Dumper;
ffd6f2f3 6
b6cf0a66
DM
7use POSIX;
8use IO::Select;
b6cf0a66 9use IO::File;
b6cf0a66
DM
10use File::Basename;
11use File::Path;
b6cf0a66 12use Cwd 'abs_path';
7a2d5c1a 13use Socket;
b6cf0a66 14
4dee23d3 15use PVE::Tools qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
83d7192f 16use PVE::Cluster qw(cfs_read_file cfs_write_file cfs_lock_file);
b6cf0a66
DM
17use PVE::Exception qw(raise_param_exc);
18use PVE::JSONSchema;
19use PVE::INotify;
88c3abaf 20use PVE::RPCEnvironment;
b6cf0a66 21
1dc01b9f
DM
22use PVE::Storage::Plugin;
23use PVE::Storage::DirPlugin;
24use PVE::Storage::LVMPlugin;
610798bc 25use PVE::Storage::LvmThinPlugin;
1dc01b9f
DM
26use PVE::Storage::NFSPlugin;
27use PVE::Storage::ISCSIPlugin;
0509010d 28use PVE::Storage::RBDPlugin;
caf1960c 29use PVE::Storage::SheepdogPlugin;
86616554 30use PVE::Storage::ISCSIDirectPlugin;
f4648aef 31use PVE::Storage::GlusterfsPlugin;
85fda4dd 32use PVE::Storage::ZFSPoolPlugin;
4f914e6e 33use PVE::Storage::ZFSPlugin;
14770890 34use PVE::Storage::DRBDPlugin;
b6cf0a66 35
4dee23d3
DP
36# Storage API version. Icrement it on changes in storage API interface.
37use constant APIVER => 1;
38
39# load standard plugins
1dc01b9f
DM
40PVE::Storage::DirPlugin->register();
41PVE::Storage::LVMPlugin->register();
610798bc 42PVE::Storage::LvmThinPlugin->register();
1dc01b9f
DM
43PVE::Storage::NFSPlugin->register();
44PVE::Storage::ISCSIPlugin->register();
0509010d 45PVE::Storage::RBDPlugin->register();
caf1960c 46PVE::Storage::SheepdogPlugin->register();
86616554 47PVE::Storage::ISCSIDirectPlugin->register();
f4648aef 48PVE::Storage::GlusterfsPlugin->register();
85fda4dd 49PVE::Storage::ZFSPoolPlugin->register();
4f914e6e 50PVE::Storage::ZFSPlugin->register();
14770890 51PVE::Storage::DRBDPlugin->register();
4dee23d3
DP
52
53# load third-party plugins
54if ( -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
1dc01b9f 80PVE::Storage::Plugin->init();
b6cf0a66 81
1dc01b9f 82my $UDEVADM = '/sbin/udevadm';
b6cf0a66 83
1dc01b9f 84# PVE::Storage utility functions
b6cf0a66
DM
85
86sub config {
87 return cfs_read_file("storage.cfg");
88}
89
83d7192f
FG
90sub write_config {
91 my ($cfg) = @_;
92
93 cfs_write_file('storage.cfg', $cfg);
94}
95
b6cf0a66
DM
96sub 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
b6cf0a66
DM
106sub storage_config {
107 my ($cfg, $storeid, $noerr) = @_;
108
82fc923f 109 die "no storage ID specified\n" if !$storeid;
1a3459ac 110
b6cf0a66
DM
111 my $scfg = $cfg->{ids}->{$storeid};
112
113 die "storage '$storeid' does not exists\n" if (!$noerr && !$scfg);
114
115 return $scfg;
116}
117
118sub storage_check_node {
119 my ($cfg, $storeid, $node, $noerr) = @_;
120
1dc01b9f 121 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
122
123 if ($scfg->{nodes}) {
124 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
125 if (!$scfg->{nodes}->{$node}) {
da156fb3 126 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
b6cf0a66
DM
127 return undef;
128 }
129 }
130
131 return $scfg;
132}
133
134sub storage_check_enabled {
135 my ($cfg, $storeid, $node, $noerr) = @_;
136
1dc01b9f 137 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
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
147sub storage_ids {
148 my ($cfg) = @_;
149
1dc01b9f 150 return keys %{$cfg->{ids}};
b6cf0a66
DM
151}
152
1dc01b9f
DM
153sub file_size_info {
154 my ($filename, $timeout) = @_;
b6cf0a66 155
1dc01b9f 156 return PVE::Storage::Plugin::file_size_info($filename, $timeout);
b6cf0a66
DM
157}
158
20ccac1b
AD
159sub volume_size_info {
160 my ($cfg, $volid, $timeout) = @_;
161
f18199e5
DM
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 }
20ccac1b
AD
172}
173
7e6c05dc
AD
174sub 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) {
f824c722 183 die "resize file/device '$volid' is not possible\n";
7e6c05dc 184 } else {
f824c722 185 die "unable to parse volume ID '$volid'\n";
7e6c05dc
AD
186 }
187}
188
1597f1f9
WL
189sub volume_rollback_is_possible {
190 my ($cfg, $volid, $snap) = @_;
e0852ba7 191
1597f1f9
WL
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) {
f824c722 198 die "snapshot rollback file/device '$volid' is not possible\n";
1597f1f9 199 } else {
f824c722 200 die "unable to parse volume ID '$volid'\n";
1597f1f9
WL
201 }
202}
203
db60719c 204sub volume_snapshot {
f5640e7d 205 my ($cfg, $volid, $snap) = @_;
db60719c
AD
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});
f5640e7d 211 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
db60719c 212 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 213 die "snapshot file/device '$volid' is not possible\n";
db60719c 214 } else {
f824c722 215 die "unable to parse volume ID '$volid'\n";
db60719c
AD
216 }
217}
218
22a2a633
AD
219sub 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});
b3f302c6 226 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
22a2a633
AD
227 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
228 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 229 die "snapshot rollback file/device '$volid' is not possible\n";
22a2a633 230 } else {
f824c722 231 die "unable to parse volume ID '$volid'\n";
22a2a633
AD
232 }
233}
234
5753c9d1
AD
235sub 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});
27cc55d4 242 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
5753c9d1 243 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 244 die "snapshot delete file/device '$volid' is not possible\n";
5753c9d1 245 } else {
f824c722 246 die "unable to parse volume ID '$volid'\n";
5753c9d1
AD
247 }
248}
249
99473759
AD
250sub 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
aefe82ea 265sub volume_snapshot_list {
17be2e9a 266 my ($cfg, $volid, $prefix) = @_;
aefe82ea
WL
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});
17be2e9a 272 return $plugin->volume_snapshot_list($scfg, $storeid, $volname, $prefix);
aefe82ea
WL
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
1dc01b9f
DM
282sub get_image_dir {
283 my ($cfg, $storeid, $vmid) = @_;
b6cf0a66 284
1dc01b9f
DM
285 my $scfg = storage_config($cfg, $storeid);
286 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 287
1dc01b9f 288 my $path = $plugin->get_subdir($scfg, 'images');
b6cf0a66 289
1dc01b9f 290 return $vmid ? "$path/$vmid" : $path;
b6cf0a66
DM
291}
292
1dc01b9f 293sub get_private_dir {
b6cf0a66
DM
294 my ($cfg, $storeid, $vmid) = @_;
295
1dc01b9f
DM
296 my $scfg = storage_config($cfg, $storeid);
297 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 298
1dc01b9f 299 my $path = $plugin->get_subdir($scfg, 'rootdir');
d22a6133 300
1dc01b9f 301 return $vmid ? "$path/$vmid" : $path;
d22a6133
DM
302}
303
b6cf0a66
DM
304sub get_iso_dir {
305 my ($cfg, $storeid) = @_;
306
1dc01b9f
DM
307 my $scfg = storage_config($cfg, $storeid);
308 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 309
1dc01b9f 310 return $plugin->get_subdir($scfg, 'iso');
b6cf0a66
DM
311}
312
313sub get_vztmpl_dir {
314 my ($cfg, $storeid) = @_;
315
1dc01b9f
DM
316 my $scfg = storage_config($cfg, $storeid);
317 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 318
1dc01b9f 319 return $plugin->get_subdir($scfg, 'vztmpl');
b6cf0a66
DM
320}
321
568de3d1
DM
322sub get_backup_dir {
323 my ($cfg, $storeid) = @_;
324
1dc01b9f
DM
325 my $scfg = storage_config($cfg, $storeid);
326 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 327
1dc01b9f 328 return $plugin->get_subdir($scfg, 'backup');
b6cf0a66
DM
329}
330
331# library implementation
332
b6cf0a66
DM
333sub 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
787624df
FG
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.
ec4b0dc7
AD
344sub 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});
a6f12626
DM
352
353 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
354
ec4b0dc7
AD
355 return $plugin->parse_volname($volname);
356}
357
b6cf0a66
DM
358sub parse_volume_id {
359 my ($volid, $noerr) = @_;
360
a7f3d909 361 return PVE::Storage::Plugin::parse_volume_id($volid, $noerr);
b6cf0a66
DM
362}
363
04a13668
DM
364# test if we have read access to volid
365sub 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
17fb7e42
FG
390my $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
787624df
FG
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.
17fb7e42
FG
419sub 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
b6cf0a66
DM
431# try to map a filesystem path to a volume identifier
432sub path_to_volume_id {
433 my ($cfg, $path) = @_;
434
435 my $ids = $cfg->{ids};
436
1dc01b9f 437 my ($sid, $volname) = parse_volume_id($path, 1);
b6cf0a66 438 if ($sid) {
1dc01b9f 439 if (my $scfg = $ids->{$sid}) {
188aca38 440 if ($scfg->{path}) {
1dc01b9f
DM
441 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
442 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
b6cf0a66
DM
443 return ($vtype, $path);
444 }
445 }
446 return ('');
447 }
448
1a3459ac 449 # Note: abs_path() return undef if $path doesn not exist
75d75990
DM
450 # for example when nfs storage is not mounted
451 $path = abs_path($path) || $path;
b6cf0a66
DM
452
453 foreach my $sid (keys %$ids) {
1dc01b9f
DM
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');
b6cf0a66
DM
462
463 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
464 my $vmid = $1;
465 my $name = $2;
fcbec654
DM
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 }
b6cf0a66
DM
475 } elsif ($path =~ m!^$isodir/([^/]+\.[Ii][Ss][Oo])$!) {
476 my $name = $1;
1a3459ac 477 return ('iso', "$sid:iso/$name");
b6cf0a66
DM
478 } elsif ($path =~ m!^$tmpldir/([^/]+\.tar\.gz)$!) {
479 my $name = $1;
480 return ('vztmpl', "$sid:vztmpl/$name");
1ac17c74
DM
481 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
482 my $vmid = $1;
483 return ('rootdir', "$sid:rootdir/$vmid");
a22854e5 484 } elsif ($path =~ m!^$backupdir/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!) {
568de3d1 485 my $name = $1;
1a3459ac 486 return ('iso', "$sid:backup/$name");
b6cf0a66
DM
487 }
488 }
489
490 # can't map path to volume id
491 return ('');
492}
493
494sub path {
207ea852 495 my ($cfg, $volid, $snapname) = @_;
b6cf0a66 496
1dc01b9f 497 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 498
1dc01b9f 499 my $scfg = storage_config($cfg, $storeid);
b6cf0a66 500
1dc01b9f 501 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
207ea852 502 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
2494896a 503 return wantarray ? ($path, $owner, $vtype) : $path;
b6cf0a66
DM
504}
505
35fbb2e6
DM
506sub 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
b6cf0a66
DM
527sub storage_migrate {
528 my ($cfg, $volid, $target_host, $target_storeid, $target_volname) = @_;
529
6bf56298 530 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66
DM
531 $target_volname = $volname if !$target_volname;
532
6bf56298 533 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
534
535 # no need to migrate shared content
536 return if $storeid eq $target_storeid && $scfg->{shared};
537
6bf56298 538 my $tcfg = storage_config($cfg, $target_storeid);
b6cf0a66
DM
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
45c2ee35 544 my $sshoptions = "-o 'BatchMode=yes'";
b6cf0a66
DM
545 my $ssh = "/usr/bin/ssh $sshoptions";
546
547 local $ENV{RSYNC_RSH} = $ssh;
548
1dc01b9f
DM
549 # only implemented for file system based storage
550 if ($scfg->{path}) {
551 if ($tcfg->{path}) {
b6cf0a66 552
1dc01b9f
DM
553 my $src_plugin = PVE::Storage::Plugin->lookup($scfg->{type});
554 my $dst_plugin = PVE::Storage::Plugin->lookup($tcfg->{type});
6bf56298
DM
555 my $src = $src_plugin->path($scfg, $volname, $storeid);
556 my $dst = $dst_plugin->path($tcfg, $target_volname, $target_storeid);
b6cf0a66 557
1dc01b9f 558 my $dirname = dirname($dst);
b6cf0a66
DM
559
560 if ($tcfg->{shared}) { # we can do a local copy
1a3459ac 561
f81372ac 562 run_command(['/bin/mkdir', '-p', $dirname]);
b6cf0a66 563
1dc01b9f 564 run_command(['/bin/cp', $src, $dst]);
b6cf0a66 565
1dc01b9f 566 } else {
1a3459ac 567 run_command(['/usr/bin/ssh', "root\@${target_host}",
1dc01b9f 568 '/bin/mkdir', '-p', $dirname]);
b6cf0a66 569
1dc01b9f
DM
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) {
1a3459ac 575 run_command(['/usr/bin/ssh', "root\@${target_host}",
1dc01b9f
DM
576 'rm', '-f', $dst],
577 outfunc => sub {});
578 }
b6cf0a66 579
986303ca
WL
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 }
b6cf0a66 589
1dc01b9f 590 my $percent = -1;
b6cf0a66 591
1dc01b9f
DM
592 run_command($cmd, outfunc => sub {
593 my $line = shift;
b6cf0a66 594
1dc01b9f
DM
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 }
e0852ba7 610
3d621977
WL
611 } elsif ($scfg->{type} eq 'zfspool') {
612
e0852ba7 613 if ($tcfg->{type} eq 'zfspool') {
3d621977 614
82fc923f 615 die "$errstr - pool on target does not have the same name as on source!"
e0852ba7 616 if $tcfg->{pool} ne $scfg->{pool};
3d621977 617
e0852ba7 618 my (undef, $volname) = parse_volname($cfg, $volid);
3d621977
WL
619 my $zfspath = "$scfg->{pool}\/$volname";
620
865710f4
WB
621 my $send = ['pvesm', 'export', $volid, 'zfs', '-', '-snapshot', '__migration__', '-with-snapshots', '1'];
622 my $recv = ['ssh', "root\@$target_host", '--', 'pvesm', 'import', $volid, 'zfs', '-', '-with-snapshots', '1'];
623 my $free = ['ssh', "root\@$target_host", '--', 'pvesm', 'free', $volid, '-snapshot', '__migration__'];
3d621977 624
865710f4 625 volume_snapshot($cfg, $volid, '__migration__');
e0852ba7 626 eval{
865710f4 627 run_command([$send, $recv]);
3d621977 628 };
afd0afe4 629 my $err = $@;
865710f4
WB
630 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
631 eval { volume_snapshot_delete($cfg, $volid, '__migration__', 0) };
afd0afe4 632 warn "could not remove source snapshot: $@\n" if $@;
865710f4 633 eval { run_command($free) };
afd0afe4
FG
634 warn "could not remove target snapshot: $@\n" if $@;
635 die $err if $err;
3d621977
WL
636 } else {
637 die "$errstr - target type $tcfg->{type} is not valid\n";
638 }
0a29ad61
WL
639
640 } elsif ($scfg->{type} eq 'lvmthin' || $scfg->{type} eq 'lvm') {
641
76f13c9e
DM
642 if (($scfg->{type} eq $tcfg->{type}) &&
643 ($tcfg->{type} eq 'lvmthin' || $tcfg->{type} eq 'lvm')) {
0a29ad61 644
84252f67 645 my (undef, $volname, $vmid) = parse_volname($cfg, $volid);
0a29ad61 646 my $size = volume_size_info($cfg, $volid, 5);
84252f67
DM
647 my $src = path($cfg, $volid);
648 my $dst = path($cfg, $target_volid);
0a29ad61
WL
649
650 run_command(['/usr/bin/ssh', "root\@${target_host}",
651 'pvesm', 'alloc', $target_storeid, $vmid,
84252f67 652 $target_volname, int($size/1024)]);
0a29ad61
WL
653
654 eval {
e83f7b40 655 if ($tcfg->{type} eq 'lvmthin') {
46f114a5
DM
656 run_command([["dd", "if=$src", "bs=4k"],["/usr/bin/ssh", "root\@${target_host}",
657 "dd", 'conv=sparse', "of=$dst", "bs=4k"]]);
e83f7b40 658 } else {
46f114a5
DM
659 run_command([["dd", "if=$src", "bs=4k"],["/usr/bin/ssh", "root\@${target_host}",
660 "dd", "of=$dst", "bs=4k"]]);
e83f7b40 661 }
0a29ad61
WL
662 };
663 if (my $err = $@) {
664 run_command(['/usr/bin/ssh', "root\@${target_host}",
84252f67 665 'pvesm', 'free', $target_volid]);
966ecef2 666 die $err;
0a29ad61
WL
667 }
668 } else {
76f13c9e 669 die "$errstr - migrate from source type '$scfg->{type}' to '$tcfg->{type}' not implemented\n";
0a29ad61 670 }
1dc01b9f
DM
671 } else {
672 die "$errstr - source type '$scfg->{type}' not implemented\n";
b6cf0a66
DM
673 }
674}
675
2502b33b 676sub vdisk_clone {
7bbc4004 677 my ($cfg, $volid, $vmid, $snap) = @_;
1a3459ac 678
2502b33b
DM
679 my ($storeid, $volname) = parse_volume_id($volid);
680
681 my $scfg = storage_config($cfg, $storeid);
682
683 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 684
2502b33b
DM
685 activate_storage($cfg, $storeid);
686
687 # lock shared storage
688 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
7bbc4004 689 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
2502b33b
DM
690 return "$storeid:$volname";
691 });
692}
693
694sub vdisk_create_base {
695 my ($cfg, $volid) = @_;
696
697 my ($storeid, $volname) = parse_volume_id($volid);
698
699 my $scfg = storage_config($cfg, $storeid);
700
701 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 702
2502b33b
DM
703 activate_storage($cfg, $storeid);
704
705 # lock shared storage
706 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
707 my $volname = $plugin->create_base($storeid, $scfg, $volname);
708 return "$storeid:$volname";
709 });
710}
711
1dc01b9f
DM
712sub vdisk_alloc {
713 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
b6cf0a66 714
82fc923f 715 die "no storage ID specified\n" if !$storeid;
b6cf0a66 716
1dc01b9f 717 PVE::JSONSchema::parse_storage_id($storeid);
b6cf0a66 718
1dc01b9f 719 my $scfg = storage_config($cfg, $storeid);
b6cf0a66 720
1dc01b9f 721 die "no VMID specified\n" if !$vmid;
b6cf0a66 722
1dc01b9f 723 $vmid = parse_vmid($vmid);
b6cf0a66 724
1dc01b9f 725 my $defformat = PVE::Storage::Plugin::default_format($scfg);
b6cf0a66 726
1dc01b9f 727 $fmt = $defformat if !$fmt;
b6cf0a66 728
1dc01b9f 729 activate_storage($cfg, $storeid);
3af60e62 730
1dc01b9f 731 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 732
1dc01b9f
DM
733 # lock shared storage
734 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
afdfbe55
WB
735 my $old_umask = umask(umask|0037);
736 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
737 my $err = $@;
738 umask $old_umask;
739 die $err if $err;
1dc01b9f
DM
740 return "$storeid:$volname";
741 });
b6cf0a66
DM
742}
743
1dc01b9f
DM
744sub vdisk_free {
745 my ($cfg, $volid) = @_;
b6cf0a66 746
1dc01b9f 747 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f 748 my $scfg = storage_config($cfg, $storeid);
1dc01b9f 749 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 750
1dc01b9f 751 activate_storage($cfg, $storeid);
b6cf0a66 752
1dc01b9f 753 my $cleanup_worker;
b6cf0a66 754
1dc01b9f
DM
755 # lock shared storage
756 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
787624df 757 # LVM-thin allows deletion of still referenced base volumes!
17fb7e42
FG
758 die "base volume '$volname' is still in use by linked clones\n"
759 if &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
32437ed2 760
17fb7e42 761 my (undef, undef, undef, undef, undef, $isBase, $format) =
32437ed2 762 $plugin->parse_volname($volname);
35533c68 763 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1dc01b9f 764 });
b6cf0a66 765
1dc01b9f 766 return if !$cleanup_worker;
b6cf0a66 767
1dc01b9f
DM
768 my $rpcenv = PVE::RPCEnvironment::get();
769 my $authuser = $rpcenv->get_user();
b6cf0a66 770
1dc01b9f 771 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
b6cf0a66
DM
772}
773
b6cf0a66
DM
774#list iso or openvz template ($tt = <iso|vztmpl|backup>)
775sub template_list {
776 my ($cfg, $storeid, $tt) = @_;
777
1a3459ac
DM
778 die "unknown template type '$tt'\n"
779 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup');
b6cf0a66
DM
780
781 my $ids = $cfg->{ids};
782
783 storage_check_enabled($cfg, $storeid) if ($storeid);
784
785 my $res = {};
786
787 # query the storage
788
789 foreach my $sid (keys %$ids) {
790 next if $storeid && $storeid ne $sid;
791
792 my $scfg = $ids->{$sid};
793 my $type = $scfg->{type};
794
795 next if !storage_check_enabled($cfg, $sid, undef, 1);
796
797 next if $tt eq 'iso' && !$scfg->{content}->{iso};
798 next if $tt eq 'vztmpl' && !$scfg->{content}->{vztmpl};
799 next if $tt eq 'backup' && !$scfg->{content}->{backup};
800
1dc01b9f 801 activate_storage($cfg, $sid);
b6cf0a66 802
1dc01b9f
DM
803 if ($scfg->{path}) {
804 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 805
1dc01b9f 806 my $path = $plugin->get_subdir($scfg, $tt);
b6cf0a66
DM
807
808 foreach my $fn (<$path/*>) {
809
810 my $info;
811
812 if ($tt eq 'iso') {
813 next if $fn !~ m!/([^/]+\.[Ii][Ss][Oo])$!;
814
815 $info = { volid => "$sid:iso/$1", format => 'iso' };
816
817 } elsif ($tt eq 'vztmpl') {
13d2cb79 818 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
b6cf0a66 819
13d2cb79 820 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
b6cf0a66
DM
821
822 } elsif ($tt eq 'backup') {
a22854e5 823 next if $fn !~ m!/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!;
1a3459ac 824
b6cf0a66
DM
825 $info = { volid => "$sid:backup/$1", format => $2 };
826 }
827
828 $info->{size} = -s $fn;
829
830 push @{$res->{$sid}}, $info;
831 }
832
833 }
834
835 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
836 }
837
838 return $res;
839}
840
20ccac1b 841
b6cf0a66
DM
842sub vdisk_list {
843 my ($cfg, $storeid, $vmid, $vollist) = @_;
844
845 my $ids = $cfg->{ids};
846
847 storage_check_enabled($cfg, $storeid) if ($storeid);
848
849 my $res = {};
850
851 # prepare/activate/refresh all storages
852
b6cf0a66
DM
853 my $storage_list = [];
854 if ($vollist) {
855 foreach my $volid (@$vollist) {
1dc01b9f
DM
856 my ($sid, undef) = parse_volume_id($volid);
857 next if !defined($ids->{$sid});
b6cf0a66
DM
858 next if !storage_check_enabled($cfg, $sid, undef, 1);
859 push @$storage_list, $sid;
b6cf0a66
DM
860 }
861 } else {
862 foreach my $sid (keys %$ids) {
863 next if $storeid && $storeid ne $sid;
864 next if !storage_check_enabled($cfg, $sid, undef, 1);
865 push @$storage_list, $sid;
b6cf0a66
DM
866 }
867 }
868
1dc01b9f 869 my $cache = {};
b6cf0a66 870
1dc01b9f 871 activate_storage_list($cfg, $storage_list, $cache);
b6cf0a66
DM
872
873 foreach my $sid (keys %$ids) {
1dc01b9f
DM
874 next if $storeid && $storeid ne $sid;
875 next if !storage_check_enabled($cfg, $sid, undef, 1);
b6cf0a66 876
1dc01b9f
DM
877 my $scfg = $ids->{$sid};
878 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
879 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
b6cf0a66
DM
880 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
881 }
882
883 return $res;
884}
885
37ba0aea
DM
886sub volume_list {
887 my ($cfg, $storeid, $vmid, $content) = @_;
888
889 my @ctypes = qw(images vztmpl iso backup);
890
891 my $cts = $content ? [ $content ] : [ @ctypes ];
892
893 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
894
895 my $res = [];
896 foreach my $ct (@$cts) {
897 my $data;
898 if ($ct eq 'images') {
899 $data = vdisk_list($cfg, $storeid, $vmid);
900 } elsif ($ct eq 'iso' && !defined($vmid)) {
901 $data = template_list($cfg, $storeid, 'iso');
902 } elsif ($ct eq 'vztmpl'&& !defined($vmid)) {
903 $data = template_list ($cfg, $storeid, 'vztmpl');
904 } elsif ($ct eq 'backup') {
905 $data = template_list ($cfg, $storeid, 'backup');
906 foreach my $item (@{$data->{$storeid}}) {
907 if (defined($vmid)) {
908 @{$data->{$storeid}} = grep { $_->{volid} =~ m/\S+-$vmid-\S+/ } @{$data->{$storeid}};
909 }
910 }
911 }
912
913 next if !$data || !$data->{$storeid};
914
915 foreach my $item (@{$data->{$storeid}}) {
916 $item->{content} = $ct;
917 push @$res, $item;
918 }
919 }
920
921 return $res;
922}
923
b6cf0a66
DM
924sub uevent_seqnum {
925
926 my $filename = "/sys/kernel/uevent_seqnum";
927
928 my $seqnum = 0;
1dc01b9f 929 if (my $fh = IO::File->new($filename, "r")) {
b6cf0a66
DM
930 my $line = <$fh>;
931 if ($line =~ m/^(\d+)$/) {
1dc01b9f 932 $seqnum = int($1);
b6cf0a66
DM
933 }
934 close ($fh);
935 }
936 return $seqnum;
937}
938
f3d4ef46 939sub activate_storage {
1dc01b9f 940 my ($cfg, $storeid, $cache) = @_;
b6cf0a66 941
f3d4ef46
DM
942 $cache = {} if !$cache;
943
b6cf0a66
DM
944 my $scfg = storage_check_enabled($cfg, $storeid);
945
1dc01b9f 946 return if $cache->{activated}->{$storeid};
b6cf0a66 947
1dc01b9f 948 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
b6cf0a66 949
1dc01b9f 950 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 951
1dc01b9f
DM
952 if ($scfg->{base}) {
953 my ($baseid, undef) = parse_volume_id ($scfg->{base});
f3d4ef46
DM
954 activate_storage($cfg, $baseid, $cache);
955 }
956
957 if (!$plugin->check_connection($storeid, $scfg)) {
958 die "storage '$storeid' is not online\n";
b6cf0a66
DM
959 }
960
1dc01b9f
DM
961 $plugin->activate_storage($storeid, $scfg, $cache);
962
b6cf0a66
DM
963 my $newseq = uevent_seqnum ();
964
965 # only call udevsettle if there are events
1dc01b9f 966 if ($newseq > $cache->{uevent_seqnum}) {
b6cf0a66
DM
967 my $timeout = 30;
968 system ("$UDEVADM settle --timeout=$timeout"); # ignore errors
1dc01b9f 969 $cache->{uevent_seqnum} = $newseq;
b6cf0a66
DM
970 }
971
1dc01b9f 972 $cache->{activated}->{$storeid} = 1;
b6cf0a66
DM
973}
974
975sub activate_storage_list {
1dc01b9f 976 my ($cfg, $storeid_list, $cache) = @_;
b6cf0a66 977
1dc01b9f 978 $cache = {} if !$cache;
b6cf0a66
DM
979
980 foreach my $storeid (@$storeid_list) {
f3d4ef46 981 activate_storage($cfg, $storeid, $cache);
b6cf0a66
DM
982 }
983}
984
1dc01b9f
DM
985sub deactivate_storage {
986 my ($cfg, $storeid) = @_;
987
988 my $scfg = storage_config ($cfg, $storeid);
989 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 990
1dc01b9f
DM
991 my $cache = {};
992 $plugin->deactivate_storage($storeid, $scfg, $cache);
b6cf0a66
DM
993}
994
995sub activate_volumes {
02e797b8 996 my ($cfg, $vollist, $snapname) = @_;
6703353b
DM
997
998 return if !($vollist && scalar(@$vollist));
999
b6cf0a66
DM
1000 my $storagehash = {};
1001 foreach my $volid (@$vollist) {
1dc01b9f 1002 my ($storeid, undef) = parse_volume_id($volid);
b6cf0a66
DM
1003 $storagehash->{$storeid} = 1;
1004 }
1005
1dc01b9f
DM
1006 my $cache = {};
1007
1008 activate_storage_list($cfg, [keys %$storagehash], $cache);
b6cf0a66
DM
1009
1010 foreach my $volid (@$vollist) {
5521b580 1011 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f
DM
1012 my $scfg = storage_config($cfg, $storeid);
1013 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
02e797b8 1014 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
b6cf0a66
DM
1015 }
1016}
1017
1018sub deactivate_volumes {
02e797b8 1019 my ($cfg, $vollist, $snapname) = @_;
b6cf0a66 1020
6703353b
DM
1021 return if !($vollist && scalar(@$vollist));
1022
1dc01b9f
DM
1023 my $cache = {};
1024
6703353b 1025 my @errlist = ();
b6cf0a66 1026 foreach my $volid (@$vollist) {
1dc01b9f 1027 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 1028
1dc01b9f
DM
1029 my $scfg = storage_config($cfg, $storeid);
1030 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 1031
1dc01b9f 1032 eval {
02e797b8 1033 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1dc01b9f
DM
1034 };
1035 if (my $err = $@) {
1036 warn $err;
1037 push @errlist, $volid;
b6cf0a66
DM
1038 }
1039 }
6703353b 1040
82fc923f 1041 die "volume deactivation failed: " . join(' ', @errlist)
6703353b 1042 if scalar(@errlist);
b6cf0a66
DM
1043}
1044
1a3459ac 1045sub storage_info {
b6cf0a66
DM
1046 my ($cfg, $content) = @_;
1047
1048 my $ids = $cfg->{ids};
1049
1050 my $info = {};
ff3badd8 1051
583c2802 1052 my @ctypes = PVE::Tools::split_list($content);
ff3badd8 1053
b6cf0a66
DM
1054 my $slist = [];
1055 foreach my $storeid (keys %$ids) {
1056
b6cf0a66
DM
1057 next if !storage_check_enabled($cfg, $storeid, undef, 1);
1058
d73060be
DM
1059 if (defined($content)) {
1060 my $want_ctype = 0;
1061 foreach my $ctype (@ctypes) {
1062 if ($ids->{$storeid}->{content}->{$ctype}) {
1063 $want_ctype = 1;
1064 last;
1065 }
583c2802 1066 }
d73060be 1067 next if !$want_ctype;
583c2802 1068 }
ff3badd8 1069
b6cf0a66
DM
1070 my $type = $ids->{$storeid}->{type};
1071
1a3459ac 1072 $info->{$storeid} = {
b6cf0a66 1073 type => $type,
1a3459ac
DM
1074 total => 0,
1075 avail => 0,
1076 used => 0,
04a2e4f3 1077 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1dc01b9f 1078 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
b6cf0a66
DM
1079 active => 0,
1080 };
1081
b6cf0a66
DM
1082 push @$slist, $storeid;
1083 }
1084
1dc01b9f 1085 my $cache = {};
b6cf0a66 1086
b6cf0a66
DM
1087 foreach my $storeid (keys %$ids) {
1088 my $scfg = $ids->{$storeid};
b6cf0a66
DM
1089 next if !$info->{$storeid};
1090
f3d4ef46
DM
1091 eval { activate_storage($cfg, $storeid, $cache); };
1092 if (my $err = $@) {
1093 warn $err;
1094 next;
1095 }
1096
1dc01b9f 1097 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
7028645e
DM
1098 my ($total, $avail, $used, $active);
1099 eval { ($total, $avail, $used, $active) = $plugin->status($storeid, $scfg, $cache); };
1100 warn $@ if $@;
1dc01b9f 1101 next if !$active;
ff3badd8
DM
1102 $info->{$storeid}->{total} = int($total);
1103 $info->{$storeid}->{avail} = int($avail);
1104 $info->{$storeid}->{used} = int($used);
1dc01b9f 1105 $info->{$storeid}->{active} = $active;
b6cf0a66
DM
1106 }
1107
1108 return $info;
1109}
1110
1111sub resolv_server {
1112 my ($server) = @_;
1a3459ac 1113
c67daeac
WB
1114 my ($packed_ip, $family);
1115 eval {
1116 my @res = PVE::Tools::getaddrinfo_all($server);
1117 $family = $res[0]->{family};
1118 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1119 };
b6cf0a66 1120 if (defined $packed_ip) {
ee302b1c 1121 return Socket::inet_ntop($family, $packed_ip);
b6cf0a66
DM
1122 }
1123 return undef;
1124}
1125
1126sub scan_nfs {
1127 my ($server_in) = @_;
1128
1129 my $server;
1130 if (!($server = resolv_server ($server_in))) {
1131 die "unable to resolve address for server '${server_in}'\n";
1132 }
1133
1134 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1135
1136 my $res = {};
f81372ac 1137 run_command($cmd, outfunc => sub {
b6cf0a66
DM
1138 my $line = shift;
1139
1140 # note: howto handle white spaces in export path??
1141 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1142 $res->{$1} = $2;
1143 }
1144 });
1145
1146 return $res;
1147}
1148
584d97f6
DM
1149sub scan_zfs {
1150
3932390b 1151 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-H', '-o', 'name,avail,used'];
584d97f6
DM
1152
1153 my $res = [];
1154 run_command($cmd, outfunc => sub {
1155 my $line = shift;
1156
1157 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
3932390b 1158 my ($pool, $size_str, $used_str) = ($1, $2, $3);
584d97f6 1159 my $size = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($size_str);
3932390b 1160 my $used = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($used_str);
48e27f79 1161 # ignore subvolumes generated by our ZFSPoolPlugin
851658c3
WL
1162 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1163 return if $pool =~ m!/basevol-\d+-[^/]+$!;
3932390b 1164 push @$res, { pool => $pool, size => $size, free => $size-$used };
584d97f6
DM
1165 }
1166 });
1167
1168 return $res;
1169}
1170
b6cf0a66
DM
1171sub resolv_portal {
1172 my ($portal, $noerr) = @_;
1173
1689e627
WB
1174 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1175 if ($server) {
b6cf0a66
DM
1176 if (my $ip = resolv_server($server)) {
1177 $server = $ip;
1689e627 1178 $server = "[$server]" if $server =~ /^$IPV6RE$/;
b6cf0a66
DM
1179 return $port ? "$server:$port" : $server;
1180 }
1181 }
1182 return undef if $noerr;
1183
1184 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1185}
1186
1187# idea is from usbutils package (/usr/bin/usb-devices) script
1188sub __scan_usb_device {
1189 my ($res, $devpath, $parent, $level) = @_;
1190
1191 return if ! -d $devpath;
1192 return if $level && $devpath !~ m/^.*[-.](\d+)$/;
1193 my $port = $level ? int($1 - 1) : 0;
1194
1195 my $busnum = int(file_read_firstline("$devpath/busnum"));
1196 my $devnum = int(file_read_firstline("$devpath/devnum"));
1197
1198 my $d = {
1199 port => $port,
1200 level => $level,
1201 busnum => $busnum,
1202 devnum => $devnum,
1203 speed => file_read_firstline("$devpath/speed"),
1204 class => hex(file_read_firstline("$devpath/bDeviceClass")),
1205 vendid => file_read_firstline("$devpath/idVendor"),
1206 prodid => file_read_firstline("$devpath/idProduct"),
1207 };
1208
1209 if ($level) {
1210 my $usbpath = $devpath;
1211 $usbpath =~ s|^.*/\d+\-||;
1212 $d->{usbpath} = $usbpath;
1213 }
1214
1215 my $product = file_read_firstline("$devpath/product");
1216 $d->{product} = $product if $product;
1a3459ac 1217
b6cf0a66
DM
1218 my $manu = file_read_firstline("$devpath/manufacturer");
1219 $d->{manufacturer} = $manu if $manu;
1220
1221 my $serial => file_read_firstline("$devpath/serial");
1222 $d->{serial} = $serial if $serial;
1223
1224 push @$res, $d;
1225
1226 foreach my $subdev (<$devpath/$busnum-*>) {
1227 next if $subdev !~ m|/$busnum-[0-9]+(\.[0-9]+)*$|;
1228 __scan_usb_device($res, $subdev, $devnum, $level + 1);
1229 }
1230
1231};
1232
1233sub scan_usb {
1234
1235 my $devlist = [];
1236
1237 foreach my $device (</sys/bus/usb/devices/usb*>) {
1238 __scan_usb_device($devlist, $device, 0, 0);
1239 }
1240
1241 return $devlist;
1242}
1243
1244sub scan_iscsi {
1245 my ($portal_in) = @_;
1246
1247 my $portal;
1dc01b9f 1248 if (!($portal = resolv_portal($portal_in))) {
b6cf0a66
DM
1249 die "unable to parse/resolve portal address '${portal_in}'\n";
1250 }
1251
1dc01b9f 1252 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
b6cf0a66
DM
1253}
1254
1255sub storage_default_format {
1256 my ($cfg, $storeid) = @_;
1257
1258 my $scfg = storage_config ($cfg, $storeid);
1259
1dc01b9f 1260 return PVE::Storage::Plugin::default_format($scfg);
b6cf0a66
DM
1261}
1262
1263sub vgroup_is_used {
1264 my ($cfg, $vgname) = @_;
1265
1266 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1267 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1268 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1269 return 1;
1270 }
1271 }
1272
1273 return undef;
1274}
1275
1276sub target_is_used {
1277 my ($cfg, $target) = @_;
1278
1279 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1280 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1281 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1282 return 1;
1283 }
1284 }
1285
1286 return undef;
1287}
1288
1289sub volume_is_used {
1290 my ($cfg, $volid) = @_;
1291
1292 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1293 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1294 if ($scfg->{base} && $scfg->{base} eq $volid) {
1295 return 1;
1296 }
1297 }
1298
1299 return undef;
1300}
1301
1302sub storage_is_used {
1303 my ($cfg, $storeid) = @_;
1304
1305 foreach my $sid (keys %{$cfg->{ids}}) {
1dc01b9f 1306 my $scfg = storage_config($cfg, $sid);
b6cf0a66 1307 next if !$scfg->{base};
1dc01b9f 1308 my ($st) = parse_volume_id($scfg->{base});
b6cf0a66
DM
1309 return 1 if $st && $st eq $storeid;
1310 }
1311
1312 return undef;
1313}
1314
1315sub foreach_volid {
1316 my ($list, $func) = @_;
1317
1318 return if !$list;
1319
1320 foreach my $sid (keys %$list) {
1321 foreach my $info (@{$list->{$sid}}) {
1322 my $volid = $info->{volid};
1dc01b9f 1323 my ($sid1, $volname) = parse_volume_id($volid, 1);
b6cf0a66
DM
1324 if ($sid1 && $sid1 eq $sid) {
1325 &$func ($volid, $sid, $info);
1326 } else {
1327 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1328 }
1329 }
1330 }
1331}
1332
8898dd7b
FG
1333sub extract_vzdump_config_tar {
1334 my ($archive, $conf_re) = @_;
1335
1336 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1337
1338 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1339 die "unable to open file '$archive'\n";
1340
1341 my $file;
1342 while (defined($file = <$fh>)) {
086c4bf1 1343 if ($file =~ $conf_re) {
8898dd7b
FG
1344 $file = $1; # untaint
1345 last;
1346 }
1347 }
1348
1349 kill 15, $pid;
1350 waitpid $pid, 0;
1351 close $fh;
1352
1353 die "ERROR: archive contains no configuration file\n" if !$file;
1354 chomp $file;
1355
1356 my $raw = '';
1357 my $out = sub {
1358 my $output = shift;
1359 $raw .= "$output\n";
1360 };
1361
1362 PVE::Tools::run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
1363
1364 return wantarray ? ($raw, $file) : $raw;
1365}
1366
1367sub extract_vzdump_config_vma {
1368 my ($archive, $comp) = @_;
1369
1370 my $cmd;
1371 my $raw = '';
1372 my $out = sub {
1373 my $output = shift;
1374 $raw .= "$output\n";
1375 };
1376
1377
1378 if ($comp) {
1379 my $uncomp;
1380 if ($comp eq 'gz') {
1381 $uncomp = ["zcat", $archive];
1382 } elsif ($comp eq 'lzo') {
1383 $uncomp = ["lzop", "-d", "-c", $archive];
1384 } else {
1385 die "unknown compression method '$comp'\n";
1386 }
1387 $cmd = [$uncomp, ["vma", "config", "-"]];
1388
1389 # in some cases, lzop/zcat exits with 1 when its stdout pipe is
1390 # closed early by vma, detect this and ignore the exit code later
1391 my $broken_pipe;
1392 my $errstring;
1393 my $err = sub {
1394 my $output = shift;
1395 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/) {
1396 $broken_pipe = 1;
1397 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1398 $errstring = "Failed to extract config from VMA archive: $output\n";
1399 }
1400 };
1401
1402 # in other cases, the pipeline will exit with exit code 141
1403 # because of the broken pipe, handle / ignore this as well
1404 my $rc;
1405 eval {
1406 $rc = PVE::Tools::run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1);
1407 };
1408 my $rerr = $@;
1409
1410 # use exit code if no stderr output and not just broken pipe
fc1089fc 1411 if (!$errstring && !$broken_pipe && $rc != 0 && $rc != 141) {
8898dd7b
FG
1412 die "$rerr\n" if $rerr;
1413 die "config extraction failed with exit code $rc\n";
1414 }
1415 die "$errstring\n" if $errstring;
1416 } else {
1417 # simple case without compression and weird piping behaviour
1418 PVE::Tools::run_command(["vma", "config", $archive], outfunc => $out);
1419 }
1420
1421 return wantarray ? ($raw, undef) : $raw;
1422}
1423
1424sub extract_vzdump_config {
1425 my ($cfg, $volid) = @_;
1426
1427 my $archive = abs_filesystem_path($cfg, $volid);
1428
89443394 1429 if ($volid =~ /vzdump-(lxc|openvz)-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|(tar(\.(gz|lzo))?))$/) {
086c4bf1 1430 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
89443394 1431 } elsif ($volid =~ /vzdump-qemu-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?))$/) {
8898dd7b
FG
1432 my $format;
1433 my $comp;
1434 if ($7 eq 'tgz') {
1435 $format = 'tar';
1436 $comp = 'gz';
1437 } else {
1438 $format = $9;
1439 $comp = $11 if defined($11);
1440 }
1441
1442 if ($format eq 'tar') {
1443 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1444 } else {
1445 return extract_vzdump_config_vma($archive, $comp);
1446 }
1447 } else {
1448 die "cannot determine backup guest type for backup archive '$volid'\n";
1449 }
1450}
1451
47f37b53
WB
1452sub volume_export {
1453 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1454
1455 my ($storeid, $volname) = parse_volume_id($volid, 1);
1456 die "cannot export volume '$volid'\n" if !$storeid;
1457 my $scfg = storage_config($cfg, $storeid);
1458 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1459 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1460 $snapshot, $base_snapshot, $with_snapshots);
1461}
1462
1463sub volume_import {
1464 my ($cfg, $fh, $volid, $format, $base_snapshot, $with_snapshots) = @_;
1465
1466 my ($storeid, $volname) = parse_volume_id($volid, 1);
1467 die "cannot import into volume '$volid'\n" if !$storeid;
1468 my $scfg = storage_config($cfg, $storeid);
1469 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1470 return $plugin->volume_import($scfg, $storeid, $fh, $volname, $format,
1471 $base_snapshot, $with_snapshots);
1472}
1473
f7621c01
DM
1474# bash completion helper
1475
1476sub complete_storage {
746e530f 1477 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1478
746e530f 1479 my $cfg = PVE::Storage::config();
180c8b02 1480
746e530f 1481 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
f7621c01
DM
1482}
1483
1484sub complete_storage_enabled {
746e530f 1485 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1486
746e530f 1487 my $res = [];
f7621c01 1488
746e530f
DM
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;
f7621c01
DM
1495}
1496
98437f4c
DM
1497sub complete_content_type {
1498 my ($cmdname, $pname, $cvalue) = @_;
1499
1500 return [qw(rootdir images vztmpl iso backup)];
1501}
1502
bf7aed26
DM
1503sub complete_volume {
1504 my ($cmdname, $pname, $cvalue) = @_;
1505
1506 my $cfg = config();
1507
1508 my $storage_list = complete_storage_enabled();
1509
b70b0c58
DM
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
bf7aed26
DM
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
b6cf0a66 15371;