]> git.proxmox.com Git - pve-storage.git/blame - PVE/Storage.pm
LVM: lock on volume_resize
[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;
7ba34faa 10use IO::Socket::IP;
b6cf0a66
DM
11use File::Basename;
12use File::Path;
b6cf0a66 13use Cwd 'abs_path';
7a2d5c1a 14use Socket;
b6cf0a66 15
4dee23d3 16use PVE::Tools qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
83d7192f 17use PVE::Cluster qw(cfs_read_file cfs_write_file cfs_lock_file);
b6cf0a66
DM
18use PVE::Exception qw(raise_param_exc);
19use PVE::JSONSchema;
20use PVE::INotify;
88c3abaf 21use PVE::RPCEnvironment;
b6cf0a66 22
1dc01b9f
DM
23use PVE::Storage::Plugin;
24use PVE::Storage::DirPlugin;
25use PVE::Storage::LVMPlugin;
610798bc 26use PVE::Storage::LvmThinPlugin;
1dc01b9f 27use PVE::Storage::NFSPlugin;
d7875239 28use PVE::Storage::CIFSPlugin;
1dc01b9f 29use PVE::Storage::ISCSIPlugin;
0509010d 30use PVE::Storage::RBDPlugin;
e34ce144 31use PVE::Storage::CephFSPlugin;
caf1960c 32use PVE::Storage::SheepdogPlugin;
86616554 33use PVE::Storage::ISCSIDirectPlugin;
f4648aef 34use PVE::Storage::GlusterfsPlugin;
85fda4dd 35use PVE::Storage::ZFSPoolPlugin;
4f914e6e 36use PVE::Storage::ZFSPlugin;
14770890 37use PVE::Storage::DRBDPlugin;
b6cf0a66 38
4dee23d3 39# Storage API version. Icrement it on changes in storage API interface.
40d69893 40use constant APIVER => 2;
4dee23d3
DP
41
42# load standard plugins
1dc01b9f
DM
43PVE::Storage::DirPlugin->register();
44PVE::Storage::LVMPlugin->register();
610798bc 45PVE::Storage::LvmThinPlugin->register();
1dc01b9f 46PVE::Storage::NFSPlugin->register();
d7875239 47PVE::Storage::CIFSPlugin->register();
1dc01b9f 48PVE::Storage::ISCSIPlugin->register();
0509010d 49PVE::Storage::RBDPlugin->register();
e34ce144 50PVE::Storage::CephFSPlugin->register();
caf1960c 51PVE::Storage::SheepdogPlugin->register();
86616554 52PVE::Storage::ISCSIDirectPlugin->register();
f4648aef 53PVE::Storage::GlusterfsPlugin->register();
85fda4dd 54PVE::Storage::ZFSPoolPlugin->register();
4f914e6e 55PVE::Storage::ZFSPlugin->register();
14770890 56PVE::Storage::DRBDPlugin->register();
4dee23d3
DP
57
58# load third-party plugins
59if ( -d '/usr/share/perl5/PVE/Storage/Custom' ) {
60 dir_glob_foreach('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
61 my ($file) = @_;
62 my $modname = 'PVE::Storage::Custom::' . $file;
63 $modname =~ s!\.pm$!!;
64 $file = 'PVE/Storage/Custom/' . $file;
65
66 eval {
67 require $file;
68 };
69 if ($@) {
70 warn $@;
71 # Check storage API version and that file is really storage plugin.
72 } elsif ($modname->isa('PVE::Storage::Plugin') && $modname->can('api') && $modname->api() == APIVER) {
73 eval {
74 import $file;
75 $modname->register();
76 };
77 warn $@ if $@;
78 } else {
79 warn "Error loading storage plugin \"$modname\" because of API version mismatch. Please, update it.\n"
80 }
81 });
82}
83
84# initialize all plugins
1dc01b9f 85PVE::Storage::Plugin->init();
b6cf0a66 86
1dc01b9f 87my $UDEVADM = '/sbin/udevadm';
b6cf0a66 88
1dc01b9f 89# PVE::Storage utility functions
b6cf0a66
DM
90
91sub config {
92 return cfs_read_file("storage.cfg");
93}
94
83d7192f
FG
95sub write_config {
96 my ($cfg) = @_;
97
98 cfs_write_file('storage.cfg', $cfg);
99}
100
b6cf0a66
DM
101sub lock_storage_config {
102 my ($code, $errmsg) = @_;
103
104 cfs_lock_file("storage.cfg", undef, $code);
105 my $err = $@;
106 if ($err) {
107 $errmsg ? die "$errmsg: $err" : die $err;
108 }
109}
110
b6cf0a66
DM
111sub storage_config {
112 my ($cfg, $storeid, $noerr) = @_;
113
82fc923f 114 die "no storage ID specified\n" if !$storeid;
1a3459ac 115
b6cf0a66
DM
116 my $scfg = $cfg->{ids}->{$storeid};
117
118 die "storage '$storeid' does not exists\n" if (!$noerr && !$scfg);
119
120 return $scfg;
121}
122
123sub storage_check_node {
124 my ($cfg, $storeid, $node, $noerr) = @_;
125
1dc01b9f 126 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
127
128 if ($scfg->{nodes}) {
129 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
130 if (!$scfg->{nodes}->{$node}) {
da156fb3 131 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
b6cf0a66
DM
132 return undef;
133 }
134 }
135
136 return $scfg;
137}
138
139sub storage_check_enabled {
140 my ($cfg, $storeid, $node, $noerr) = @_;
141
1dc01b9f 142 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
143
144 if ($scfg->{disable}) {
145 die "storage '$storeid' is disabled\n" if !$noerr;
146 return undef;
147 }
148
149 return storage_check_node($cfg, $storeid, $node, $noerr);
150}
151
7118dd91
DM
152# storage_can_replicate:
153# return true if storage supports replication
154# (volumes alocated with vdisk_alloc() has replication feature)
155sub storage_can_replicate {
156 my ($cfg, $storeid, $format) = @_;
157
158 my $scfg = storage_config($cfg, $storeid);
159 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
160 return $plugin->storage_can_replicate($scfg, $storeid, $format);
161}
162
b6cf0a66
DM
163sub storage_ids {
164 my ($cfg) = @_;
165
1dc01b9f 166 return keys %{$cfg->{ids}};
b6cf0a66
DM
167}
168
1dc01b9f
DM
169sub file_size_info {
170 my ($filename, $timeout) = @_;
b6cf0a66 171
1dc01b9f 172 return PVE::Storage::Plugin::file_size_info($filename, $timeout);
b6cf0a66
DM
173}
174
20ccac1b
AD
175sub volume_size_info {
176 my ($cfg, $volid, $timeout) = @_;
177
f18199e5
DM
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_size_info($scfg, $storeid, $volname, $timeout);
183 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
184 return file_size_info($volid, $timeout);
185 } else {
186 return 0;
187 }
20ccac1b
AD
188}
189
7e6c05dc
AD
190sub volume_resize {
191 my ($cfg, $volid, $size, $running) = @_;
192
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_resize($scfg, $storeid, $volname, $size, $running);
198 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 199 die "resize file/device '$volid' is not possible\n";
7e6c05dc 200 } else {
f824c722 201 die "unable to parse volume ID '$volid'\n";
7e6c05dc
AD
202 }
203}
204
1597f1f9
WL
205sub volume_rollback_is_possible {
206 my ($cfg, $volid, $snap) = @_;
e0852ba7 207
1597f1f9
WL
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});
212 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
213 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 214 die "snapshot rollback file/device '$volid' is not possible\n";
1597f1f9 215 } else {
f824c722 216 die "unable to parse volume ID '$volid'\n";
1597f1f9
WL
217 }
218}
219
db60719c 220sub volume_snapshot {
f5640e7d 221 my ($cfg, $volid, $snap) = @_;
db60719c
AD
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});
f5640e7d 227 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
db60719c 228 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 229 die "snapshot file/device '$volid' is not possible\n";
db60719c 230 } else {
f824c722 231 die "unable to parse volume ID '$volid'\n";
db60719c
AD
232 }
233}
234
22a2a633
AD
235sub volume_snapshot_rollback {
236 my ($cfg, $volid, $snap) = @_;
237
238 my ($storeid, $volname) = parse_volume_id($volid, 1);
239 if ($storeid) {
240 my $scfg = storage_config($cfg, $storeid);
241 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b3f302c6 242 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
22a2a633
AD
243 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
244 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 245 die "snapshot rollback file/device '$volid' is not possible\n";
22a2a633 246 } else {
f824c722 247 die "unable to parse volume ID '$volid'\n";
22a2a633
AD
248 }
249}
250
5753c9d1
AD
251sub volume_snapshot_delete {
252 my ($cfg, $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});
27cc55d4 258 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
5753c9d1 259 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
f824c722 260 die "snapshot delete file/device '$volid' is not possible\n";
5753c9d1 261 } else {
f824c722 262 die "unable to parse volume ID '$volid'\n";
5753c9d1
AD
263 }
264}
265
99473759
AD
266sub volume_has_feature {
267 my ($cfg, $feature, $volid, $snap, $running) = @_;
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_has_feature($scfg, $feature, $storeid, $volname, $snap, $running);
274 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
275 return undef;
276 } else {
277 return undef;
278 }
279}
280
aefe82ea 281sub volume_snapshot_list {
8b622c2d 282 my ($cfg, $volid) = @_;
aefe82ea
WL
283
284 my ($storeid, $volname) = parse_volume_id($volid, 1);
285 if ($storeid) {
286 my $scfg = storage_config($cfg, $storeid);
287 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
8b622c2d 288 return $plugin->volume_snapshot_list($scfg, $storeid, $volname);
aefe82ea
WL
289 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
290 die "send file/device '$volid' is not possible\n";
291 } else {
292 die "unable to parse volume ID '$volid'\n";
293 }
294 # return an empty array if dataset does not exist.
aefe82ea
WL
295}
296
1dc01b9f
DM
297sub get_image_dir {
298 my ($cfg, $storeid, $vmid) = @_;
b6cf0a66 299
1dc01b9f
DM
300 my $scfg = storage_config($cfg, $storeid);
301 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 302
1dc01b9f 303 my $path = $plugin->get_subdir($scfg, 'images');
b6cf0a66 304
1dc01b9f 305 return $vmid ? "$path/$vmid" : $path;
b6cf0a66
DM
306}
307
1dc01b9f 308sub get_private_dir {
b6cf0a66
DM
309 my ($cfg, $storeid, $vmid) = @_;
310
1dc01b9f
DM
311 my $scfg = storage_config($cfg, $storeid);
312 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 313
1dc01b9f 314 my $path = $plugin->get_subdir($scfg, 'rootdir');
d22a6133 315
1dc01b9f 316 return $vmid ? "$path/$vmid" : $path;
d22a6133
DM
317}
318
b6cf0a66
DM
319sub get_iso_dir {
320 my ($cfg, $storeid) = @_;
321
1dc01b9f
DM
322 my $scfg = storage_config($cfg, $storeid);
323 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 324
1dc01b9f 325 return $plugin->get_subdir($scfg, 'iso');
b6cf0a66
DM
326}
327
328sub get_vztmpl_dir {
329 my ($cfg, $storeid) = @_;
330
1dc01b9f
DM
331 my $scfg = storage_config($cfg, $storeid);
332 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 333
1dc01b9f 334 return $plugin->get_subdir($scfg, 'vztmpl');
b6cf0a66
DM
335}
336
568de3d1
DM
337sub get_backup_dir {
338 my ($cfg, $storeid) = @_;
339
1dc01b9f
DM
340 my $scfg = storage_config($cfg, $storeid);
341 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 342
1dc01b9f 343 return $plugin->get_subdir($scfg, 'backup');
b6cf0a66
DM
344}
345
346# library implementation
347
b6cf0a66
DM
348sub parse_vmid {
349 my $vmid = shift;
350
351 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
352
353 return int($vmid);
354}
355
787624df
FG
356# NOTE: basename and basevmid are always undef for LVM-thin, where the
357# clone -> base reference is not encoded in the volume ID.
358# see note in PVE::Storage::LvmThinPlugin for details.
ec4b0dc7
AD
359sub parse_volname {
360 my ($cfg, $volid) = @_;
361
362 my ($storeid, $volname) = parse_volume_id($volid);
363
364 my $scfg = storage_config($cfg, $storeid);
365
366 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
a6f12626
DM
367
368 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
369
ec4b0dc7
AD
370 return $plugin->parse_volname($volname);
371}
372
b6cf0a66
DM
373sub parse_volume_id {
374 my ($volid, $noerr) = @_;
375
a7f3d909 376 return PVE::Storage::Plugin::parse_volume_id($volid, $noerr);
b6cf0a66
DM
377}
378
04a13668
DM
379# test if we have read access to volid
380sub check_volume_access {
381 my ($rpcenv, $user, $cfg, $vmid, $volid) = @_;
382
383 my ($sid, $volname) = parse_volume_id($volid, 1);
384 if ($sid) {
385 my ($vtype, undef, $ownervm) = parse_volname($cfg, $volid);
386 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
387 # we simply allow access
388 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
389 # we are owner - allow access
390 } elsif ($vtype eq 'backup' && $ownervm) {
391 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
392 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
393 } else {
394 # allow if we are Datastore administrator
395 $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate']);
396 }
397 } else {
398 die "Only root can pass arbitrary filesystem paths."
399 if $user ne 'root@pam';
400 }
401
402 return undef;
403}
404
17fb7e42
FG
405my $volume_is_base_and_used__no_lock = sub {
406 my ($scfg, $storeid, $plugin, $volname) = @_;
407
408 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
409 $plugin->parse_volname($volname);
410
411 if ($isBase) {
412 my $vollist = $plugin->list_images($storeid, $scfg);
413 foreach my $info (@$vollist) {
414 my (undef, $tmpvolname) = parse_volume_id($info->{volid});
415 my $basename = undef;
416 my $basevmid = undef;
417
418 eval{
419 (undef, undef, undef, $basename, $basevmid) =
420 $plugin->parse_volname($tmpvolname);
421 };
422
423 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
424 return 1;
425 }
426 }
427 }
428 return 0;
429};
430
787624df
FG
431# NOTE: this check does not work for LVM-thin, where the clone -> base
432# reference is not encoded in the volume ID.
433# see note in PVE::Storage::LvmThinPlugin for details.
17fb7e42
FG
434sub volume_is_base_and_used {
435 my ($cfg, $volid) = @_;
436
437 my ($storeid, $volname) = parse_volume_id($volid);
438 my $scfg = storage_config($cfg, $storeid);
439 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
440
441 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
442 return &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
443 });
444}
445
b6cf0a66
DM
446# try to map a filesystem path to a volume identifier
447sub path_to_volume_id {
448 my ($cfg, $path) = @_;
449
450 my $ids = $cfg->{ids};
451
1dc01b9f 452 my ($sid, $volname) = parse_volume_id($path, 1);
b6cf0a66 453 if ($sid) {
1dc01b9f 454 if (my $scfg = $ids->{$sid}) {
188aca38 455 if ($scfg->{path}) {
1dc01b9f
DM
456 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
457 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
b6cf0a66
DM
458 return ($vtype, $path);
459 }
460 }
461 return ('');
462 }
463
1a3459ac 464 # Note: abs_path() return undef if $path doesn not exist
75d75990
DM
465 # for example when nfs storage is not mounted
466 $path = abs_path($path) || $path;
b6cf0a66
DM
467
468 foreach my $sid (keys %$ids) {
1dc01b9f
DM
469 my $scfg = $ids->{$sid};
470 next if !$scfg->{path};
471 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
472 my $imagedir = $plugin->get_subdir($scfg, 'images');
473 my $isodir = $plugin->get_subdir($scfg, 'iso');
474 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
475 my $backupdir = $plugin->get_subdir($scfg, 'backup');
476 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
b6cf0a66
DM
477
478 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
479 my $vmid = $1;
480 my $name = $2;
fcbec654
DM
481
482 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
483 foreach my $info (@$vollist) {
484 my ($storeid, $volname) = parse_volume_id($info->{volid});
485 my $volpath = $plugin->path($scfg, $volname, $storeid);
486 if ($volpath eq $path) {
487 return ('images', $info->{volid});
488 }
489 }
b6cf0a66
DM
490 } elsif ($path =~ m!^$isodir/([^/]+\.[Ii][Ss][Oo])$!) {
491 my $name = $1;
1a3459ac 492 return ('iso', "$sid:iso/$name");
b6cf0a66
DM
493 } elsif ($path =~ m!^$tmpldir/([^/]+\.tar\.gz)$!) {
494 my $name = $1;
495 return ('vztmpl', "$sid:vztmpl/$name");
1ac17c74
DM
496 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
497 my $vmid = $1;
498 return ('rootdir', "$sid:rootdir/$vmid");
a22854e5 499 } elsif ($path =~ m!^$backupdir/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!) {
568de3d1 500 my $name = $1;
1a3459ac 501 return ('iso', "$sid:backup/$name");
b6cf0a66
DM
502 }
503 }
504
505 # can't map path to volume id
506 return ('');
507}
508
509sub path {
207ea852 510 my ($cfg, $volid, $snapname) = @_;
b6cf0a66 511
1dc01b9f 512 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 513
1dc01b9f 514 my $scfg = storage_config($cfg, $storeid);
b6cf0a66 515
1dc01b9f 516 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
207ea852 517 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
2494896a 518 return wantarray ? ($path, $owner, $vtype) : $path;
b6cf0a66
DM
519}
520
35fbb2e6
DM
521sub abs_filesystem_path {
522 my ($cfg, $volid) = @_;
523
524 my $path;
525 if (PVE::Storage::parse_volume_id ($volid, 1)) {
526 PVE::Storage::activate_volumes($cfg, [ $volid ]);
527 $path = PVE::Storage::path($cfg, $volid);
528 } else {
529 if (-f $volid) {
530 my $abspath = abs_path($volid);
531 if ($abspath && $abspath =~ m|^(/.+)$|) {
532 $path = $1; # untaint any path
533 }
534 }
535 }
536
537 die "can't find file '$volid'\n" if !($path && -f $path);
538
539 return $path;
540}
541
b6cf0a66 542sub storage_migrate {
8fe00d99 543 my ($cfg, $volid, $target_sshinfo, $target_storeid, $target_volname, $base_snapshot, $snapshot, $ratelimit_bps, $insecure, $with_snapshots, $logfunc) = @_;
b6cf0a66 544
6bf56298 545 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66
DM
546 $target_volname = $volname if !$target_volname;
547
6bf56298 548 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
549
550 # no need to migrate shared content
551 return if $storeid eq $target_storeid && $scfg->{shared};
552
6bf56298 553 my $tcfg = storage_config($cfg, $target_storeid);
b6cf0a66
DM
554
555 my $target_volid = "${target_storeid}:${target_volname}";
556
4b4c580d
WB
557 my $target_ip = $target_sshinfo->{ip};
558 my $errstr = "unable to migrate '$volid' to '${target_volid}' on host '$target_sshinfo->{name}'";
b6cf0a66 559
acd27197 560 my $ssh = PVE::Cluster::ssh_info_to_command($target_sshinfo);
47cea194
WB
561 my $ssh_base = PVE::Cluster::ssh_info_to_command_base($target_sshinfo);
562 local $ENV{RSYNC_RSH} = PVE::Tools::cmd2string($ssh_base);
b6cf0a66 563
01f7e902
WB
564 my @cstream = ([ '/usr/bin/cstream', '-t', $ratelimit_bps ])
565 if defined($ratelimit_bps);
566
da72898c
WB
567 my $migration_snapshot;
568 if (!defined($snapshot)) {
569 if ($scfg->{type} eq 'zfspool') {
570 $migration_snapshot = 1;
571 $snapshot = '__migration__';
1dc01b9f 572 }
da72898c 573 }
e0852ba7 574
e8a7e764 575 my @formats = volume_transfer_formats($cfg, $volid, $volid, $snapshot, $base_snapshot, $with_snapshots);
da72898c
WB
576 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
577 my $format = $formats[0];
7459cb3d 578
da72898c
WB
579 my @insecurecmd;
580 if ($insecure) {
581 @insecurecmd = ('pvecm', 'mtunnel', '-run-command', 1);
582 if (my $network = $target_sshinfo->{network}) {
583 push @insecurecmd, '-migration_network', $network;
584 }
585 }
7ba34faa 586
e8a7e764
WB
587 $with_snapshots = $with_snapshots ? 1 : 0; # sanitize for passing as cli parameter
588 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
589 my $recv = [@$ssh, @insecurecmd, '--', 'pvesm', 'import', $volid, $format, '-', '-with-snapshots', $with_snapshots];
da72898c
WB
590 if (defined($snapshot)) {
591 push @$send, '-snapshot', $snapshot
592 }
593 if ($migration_snapshot) {
594 push @$recv, '-delete-snapshot', $snapshot;
595 }
3d621977 596
da72898c
WB
597 if (defined($base_snapshot)) {
598 # Check if the snapshot exists on the remote side:
599 push @$send, '-base', $base_snapshot;
600 push @$recv, '-base', $base_snapshot;
601 }
ac191ec7 602
da72898c
WB
603 volume_snapshot($cfg, $volid, $snapshot) if $migration_snapshot;
604 eval {
605 if ($insecure) {
606 open(my $info, '-|', @$recv)
607 or die "receive command failed: $!\n";
608 my ($ip) = <$info> =~ /^($PVE::Tools::IPRE)$/ or die "no tunnel IP received\n";
609 my ($port) = <$info> =~ /^(\d+)$/ or die "no tunnel port received\n";
610 my $socket = IO::Socket::IP->new(PeerHost => $ip, PeerPort => $port, Type => SOCK_STREAM)
611 or die "failed to connect to tunnel at $ip:$port\n";
612 # we won't be reading from the socket
613 shutdown($socket, 0);
614 run_command([$send, @cstream], output => '>&'.fileno($socket));
615 # don't close the connection entirely otherwise the receiving end
616 # might not get all buffered data (and fails with 'connection reset by peer')
617 shutdown($socket, 1);
618 1 while <$info>; # wait for the remote process to finish
619 # now close the socket
620 close($socket);
621 if (!close($info)) { # does waitpid()
622 die "import failed: $!\n" if $!;
623 die "import failed: exit code ".($?>>8)."\n";
0a29ad61
WL
624 }
625 } else {
8fe00d99 626 run_command([$send, @cstream, $recv], logfunc => $logfunc);
0a29ad61 627 }
da72898c
WB
628 };
629 my $err = $@;
630 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
631 if ($migration_snapshot) {
632 eval { volume_snapshot_delete($cfg, $volid, $snapshot, 0) };
633 warn "could not remove source snapshot: $@\n" if $@;
b6cf0a66 634 }
da72898c 635 die $err if $err;
b6cf0a66
DM
636}
637
2502b33b 638sub vdisk_clone {
7bbc4004 639 my ($cfg, $volid, $vmid, $snap) = @_;
1a3459ac 640
2502b33b
DM
641 my ($storeid, $volname) = parse_volume_id($volid);
642
643 my $scfg = storage_config($cfg, $storeid);
644
645 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 646
2502b33b
DM
647 activate_storage($cfg, $storeid);
648
649 # lock shared storage
650 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
7bbc4004 651 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
2502b33b
DM
652 return "$storeid:$volname";
653 });
654}
655
656sub vdisk_create_base {
657 my ($cfg, $volid) = @_;
658
659 my ($storeid, $volname) = parse_volume_id($volid);
660
661 my $scfg = storage_config($cfg, $storeid);
662
663 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 664
2502b33b
DM
665 activate_storage($cfg, $storeid);
666
667 # lock shared storage
668 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
669 my $volname = $plugin->create_base($storeid, $scfg, $volname);
670 return "$storeid:$volname";
671 });
672}
673
40d69893
DM
674sub map_volume {
675 my ($cfg, $volid, $snapname) = @_;
676
677 my ($storeid, $volname) = parse_volume_id($volid);
678
679 my $scfg = storage_config($cfg, $storeid);
680
681 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
682
683 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
684}
685
686sub unmap_volume {
687 my ($cfg, $volid, $snapname) = @_;
688
689 my ($storeid, $volname) = parse_volume_id($volid);
690
691 my $scfg = storage_config($cfg, $storeid);
692
693 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
694
695 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
696}
697
1dc01b9f
DM
698sub vdisk_alloc {
699 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
b6cf0a66 700
82fc923f 701 die "no storage ID specified\n" if !$storeid;
b6cf0a66 702
1dc01b9f 703 PVE::JSONSchema::parse_storage_id($storeid);
b6cf0a66 704
1dc01b9f 705 my $scfg = storage_config($cfg, $storeid);
b6cf0a66 706
1dc01b9f 707 die "no VMID specified\n" if !$vmid;
b6cf0a66 708
1dc01b9f 709 $vmid = parse_vmid($vmid);
b6cf0a66 710
1dc01b9f 711 my $defformat = PVE::Storage::Plugin::default_format($scfg);
b6cf0a66 712
1dc01b9f 713 $fmt = $defformat if !$fmt;
b6cf0a66 714
1dc01b9f 715 activate_storage($cfg, $storeid);
3af60e62 716
1dc01b9f 717 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 718
1dc01b9f
DM
719 # lock shared storage
720 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
afdfbe55
WB
721 my $old_umask = umask(umask|0037);
722 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
723 my $err = $@;
724 umask $old_umask;
725 die $err if $err;
1dc01b9f
DM
726 return "$storeid:$volname";
727 });
b6cf0a66
DM
728}
729
1dc01b9f
DM
730sub vdisk_free {
731 my ($cfg, $volid) = @_;
b6cf0a66 732
1dc01b9f 733 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f 734 my $scfg = storage_config($cfg, $storeid);
1dc01b9f 735 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 736
1dc01b9f 737 activate_storage($cfg, $storeid);
b6cf0a66 738
1dc01b9f 739 my $cleanup_worker;
b6cf0a66 740
1dc01b9f
DM
741 # lock shared storage
742 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
787624df 743 # LVM-thin allows deletion of still referenced base volumes!
17fb7e42
FG
744 die "base volume '$volname' is still in use by linked clones\n"
745 if &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
32437ed2 746
17fb7e42 747 my (undef, undef, undef, undef, undef, $isBase, $format) =
32437ed2 748 $plugin->parse_volname($volname);
35533c68 749 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
1dc01b9f 750 });
b6cf0a66 751
1dc01b9f 752 return if !$cleanup_worker;
b6cf0a66 753
1dc01b9f
DM
754 my $rpcenv = PVE::RPCEnvironment::get();
755 my $authuser = $rpcenv->get_user();
b6cf0a66 756
1dc01b9f 757 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
b6cf0a66
DM
758}
759
b6cf0a66
DM
760#list iso or openvz template ($tt = <iso|vztmpl|backup>)
761sub template_list {
762 my ($cfg, $storeid, $tt) = @_;
763
1a3459ac
DM
764 die "unknown template type '$tt'\n"
765 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup');
b6cf0a66
DM
766
767 my $ids = $cfg->{ids};
768
769 storage_check_enabled($cfg, $storeid) if ($storeid);
770
771 my $res = {};
772
773 # query the storage
774
775 foreach my $sid (keys %$ids) {
776 next if $storeid && $storeid ne $sid;
777
778 my $scfg = $ids->{$sid};
779 my $type = $scfg->{type};
780
781 next if !storage_check_enabled($cfg, $sid, undef, 1);
782
783 next if $tt eq 'iso' && !$scfg->{content}->{iso};
784 next if $tt eq 'vztmpl' && !$scfg->{content}->{vztmpl};
785 next if $tt eq 'backup' && !$scfg->{content}->{backup};
786
1dc01b9f 787 activate_storage($cfg, $sid);
b6cf0a66 788
1dc01b9f
DM
789 if ($scfg->{path}) {
790 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 791
1dc01b9f 792 my $path = $plugin->get_subdir($scfg, $tt);
b6cf0a66
DM
793
794 foreach my $fn (<$path/*>) {
795
796 my $info;
797
798 if ($tt eq 'iso') {
799 next if $fn !~ m!/([^/]+\.[Ii][Ss][Oo])$!;
800
801 $info = { volid => "$sid:iso/$1", format => 'iso' };
802
803 } elsif ($tt eq 'vztmpl') {
13d2cb79 804 next if $fn !~ m!/([^/]+\.tar\.([gx]z))$!;
b6cf0a66 805
13d2cb79 806 $info = { volid => "$sid:vztmpl/$1", format => "t$2" };
b6cf0a66
DM
807
808 } elsif ($tt eq 'backup') {
a22854e5 809 next if $fn !~ m!/([^/]+\.(tar|tar\.gz|tar\.lzo|tgz|vma|vma\.gz|vma\.lzo))$!;
1a3459ac 810
b6cf0a66
DM
811 $info = { volid => "$sid:backup/$1", format => $2 };
812 }
813
814 $info->{size} = -s $fn;
815
816 push @{$res->{$sid}}, $info;
817 }
818
819 }
820
821 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
822 }
823
824 return $res;
825}
826
20ccac1b 827
b6cf0a66
DM
828sub vdisk_list {
829 my ($cfg, $storeid, $vmid, $vollist) = @_;
830
831 my $ids = $cfg->{ids};
832
833 storage_check_enabled($cfg, $storeid) if ($storeid);
834
835 my $res = {};
836
837 # prepare/activate/refresh all storages
838
b6cf0a66
DM
839 my $storage_list = [];
840 if ($vollist) {
841 foreach my $volid (@$vollist) {
1dc01b9f
DM
842 my ($sid, undef) = parse_volume_id($volid);
843 next if !defined($ids->{$sid});
b6cf0a66
DM
844 next if !storage_check_enabled($cfg, $sid, undef, 1);
845 push @$storage_list, $sid;
b6cf0a66
DM
846 }
847 } else {
848 foreach my $sid (keys %$ids) {
849 next if $storeid && $storeid ne $sid;
850 next if !storage_check_enabled($cfg, $sid, undef, 1);
851 push @$storage_list, $sid;
b6cf0a66
DM
852 }
853 }
854
1dc01b9f 855 my $cache = {};
b6cf0a66 856
1dc01b9f 857 activate_storage_list($cfg, $storage_list, $cache);
b6cf0a66
DM
858
859 foreach my $sid (keys %$ids) {
1dc01b9f
DM
860 next if $storeid && $storeid ne $sid;
861 next if !storage_check_enabled($cfg, $sid, undef, 1);
b6cf0a66 862
1dc01b9f
DM
863 my $scfg = $ids->{$sid};
864 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
865 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
b6cf0a66
DM
866 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
867 }
868
869 return $res;
870}
871
37ba0aea
DM
872sub volume_list {
873 my ($cfg, $storeid, $vmid, $content) = @_;
874
875 my @ctypes = qw(images vztmpl iso backup);
876
877 my $cts = $content ? [ $content ] : [ @ctypes ];
878
879 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
880
881 my $res = [];
882 foreach my $ct (@$cts) {
883 my $data;
884 if ($ct eq 'images') {
885 $data = vdisk_list($cfg, $storeid, $vmid);
886 } elsif ($ct eq 'iso' && !defined($vmid)) {
887 $data = template_list($cfg, $storeid, 'iso');
888 } elsif ($ct eq 'vztmpl'&& !defined($vmid)) {
889 $data = template_list ($cfg, $storeid, 'vztmpl');
890 } elsif ($ct eq 'backup') {
891 $data = template_list ($cfg, $storeid, 'backup');
892 foreach my $item (@{$data->{$storeid}}) {
893 if (defined($vmid)) {
894 @{$data->{$storeid}} = grep { $_->{volid} =~ m/\S+-$vmid-\S+/ } @{$data->{$storeid}};
895 }
896 }
897 }
898
899 next if !$data || !$data->{$storeid};
900
901 foreach my $item (@{$data->{$storeid}}) {
902 $item->{content} = $ct;
903 push @$res, $item;
904 }
905 }
906
907 return $res;
908}
909
b6cf0a66
DM
910sub uevent_seqnum {
911
912 my $filename = "/sys/kernel/uevent_seqnum";
913
914 my $seqnum = 0;
1dc01b9f 915 if (my $fh = IO::File->new($filename, "r")) {
b6cf0a66
DM
916 my $line = <$fh>;
917 if ($line =~ m/^(\d+)$/) {
1dc01b9f 918 $seqnum = int($1);
b6cf0a66
DM
919 }
920 close ($fh);
921 }
922 return $seqnum;
923}
924
f3d4ef46 925sub activate_storage {
1dc01b9f 926 my ($cfg, $storeid, $cache) = @_;
b6cf0a66 927
f3d4ef46
DM
928 $cache = {} if !$cache;
929
b6cf0a66
DM
930 my $scfg = storage_check_enabled($cfg, $storeid);
931
1dc01b9f 932 return if $cache->{activated}->{$storeid};
b6cf0a66 933
1dc01b9f 934 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
b6cf0a66 935
1dc01b9f 936 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 937
1dc01b9f
DM
938 if ($scfg->{base}) {
939 my ($baseid, undef) = parse_volume_id ($scfg->{base});
f3d4ef46
DM
940 activate_storage($cfg, $baseid, $cache);
941 }
942
943 if (!$plugin->check_connection($storeid, $scfg)) {
944 die "storage '$storeid' is not online\n";
b6cf0a66
DM
945 }
946
1dc01b9f
DM
947 $plugin->activate_storage($storeid, $scfg, $cache);
948
b6cf0a66
DM
949 my $newseq = uevent_seqnum ();
950
951 # only call udevsettle if there are events
1dc01b9f 952 if ($newseq > $cache->{uevent_seqnum}) {
b6cf0a66
DM
953 my $timeout = 30;
954 system ("$UDEVADM settle --timeout=$timeout"); # ignore errors
1dc01b9f 955 $cache->{uevent_seqnum} = $newseq;
b6cf0a66
DM
956 }
957
1dc01b9f 958 $cache->{activated}->{$storeid} = 1;
b6cf0a66
DM
959}
960
961sub activate_storage_list {
1dc01b9f 962 my ($cfg, $storeid_list, $cache) = @_;
b6cf0a66 963
1dc01b9f 964 $cache = {} if !$cache;
b6cf0a66
DM
965
966 foreach my $storeid (@$storeid_list) {
f3d4ef46 967 activate_storage($cfg, $storeid, $cache);
b6cf0a66
DM
968 }
969}
970
1dc01b9f
DM
971sub deactivate_storage {
972 my ($cfg, $storeid) = @_;
973
974 my $scfg = storage_config ($cfg, $storeid);
975 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
b6cf0a66 976
1dc01b9f
DM
977 my $cache = {};
978 $plugin->deactivate_storage($storeid, $scfg, $cache);
b6cf0a66
DM
979}
980
981sub activate_volumes {
02e797b8 982 my ($cfg, $vollist, $snapname) = @_;
6703353b
DM
983
984 return if !($vollist && scalar(@$vollist));
985
b6cf0a66
DM
986 my $storagehash = {};
987 foreach my $volid (@$vollist) {
1dc01b9f 988 my ($storeid, undef) = parse_volume_id($volid);
b6cf0a66
DM
989 $storagehash->{$storeid} = 1;
990 }
991
1dc01b9f
DM
992 my $cache = {};
993
994 activate_storage_list($cfg, [keys %$storagehash], $cache);
b6cf0a66
DM
995
996 foreach my $volid (@$vollist) {
5521b580 997 my ($storeid, $volname) = parse_volume_id($volid);
1dc01b9f
DM
998 my $scfg = storage_config($cfg, $storeid);
999 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
02e797b8 1000 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
b6cf0a66
DM
1001 }
1002}
1003
1004sub deactivate_volumes {
02e797b8 1005 my ($cfg, $vollist, $snapname) = @_;
b6cf0a66 1006
6703353b
DM
1007 return if !($vollist && scalar(@$vollist));
1008
1dc01b9f
DM
1009 my $cache = {};
1010
6703353b 1011 my @errlist = ();
b6cf0a66 1012 foreach my $volid (@$vollist) {
1dc01b9f 1013 my ($storeid, $volname) = parse_volume_id($volid);
b6cf0a66 1014
1dc01b9f
DM
1015 my $scfg = storage_config($cfg, $storeid);
1016 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1a3459ac 1017
1dc01b9f 1018 eval {
02e797b8 1019 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1dc01b9f
DM
1020 };
1021 if (my $err = $@) {
1022 warn $err;
1023 push @errlist, $volid;
b6cf0a66
DM
1024 }
1025 }
6703353b 1026
82fc923f 1027 die "volume deactivation failed: " . join(' ', @errlist)
6703353b 1028 if scalar(@errlist);
b6cf0a66
DM
1029}
1030
1a3459ac 1031sub storage_info {
856c54bd 1032 my ($cfg, $content, $includeformat) = @_;
b6cf0a66
DM
1033
1034 my $ids = $cfg->{ids};
1035
1036 my $info = {};
ff3badd8 1037
583c2802 1038 my @ctypes = PVE::Tools::split_list($content);
ff3badd8 1039
b6cf0a66
DM
1040 my $slist = [];
1041 foreach my $storeid (keys %$ids) {
6ce4f724 1042 my $storage_enabled = defined(storage_check_enabled($cfg, $storeid, undef, 1));
b6cf0a66 1043
d73060be
DM
1044 if (defined($content)) {
1045 my $want_ctype = 0;
1046 foreach my $ctype (@ctypes) {
1047 if ($ids->{$storeid}->{content}->{$ctype}) {
1048 $want_ctype = 1;
1049 last;
1050 }
583c2802 1051 }
6ce4f724 1052 next if !$want_ctype || !$storage_enabled;
583c2802 1053 }
ff3badd8 1054
b6cf0a66
DM
1055 my $type = $ids->{$storeid}->{type};
1056
1a3459ac 1057 $info->{$storeid} = {
b6cf0a66 1058 type => $type,
1a3459ac
DM
1059 total => 0,
1060 avail => 0,
1061 used => 0,
04a2e4f3 1062 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1dc01b9f 1063 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
b6cf0a66 1064 active => 0,
6ce4f724 1065 enabled => $storage_enabled ? 1 : 0,
b6cf0a66
DM
1066 };
1067
b6cf0a66
DM
1068 push @$slist, $storeid;
1069 }
1070
1dc01b9f 1071 my $cache = {};
b6cf0a66 1072
b6cf0a66
DM
1073 foreach my $storeid (keys %$ids) {
1074 my $scfg = $ids->{$storeid};
b43b073b 1075
b6cf0a66 1076 next if !$info->{$storeid};
b43b073b 1077 next if !$info->{$storeid}->{enabled};
b6cf0a66 1078
856c54bd
DC
1079 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1080 if ($includeformat) {
1081 my $pd = $plugin->plugindata();
1082 $info->{$storeid}->{format} = $pd->{format}
1083 if $pd->{format};
1084 $info->{$storeid}->{select_existing} = $pd->{select_existing}
1085 if $pd->{select_existing};
1086 }
1087
f3d4ef46
DM
1088 eval { activate_storage($cfg, $storeid, $cache); };
1089 if (my $err = $@) {
1090 warn $err;
1091 next;
1092 }
1093
41aacc6c 1094 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
7028645e 1095 warn $@ if $@;
1dc01b9f 1096 next if !$active;
ff3badd8
DM
1097 $info->{$storeid}->{total} = int($total);
1098 $info->{$storeid}->{avail} = int($avail);
1099 $info->{$storeid}->{used} = int($used);
1dc01b9f 1100 $info->{$storeid}->{active} = $active;
b6cf0a66
DM
1101 }
1102
1103 return $info;
1104}
1105
1106sub resolv_server {
1107 my ($server) = @_;
1a3459ac 1108
c67daeac
WB
1109 my ($packed_ip, $family);
1110 eval {
1111 my @res = PVE::Tools::getaddrinfo_all($server);
1112 $family = $res[0]->{family};
1113 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1114 };
b6cf0a66 1115 if (defined $packed_ip) {
ee302b1c 1116 return Socket::inet_ntop($family, $packed_ip);
b6cf0a66
DM
1117 }
1118 return undef;
1119}
1120
1121sub scan_nfs {
1122 my ($server_in) = @_;
1123
1124 my $server;
1125 if (!($server = resolv_server ($server_in))) {
1126 die "unable to resolve address for server '${server_in}'\n";
1127 }
1128
1129 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1130
1131 my $res = {};
f81372ac 1132 run_command($cmd, outfunc => sub {
b6cf0a66
DM
1133 my $line = shift;
1134
1135 # note: howto handle white spaces in export path??
1136 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1137 $res->{$1} = $2;
1138 }
1139 });
1140
1141 return $res;
1142}
1143
4cab0acd
WL
1144sub scan_cifs {
1145 my ($server_in, $user, $password, $domain) = @_;
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 # we support only Windows grater than 2012 cifsscan so use smb3
1153 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1154 if (defined($user)) {
1155 die "password is required" if !defined($password);
1156 push @$cmd, '-U', "$user\%$password";
1157 push @$cmd, '-W', $domain if defined($domain);
1158 } else {
1159 push @$cmd, '-N';
1160 }
1161
1162 my $res = {};
1163 run_command($cmd,
1164 outfunc => sub {
1165 my $line = shift;
1166 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1167 $res->{$1} = $2;
1168 } elsif ($line =~ m/(NT_STATUS_(\S*))/) {
1169 $res->{$1} = '';
1170 }
1171 },
1172 errfunc => sub {},
1173 noerr => 1
1174 );
1175
1176 return $res;
1177}
1178
584d97f6
DM
1179sub scan_zfs {
1180
3932390b 1181 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-H', '-o', 'name,avail,used'];
584d97f6
DM
1182
1183 my $res = [];
1184 run_command($cmd, outfunc => sub {
1185 my $line = shift;
1186
1187 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
3932390b 1188 my ($pool, $size_str, $used_str) = ($1, $2, $3);
584d97f6 1189 my $size = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($size_str);
3932390b 1190 my $used = PVE::Storage::ZFSPoolPlugin::zfs_parse_size($used_str);
48e27f79 1191 # ignore subvolumes generated by our ZFSPoolPlugin
851658c3
WL
1192 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1193 return if $pool =~ m!/basevol-\d+-[^/]+$!;
3932390b 1194 push @$res, { pool => $pool, size => $size, free => $size-$used };
584d97f6
DM
1195 }
1196 });
1197
1198 return $res;
1199}
1200
b6cf0a66
DM
1201sub resolv_portal {
1202 my ($portal, $noerr) = @_;
1203
1689e627
WB
1204 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1205 if ($server) {
b6cf0a66
DM
1206 if (my $ip = resolv_server($server)) {
1207 $server = $ip;
1689e627 1208 $server = "[$server]" if $server =~ /^$IPV6RE$/;
b6cf0a66
DM
1209 return $port ? "$server:$port" : $server;
1210 }
1211 }
1212 return undef if $noerr;
1213
1214 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1215}
1216
1217# idea is from usbutils package (/usr/bin/usb-devices) script
1218sub __scan_usb_device {
1219 my ($res, $devpath, $parent, $level) = @_;
1220
1221 return if ! -d $devpath;
1222 return if $level && $devpath !~ m/^.*[-.](\d+)$/;
1223 my $port = $level ? int($1 - 1) : 0;
1224
1225 my $busnum = int(file_read_firstline("$devpath/busnum"));
1226 my $devnum = int(file_read_firstline("$devpath/devnum"));
1227
1228 my $d = {
1229 port => $port,
1230 level => $level,
1231 busnum => $busnum,
1232 devnum => $devnum,
1233 speed => file_read_firstline("$devpath/speed"),
1234 class => hex(file_read_firstline("$devpath/bDeviceClass")),
1235 vendid => file_read_firstline("$devpath/idVendor"),
1236 prodid => file_read_firstline("$devpath/idProduct"),
1237 };
1238
1239 if ($level) {
1240 my $usbpath = $devpath;
1241 $usbpath =~ s|^.*/\d+\-||;
1242 $d->{usbpath} = $usbpath;
1243 }
1244
1245 my $product = file_read_firstline("$devpath/product");
1246 $d->{product} = $product if $product;
1a3459ac 1247
b6cf0a66
DM
1248 my $manu = file_read_firstline("$devpath/manufacturer");
1249 $d->{manufacturer} = $manu if $manu;
1250
1251 my $serial => file_read_firstline("$devpath/serial");
1252 $d->{serial} = $serial if $serial;
1253
1254 push @$res, $d;
1255
1256 foreach my $subdev (<$devpath/$busnum-*>) {
1257 next if $subdev !~ m|/$busnum-[0-9]+(\.[0-9]+)*$|;
1258 __scan_usb_device($res, $subdev, $devnum, $level + 1);
1259 }
1260
1261};
1262
1263sub scan_usb {
1264
1265 my $devlist = [];
1266
1267 foreach my $device (</sys/bus/usb/devices/usb*>) {
1268 __scan_usb_device($devlist, $device, 0, 0);
1269 }
1270
1271 return $devlist;
1272}
1273
1274sub scan_iscsi {
1275 my ($portal_in) = @_;
1276
1277 my $portal;
1dc01b9f 1278 if (!($portal = resolv_portal($portal_in))) {
b6cf0a66
DM
1279 die "unable to parse/resolve portal address '${portal_in}'\n";
1280 }
1281
1dc01b9f 1282 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
b6cf0a66
DM
1283}
1284
1285sub storage_default_format {
1286 my ($cfg, $storeid) = @_;
1287
1288 my $scfg = storage_config ($cfg, $storeid);
1289
1dc01b9f 1290 return PVE::Storage::Plugin::default_format($scfg);
b6cf0a66
DM
1291}
1292
1293sub vgroup_is_used {
1294 my ($cfg, $vgname) = @_;
1295
1296 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1297 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1298 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1299 return 1;
1300 }
1301 }
1302
1303 return undef;
1304}
1305
1306sub target_is_used {
1307 my ($cfg, $target) = @_;
1308
1309 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1310 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1311 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1312 return 1;
1313 }
1314 }
1315
1316 return undef;
1317}
1318
1319sub volume_is_used {
1320 my ($cfg, $volid) = @_;
1321
1322 foreach my $storeid (keys %{$cfg->{ids}}) {
1dc01b9f 1323 my $scfg = storage_config($cfg, $storeid);
b6cf0a66
DM
1324 if ($scfg->{base} && $scfg->{base} eq $volid) {
1325 return 1;
1326 }
1327 }
1328
1329 return undef;
1330}
1331
1332sub storage_is_used {
1333 my ($cfg, $storeid) = @_;
1334
1335 foreach my $sid (keys %{$cfg->{ids}}) {
1dc01b9f 1336 my $scfg = storage_config($cfg, $sid);
b6cf0a66 1337 next if !$scfg->{base};
1dc01b9f 1338 my ($st) = parse_volume_id($scfg->{base});
b6cf0a66
DM
1339 return 1 if $st && $st eq $storeid;
1340 }
1341
1342 return undef;
1343}
1344
1345sub foreach_volid {
1346 my ($list, $func) = @_;
1347
1348 return if !$list;
1349
1350 foreach my $sid (keys %$list) {
1351 foreach my $info (@{$list->{$sid}}) {
1352 my $volid = $info->{volid};
1dc01b9f 1353 my ($sid1, $volname) = parse_volume_id($volid, 1);
b6cf0a66
DM
1354 if ($sid1 && $sid1 eq $sid) {
1355 &$func ($volid, $sid, $info);
1356 } else {
1357 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1358 }
1359 }
1360 }
1361}
1362
8898dd7b
FG
1363sub extract_vzdump_config_tar {
1364 my ($archive, $conf_re) = @_;
1365
1366 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1367
1368 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1369 die "unable to open file '$archive'\n";
1370
1371 my $file;
1372 while (defined($file = <$fh>)) {
086c4bf1 1373 if ($file =~ $conf_re) {
8898dd7b
FG
1374 $file = $1; # untaint
1375 last;
1376 }
1377 }
1378
1379 kill 15, $pid;
1380 waitpid $pid, 0;
1381 close $fh;
1382
1383 die "ERROR: archive contains no configuration file\n" if !$file;
1384 chomp $file;
1385
1386 my $raw = '';
1387 my $out = sub {
1388 my $output = shift;
1389 $raw .= "$output\n";
1390 };
1391
1392 PVE::Tools::run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
1393
1394 return wantarray ? ($raw, $file) : $raw;
1395}
1396
1397sub extract_vzdump_config_vma {
1398 my ($archive, $comp) = @_;
1399
1400 my $cmd;
1401 my $raw = '';
1402 my $out = sub {
1403 my $output = shift;
1404 $raw .= "$output\n";
1405 };
1406
1407
1408 if ($comp) {
1409 my $uncomp;
1410 if ($comp eq 'gz') {
1411 $uncomp = ["zcat", $archive];
1412 } elsif ($comp eq 'lzo') {
1413 $uncomp = ["lzop", "-d", "-c", $archive];
1414 } else {
1415 die "unknown compression method '$comp'\n";
1416 }
1417 $cmd = [$uncomp, ["vma", "config", "-"]];
1418
1419 # in some cases, lzop/zcat exits with 1 when its stdout pipe is
1420 # closed early by vma, detect this and ignore the exit code later
1421 my $broken_pipe;
1422 my $errstring;
1423 my $err = sub {
1424 my $output = shift;
1425 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/) {
1426 $broken_pipe = 1;
1427 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1428 $errstring = "Failed to extract config from VMA archive: $output\n";
1429 }
1430 };
1431
1432 # in other cases, the pipeline will exit with exit code 141
1433 # because of the broken pipe, handle / ignore this as well
1434 my $rc;
1435 eval {
1436 $rc = PVE::Tools::run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1);
1437 };
1438 my $rerr = $@;
1439
1440 # use exit code if no stderr output and not just broken pipe
fc1089fc 1441 if (!$errstring && !$broken_pipe && $rc != 0 && $rc != 141) {
8898dd7b
FG
1442 die "$rerr\n" if $rerr;
1443 die "config extraction failed with exit code $rc\n";
1444 }
1445 die "$errstring\n" if $errstring;
1446 } else {
1447 # simple case without compression and weird piping behaviour
1448 PVE::Tools::run_command(["vma", "config", $archive], outfunc => $out);
1449 }
1450
1451 return wantarray ? ($raw, undef) : $raw;
1452}
1453
1454sub extract_vzdump_config {
1455 my ($cfg, $volid) = @_;
1456
1457 my $archive = abs_filesystem_path($cfg, $volid);
1458
89443394 1459 if ($volid =~ /vzdump-(lxc|openvz)-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|(tar(\.(gz|lzo))?))$/) {
086c4bf1 1460 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
89443394 1461 } elsif ($volid =~ /vzdump-qemu-\d+-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?))$/) {
8898dd7b
FG
1462 my $format;
1463 my $comp;
1464 if ($7 eq 'tgz') {
1465 $format = 'tar';
1466 $comp = 'gz';
1467 } else {
1468 $format = $9;
1469 $comp = $11 if defined($11);
1470 }
1471
1472 if ($format eq 'tar') {
1473 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1474 } else {
1475 return extract_vzdump_config_vma($archive, $comp);
1476 }
1477 } else {
1478 die "cannot determine backup guest type for backup archive '$volid'\n";
1479 }
1480}
1481
47f37b53
WB
1482sub volume_export {
1483 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1484
1485 my ($storeid, $volname) = parse_volume_id($volid, 1);
1486 die "cannot export volume '$volid'\n" if !$storeid;
1487 my $scfg = storage_config($cfg, $storeid);
1488 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1489 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1490 $snapshot, $base_snapshot, $with_snapshots);
1491}
1492
1493sub volume_import {
1494 my ($cfg, $fh, $volid, $format, $base_snapshot, $with_snapshots) = @_;
1495
1496 my ($storeid, $volname) = parse_volume_id($volid, 1);
1497 die "cannot import into volume '$volid'\n" if !$storeid;
1498 my $scfg = storage_config($cfg, $storeid);
1499 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1500 return $plugin->volume_import($scfg, $storeid, $fh, $volname, $format,
1501 $base_snapshot, $with_snapshots);
1502}
1503
d390328b
WB
1504sub volume_export_formats {
1505 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1506
1507 my ($storeid, $volname) = parse_volume_id($volid, 1);
1508 return if !$storeid;
1509 my $scfg = storage_config($cfg, $storeid);
1510 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1511 return $plugin->volume_export_formats($scfg, $storeid, $volname,
ae36189d
WB
1512 $snapshot, $base_snapshot,
1513 $with_snapshots);
d390328b
WB
1514}
1515
1516sub volume_import_formats {
1517 my ($cfg, $volid, $base_snapshot, $with_snapshots) = @_;
1518
1519 my ($storeid, $volname) = parse_volume_id($volid, 1);
1520 return if !$storeid;
1521 my $scfg = storage_config($cfg, $storeid);
1522 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1523 return $plugin->volume_import_formats($scfg, $storeid, $volname,
1524 $base_snapshot, $with_snapshots);
1525}
1526
1527sub volume_transfer_formats {
1528 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1529 my @export_formats = volume_export_formats($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1530 my @import_formats = volume_import_formats($cfg, $dst_volid, $base_snapshot, $with_snapshots);
1531 my %import_hash = map { $_ => 1 } @import_formats;
1532 my @common = grep { $import_hash{$_} } @export_formats;
1533 return @common;
1534}
1535
f7621c01
DM
1536# bash completion helper
1537
1538sub complete_storage {
746e530f 1539 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1540
746e530f 1541 my $cfg = PVE::Storage::config();
180c8b02 1542
746e530f 1543 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
f7621c01
DM
1544}
1545
1546sub complete_storage_enabled {
746e530f 1547 my ($cmdname, $pname, $cvalue) = @_;
f7621c01 1548
746e530f 1549 my $res = [];
f7621c01 1550
746e530f
DM
1551 my $cfg = PVE::Storage::config();
1552 foreach my $sid (keys %{$cfg->{ids}}) {
1553 next if !storage_check_enabled($cfg, $sid, undef, 1);
1554 push @$res, $sid;
1555 }
1556 return $res;
f7621c01
DM
1557}
1558
98437f4c
DM
1559sub complete_content_type {
1560 my ($cmdname, $pname, $cvalue) = @_;
1561
1562 return [qw(rootdir images vztmpl iso backup)];
1563}
1564
bf7aed26
DM
1565sub complete_volume {
1566 my ($cmdname, $pname, $cvalue) = @_;
1567
1568 my $cfg = config();
1569
1570 my $storage_list = complete_storage_enabled();
1571
b70b0c58
DM
1572 if ($cvalue =~ m/^([^:]+):/) {
1573 $storage_list = [ $1 ];
1574 } else {
1575 if (scalar(@$storage_list) > 1) {
1576 # only list storage IDs to avoid large listings
1577 my $res = [];
1578 foreach my $storeid (@$storage_list) {
1579 # Hack: simply return 2 artificial values, so that
1580 # completions does not finish
1581 push @$res, "$storeid:volname", "$storeid:...";
1582 }
1583 return $res;
1584 }
1585 }
1586
bf7aed26
DM
1587 my $res = [];
1588 foreach my $storeid (@$storage_list) {
1589 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
1590
1591 foreach my $item (@$vollist) {
1592 push @$res, $item->{volid};
1593 }
1594 }
1595
1596 return $res;
1597}
1598
9edb99a5
WB
1599# Various io-heavy operations require io/bandwidth limits which can be
1600# configured on multiple levels: The global defaults in datacenter.cfg, and
1601# per-storage overrides. When we want to do a restore from storage A to storage
1602# B, we should take the smaller limit defined for storages A and B, and if no
1603# such limit was specified, use the one from datacenter.cfg.
1604sub get_bandwidth_limit {
1605 my ($operation, $storage_list, $override) = @_;
1606
1607 # called for each limit (global, per-storage) with the 'default' and the
1608 # $operation limit and should udpate $override for every limit affecting
1609 # us.
1610 my $use_global_limits = 0;
1611 my $apply_limit = sub {
1612 my ($bwlimit) = @_;
1613 if (defined($bwlimit)) {
1614 my $limits = PVE::JSONSchema::parse_property_string('bwlimit', $bwlimit);
1615 my $limit = $limits->{$operation} // $limits->{default};
1616 if (defined($limit)) {
1617 if (!$override || $limit < $override) {
1618 $override = $limit;
1619 }
1620 return;
1621 }
1622 }
1623 # If there was no applicable limit, try to apply the global ones.
1624 $use_global_limits = 1;
1625 };
1626
77445e9b
WB
1627 my ($rpcenv, $authuser);
1628 if (defined($override)) {
1629 $rpcenv = PVE::RPCEnvironment->get();
1630 $authuser = $rpcenv->get_user();
1631 }
9edb99a5
WB
1632
1633 # Apply per-storage limits - if there are storages involved.
1634 if (@$storage_list) {
1635 my $config = config();
1636
1637 # The Datastore.Allocate permission allows us to modify the per-storage
1638 # limits, therefore it also allows us to override them.
1639 # Since we have most likely multiple storages to check, do a quick check on
1640 # the general '/storage' path to see if we can skip the checks entirely:
77445e9b 1641 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
9edb99a5
WB
1642
1643 my %done;
1644 foreach my $storage (@$storage_list) {
1645 # Avoid duplicate checks:
1646 next if $done{$storage};
1647 $done{$storage} = 1;
1648
1649 # Otherwise we may still have individual /storage/$ID permissions:
77445e9b 1650 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
9edb99a5
WB
1651 # And if not: apply the limits.
1652 my $storecfg = storage_config($config, $storage);
1653 $apply_limit->($storecfg->{bwlimit});
1654 }
1655 }
1656
1657 # Storage limits take precedence over the datacenter defaults, so if
1658 # a limit was applied:
1659 return $override if !$use_global_limits;
1660 }
1661
1662 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
1663 # global default limits.
77445e9b 1664 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
9edb99a5
WB
1665 # So if we cannot modify global limits, apply them to our currently
1666 # requested override.
1667 my $dc = cfs_read_file('datacenter.cfg');
1668 $apply_limit->($dc->{bwlimit});
1669 }
1670
1671 return $override;
1672}
1673
76c1e57b 1674# checks if the storage id is available and dies if not
9280153e
TL
1675sub assert_sid_unused {
1676 my ($sid) = @_;
76c1e57b
DC
1677
1678 my $cfg = config();
9280153e
TL
1679 if (my $scfg = storage_config($cfg, $sid, 1)) {
1680 die "storage ID '$sid' already defined\n";
76c1e57b
DC
1681 }
1682
1683 return undef;
1684}
1685
b6cf0a66 16861;