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