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