]> git.proxmox.com Git - pve-storage.git/blame - PVE/Storage.pm
Revert "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;
4537523b 35use PVE::ReplicationTools;
b6cf0a66 36
4dee23d3
DP
37# Storage API version. Icrement it on changes in storage API interface.
38use constant APIVER => 1;
39
40# load standard plugins
1dc01b9f
DM
41PVE::Storage::DirPlugin->register();
42PVE::Storage::LVMPlugin->register();
610798bc 43PVE::Storage::LvmThinPlugin->register();
1dc01b9f
DM
44PVE::Storage::NFSPlugin->register();
45PVE::Storage::ISCSIPlugin->register();
0509010d 46PVE::Storage::RBDPlugin->register();
caf1960c 47PVE::Storage::SheepdogPlugin->register();
86616554 48PVE::Storage::ISCSIDirectPlugin->register();
f4648aef 49PVE::Storage::GlusterfsPlugin->register();
85fda4dd 50PVE::Storage::ZFSPoolPlugin->register();
4f914e6e 51PVE::Storage::ZFSPlugin->register();
14770890 52PVE::Storage::DRBDPlugin->register();
4dee23d3
DP
53
54# load third-party plugins
55if ( -d '/usr/share/perl5/PVE/Storage/Custom' ) {
56 dir_glob_foreach('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
57 my ($file) = @_;
58 my $modname = 'PVE::Storage::Custom::' . $file;
59 $modname =~ s!\.pm$!!;
60 $file = 'PVE/Storage/Custom/' . $file;
61
62 eval {
63 require $file;
64 };
65 if ($@) {
66 warn $@;
67 # Check storage API version and that file is really storage plugin.
68 } elsif ($modname->isa('PVE::Storage::Plugin') && $modname->can('api') && $modname->api() == APIVER) {
69 eval {
70 import $file;
71 $modname->register();
72 };
73 warn $@ if $@;
74 } else {
75 warn "Error loading storage plugin \"$modname\" because of API version mismatch. Please, update it.\n"
76 }
77 });
78}
79
80# initialize all plugins
1dc01b9f 81PVE::Storage::Plugin->init();
b6cf0a66 82
1dc01b9f 83my $UDEVADM = '/sbin/udevadm';
b6cf0a66 84
1dc01b9f 85# PVE::Storage utility functions
b6cf0a66
DM
86
87sub config {
88 return cfs_read_file("storage.cfg");
89}
90
83d7192f
FG
91sub write_config {
92 my ($cfg) = @_;
93
94 cfs_write_file('storage.cfg', $cfg);
95}
96
b6cf0a66
DM
97sub lock_storage_config {
98 my ($code, $errmsg) = @_;
99
100 cfs_lock_file("storage.cfg", undef, $code);
101 my $err = $@;
102 if ($err) {
103 $errmsg ? die "$errmsg: $err" : die $err;
104 }
105}
106
b6cf0a66
DM
107sub storage_config {
108 my ($cfg, $storeid, $noerr) = @_;
109
82fc923f 110 die "no storage ID specified\n" if !$storeid;
1a3459ac 111
b6cf0a66
DM
112 my $scfg = $cfg->{ids}->{$storeid};
113
114 die "storage '$storeid' does not exists\n" if (!$noerr && !$scfg);
115
116 return $scfg;
117}
118
119sub storage_check_node {
120 my ($cfg, $storeid, $node, $noerr) = @_;
121
1dc01b9f 122 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
123
124 if ($scfg->{nodes}) {
125 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
126 if (!$scfg->{nodes}->{$node}) {
da156fb3 127 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
b6cf0a66
DM
128 return undef;
129 }
130 }
131
132 return $scfg;
133}
134
135sub storage_check_enabled {
136 my ($cfg, $storeid, $node, $noerr) = @_;
137
1dc01b9f 138 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
139
140 if ($scfg->{disable}) {
141 die "storage '$storeid' is disabled\n" if !$noerr;
142 return undef;
143 }
144
145 return storage_check_node($cfg, $storeid, $node, $noerr);
146}
147
148sub storage_ids {
149 my ($cfg) = @_;
150
1dc01b9f 151 return keys %{$cfg->{ids}};
b6cf0a66
DM
152}
153
1dc01b9f
DM
154sub file_size_info {
155 my ($filename, $timeout) = @_;
b6cf0a66 156
1dc01b9f 157 return PVE::Storage::Plugin::file_size_info($filename, $timeout);
b6cf0a66
DM
158}
159
20ccac1b
AD
160sub volume_size_info {
161 my ($cfg, $volid, $timeout) = @_;
162
f18199e5
DM
163 my ($storeid, $volname) = parse_volume_id($volid, 1);
164 if ($storeid) {
165 my $scfg = storage_config($cfg, $storeid);
166 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
167 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
168 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
169 return file_size_info($volid, $timeout);
170 } else {
171 return 0;
172 }
20ccac1b
AD
173}
174
7e6c05dc
AD
175sub volume_resize {
176 my ($cfg, $volid, $size, $running) = @_;
177
178 my ($storeid, $volname) = parse_volume_id($volid, 1);
179 if ($storeid) {
180 my $scfg = storage_config($cfg, $storeid);
181 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
182 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
183 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 184 die "resize file/device '$volid' is not possible\n";
7e6c05dc 185 } else {
f824c722 186 die "unable to parse volume ID '$volid'\n";
7e6c05dc
AD
187 }
188}
189
1597f1f9
WL
190sub volume_rollback_is_possible {
191 my ($cfg, $volid, $snap) = @_;
e0852ba7 192
1597f1f9
WL
193 my ($storeid, $volname) = parse_volume_id($volid, 1);
194 if ($storeid) {
195 my $scfg = storage_config($cfg, $storeid);
196 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
197 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
198 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 199 die "snapshot rollback file/device '$volid' is not possible\n";
1597f1f9 200 } else {
f824c722 201 die "unable to parse volume ID '$volid'\n";
1597f1f9
WL
202 }
203}
204
db60719c 205sub volume_snapshot {
f5640e7d 206 my ($cfg, $volid, $snap) = @_;
db60719c
AD
207
208 my ($storeid, $volname) = parse_volume_id($volid, 1);
209 if ($storeid) {
210 my $scfg = storage_config($cfg, $storeid);
211 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
f5640e7d 212 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
db60719c 213 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 214 die "snapshot file/device '$volid' is not possible\n";
db60719c 215 } else {
f824c722 216 die "unable to parse volume ID '$volid'\n";
db60719c
AD
217 }
218}
219
22a2a633
AD
220sub volume_snapshot_rollback {
221 my ($cfg, $volid, $snap) = @_;
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});
b3f302c6 227 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
22a2a633
AD
228 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
229 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 230 die "snapshot rollback file/device '$volid' is not possible\n";
22a2a633 231 } else {
f824c722 232 die "unable to parse volume ID '$volid'\n";
22a2a633
AD
233 }
234}
235
5753c9d1
AD
236sub volume_snapshot_delete {
237 my ($cfg, $volid, $snap, $running) = @_;
238
239 my ($storeid, $volname) = parse_volume_id($volid, 1);
240 if ($storeid) {
241 my $scfg = storage_config($cfg, $storeid);
242 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
27cc55d4 243 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
5753c9d1 244 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 245 die "snapshot delete file/device '$volid' is not possible\n";
5753c9d1 246 } else {
f824c722 247 die "unable to parse volume ID '$volid'\n";
5753c9d1
AD
248 }
249}
250
99473759
AD
251sub volume_has_feature {
252 my ($cfg, $feature, $volid, $snap, $running) = @_;
253
254 my ($storeid, $volname) = parse_volume_id($volid, 1);
255 if ($storeid) {
256 my $scfg = storage_config($cfg, $storeid);
257 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
258 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running);
259 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
260 return undef;
261 } else {
262 return undef;
263 }
264}
265
aefe82ea
WL
266sub volume_snapshot_list {
267 my ($cfg, $volid, $prefix, $ip) = @_;
268
269 my ($storeid, $volname) = parse_volume_id($volid, 1);
270 if ($storeid) {
271 my $scfg = storage_config($cfg, $storeid);
272 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
273 return $plugin->volume_snapshot_list($scfg, $storeid, $volname, $prefix, $ip);
274 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
275 die "send file/device '$volid' is not possible\n";
276 } else {
277 die "unable to parse volume ID '$volid'\n";
278 }
279 # return an empty array if dataset does not exist.
280 # youngest snap first
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__"];
4537523b
WL
624 my $send = ['zfs', 'send', '-Rpv'];
625 my $rec = ['ssh', "root\@$target_host", 'zfs', 'recv','-F' ,$zfspath];
3d621977 626
4537523b
WL
627 if (my $snapname = PVE::ReplicationTools::get_last_replica_snap($volid)) {
628
629 #check if target snapshot exists.
630 my $checksnap = ['/usr/bin/ssh', "root\@${target_host}", "-o",
631 'BatchMode=yes', 'zfs', 'list', '-Hrt', 'snap',
632 "$zfspath\@$snapname "];
633 eval {
634 run_command($checksnap);
635 push @$send, '-I', "$zfspath\@$snapname";
636 };
637
638 }
639 push @$send, "--", "$zfspath\@__migration__";
3d621977 640
b650f029 641 my $destroy_target = ['ssh', "root\@$target_host", 'zfs', 'destroy', "$zfspath\@__migration__"];
3d621977 642 run_command($snap);
e0852ba7 643 eval{
4537523b 644 run_command([$send,$rec]);
3d621977 645 };
afd0afe4
FG
646 my $err = $@;
647 warn "zfs send/receive failed, cleaning up snapshot(s)..\n" if $err;
648 eval { run_command(['zfs', 'destroy', "$zfspath\@__migration__"]); };
649 warn "could not remove source snapshot: $@\n" if $@;
650 eval { run_command($destroy_target); };
651 warn "could not remove target snapshot: $@\n" if $@;
652 die $err if $err;
3d621977
WL
653
654 } else {
655 die "$errstr - target type $tcfg->{type} is not valid\n";
656 }
0a29ad61
WL
657
658 } elsif ($scfg->{type} eq 'lvmthin' || $scfg->{type} eq 'lvm') {
659
76f13c9e
DM
660 if (($scfg->{type} eq $tcfg->{type}) &&
661 ($tcfg->{type} eq 'lvmthin' || $tcfg->{type} eq 'lvm')) {
0a29ad61 662
84252f67 663 my (undef, $volname, $vmid) = parse_volname($cfg, $volid);
0a29ad61 664 my $size = volume_size_info($cfg, $volid, 5);
84252f67
DM
665 my $src = path($cfg, $volid);
666 my $dst = path($cfg, $target_volid);
0a29ad61
WL
667
668 run_command(['/usr/bin/ssh', "root\@${target_host}",
669 'pvesm', 'alloc', $target_storeid, $vmid,
84252f67 670 $target_volname, int($size/1024)]);
0a29ad61
WL
671
672 eval {
e83f7b40 673 if ($tcfg->{type} eq 'lvmthin') {
46f114a5
DM
674 run_command([["dd", "if=$src", "bs=4k"],["/usr/bin/ssh", "root\@${target_host}",
675 "dd", 'conv=sparse', "of=$dst", "bs=4k"]]);
e83f7b40 676 } else {
46f114a5
DM
677 run_command([["dd", "if=$src", "bs=4k"],["/usr/bin/ssh", "root\@${target_host}",
678 "dd", "of=$dst", "bs=4k"]]);
e83f7b40 679 }
0a29ad61
WL
680 };
681 if (my $err = $@) {
682 run_command(['/usr/bin/ssh', "root\@${target_host}",
84252f67 683 'pvesm', 'free', $target_volid]);
966ecef2 684 die $err;
0a29ad61
WL
685 }
686 } else {
76f13c9e 687 die "$errstr - migrate from source type '$scfg->{type}' to '$tcfg->{type}' not implemented\n";
0a29ad61 688 }
1dc01b9f
DM
689 } else {
690 die "$errstr - source type '$scfg->{type}' not implemented\n";
b6cf0a66
DM
691 }
692}
693
2502b33b 694sub vdisk_clone {
7bbc4004 695 my ($cfg, $volid, $vmid, $snap) = @_;
1a3459ac 696
2502b33b
DM
697 my ($storeid, $volname) = parse_volume_id($volid);
698
699 my $scfg = storage_config($cfg, $storeid);
700
701 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 702
2502b33b
DM
703 activate_storage($cfg, $storeid);
704
705 # lock shared storage
706 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
7bbc4004 707 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
2502b33b
DM
708 return "$storeid:$volname";
709 });
710}
711
712sub vdisk_create_base {
713 my ($cfg, $volid) = @_;
714
715 my ($storeid, $volname) = parse_volume_id($volid);
716
717 my $scfg = storage_config($cfg, $storeid);
718
719 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 720
2502b33b
DM
721 activate_storage($cfg, $storeid);
722
723 # lock shared storage
724 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
725 my $volname = $plugin->create_base($storeid, $scfg, $volname);
726 return "$storeid:$volname";
727 });
728}
729
1dc01b9f
DM
730sub vdisk_alloc {
731 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
b6cf0a66 732
82fc923f 733 die "no storage ID specified\n" if !$storeid;
b6cf0a66 734
1dc01b9f 735 PVE::JSONSchema::parse_storage_id($storeid);
b6cf0a66 736
1dc01b9f 737 my $scfg = storage_config($cfg, $storeid);
b6cf0a66 738
1dc01b9f 739 die "no VMID specified\n" if !$vmid;
b6cf0a66 740
1dc01b9f 741 $vmid = parse_vmid($vmid);
b6cf0a66 742
1dc01b9f 743 my $defformat = PVE::Storage::Plugin::default_format($scfg);
b6cf0a66 744
1dc01b9f 745 $fmt = $defformat if !$fmt;
b6cf0a66 746
1dc01b9f 747 activate_storage($cfg, $storeid);
3af60e62 748
1dc01b9f 749 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 750
1dc01b9f
DM
751 # lock shared storage
752 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
afdfbe55
WB
753 my $old_umask = umask(umask|0037);
754 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
755 my $err = $@;
756 umask $old_umask;
757 die $err if $err;
1dc01b9f
DM
758 return "$storeid:$volname";
759 });
b6cf0a66
DM
760}
761
1dc01b9f
DM
762sub vdisk_free {
763 my ($cfg, $volid) = @_;
b6cf0a66 764
1dc01b9f 765 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f 766 my $scfg = storage_config($cfg, $storeid);
1dc01b9f 767 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 768
1dc01b9f 769 activate_storage($cfg, $storeid);
b6cf0a66 770
1dc01b9f 771 my $cleanup_worker;
b6cf0a66 772
1dc01b9f
DM
773 # lock shared storage
774 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
787624df 775 # LVM-thin allows deletion of still referenced base volumes!
17fb7e42
FG
776 die "base volume '$volname' is still in use by linked clones\n"
777 if &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
32437ed2 778
17fb7e42 779 my (undef, undef, undef, undef, undef, $isBase, $format) =
32437ed2 780 $plugin->parse_volname($volname);
35533c68 781 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1dc01b9f 782 });
b6cf0a66 783
1dc01b9f 784 return if !$cleanup_worker;
b6cf0a66 785
1dc01b9f
DM
786 my $rpcenv = PVE::RPCEnvironment::get();
787 my $authuser = $rpcenv->get_user();
b6cf0a66 788
1dc01b9f 789 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
b6cf0a66
DM
790}
791
b6cf0a66
DM
792#list iso or openvz template ($tt = <iso|vztmpl|backup>)
793sub template_list {
794 my ($cfg, $storeid, $tt) = @_;
795
1a3459ac
DM
796 die "unknown template type '$tt'\n"
797 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup');
b6cf0a66
DM
798
799 my $ids = $cfg->{ids};
800
801 storage_check_enabled($cfg, $storeid) if ($storeid);
802
803 my $res = {};
804
805 # query the storage
806
807 foreach my $sid (keys %$ids) {
808 next if $storeid && $storeid ne $sid;
809
810 my $scfg = $ids->{$sid};
811 my $type = $scfg->{type};
812
813 next if !storage_check_enabled($cfg, $sid, undef, 1);
814
815 next if $tt eq 'iso' && !$scfg->{content}->{iso};
816 next if $tt eq 'vztmpl' && !$scfg->{content}->{vztmpl};
817 next if $tt eq 'backup' && !$scfg->{content}->{backup};
818
1dc01b9f 819 activate_storage($cfg, $sid);
b6cf0a66 820
1dc01b9f
DM
821 if ($scfg->{path}) {
822 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 823
1dc01b9f 824 my $path = $plugin->get_subdir($scfg, $tt);
b6cf0a66
DM
825
826 foreach my $fn (<$path/*>) {
827
828 my $info;
829
830 if ($tt eq 'iso') {
831 next if $fn !~ m!/([^/]+\.[Ii][Ss][Oo])$!;
832
833 $info = { volid => "$sid:iso/$1", format => 'iso' };
834
835 } elsif ($tt eq 'vztmpl') {
13d2cb79 836 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
b6cf0a66 837
13d2cb79 838 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
b6cf0a66
DM
839
840 } elsif ($tt eq 'backup') {
a22854e5 841 next if $fn !~ m!/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!;
1a3459ac 842
b6cf0a66
DM
843 $info = { volid => "$sid:backup/$1", format => $2 };
844 }
845
846 $info->{size} = -s $fn;
847
848 push @{$res->{$sid}}, $info;
849 }
850
851 }
852
853 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
854 }
855
856 return $res;
857}
858
20ccac1b 859
b6cf0a66
DM
860sub vdisk_list {
861 my ($cfg, $storeid, $vmid, $vollist) = @_;
862
863 my $ids = $cfg->{ids};
864
865 storage_check_enabled($cfg, $storeid) if ($storeid);
866
867 my $res = {};
868
869 # prepare/activate/refresh all storages
870
b6cf0a66
DM
871 my $storage_list = [];
872 if ($vollist) {
873 foreach my $volid (@$vollist) {
1dc01b9f
DM
874 my ($sid, undef) = parse_volume_id($volid);
875 next if !defined($ids->{$sid});
b6cf0a66
DM
876 next if !storage_check_enabled($cfg, $sid, undef, 1);
877 push @$storage_list, $sid;
b6cf0a66
DM
878 }
879 } else {
880 foreach my $sid (keys %$ids) {
881 next if $storeid && $storeid ne $sid;
882 next if !storage_check_enabled($cfg, $sid, undef, 1);
883 push @$storage_list, $sid;
b6cf0a66
DM
884 }
885 }
886
1dc01b9f 887 my $cache = {};
b6cf0a66 888
1dc01b9f 889 activate_storage_list($cfg, $storage_list, $cache);
b6cf0a66
DM
890
891 foreach my $sid (keys %$ids) {
1dc01b9f
DM
892 next if $storeid && $storeid ne $sid;
893 next if !storage_check_enabled($cfg, $sid, undef, 1);
b6cf0a66 894
1dc01b9f
DM
895 my $scfg = $ids->{$sid};
896 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
897 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
b6cf0a66
DM
898 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
899 }
900
901 return $res;
902}
903
37ba0aea
DM
904sub volume_list {
905 my ($cfg, $storeid, $vmid, $content) = @_;
906
907 my @ctypes = qw(images vztmpl iso backup);
908
909 my $cts = $content ? [ $content ] : [ @ctypes ];
910
911 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
912
913 my $res = [];
914 foreach my $ct (@$cts) {
915 my $data;
916 if ($ct eq 'images') {
917 $data = vdisk_list($cfg, $storeid, $vmid);
918 } elsif ($ct eq 'iso' && !defined($vmid)) {
919 $data = template_list($cfg, $storeid, 'iso');
920 } elsif ($ct eq 'vztmpl'&& !defined($vmid)) {
921 $data = template_list ($cfg, $storeid, 'vztmpl');
922 } elsif ($ct eq 'backup') {
923 $data = template_list ($cfg, $storeid, 'backup');
924 foreach my $item (@{$data->{$storeid}}) {
925 if (defined($vmid)) {
926 @{$data->{$storeid}} = grep { $_->{volid} =~ m/\S+-$vmid-\S+/ } @{$data->{$storeid}};
927 }
928 }
929 }
930
931 next if !$data || !$data->{$storeid};
932
933 foreach my $item (@{$data->{$storeid}}) {
934 $item->{content} = $ct;
935 push @$res, $item;
936 }
937 }
938
939 return $res;
940}
941
b6cf0a66
DM
942sub uevent_seqnum {
943
944 my $filename = "/sys/kernel/uevent_seqnum";
945
946 my $seqnum = 0;
1dc01b9f 947 if (my $fh = IO::File->new($filename, "r")) {
b6cf0a66
DM
948 my $line = <$fh>;
949 if ($line =~ m/^(\d+)$/) {
1dc01b9f 950 $seqnum = int($1);
b6cf0a66
DM
951 }
952 close ($fh);
953 }
954 return $seqnum;
955}
956
f3d4ef46 957sub activate_storage {
1dc01b9f 958 my ($cfg, $storeid, $cache) = @_;
b6cf0a66 959
f3d4ef46
DM
960 $cache = {} if !$cache;
961
b6cf0a66
DM
962 my $scfg = storage_check_enabled($cfg, $storeid);
963
1dc01b9f 964 return if $cache->{activated}->{$storeid};
b6cf0a66 965
1dc01b9f 966 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
b6cf0a66 967
1dc01b9f 968 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 969
1dc01b9f
DM
970 if ($scfg->{base}) {
971 my ($baseid, undef) = parse_volume_id ($scfg->{base});
f3d4ef46
DM
972 activate_storage($cfg, $baseid, $cache);
973 }
974
975 if (!$plugin->check_connection($storeid, $scfg)) {
976 die "storage '$storeid' is not online\n";
b6cf0a66
DM
977 }
978
1dc01b9f
DM
979 $plugin->activate_storage($storeid, $scfg, $cache);
980
b6cf0a66
DM
981 my $newseq = uevent_seqnum ();
982
983 # only call udevsettle if there are events
1dc01b9f 984 if ($newseq > $cache->{uevent_seqnum}) {
b6cf0a66
DM
985 my $timeout = 30;
986 system ("$UDEVADM settle --timeout=$timeout"); # ignore errors
1dc01b9f 987 $cache->{uevent_seqnum} = $newseq;
b6cf0a66
DM
988 }
989
1dc01b9f 990 $cache->{activated}->{$storeid} = 1;
b6cf0a66
DM
991}
992
993sub activate_storage_list {
1dc01b9f 994 my ($cfg, $storeid_list, $cache) = @_;
b6cf0a66 995
1dc01b9f 996 $cache = {} if !$cache;
b6cf0a66
DM
997
998 foreach my $storeid (@$storeid_list) {
f3d4ef46 999 activate_storage($cfg, $storeid, $cache);
b6cf0a66
DM
1000 }
1001}
1002
1dc01b9f
DM
1003sub deactivate_storage {
1004 my ($cfg, $storeid) = @_;
1005
1006 my $scfg = storage_config ($cfg, $storeid);
1007 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 1008
1dc01b9f
DM
1009 my $cache = {};
1010 $plugin->deactivate_storage($storeid, $scfg, $cache);
b6cf0a66
DM
1011}
1012
1013sub activate_volumes {
02e797b8 1014 my ($cfg, $vollist, $snapname) = @_;
6703353b
DM
1015
1016 return if !($vollist && scalar(@$vollist));
1017
b6cf0a66
DM
1018 my $storagehash = {};
1019 foreach my $volid (@$vollist) {
1dc01b9f 1020 my ($storeid, undef) = parse_volume_id($volid);
b6cf0a66
DM
1021 $storagehash->{$storeid} = 1;
1022 }
1023
1dc01b9f
DM
1024 my $cache = {};
1025
1026 activate_storage_list($cfg, [keys %$storagehash], $cache);
b6cf0a66
DM
1027
1028 foreach my $volid (@$vollist) {
5521b580 1029 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f
DM
1030 my $scfg = storage_config($cfg, $storeid);
1031 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
02e797b8 1032 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
b6cf0a66
DM
1033 }
1034}
1035
1036sub deactivate_volumes {
02e797b8 1037 my ($cfg, $vollist, $snapname) = @_;
b6cf0a66 1038
6703353b
DM
1039 return if !($vollist && scalar(@$vollist));
1040
1dc01b9f
DM
1041 my $cache = {};
1042
6703353b 1043 my @errlist = ();
b6cf0a66 1044 foreach my $volid (@$vollist) {
1dc01b9f 1045 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 1046
1dc01b9f
DM
1047 my $scfg = storage_config($cfg, $storeid);
1048 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 1049
1dc01b9f 1050 eval {
02e797b8 1051 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1dc01b9f
DM
1052 };
1053 if (my $err = $@) {
1054 warn $err;
1055 push @errlist, $volid;
b6cf0a66
DM
1056 }
1057 }
6703353b 1058
82fc923f 1059 die "volume deactivation failed: " . join(' ', @errlist)
6703353b 1060 if scalar(@errlist);
b6cf0a66
DM
1061}
1062
1a3459ac 1063sub storage_info {
b6cf0a66
DM
1064 my ($cfg, $content) = @_;
1065
1066 my $ids = $cfg->{ids};
1067
1068 my $info = {};
ff3badd8 1069
583c2802 1070 my @ctypes = PVE::Tools::split_list($content);
ff3badd8 1071
b6cf0a66
DM
1072 my $slist = [];
1073 foreach my $storeid (keys %$ids) {
1074
b6cf0a66
DM
1075 next if !storage_check_enabled($cfg, $storeid, undef, 1);
1076
d73060be
DM
1077 if (defined($content)) {
1078 my $want_ctype = 0;
1079 foreach my $ctype (@ctypes) {
1080 if ($ids->{$storeid}->{content}->{$ctype}) {
1081 $want_ctype = 1;
1082 last;
1083 }
583c2802 1084 }
d73060be 1085 next if !$want_ctype;
583c2802 1086 }
ff3badd8 1087
b6cf0a66
DM
1088 my $type = $ids->{$storeid}->{type};
1089
1a3459ac 1090 $info->{$storeid} = {
b6cf0a66 1091 type => $type,
1a3459ac
DM
1092 total => 0,
1093 avail => 0,
1094 used => 0,
04a2e4f3 1095 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1dc01b9f 1096 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
b6cf0a66
DM
1097 active => 0,
1098 };
1099
b6cf0a66
DM
1100 push @$slist, $storeid;
1101 }
1102
1dc01b9f 1103 my $cache = {};
b6cf0a66 1104
b6cf0a66
DM
1105 foreach my $storeid (keys %$ids) {
1106 my $scfg = $ids->{$storeid};
b6cf0a66
DM
1107 next if !$info->{$storeid};
1108
f3d4ef46
DM
1109 eval { activate_storage($cfg, $storeid, $cache); };
1110 if (my $err = $@) {
1111 warn $err;
1112 next;
1113 }
1114
1dc01b9f 1115 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
7028645e
DM
1116 my ($total, $avail, $used, $active);
1117 eval { ($total, $avail, $used, $active) = $plugin->status($storeid, $scfg, $cache); };
1118 warn $@ if $@;
1dc01b9f 1119 next if !$active;
ff3badd8
DM
1120 $info->{$storeid}->{total} = int($total);
1121 $info->{$storeid}->{avail} = int($avail);
1122 $info->{$storeid}->{used} = int($used);
1dc01b9f 1123 $info->{$storeid}->{active} = $active;
b6cf0a66
DM
1124 }
1125
1126 return $info;
1127}
1128
1129sub resolv_server {
1130 my ($server) = @_;
1a3459ac 1131
c67daeac
WB
1132 my ($packed_ip, $family);
1133 eval {
1134 my @res = PVE::Tools::getaddrinfo_all($server);
1135 $family = $res[0]->{family};
1136 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1137 };
b6cf0a66 1138 if (defined $packed_ip) {
ee302b1c 1139 return Socket::inet_ntop($family, $packed_ip);
b6cf0a66
DM
1140 }
1141 return undef;
1142}
1143
1144sub scan_nfs {
1145 my ($server_in) = @_;
1146
1147 my $server;
1148 if (!($server = resolv_server ($server_in))) {
1149 die "unable to resolve address for server '${server_in}'\n";
1150 }
1151
1152 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1153
1154 my $res = {};
f81372ac 1155 run_command($cmd, outfunc => sub {
b6cf0a66
DM
1156 my $line = shift;
1157
1158 # note: howto handle white spaces in export path??
1159 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1160 $res->{$1} = $2;
1161 }
1162 });
1163
1164 return $res;
1165}
1166
584d97f6
DM
1167sub scan_zfs {
1168
3932390b 1169 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-H', '-o', 'name,avail,used'];
584d97f6
DM
1170
1171 my $res = [];
1172 run_command($cmd, outfunc => sub {
1173 my $line = shift;
1174
1175 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
3932390b 1176 my ($pool, $size_str, $used_str) = ($1, $2, $3);
584d97f6 1177 my $size = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($size_str);
3932390b 1178 my $used = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($used_str);
48e27f79 1179 # ignore subvolumes generated by our ZFSPoolPlugin
851658c3
WL
1180 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1181 return if $pool =~ m!/basevol-\d+-[^/]+$!;
3932390b 1182 push @$res, { pool => $pool, size => $size, free => $size-$used };
584d97f6
DM
1183 }
1184 });
1185
1186 return $res;
1187}
1188
b6cf0a66
DM
1189sub resolv_portal {
1190 my ($portal, $noerr) = @_;
1191
1689e627
WB
1192 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1193 if ($server) {
b6cf0a66
DM
1194 if (my $ip = resolv_server($server)) {
1195 $server = $ip;
1689e627 1196 $server = "[$server]" if $server =~ /^$IPV6RE$/;
b6cf0a66
DM
1197 return $port ? "$server:$port" : $server;
1198 }
1199 }
1200 return undef if $noerr;
1201
1202 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1203}
1204
1205# idea is from usbutils package (/usr/bin/usb-devices) script
1206sub __scan_usb_device {
1207 my ($res, $devpath, $parent, $level) = @_;
1208
1209 return if ! -d $devpath;
1210 return if $level && $devpath !~ m/^.*[-.](\d+)$/;
1211 my $port = $level ? int($1 - 1) : 0;
1212
1213 my $busnum = int(file_read_firstline("$devpath/busnum"));
1214 my $devnum = int(file_read_firstline("$devpath/devnum"));
1215
1216 my $d = {
1217 port => $port,
1218 level => $level,
1219 busnum => $busnum,
1220 devnum => $devnum,
1221 speed => file_read_firstline("$devpath/speed"),
1222 class => hex(file_read_firstline("$devpath/bDeviceClass")),
1223 vendid => file_read_firstline("$devpath/idVendor"),
1224 prodid => file_read_firstline("$devpath/idProduct"),
1225 };
1226
1227 if ($level) {
1228 my $usbpath = $devpath;
1229 $usbpath =~ s|^.*/\d+\-||;
1230 $d->{usbpath} = $usbpath;
1231 }
1232
1233 my $product = file_read_firstline("$devpath/product");
1234 $d->{product} = $product if $product;
1a3459ac 1235
b6cf0a66
DM
1236 my $manu = file_read_firstline("$devpath/manufacturer");
1237 $d->{manufacturer} = $manu if $manu;
1238
1239 my $serial => file_read_firstline("$devpath/serial");
1240 $d->{serial} = $serial if $serial;
1241
1242 push @$res, $d;
1243
1244 foreach my $subdev (<$devpath/$busnum-*>) {
1245 next if $subdev !~ m|/$busnum-[0-9]+(\.[0-9]+)*$|;
1246 __scan_usb_device($res, $subdev, $devnum, $level + 1);
1247 }
1248
1249};
1250
1251sub scan_usb {
1252
1253 my $devlist = [];
1254
1255 foreach my $device (</sys/bus/usb/devices/usb*>) {
1256 __scan_usb_device($devlist, $device, 0, 0);
1257 }
1258
1259 return $devlist;
1260}
1261
1262sub scan_iscsi {
1263 my ($portal_in) = @_;
1264
1265 my $portal;
1dc01b9f 1266 if (!($portal = resolv_portal($portal_in))) {
b6cf0a66
DM
1267 die "unable to parse/resolve portal address '${portal_in}'\n";
1268 }
1269
1dc01b9f 1270 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
b6cf0a66
DM
1271}
1272
1273sub storage_default_format {
1274 my ($cfg, $storeid) = @_;
1275
1276 my $scfg = storage_config ($cfg, $storeid);
1277
1dc01b9f 1278 return PVE::Storage::Plugin::default_format($scfg);
b6cf0a66
DM
1279}
1280
1281sub vgroup_is_used {
1282 my ($cfg, $vgname) = @_;
1283
1284 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1285 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1286 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1287 return 1;
1288 }
1289 }
1290
1291 return undef;
1292}
1293
1294sub target_is_used {
1295 my ($cfg, $target) = @_;
1296
1297 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1298 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1299 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1300 return 1;
1301 }
1302 }
1303
1304 return undef;
1305}
1306
1307sub volume_is_used {
1308 my ($cfg, $volid) = @_;
1309
1310 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1311 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1312 if ($scfg->{base} && $scfg->{base} eq $volid) {
1313 return 1;
1314 }
1315 }
1316
1317 return undef;
1318}
1319
1320sub storage_is_used {
1321 my ($cfg, $storeid) = @_;
1322
1323 foreach my $sid (keys %{$cfg->{ids}}) {
1dc01b9f 1324 my $scfg = storage_config($cfg, $sid);
b6cf0a66 1325 next if !$scfg->{base};
1dc01b9f 1326 my ($st) = parse_volume_id($scfg->{base});
b6cf0a66
DM
1327 return 1 if $st && $st eq $storeid;
1328 }
1329
1330 return undef;
1331}
1332
1333sub foreach_volid {
1334 my ($list, $func) = @_;
1335
1336 return if !$list;
1337
1338 foreach my $sid (keys %$list) {
1339 foreach my $info (@{$list->{$sid}}) {
1340 my $volid = $info->{volid};
1dc01b9f 1341 my ($sid1, $volname) = parse_volume_id($volid, 1);
b6cf0a66
DM
1342 if ($sid1 && $sid1 eq $sid) {
1343 &$func ($volid, $sid, $info);
1344 } else {
1345 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1346 }
1347 }
1348 }
1349}
1350
8898dd7b
FG
1351sub extract_vzdump_config_tar {
1352 my ($archive, $conf_re) = @_;
1353
1354 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1355
1356 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1357 die "unable to open file '$archive'\n";
1358
1359 my $file;
1360 while (defined($file = <$fh>)) {
086c4bf1 1361 if ($file =~ $conf_re) {
8898dd7b
FG
1362 $file = $1; # untaint
1363 last;
1364 }
1365 }
1366
1367 kill 15, $pid;
1368 waitpid $pid, 0;
1369 close $fh;
1370
1371 die "ERROR: archive contains no configuration file\n" if !$file;
1372 chomp $file;
1373
1374 my $raw = '';
1375 my $out = sub {
1376 my $output = shift;
1377 $raw .= "$output\n";
1378 };
1379
1380 PVE::Tools::run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
1381
1382 return wantarray ? ($raw, $file) : $raw;
1383}
1384
1385sub extract_vzdump_config_vma {
1386 my ($archive, $comp) = @_;
1387
1388 my $cmd;
1389 my $raw = '';
1390 my $out = sub {
1391 my $output = shift;
1392 $raw .= "$output\n";
1393 };
1394
1395
1396 if ($comp) {
1397 my $uncomp;
1398 if ($comp eq 'gz') {
1399 $uncomp = ["zcat", $archive];
1400 } elsif ($comp eq 'lzo') {
1401 $uncomp = ["lzop", "-d", "-c", $archive];
1402 } else {
1403 die "unknown compression method '$comp'\n";
1404 }
1405 $cmd = [$uncomp, ["vma", "config", "-"]];
1406
1407 # in some cases, lzop/zcat exits with 1 when its stdout pipe is
1408 # closed early by vma, detect this and ignore the exit code later
1409 my $broken_pipe;
1410 my $errstring;
1411 my $err = sub {
1412 my $output = shift;
1413 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/) {
1414 $broken_pipe = 1;
1415 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1416 $errstring = "Failed to extract config from VMA archive: $output\n";
1417 }
1418 };
1419
1420 # in other cases, the pipeline will exit with exit code 141
1421 # because of the broken pipe, handle / ignore this as well
1422 my $rc;
1423 eval {
1424 $rc = PVE::Tools::run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1);
1425 };
1426 my $rerr = $@;
1427
1428 # use exit code if no stderr output and not just broken pipe
fc1089fc 1429 if (!$errstring && !$broken_pipe && $rc != 0 && $rc != 141) {
8898dd7b
FG
1430 die "$rerr\n" if $rerr;
1431 die "config extraction failed with exit code $rc\n";
1432 }
1433 die "$errstring\n" if $errstring;
1434 } else {
1435 # simple case without compression and weird piping behaviour
1436 PVE::Tools::run_command(["vma", "config", $archive], outfunc => $out);
1437 }
1438
1439 return wantarray ? ($raw, undef) : $raw;
1440}
1441
1442sub extract_vzdump_config {
1443 my ($cfg, $volid) = @_;
1444
1445 my $archive = abs_filesystem_path($cfg, $volid);
1446
89443394 1447 if ($volid =~ /vzdump-(lxc|openvz)-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|(tar(\.(gz|lzo))?))$/) {
086c4bf1 1448 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
89443394 1449 } elsif ($volid =~ /vzdump-qemu-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?))$/) {
8898dd7b
FG
1450 my $format;
1451 my $comp;
1452 if ($7 eq 'tgz') {
1453 $format = 'tar';
1454 $comp = 'gz';
1455 } else {
1456 $format = $9;
1457 $comp = $11 if defined($11);
1458 }
1459
1460 if ($format eq 'tar') {
1461 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1462 } else {
1463 return extract_vzdump_config_vma($archive, $comp);
1464 }
1465 } else {
1466 die "cannot determine backup guest type for backup archive '$volid'\n";
1467 }
1468}
1469
f7621c01
DM
1470# bash completion helper
1471
1472sub complete_storage {
746e530f 1473 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1474
746e530f 1475 my $cfg = PVE::Storage::config();
180c8b02 1476
746e530f 1477 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
f7621c01
DM
1478}
1479
1480sub complete_storage_enabled {
746e530f 1481 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1482
746e530f 1483 my $res = [];
f7621c01 1484
746e530f
DM
1485 my $cfg = PVE::Storage::config();
1486 foreach my $sid (keys %{$cfg->{ids}}) {
1487 next if !storage_check_enabled($cfg, $sid, undef, 1);
1488 push @$res, $sid;
1489 }
1490 return $res;
f7621c01
DM
1491}
1492
98437f4c
DM
1493sub complete_content_type {
1494 my ($cmdname, $pname, $cvalue) = @_;
1495
1496 return [qw(rootdir images vztmpl iso backup)];
1497}
1498
bf7aed26
DM
1499sub complete_volume {
1500 my ($cmdname, $pname, $cvalue) = @_;
1501
1502 my $cfg = config();
1503
1504 my $storage_list = complete_storage_enabled();
1505
b70b0c58
DM
1506 if ($cvalue =~ m/^([^:]+):/) {
1507 $storage_list = [ $1 ];
1508 } else {
1509 if (scalar(@$storage_list) > 1) {
1510 # only list storage IDs to avoid large listings
1511 my $res = [];
1512 foreach my $storeid (@$storage_list) {
1513 # Hack: simply return 2 artificial values, so that
1514 # completions does not finish
1515 push @$res, "$storeid:volname", "$storeid:...";
1516 }
1517 return $res;
1518 }
1519 }
1520
bf7aed26
DM
1521 my $res = [];
1522 foreach my $storeid (@$storage_list) {
1523 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
1524
1525 foreach my $item (@$vollist) {
1526 push @$res, $item->{volid};
1527 }
1528 }
1529
1530 return $res;
1531}
1532
b6cf0a66 15331;