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