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