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