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