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