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