]> git.proxmox.com Git - pve-storage.git/blame - PVE/Storage.pm
fix bug 44: allow to store vztmpl on NFS
[pve-storage.git] / PVE / Storage.pm
CommitLineData
b6cf0a66
DM
1package PVE::Storage;
2
3use strict;
4use POSIX;
5use IO::Select;
6use IO::Dir;
7use IO::File;
8use Fcntl ':flock';
9use File::stat;
10use File::Basename;
11use File::Path;
12use IPC::Open2;
13use Cwd 'abs_path';
14use Getopt::Long qw(GetOptionsFromArray);
15use Socket;
16use Digest::SHA1;
17use Net::Ping;
18
19use PVE::Tools qw(run_command file_read_firstline trim);
20use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
21use PVE::Exception qw(raise_param_exc);
22use PVE::JSONSchema;
23use PVE::INotify;
24
25my $ISCSIADM = '/usr/bin/iscsiadm';
26my $UDEVADM = '/sbin/udevadm';
27
28$ISCSIADM = undef if ! -X $ISCSIADM;
29
30# fixme: always_call_parser => 1 ??
31cfs_register_file ('storage.cfg',
32 \&parse_config,
33 \&write_config);
34
35# generic utility function
36
37sub config {
38 return cfs_read_file("storage.cfg");
39}
40
41sub check_iscsi_support {
42 my $noerr = shift;
43
44 if (!$ISCSIADM) {
45 my $msg = "no iscsi support - please install open-iscsi";
46 if ($noerr) {
47 warn "warning: $msg\n";
48 return 0;
49 }
50
51 die "error: $msg\n";
52 }
53
54 return 1;
55}
56
57sub load_stable_scsi_paths {
58
59 my $stable_paths = {};
60
61 my $stabledir = "/dev/disk/by-id";
62
63 if (my $dh = IO::Dir->new($stabledir)) {
64 while (defined(my $tmp = $dh->read)) {
65 # exclude filenames with part in name (same disk but partitions)
66 # use only filenames with scsi(with multipath i have the same device
67 # with dm-uuid-mpath , dm-name and scsi in name)
68 if($tmp !~ m/-part\d+$/ && $tmp =~ m/^scsi-/) {
69 my $path = "$stabledir/$tmp";
70 my $bdevdest = readlink($path);
71 if ($bdevdest && $bdevdest =~ m|^../../([^/]+)|) {
72 $stable_paths->{$1}=$tmp;
73 }
74 }
75 }
76 $dh->close;
77 }
78 return $stable_paths;
79}
80
81sub dir_glob_regex {
82 my ($dir, $regex) = @_;
83
84 my $dh = IO::Dir->new ($dir);
85 return wantarray ? () : undef if !$dh;
86
87 while (defined(my $tmp = $dh->read)) {
88 if (my @res = $tmp =~ m/^($regex)$/) {
89 $dh->close;
90 return wantarray ? @res : $tmp;
91 }
92 }
93 $dh->close;
94
95 return wantarray ? () : undef;
96}
97
98sub dir_glob_foreach {
99 my ($dir, $regex, $func) = @_;
100
101 my $dh = IO::Dir->new ($dir);
102 if (defined $dh) {
103 while (defined(my $tmp = $dh->read)) {
104 if (my @res = $tmp =~ m/^($regex)$/) {
105 &$func (@res);
106 }
107 }
108 }
109}
110
111sub read_proc_mounts {
112
113 local $/; # enable slurp mode
114
115 my $data = "";
116 if (my $fd = IO::File->new ("/proc/mounts", "r")) {
117 $data = <$fd>;
118 close ($fd);
119 }
120
121 return $data;
122}
123
124# PVE::Storage utility functions
125
126sub lock_storage_config {
127 my ($code, $errmsg) = @_;
128
129 cfs_lock_file("storage.cfg", undef, $code);
130 my $err = $@;
131 if ($err) {
132 $errmsg ? die "$errmsg: $err" : die $err;
133 }
134}
135
136my $confvars = {
137 path => 'path',
138 shared => 'bool',
139 disable => 'bool',
140 format => 'format',
141 content => 'content',
142 server => 'server',
143 export => 'path',
144 vgname => 'vgname',
145 base => 'volume',
146 portal => 'portal',
147 target => 'target',
148 nodes => 'nodes',
149 options => 'options',
150};
151
152my $required_config = {
153 dir => ['path'],
154 nfs => ['path', 'server', 'export'],
155 lvm => ['vgname'],
156 iscsi => ['portal', 'target'],
157};
158
159my $fixed_config = {
160 dir => ['path'],
161 nfs => ['path', 'server', 'export'],
162 lvm => ['vgname', 'base'],
163 iscsi => ['portal', 'target'],
164};
165
166my $default_config = {
167 dir => {
168 path => 1,
169 nodes => 0,
170 shared => 0,
171 disable => 0,
172 content => [ { images => 1, rootdir => 1, vztmpl => 1, iso => 1, backup => 1, none => 1 },
173 { images => 1, rootdir => 1 }],
174 format => [ { raw => 1, qcow2 => 1, vmdk => 1 } , 'raw' ],
175 },
176
177 nfs => {
178 path => 1,
179 nodes => 0,
180 disable => 0,
181 server => 1,
182 export => 1,
183 options => 0,
c63913bf 184 content => [ { images => 1, rootdir => 1, vztmpl => 1, iso => 1, backup => 1},
b6cf0a66
DM
185 { images => 1 }],
186 format => [ { raw => 1, qcow2 => 1, vmdk => 1 } , 'raw' ],
187 },
188
189 lvm => {
190 vgname => 1,
191 nodes => 0,
192 shared => 0,
193 disable => 0,
194 content => [ {images => 1}, { images => 1 }],
195 base => 1,
196 },
197
198 iscsi => {
199 portal => 1,
200 target => 1,
201 nodes => 0,
202 disable => 0,
203 content => [ {images => 1, none => 1}, { images => 1 }],
204 },
205};
206
207sub valid_content_types {
208 my ($stype) = @_;
209
210 my $def = $default_config->{$stype};
211
212 return {} if !$def;
213
214 return $def->{content}->[0];
215}
216
217sub content_hash_to_string {
218 my $hash = shift;
219
220 my @cta;
221 foreach my $ct (keys %$hash) {
222 push @cta, $ct if $hash->{$ct};
223 }
224
225 return join(',', @cta);
226}
227
228PVE::JSONSchema::register_format('pve-storage-path', \&verify_path);
229sub verify_path {
230 my ($path, $noerr) = @_;
231
232 # fixme: exclude more shell meta characters?
233 # we need absolute paths
234 if ($path !~ m|^/[^;\(\)]+|) {
235 return undef if $noerr;
236 die "value does not look like a valid absolute path\n";
237 }
238 return $path;
239}
240
241PVE::JSONSchema::register_format('pve-storage-server', \&verify_server);
242sub verify_server {
243 my ($server, $noerr) = @_;
244
245 # fixme: use better regex ?
246 # IP or DNS name
247 if ($server !~ m/^[[:alnum:]\-\.]+$/) {
248 return undef if $noerr;
249 die "value does not look like a valid server name or IP address\n";
250 }
251 return $server;
252}
253
254PVE::JSONSchema::register_format('pve-storage-portal', \&verify_portal);
255sub verify_portal {
256 my ($portal, $noerr) = @_;
257
258 # IP with optional port
259 if ($portal !~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$/) {
260 return undef if $noerr;
261 die "value does not look like a valid portal address\n";
262 }
263 return $portal;
264}
265
266PVE::JSONSchema::register_format('pve-storage-portal-dns', \&verify_portal_dns);
267sub verify_portal_dns {
268 my ($portal, $noerr) = @_;
269
270 # IP or DNS name with optional port
271 if ($portal !~ m/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|[[:alnum:]\-\.]+)(:\d+)?$/) {
272 return undef if $noerr;
273 die "value does not look like a valid portal address\n";
274 }
275 return $portal;
276}
277
278PVE::JSONSchema::register_format('pve-storage-content', \&verify_content);
279sub verify_content {
280 my ($ct, $noerr) = @_;
281
282 my $valid_content = valid_content_types('dir'); # dir includes all types
283
284 if (!$valid_content->{$ct}) {
285 return undef if $noerr;
286 die "invalid content type '$ct'\n";
287 }
288
289 return $ct;
290}
291
292PVE::JSONSchema::register_format('pve-storage-format', \&verify_format);
293sub verify_format {
294 my ($fmt, $noerr) = @_;
295
296 if ($fmt !~ m/(raw|qcow2|vmdk)/) {
297 return undef if $noerr;
298 die "invalid format '$fmt'\n";
299 }
300
301 return $fmt;
302}
303
304PVE::JSONSchema::register_format('pve-storage-options', \&verify_options);
305sub verify_options {
306 my ($value, $noerr) = @_;
307
308 # mount options (see man fstab)
309 if ($value !~ m/^\S+$/) {
310 return undef if $noerr;
311 die "invalid options '$value'\n";
312 }
313
314 return $value;
315}
316
317sub check_type {
318 my ($stype, $ct, $key, $value, $storeid, $noerr) = @_;
319
320 my $def = $default_config->{$stype};
321
322 if (!$def) { # should not happen
323 return undef if $noerr;
324 die "unknown storage type '$stype'\n";
325 }
326
327 if (!defined($def->{$key})) {
328 return undef if $noerr;
329 die "unexpected property\n";
330 }
331
332 if (!defined ($value)) {
333 return undef if $noerr;
334 die "got undefined value\n";
335 }
336
337 if ($value =~ m/[\n\r]/) {
338 return undef if $noerr;
339 die "property contains a line feed\n";
340 }
341
342 if ($ct eq 'bool') {
343 return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i);
344 return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i);
345 return undef if $noerr;
346 die "type check ('boolean') failed - got '$value'\n";
347 } elsif ($ct eq 'options') {
348 return verify_options($value, $noerr);
349 } elsif ($ct eq 'path') {
350 return verify_path($value, $noerr);
351 } elsif ($ct eq 'server') {
352 return verify_server($value, $noerr);
353 } elsif ($ct eq 'vgname') {
354 return parse_lvm_name ($value, $noerr);
355 } elsif ($ct eq 'portal') {
356 return verify_portal($value, $noerr);
357 } elsif ($ct eq 'nodes') {
358 my $res = {};
359
360 foreach my $node (PVE::Tools::split_list($value)) {
361 if (PVE::JSONSchema::pve_verify_node_name($node, $noerr)) {
362 $res->{$node} = 1;
363 }
364 }
365
366 # no node restrictions for local storage
367 if ($storeid && $storeid eq 'local' && scalar(keys(%$res))) {
368 return undef if $noerr;
369 die "storage '$storeid' does not allow node restrictions\n";
370 }
371
372 return $res;
373 } elsif ($ct eq 'target') {
374 return $value;
375 } elsif ($ct eq 'string') {
376 return $value;
377 } elsif ($ct eq 'format') {
378 my $valid_formats = $def->{format}->[0];
379
380 if (!$valid_formats->{$value}) {
381 return undef if $noerr;
382 die "storage does not support format '$value'\n";
383 }
384
385 return $value;
386
387 } elsif ($ct eq 'content') {
388 my $valid_content = $def->{content}->[0];
389
390 my $res = {};
391
392 foreach my $c (PVE::Tools::split_list($value)) {
393 if (!$valid_content->{$c}) {
394 return undef if $noerr;
395 die "storage does not support content type '$c'\n";
396 }
397 $res->{$c} = 1;
398 }
399
6a4d7398 400 if ($res->{none} && scalar (keys %$res) > 1) {
b6cf0a66 401 return undef if $noerr;
6a4d7398 402 die "unable to combine 'none' with other content types\n";
b6cf0a66
DM
403 }
404
b6cf0a66
DM
405 return $res;
406 } elsif ($ct eq 'volume') {
407 return $value if parse_volume_id ($value, $noerr);
408 }
409
410 return undef if $noerr;
411 die "type check not implemented - internal error\n";
412}
413
414sub parse_config {
415 my ($filename, $raw) = @_;
416
417 my $ids = {};
418
6c64928f 419 my $digest = Digest::SHA1::sha1_hex(defined($raw) ? $raw : '');
b6cf0a66
DM
420
421 my $pri = 0;
422
423 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
424 my $line = $1;
425
b6cf0a66
DM
426 next if $line =~ m/^\#/;
427 next if $line =~ m/^\s*$/;
428
429 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
430 my $storeid = $2;
431 my $type = $1;
432 my $ignore = 0;
433
434 if (!parse_storage_id ($storeid, 1)) {
435 $ignore = 1;
436 warn "ignoring storage '$storeid' - (illegal characters)\n";
437 } elsif (!$default_config->{$type}) {
438 $ignore = 1;
439 warn "ignoring storage '$storeid' (unsupported type '$type')\n";
440 } else {
441 $ids->{$storeid}->{type} = $type;
442 $ids->{$storeid}->{priority} = $pri++;
443 }
444
445 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
446 $line = $1;
447
448 next if $line =~ m/^\#/;
449 last if $line =~ m/^\s*$/;
450
451 next if $ignore; # skip
452
453 if ($line =~ m/^\s+(\S+)(\s+(.*\S))?\s*$/) {
454 my ($k, $v) = ($1, $3);
455 if (my $ct = $confvars->{$k}) {
456 $v = 1 if $ct eq 'bool' && !defined($v);
457 eval {
458 $ids->{$storeid}->{$k} = check_type ($type, $ct, $k, $v, $storeid);
459 };
460 warn "storage '$storeid' - unable to parse value of '$k': $@" if $@;
461 } else {
462 warn "storage '$storeid' - unable to parse value of '$k'\n";
463 }
464
465 } else {
466 warn "storage '$storeid' - ignore config line: $line\n";
467 }
468 }
469 } else {
470 warn "ignore config line: $line\n";
471 }
472 }
473
474 # make sure we have a reasonable 'local:' storage
475 # openvz expects things to be there
476 if (!$ids->{local} || $ids->{local}->{type} ne 'dir' ||
477 $ids->{local}->{path} ne '/var/lib/vz') {
478 $ids->{local} = {
479 type => 'dir',
480 priority => $pri++,
481 path => '/var/lib/vz',
482 content => { images => 1, rootdir => 1, vztmpl => 1, iso => 1},
483 };
484 }
485
486 # we always need this for OpenVZ
487 $ids->{local}->{content}->{rootdir} = 1;
488 $ids->{local}->{content}->{vztmpl} = 1;
489 delete ($ids->{local}->{disable});
490
491 # remove node restrictions for local storage
492 delete($ids->{local}->{nodes});
493
494 foreach my $storeid (keys %$ids) {
495 my $d = $ids->{$storeid};
496
497 my $req_keys = $required_config->{$d->{type}};
498 foreach my $k (@$req_keys) {
499 if (!defined ($d->{$k})) {
500 warn "ignoring storage '$storeid' - missing value " .
501 "for required option '$k'\n";
502 delete $ids->{$storeid};
503 next;
504 }
505 }
506
507 my $def = $default_config->{$d->{type}};
508
509 if ($def->{content}) {
510 $d->{content} = $def->{content}->[1] if !$d->{content};
511 }
512
513 if ($d->{type} eq 'iscsi' || $d->{type} eq 'nfs') {
514 $d->{shared} = 1;
515 }
516 }
517
b6cf0a66
DM
518 my $cfg = { ids => $ids, digest => $digest};
519
520 return $cfg;
521}
522
523sub parse_options {
524 my ($storeid, $stype, $param, $create) = @_;
525
526 my $settings = { type => $stype };
527
528 die "unknown storage type '$stype'\n"
529 if !$default_config->{$stype};
530
531 foreach my $opt (keys %$param) {
532 my $value = $param->{$opt};
533
534 my $ct = $confvars->{$opt};
535 if (defined($value)) {
536 eval {
537 $settings->{$opt} = check_type ($stype, $ct, $opt, $value, $storeid);
538 };
539 raise_param_exc({ $opt => $@ }) if $@;
540 } else {
541 raise_param_exc({ $opt => "got undefined value" });
542 }
543 }
544
545 if ($create) {
546 my $req_keys = $required_config->{$stype};
547 foreach my $k (@$req_keys) {
548
549 if ($stype eq 'nfs' && !$settings->{path}) {
550 $settings->{path} = "/mnt/pve/$storeid";
551 }
552
553 # check if we have a value for all required options
554 if (!defined ($settings->{$k})) {
555 raise_param_exc({ $k => "property is missing and it is not optional" });
556 }
557 }
558 } else {
559 my $fixed_keys = $fixed_config->{$stype};
560 foreach my $k (@$fixed_keys) {
561
562 # only allow to change non-fixed values
563
564 if (defined ($settings->{$k})) {
565 raise_param_exc({$k => "can't change value (fixed parameter)"});
566 }
567 }
568 }
569
570 return $settings;
571}
572
573sub cluster_lock_storage {
574 my ($storeid, $shared, $timeout, $func, @param) = @_;
575
576 my $res;
577 if (!$shared) {
578 my $lockid = "pve-storage-$storeid";
579 my $lockdir = "/var/lock/pve-manager";
580 mkdir $lockdir;
581 $res = PVE::Tools::lock_file("$lockdir/$lockid", $timeout, $func, @param);
582 die $@ if $@;
583 } else {
584 $res = PVE::Cluster::cfs_lock_storage($storeid, $timeout, $func, @param);
585 die $@ if $@;
586 }
587 return $res;
588}
589
590sub storage_config {
591 my ($cfg, $storeid, $noerr) = @_;
592
593 die "no storage id specified\n" if !$storeid;
594
595 my $scfg = $cfg->{ids}->{$storeid};
596
597 die "storage '$storeid' does not exists\n" if (!$noerr && !$scfg);
598
599 return $scfg;
600}
601
602sub storage_check_node {
603 my ($cfg, $storeid, $node, $noerr) = @_;
604
605 my $scfg = storage_config ($cfg, $storeid);
606
607 if ($scfg->{nodes}) {
608 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
609 if (!$scfg->{nodes}->{$node}) {
610 die "storage '$storeid' is not available on node '$node'" if !$noerr;
611 return undef;
612 }
613 }
614
615 return $scfg;
616}
617
618sub storage_check_enabled {
619 my ($cfg, $storeid, $node, $noerr) = @_;
620
621 my $scfg = storage_config ($cfg, $storeid);
622
623 if ($scfg->{disable}) {
624 die "storage '$storeid' is disabled\n" if !$noerr;
625 return undef;
626 }
627
628 return storage_check_node($cfg, $storeid, $node, $noerr);
629}
630
631sub storage_ids {
632 my ($cfg) = @_;
633
634 my $ids = $cfg->{ids};
635
636 my @sa = sort {$ids->{$a}->{priority} <=> $ids->{$b}->{priority}} keys %$ids;
637
638 return @sa;
639}
640
641sub assert_if_modified {
642 my ($cfg, $digest) = @_;
643
644 if ($digest && ($cfg->{digest} ne $digest)) {
645 die "detected modified storage configuration - try again\n";
646 }
647}
648
649sub sprint_config_line {
650 my ($k, $v) = @_;
651
652 my $ct = $confvars->{$k};
653
654 if ($ct eq 'bool') {
655 return $v ? "\t$k\n" : '';
656 } elsif ($ct eq 'nodes') {
657 my $nlist = join(',', keys(%$v));
658 return $nlist ? "\tnodes $nlist\n" : '';
659 } elsif ($ct eq 'content') {
660 my $clist = content_hash_to_string($v);
661 if ($clist) {
662 return "\t$k $clist\n";
663 } else {
664 return "\t$k none\n";
665 }
666 } else {
667 return "\t$k $v\n";
668 }
669}
670
671sub write_config {
672 my ($filename, $cfg) = @_;
673
674 my $out = '';
675
676 my $ids = $cfg->{ids};
677
678 my $maxpri = 0;
679 foreach my $storeid (keys %$ids) {
680 my $pri = $ids->{$storeid}->{priority};
681 $maxpri = $pri if $pri && $pri > $maxpri;
682 }
683 foreach my $storeid (keys %$ids) {
684 if (!defined ($ids->{$storeid}->{priority})) {
685 $ids->{$storeid}->{priority} = ++$maxpri;
686 }
687 }
688
689 foreach my $storeid (sort {$ids->{$a}->{priority} <=> $ids->{$b}->{priority}} keys %$ids) {
690 my $scfg = $ids->{$storeid};
691 my $type = $scfg->{type};
692 my $def = $default_config->{$type};
693
694 die "unknown storage type '$type'\n" if !$def;
695
696 my $data = "$type: $storeid\n";
697
698 $data .= "\tdisable\n" if $scfg->{disable};
699
700 my $done_hash = { disable => 1};
701 foreach my $k (@{$required_config->{$type}}) {
702 $done_hash->{$k} = 1;
703 my $v = $ids->{$storeid}->{$k};
704 die "storage '$storeid' - missing value for required option '$k'\n"
705 if !defined ($v);
706 $data .= sprint_config_line ($k, $v);
707 }
708
709 foreach my $k (keys %$def) {
710 next if defined ($done_hash->{$k});
711 if (defined (my $v = $ids->{$storeid}->{$k})) {
712 $data .= sprint_config_line ($k, $v);
713 }
714 }
715
716 $out .= "$data\n";
717 }
718
719 return $out;
720}
721
722sub get_image_dir {
723 my ($cfg, $storeid, $vmid) = @_;
724
725 my $path = $cfg->{ids}->{$storeid}->{path};
726 return $vmid ? "$path/images/$vmid" : "$path/images";
727}
728
d22a6133
DM
729sub get_private_dir {
730 my ($cfg, $storeid, $vmid) = @_;
731
732 my $path = $cfg->{ids}->{$storeid}->{path};
733 return $vmid ? "$path/private/$vmid" : "$path/private";
734}
735
b6cf0a66
DM
736sub get_iso_dir {
737 my ($cfg, $storeid) = @_;
738
739 my $isodir = $cfg->{ids}->{$storeid}->{path};
6a4d7398 740 $isodir .= '/template/iso';
b6cf0a66
DM
741
742 return $isodir;
743}
744
745sub get_vztmpl_dir {
746 my ($cfg, $storeid) = @_;
747
748 my $tmpldir = $cfg->{ids}->{$storeid}->{path};
6a4d7398 749 $tmpldir .= '/template/cache';
b6cf0a66
DM
750
751 return $tmpldir;
752}
753
568de3d1
DM
754sub get_backup_dir {
755 my ($cfg, $storeid) = @_;
756
757 my $dir = $cfg->{ids}->{$storeid}->{path};
6a4d7398 758 $dir .= '/dump';
568de3d1
DM
759
760 return $dir;
761}
762
b6cf0a66
DM
763# iscsi utility functions
764
765sub iscsi_session_list {
766
767 check_iscsi_support ();
768
769 my $cmd = [$ISCSIADM, '--mode', 'session'];
770
771 my $res = {};
772
773 run_command ($cmd, outfunc => sub {
774 my $line = shift;
775
776 if ($line =~ m/^tcp:\s+\[(\S+)\]\s+\S+\s+(\S+)\s*$/) {
777 my ($session, $target) = ($1, $2);
778 # there can be several sessions per target (multipath)
779 push @{$res->{$target}}, $session;
780
781 }
782 });
783
784 return $res;
785}
786
787sub iscsi_test_portal {
788 my ($portal) = @_;
789
790 my ($server, $port) = split(':', $portal);
791 my $p = Net::Ping->new("tcp", 2);
792 $p->port_number($port || 3260);
793 return $p->ping($server);
794}
795
796sub iscsi_discovery {
797 my ($portal) = @_;
798
799 check_iscsi_support ();
800
801 my $cmd = [$ISCSIADM, '--mode', 'discovery', '--type', 'sendtargets',
802 '--portal', $portal];
803
804 my $res = {};
805
806 return $res if !iscsi_test_portal($portal); # fixme: raise exception here?
807
808 run_command ($cmd, outfunc => sub {
809 my $line = shift;
810
811 if ($line =~ m/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+)\,\S+\s+(\S+)\s*$/) {
812 my $portal = $1;
813 my $target = $2;
814 # one target can have more than one portal (multipath).
815 push @{$res->{$target}}, $portal;
816 }
817 });
818
819 return $res;
820}
821
822sub iscsi_login {
823 my ($target, $portal_in) = @_;
824
825 check_iscsi_support ();
826
827 eval { iscsi_discovery ($portal_in); };
828 warn $@ if $@;
829
830 my $cmd = [$ISCSIADM, '--mode', 'node', '--targetname', $target, '--login'];
831 run_command ($cmd);
832}
833
834sub iscsi_logout {
835 my ($target, $portal) = @_;
836
837 check_iscsi_support ();
838
839 my $cmd = [$ISCSIADM, '--mode', 'node', '--targetname', $target, '--logout'];
840 run_command ($cmd);
841}
842
843my $rescan_filename = "/var/run/pve-iscsi-rescan.lock";
844
845sub iscsi_session_rescan {
846 my $session_list = shift;
847
848 check_iscsi_support ();
849
850 my $rstat = stat ($rescan_filename);
851
852 if (!$rstat) {
853 if (my $fh = IO::File->new ($rescan_filename, "a")) {
854 utime undef, undef, $fh;
855 close ($fh);
856 }
857 } else {
858 my $atime = $rstat->atime;
859 my $tdiff = time() - $atime;
860 # avoid frequent rescans
861 return if !($tdiff < 0 || $tdiff > 10);
862 utime undef, undef, $rescan_filename;
863 }
864
865 foreach my $session (@$session_list) {
866 my $cmd = [$ISCSIADM, '--mode', 'session', '-r', $session, '-R'];
867 eval { run_command ($cmd, outfunc => sub {}); };
868 warn $@ if $@;
869 }
870}
871
872sub iscsi_device_list {
873
874 my $res = {};
875
876 my $dirname = '/sys/class/iscsi_session';
877
878 my $stable_paths = load_stable_scsi_paths();
879
880 dir_glob_foreach ($dirname, 'session(\d+)', sub {
881 my ($ent, $session) = @_;
882
883 my $target = file_read_firstline ("$dirname/$ent/targetname");
884 return if !$target;
885
886 my (undef, $host) = dir_glob_regex ("$dirname/$ent/device", 'target(\d+):.*');
887 return if !defined($host);
888
889 dir_glob_foreach ("/sys/bus/scsi/devices", "$host:" . '(\d+):(\d+):(\d+)', sub {
890 my ($tmp, $channel, $id, $lun) = @_;
891
892 my $type = file_read_firstline ("/sys/bus/scsi/devices/$tmp/type");
893 return if !defined($type) || $type ne '0'; # list disks only
894
895 my $bdev;
896 if (-d "/sys/bus/scsi/devices/$tmp/block") { # newer kernels
897 (undef, $bdev) = dir_glob_regex ("/sys/bus/scsi/devices/$tmp/block/", '([A-Za-z]\S*)');
898 } else {
899 (undef, $bdev) = dir_glob_regex ("/sys/bus/scsi/devices/$tmp", 'block:(\S+)');
900 }
901 return if !$bdev;
902
903 #check multipath
904 if (-d "/sys/block/$bdev/holders") {
905 my $multipathdev = dir_glob_regex ("/sys/block/$bdev/holders", '[A-Za-z]\S*');
906 $bdev = $multipathdev if $multipathdev;
907 }
908
909 my $blockdev = $stable_paths->{$bdev};
910 return if !$blockdev;
911
912 my $size = file_read_firstline ("/sys/block/$bdev/size");
913 return if !$size;
914
915 my $volid = "$channel.$id.$lun.$blockdev";
916
917 $res->{$target}->{$volid} = {
918 'format' => 'raw',
919 'size' => int($size / 2),
920 'vmid' => 0, # not assigned to any vm
921 'channel' => int($channel),
922 'id' => int($id),
923 'lun' => int($lun),
924 };
925
926 #print "TEST: $target $session $host,$bus,$tg,$lun $blockdev\n";
927 });
928
929 });
930
931 return $res;
932}
933
934# library implementation
935
936
937PVE::JSONSchema::register_format('pve-storage-id', \&parse_storage_id);
938sub parse_storage_id {
939 my ($storeid, $noerr) = @_;
940
941 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
942 return undef if $noerr;
943 die "storage ID '$storeid' contains illegal characters\n";
944 }
945 return $storeid;
946}
947
948PVE::JSONSchema::register_standard_option('pve-storage-id', {
949 description => "The storage identifier.",
950 type => 'string', format => 'pve-storage-id',
951});
952
953PVE::JSONSchema::register_format('pve-storage-vgname', \&parse_lvm_name);
954sub parse_lvm_name {
955 my ($name, $noerr) = @_;
956
957 if ($name !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
958 return undef if $noerr;
959 die "lvm name '$name' contains illegal characters\n";
960 }
961
962 return $name;
963}
964
965sub parse_vmid {
966 my $vmid = shift;
967
968 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
969
970 return int($vmid);
971}
972
973PVE::JSONSchema::register_format('pve-volume-id', \&parse_volume_id);
974sub parse_volume_id {
975 my ($volid, $noerr) = @_;
976
977 if ($volid =~ m/^([a-z][a-z0-9\-\_\.]*[a-z0-9]):(.+)$/i) {
978 return wantarray ? ($1, $2) : $1;
979 }
980 return undef if $noerr;
981 die "unable to parse volume ID '$volid'\n";
982}
983
984sub parse_name_dir {
985 my $name = shift;
986
987 if ($name =~ m!^([^/\s]+\.(raw|qcow2|vmdk))$!) {
988 return ($1, $2);
989 }
990
991 die "unable to parse volume filename '$name'\n";
992}
993
994sub parse_volname_dir {
995 my $volname = shift;
996
997 if ($volname =~ m!^(\d+)/(\S+)$!) {
998 my ($vmid, $name) = ($1, $2);
999 parse_name_dir ($name);
1000 return ('image', $name, $vmid);
1001 } elsif ($volname =~ m!^iso/([^/]+\.[Ii][Ss][Oo])$!) {
1002 return ('iso', $1);
1003 } elsif ($volname =~ m!^vztmpl/([^/]+\.tar\.gz)$!) {
1004 return ('vztmpl', $1);
1ac17c74
DM
1005 } elsif ($volname =~ m!^rootdir/(\d+)$!) {
1006 return ('rootdir', $1, $1);
1007 } elsif ($volname =~ m!^backup/([^/]+(\.tar|\.tgz))$!) {
686e1d03
DM
1008 return ('backup', $1);
1009 }
b6cf0a66
DM
1010 die "unable to parse directory volume name '$volname'\n";
1011}
1012
1013sub parse_volname_lvm {
1014 my $volname = shift;
1015
1016 parse_lvm_name ($volname);
1017
1018 if ($volname =~ m/^(vm-(\d+)-\S+)$/) {
1019 return ($1, $2);
1020 }
1021
1022 die "unable to parse lvm volume name '$volname'\n";
1023}
1024
1025sub parse_volname_iscsi {
1026 my $volname = shift;
1027
1028 if ($volname =~ m!^\d+\.\d+\.\d+\.(\S+)$!) {
1029 my $byid = $1;
1030 return $byid;
1031 }
1032
1033 die "unable to parse iscsi volume name '$volname'\n";
1034}
1035
1036# try to map a filesystem path to a volume identifier
1037sub path_to_volume_id {
1038 my ($cfg, $path) = @_;
1039
1040 my $ids = $cfg->{ids};
1041
1042 my ($sid, $volname) = parse_volume_id ($path, 1);
1043 if ($sid) {
1044 if ($ids->{$sid} && (my $type = $ids->{$sid}->{type})) {
1045 if ($type eq 'dir' || $type eq 'nfs') {
1046 my ($vtype, $name, $vmid) = parse_volname_dir ($volname);
1047 return ($vtype, $path);
1048 }
1049 }
1050 return ('');
1051 }
1052
1053 $path = abs_path ($path);
1054
1055 foreach my $sid (keys %$ids) {
1056 my $type = $ids->{$sid}->{type};
1057 next if !($type eq 'dir' || $type eq 'nfs');
1058
568de3d1
DM
1059 my $imagedir = get_image_dir($cfg, $sid);
1060 my $isodir = get_iso_dir($cfg, $sid);
1061 my $tmpldir = get_vztmpl_dir($cfg, $sid);
1062 my $backupdir = get_backup_dir($cfg, $sid);
1ac17c74 1063 my $privatedir = get_private_dir($cfg, $sid);
b6cf0a66
DM
1064
1065 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
1066 my $vmid = $1;
1067 my $name = $2;
1068 return ('image', "$sid:$vmid/$name");
1069 } elsif ($path =~ m!^$isodir/([^/]+\.[Ii][Ss][Oo])$!) {
1070 my $name = $1;
1071 return ('iso', "$sid:iso/$name");
1072 } elsif ($path =~ m!^$tmpldir/([^/]+\.tar\.gz)$!) {
1073 my $name = $1;
1074 return ('vztmpl', "$sid:vztmpl/$name");
1ac17c74
DM
1075 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
1076 my $vmid = $1;
1077 return ('rootdir', "$sid:rootdir/$vmid");
568de3d1
DM
1078 } elsif ($path =~ m!^$backupdir/([^/]+\.(tar|tgz))$!) {
1079 my $name = $1;
1080 return ('iso', "$sid:backup/$name");
b6cf0a66
DM
1081 }
1082 }
1083
1084 # can't map path to volume id
1085 return ('');
1086}
1087
1088sub path {
1089 my ($cfg, $volid) = @_;
1090
1091 my ($storeid, $volname) = parse_volume_id ($volid);
1092
1093 my $scfg = storage_config ($cfg, $storeid);
1094
1095 my $path;
1096 my $owner;
1097
1098 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
1099 my ($vtype, $name, $vmid) = parse_volname_dir ($volname);
1100 $owner = $vmid;
1101
568de3d1
DM
1102 my $imagedir = get_image_dir($cfg, $storeid, $vmid);
1103 my $isodir = get_iso_dir($cfg, $storeid);
1104 my $tmpldir = get_vztmpl_dir($cfg, $storeid);
1105 my $backupdir = get_backup_dir($cfg, $storeid);
1ac17c74 1106 my $privatedir = get_private_dir($cfg, $storeid);
b6cf0a66
DM
1107
1108 if ($vtype eq 'image') {
1109 $path = "$imagedir/$name";
1110 } elsif ($vtype eq 'iso') {
1111 $path = "$isodir/$name";
1112 } elsif ($vtype eq 'vztmpl') {
1113 $path = "$tmpldir/$name";
1ac17c74
DM
1114 } elsif ($vtype eq 'rootdir') {
1115 $path = "$privatedir/$name";
568de3d1
DM
1116 } elsif ($vtype eq 'backup') {
1117 $path = "$backupdir/$name";
b6cf0a66
DM
1118 } else {
1119 die "should not be reached";
1120 }
1121
1122 } elsif ($scfg->{type} eq 'lvm') {
1123
1124 my $vg = $scfg->{vgname};
1125
1126 my ($name, $vmid) = parse_volname_lvm ($volname);
1127 $owner = $vmid;
1128
1129 $path = "/dev/$vg/$name";
1130
1131 } elsif ($scfg->{type} eq 'iscsi') {
1132 my $byid = parse_volname_iscsi ($volname);
1133 $path = "/dev/disk/by-id/$byid";
1134 } else {
1135 die "unknown storage type '$scfg->{type}'";
1136 }
1137
1138 return wantarray ? ($path, $owner) : $path;
1139}
1140
1141sub storage_migrate {
1142 my ($cfg, $volid, $target_host, $target_storeid, $target_volname) = @_;
1143
1144 my ($storeid, $volname) = parse_volume_id ($volid);
1145 $target_volname = $volname if !$target_volname;
1146
1147 my $scfg = storage_config ($cfg, $storeid);
1148
1149 # no need to migrate shared content
1150 return if $storeid eq $target_storeid && $scfg->{shared};
1151
1152 my $tcfg = storage_config ($cfg, $target_storeid);
1153
1154 my $target_volid = "${target_storeid}:${target_volname}";
1155
1156 my $errstr = "unable to migrate '$volid' to '${target_volid}' on host '$target_host'";
1157
1158 # blowfish is a fast block cipher, much faster then 3des
1159 my $sshoptions = "-c blowfish -o 'BatchMode=yes'";
1160 my $ssh = "/usr/bin/ssh $sshoptions";
1161
1162 local $ENV{RSYNC_RSH} = $ssh;
1163
1164 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
1165 if ($tcfg->{type} eq 'dir' || $tcfg->{type} eq 'nfs') {
1166
1167 my $src = path ($cfg, $volid);
1168 my $dst = path ($cfg, $target_volid);
1169
1170 my $dirname = dirname ($dst);
1171
1172 if ($tcfg->{shared}) { # we can do a local copy
1173
1174 run_command (['/bin/mkdir', '-p', $dirname]);
1175
1176 run_command (['/bin/cp', $src, $dst]);
1177
1178 } else {
1179
1180 run_command (['/usr/bin/ssh', "root\@${target_host}",
1181 '/bin/mkdir', '-p', $dirname]);
1182
1183 # we use rsync with --sparse, so we can't use --inplace,
1184 # so we remove file on the target if it already exists to
1185 # save space
1186 my ($size, $format) = file_size_info($src);
1187 if ($format && ($format eq 'raw') && $size) {
1188 run_command (['/usr/bin/ssh', "root\@${target_host}",
1189 'rm', '-f', $dst],
1190 outfunc => sub {});
1191 }
1192
1193 my $cmd = ['/usr/bin/rsync', '--progress', '--sparse', '--whole-file',
1194 $src, "root\@${target_host}:$dst"];
1195
1196 my $percent = -1;
1197
1198 run_command ($cmd, outfunc => sub {
1199 my $line = shift;
1200
1201 if ($line =~ m/^\s*(\d+\s+(\d+)%\s.*)$/) {
1202 if ($2 > $percent) {
1203 $percent = $2;
1204 print "rsync status: $1\n";
1205 *STDOUT->flush();
1206 }
1207 } else {
1208 print "$line\n";
1209 *STDOUT->flush();
1210 }
1211 });
1212 }
1213
1214
1215 } else {
1216
1217 die "$errstr - target type '$tcfg->{type}' not implemented\n";
1218 }
1219
1220 } else {
1221 die "$errstr - source type '$scfg->{type}' not implemented\n";
1222 }
1223}
1224
1225sub vdisk_alloc {
1226 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
1227
1228 die "no storage id specified\n" if !$storeid;
1229
1230 parse_storage_id ($storeid);
1231
1232 my $scfg = storage_config ($cfg, $storeid);
1233
1234 die "no VMID specified\n" if !$vmid;
1235
1236 $vmid = parse_vmid ($vmid);
1237
1238 my $defformat = storage_default_format ($cfg, $storeid);
1239
1240 $fmt = $defformat if !$fmt;
1241
1242 activate_storage ($cfg, $storeid);
1243
1244 # lock shared storage
1245 return cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
1246
1247 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
1248
1249 my $imagedir = get_image_dir ($cfg, $storeid, $vmid);
1250
1251 mkpath $imagedir;
1252
1253 if (!$name) {
1254
1255 for (my $i = 1; $i < 100; $i++) {
1256 my @gr = <$imagedir/vm-$vmid-disk-$i.*>;
1257 if (!scalar(@gr)) {
1258 $name = "vm-$vmid-disk-$i.$fmt";
1259 last;
1260 }
1261 }
1262 }
1263
1264 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
1265 if !$name;
1266
1267 my (undef, $tmpfmt) = parse_name_dir ($name);
1268
1269 die "illegal name '$name' - wrong extension for format ('$tmpfmt != '$fmt')\n"
1270 if $tmpfmt ne $fmt;
1271
1272 my $path = "$imagedir/$name";
1273
1274 die "disk image '$path' already exists\n" if -f $path;
1275
1276 run_command("/usr/bin/qemu-img create -f $fmt '$path' ${size}K",
1277 errmsg => "unable to create image");
1278
1279 return "$storeid:$vmid/$name";
1280
1281 } elsif ($scfg->{type} eq 'lvm') {
1282
1283 die "unsupported format '$fmt'" if $fmt ne 'raw';
1284
1285 die "illegal name '$name' - sould be 'vm-$vmid-*'\n"
1286 if $name && $name !~ m/^vm-$vmid-/;
1287
1288 my $vgs = lvm_vgs ();
1289
1290 my $vg = $scfg->{vgname};
1291
1292 die "no such volume gruoup '$vg'\n" if !defined ($vgs->{$vg});
1293
1294 my $free = int ($vgs->{$vg}->{free});
1295
1296 die "not enough free space ($free < $size)\n" if $free < $size;
1297
1298 if (!$name) {
1299 my $lvs = lvm_lvs ($vg);
1300
1301 for (my $i = 1; $i < 100; $i++) {
1302 my $tn = "vm-$vmid-disk-$i";
1303 if (!defined ($lvs->{$vg}->{$tn})) {
1304 $name = $tn;
1305 last;
1306 }
1307 }
1308 }
1309
1310 die "unable to allocate an image name for VM $vmid in storage '$storeid'\n"
1311 if !$name;
1312
9dec0cb1 1313 my $cmd = ['/sbin/lvcreate', '-aly', '--addtag', "pve-vm-$vmid", '--size', "${size}k", '--name', $name, $vg];
b6cf0a66
DM
1314
1315 run_command ($cmd);
1316
1317 return "$storeid:$name";
1318
1319 } elsif ($scfg->{type} eq 'iscsi') {
1320 die "can't allocate space in iscsi storage\n";
1321 } else {
1322 die "unknown storage type '$scfg->{type}'";
1323 }
1324 });
1325}
1326
1327sub vdisk_free {
1328 my ($cfg, $volid) = @_;
1329
1330 my ($storeid, $volname) = parse_volume_id ($volid);
1331
1332 my $scfg = storage_config ($cfg, $storeid);
1333
1334 activate_storage ($cfg, $storeid);
1335
1336 # lock shared storage
1337 cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
1338
1339 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
1340 my $path = path ($cfg, $volid);
1341
1342 if (! -f $path) {
1343 warn "disk image '$path' does not exists\n";
1344 } else {
1345 unlink $path;
1346 }
1347 } elsif ($scfg->{type} eq 'lvm') {
1348
1349 my $vg = $scfg->{vgname};
1350
1351 my $cmd = ['/sbin/lvremove', '-f', "$vg/$volname"];
1352
1353 run_command ($cmd);
1354 } elsif ($scfg->{type} eq 'iscsi') {
1355 die "can't free space in iscsi storage\n";
1356 } else {
1357 die "unknown storage type '$scfg->{type}'";
1358 }
1359 });
1360}
1361
1362# lvm utility functions
1363
1364sub lvm_pv_info {
1365 my ($device) = @_;
1366
1367 die "no device specified" if !$device;
1368
1369 my $has_label = 0;
1370
1371 my $cmd = ['/usr/bin/file', '-L', '-s', $device];
1372 run_command ($cmd, outfunc => sub {
1373 my $line = shift;
1374 $has_label = 1 if $line =~ m/LVM2/;
1375 });
1376
1377 return undef if !$has_label;
1378
1379 $cmd = ['/sbin/pvs', '--separator', ':', '--noheadings', '--units', 'k',
1380 '--unbuffered', '--nosuffix', '--options',
1381 'pv_name,pv_size,vg_name,pv_uuid', $device];
1382
1383 my $pvinfo;
1384 run_command ($cmd, outfunc => sub {
1385 my $line = shift;
1386
1387 $line = trim($line);
1388
1389 my ($pvname, $size, $vgname, $uuid) = split (':', $line);
1390
1391 die "found multiple pvs entries for device '$device'\n"
1392 if $pvinfo;
1393
1394 $pvinfo = {
1395 pvname => $pvname,
1396 size => $size,
1397 vgname => $vgname,
1398 uuid => $uuid,
1399 };
1400 });
1401
1402 return $pvinfo;
1403}
1404
1405sub clear_first_sector {
1406 my ($dev) = shift;
1407
1408 if (my $fh = IO::File->new ($dev, "w")) {
1409 my $buf = 0 x 512;
1410 syswrite $fh, $buf;
1411 $fh->close();
1412 }
1413}
1414
1415sub lvm_create_volume_group {
1416 my ($device, $vgname, $shared) = @_;
1417
1418 my $res = lvm_pv_info ($device);
1419
1420 if ($res->{vgname}) {
1421 return if $res->{vgname} eq $vgname; # already created
1422 die "device '$device' is already used by volume group '$res->{vgname}'\n";
1423 }
1424
1425 clear_first_sector ($device); # else pvcreate fails
1426
1427 # we use --metadatasize 250k, which reseults in "pe_start = 512"
1428 # so pe_start is aligned on a 128k boundary (advantage for SSDs)
1429 my $cmd = ['/sbin/pvcreate', '--metadatasize', '250k', $device];
1430
1431 run_command ($cmd);
1432
1433 $cmd = ['/sbin/vgcreate', $vgname, $device];
1434 # push @$cmd, '-c', 'y' if $shared; # we do not use this yet
1435
1436 run_command ($cmd);
1437}
1438
1439sub lvm_vgs {
1440
1441 my $cmd = ['/sbin/vgs', '--separator', ':', '--noheadings', '--units', 'b',
1442 '--unbuffered', '--nosuffix', '--options',
1443 'vg_name,vg_size,vg_free'];
1444
1445 my $vgs = {};
1446 run_command ($cmd, outfunc => sub {
1447 my $line = shift;
1448
1449 $line = trim($line);
1450
1451 my ($name, $size, $free) = split (':', $line);
1452
1453 $vgs->{$name} = { size => int ($size), free => int ($free) };
1454 });
1455
1456 return $vgs;
1457}
1458
1459sub lvm_lvs {
1460 my ($vgname) = @_;
1461
1462 my $cmd = ['/sbin/lvs', '--separator', ':', '--noheadings', '--units', 'b',
1463 '--unbuffered', '--nosuffix', '--options',
1464 'vg_name,lv_name,lv_size,uuid,tags'];
1465
1466 push @$cmd, $vgname if $vgname;
1467
1468 my $lvs = {};
1469 run_command ($cmd, outfunc => sub {
1470 my $line = shift;
1471
1472 $line = trim($line);
1473
1474 my ($vg, $name, $size, $uuid, $tags) = split (':', $line);
1475
1476 return if $name !~ m/^vm-(\d+)-/;
1477 my $nid = $1;
1478
1479 my $owner;
1480 foreach my $tag (split (/,/, $tags)) {
1481 if ($tag =~ m/^pve-vm-(\d+)$/) {
1482 $owner = $1;
1483 last;
1484 }
1485 }
1486
1487 if ($owner) {
1488 if ($owner ne $nid) {
1489 warn "owner mismatch name = $name, owner = $owner\n";
1490 }
1491
1492 $lvs->{$vg}->{$name} = { format => 'raw', size => $size,
1493 uuid => $uuid, tags => $tags,
1494 vmid => $owner };
1495 }
1496 });
1497
1498 return $lvs;
1499}
1500
b6cf0a66
DM
1501#list iso or openvz template ($tt = <iso|vztmpl|backup>)
1502sub template_list {
1503 my ($cfg, $storeid, $tt) = @_;
1504
1505 die "unknown template type '$tt'\n" if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup');
1506
1507 my $ids = $cfg->{ids};
1508
1509 storage_check_enabled($cfg, $storeid) if ($storeid);
1510
1511 my $res = {};
1512
1513 # query the storage
1514
1515 foreach my $sid (keys %$ids) {
1516 next if $storeid && $storeid ne $sid;
1517
1518 my $scfg = $ids->{$sid};
1519 my $type = $scfg->{type};
1520
1521 next if !storage_check_enabled($cfg, $sid, undef, 1);
1522
1523 next if $tt eq 'iso' && !$scfg->{content}->{iso};
1524 next if $tt eq 'vztmpl' && !$scfg->{content}->{vztmpl};
1525 next if $tt eq 'backup' && !$scfg->{content}->{backup};
1526
1527 activate_storage ($cfg, $sid);
1528
1529 if ($type eq 'dir' || $type eq 'nfs') {
1530
1531 my $path;
1532 if ($tt eq 'iso') {
568de3d1 1533 $path = get_iso_dir($cfg, $sid);
b6cf0a66 1534 } elsif ($tt eq 'vztmpl') {
568de3d1 1535 $path = get_vztmpl_dir($cfg, $sid);
b6cf0a66 1536 } elsif ($tt eq 'backup') {
568de3d1 1537 $path = get_backup_dir($cfg, $sid);
b6cf0a66
DM
1538 } else {
1539 die "unknown template type '$tt'\n";
1540 }
1541
1542 foreach my $fn (<$path/*>) {
1543
1544 my $info;
1545
1546 if ($tt eq 'iso') {
1547 next if $fn !~ m!/([^/]+\.[Ii][Ss][Oo])$!;
1548
1549 $info = { volid => "$sid:iso/$1", format => 'iso' };
1550
1551 } elsif ($tt eq 'vztmpl') {
1552 next if $fn !~ m!/([^/]+\.tar\.gz)$!;
1553
1554 $info = { volid => "$sid:vztmpl/$1", format => 'tgz' };
1555
1556 } elsif ($tt eq 'backup') {
1557 next if $fn !~ m!/([^/]+\.(tar|tgz))$!;
1558
1559 $info = { volid => "$sid:backup/$1", format => $2 };
1560 }
1561
1562 $info->{size} = -s $fn;
1563
1564 push @{$res->{$sid}}, $info;
1565 }
1566
1567 }
1568
1569 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
1570 }
1571
1572 return $res;
1573}
1574
1575sub file_size_info {
1576 my ($filename, $timeout) = @_;
1577
1578 my $cmd = ['/usr/bin/qemu-img', 'info', $filename];
1579
1580 my $format;
1581 my $size = 0;
1582 my $used = 0;
1583
1584 eval {
1585 run_command ($cmd, timeout => $timeout, outfunc => sub {
1586 my $line = shift;
1587
1588 if ($line =~ m/^file format:\s+(\S+)\s*$/) {
1589 $format = $1;
1590 } elsif ($line =~ m/^virtual size:\s\S+\s+\((\d+)\s+bytes\)$/) {
1591 $size = int($1);
1592 } elsif ($line =~ m/^disk size:\s+(\d+(.\d+)?)([KMGT])\s*$/) {
1593 $used = $1;
1594 my $u = $3;
1595
1596 $used *= 1024 if $u eq 'K';
1597 $used *= (1024*1024) if $u eq 'M';
1598 $used *= (1024*1024*1024) if $u eq 'G';
1599 $used *= (1024*1024*1024*1024) if $u eq 'T';
1600
1601 $used = int($used);
1602 }
1603 });
1604 };
1605
1606 return wantarray ? ($size, $format, $used) : $size;
1607}
1608
1609sub vdisk_list {
1610 my ($cfg, $storeid, $vmid, $vollist) = @_;
1611
1612 my $ids = $cfg->{ids};
1613
1614 storage_check_enabled($cfg, $storeid) if ($storeid);
1615
1616 my $res = {};
1617
1618 # prepare/activate/refresh all storages
1619
1620 my $stypes = {};
1621
1622 my $storage_list = [];
1623 if ($vollist) {
1624 foreach my $volid (@$vollist) {
1625 my ($sid, undef) = parse_volume_id ($volid);
1626 next if !defined ($ids->{$sid});
1627 next if !storage_check_enabled($cfg, $sid, undef, 1);
1628 push @$storage_list, $sid;
1629 $stypes->{$ids->{$sid}->{type}} = 1;
1630 }
1631 } else {
1632 foreach my $sid (keys %$ids) {
1633 next if $storeid && $storeid ne $sid;
1634 next if !storage_check_enabled($cfg, $sid, undef, 1);
1635 push @$storage_list, $sid;
1636 $stypes->{$ids->{$sid}->{type}} = 1;
1637 }
1638 }
1639
1640 activate_storage_list ($cfg, $storage_list);
1641
1642 my $lvs = $stypes->{lvm} ? lvm_lvs () : {};
1643
1644 my $iscsi_devices = iscsi_device_list() if $stypes->{iscsi};
1645
1646 # query the storage
1647
1648 foreach my $sid (keys %$ids) {
1649 if ($storeid) {
1650 next if $storeid ne $sid;
1651 next if !storage_check_enabled($cfg, $sid, undef, 1);
1652 }
1653 my $scfg = $ids->{$sid};
1654 my $type = $scfg->{type};
1655
1656 if ($type eq 'dir' || $type eq 'nfs') {
1657
1658 my $path = $scfg->{path};
1659
1660 my $fmts = join ('|', keys %{$default_config->{$type}->{format}->[0]});
1661
1662 foreach my $fn (<$path/images/[0-9][0-9]*/*>) {
1663
1664 next if $fn !~ m!^(/.+/images/(\d+)/([^/]+\.($fmts)))$!;
1665 $fn = $1; # untaint
1666
1667 my $owner = $2;
1668 my $name = $3;
1669 my $volid = "$sid:$owner/$name";
1670
1671 if ($vollist) {
1672 my $found = grep { $_ eq $volid } @$vollist;
1673 next if !$found;
1674 } else {
1675 next if defined ($vmid) && ($owner ne $vmid);
1676 }
1677
1678 my ($size, $format, $used) = file_size_info ($fn);
1679
1680 if ($format && $size) {
1681 push @{$res->{$sid}}, {
1682 volid => $volid, format => $format,
1683 size => $size, vmid => $owner, used => $used };
1684 }
1685
1686 }
1687
1688 } elsif ($type eq 'lvm') {
1689
1690 my $vgname = $scfg->{vgname};
1691
1692 if (my $dat = $lvs->{$vgname}) {
1693
1694 foreach my $volname (keys %$dat) {
1695
1696 my $owner = $dat->{$volname}->{vmid};
1697
1698 my $volid = "$sid:$volname";
1699
1700 if ($vollist) {
1701 my $found = grep { $_ eq $volid } @$vollist;
1702 next if !$found;
1703 } else {
1704 next if defined ($vmid) && ($owner ne $vmid);
1705 }
1706
1707 my $info = $dat->{$volname};
1708 $info->{volid} = $volid;
1709
1710 push @{$res->{$sid}}, $info;
1711 }
1712 }
1713
1714 } elsif ($type eq 'iscsi') {
1715
1716 # we have no owner for iscsi devices
1717
1718 my $target = $scfg->{target};
1719
1720 if (my $dat = $iscsi_devices->{$target}) {
1721
1722 foreach my $volname (keys %$dat) {
1723
1724 my $volid = "$sid:$volname";
1725
1726 if ($vollist) {
1727 my $found = grep { $_ eq $volid } @$vollist;
1728 next if !$found;
1729 } else {
1730 next if !($storeid && ($storeid eq $sid));
1731 }
1732
1733 my $info = $dat->{$volname};
1734 $info->{volid} = $volid;
1735
1736 push @{$res->{$sid}}, $info;
1737 }
1738 }
1739
1740 } else {
1741 die "implement me";
1742 }
1743
1744 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
1745 }
1746
1747 return $res;
1748}
1749
1750sub nfs_is_mounted {
1751 my ($server, $export, $mountpoint, $mountdata) = @_;
1752
1753 my $source = "$server:$export";
1754
1755 $mountdata = read_proc_mounts() if !$mountdata;
1756
1757 if ($mountdata =~ m/^$source\s$mountpoint\snfs/m) {
1758 return $mountpoint;
1759 }
1760
1761 return undef;
1762}
1763
1764sub nfs_mount {
1765 my ($server, $export, $mountpoint, $options) = @_;
1766
1767 my $source = "$server:$export";
1768
1769 my $cmd = ['/bin/mount', '-t', 'nfs', $source, $mountpoint];
1770 if ($options) {
1771 push @$cmd, '-o', $options;
1772 }
1773
1774 run_command ($cmd);
1775}
1776
1777sub uevent_seqnum {
1778
1779 my $filename = "/sys/kernel/uevent_seqnum";
1780
1781 my $seqnum = 0;
1782 if (my $fh = IO::File->new ($filename, "r")) {
1783 my $line = <$fh>;
1784 if ($line =~ m/^(\d+)$/) {
1785 $seqnum = int ($1);
1786 }
1787 close ($fh);
1788 }
1789 return $seqnum;
1790}
1791
1792sub __activate_storage_full {
1793 my ($cfg, $storeid, $session) = @_;
1794
1795 my $scfg = storage_check_enabled($cfg, $storeid);
1796
1797 return if $session->{activated}->{$storeid};
1798
1799 if (!$session->{mountdata}) {
1800 $session->{mountdata} = read_proc_mounts();
1801 }
1802
1803 if (!$session->{uevent_seqnum}) {
1804 $session->{uevent_seqnum} = uevent_seqnum ();
1805 }
1806
1807 my $mountdata = $session->{mountdata};
1808
1809 my $type = $scfg->{type};
1810
1811 if ($type eq 'dir' || $type eq 'nfs') {
1812
1813 my $path = $scfg->{path};
1814
1815 if ($type eq 'nfs') {
1816 my $server = $scfg->{server};
1817 my $export = $scfg->{export};
1818
1819 if (!nfs_is_mounted ($server, $export, $path, $mountdata)) {
1820
1821 # NOTE: only call mkpath when not mounted (avoid hang
1822 # when NFS server is offline
1823
1824 mkpath $path;
1825
1826 die "unable to activate storage '$storeid' - " .
1827 "directory '$path' does not exist\n" if ! -d $path;
1828
1829 nfs_mount ($server, $export, $path, $scfg->{options});
1830 }
1831
1832 } else {
1833
1834 mkpath $path;
1835
1836 die "unable to activate storage '$storeid' - " .
1837 "directory '$path' does not exist\n" if ! -d $path;
1838 }
1839
568de3d1
DM
1840 my $imagedir = get_image_dir($cfg, $storeid);
1841 my $isodir = get_iso_dir($cfg, $storeid);
1842 my $tmpldir = get_vztmpl_dir($cfg, $storeid);
1843 my $backupdir = get_backup_dir($cfg, $storeid);
1ac17c74 1844 my $privatedir = get_private_dir($cfg, $storeid);
b6cf0a66
DM
1845
1846 if (defined($scfg->{content})) {
1847 mkpath $imagedir if $scfg->{content}->{images} &&
1848 $imagedir ne $path;
1849 mkpath $isodir if $scfg->{content}->{iso} &&
1850 $isodir ne $path;
1851 mkpath $tmpldir if $scfg->{content}->{vztmpl} &&
1852 $tmpldir ne $path;
1ac17c74
DM
1853 mkpath $privatedir if $scfg->{content}->{rootdir} &&
1854 $privatedir ne $path;
568de3d1
DM
1855 mkpath $backupdir if $scfg->{content}->{backup} &&
1856 $backupdir ne $path;
b6cf0a66
DM
1857 }
1858
1859 } elsif ($type eq 'lvm') {
1860
1861 if ($scfg->{base}) {
1862 my ($baseid, undef) = parse_volume_id ($scfg->{base});
1863 __activate_storage_full ($cfg, $baseid, $session);
1864 }
1865
1866 if (!$session->{vgs}) {
1867 $session->{vgs} = lvm_vgs();
1868 }
1869
1870 # In LVM2, vgscans take place automatically;
1871 # this is just to be sure
1872 if ($session->{vgs} && !$session->{vgscaned} &&
1873 !$session->{vgs}->{$scfg->{vgname}}) {
1874 $session->{vgscaned} = 1;
1875 my $cmd = ['/sbin/vgscan', '--ignorelockingfailure', '--mknodes'];
1876 eval { run_command ($cmd, outfunc => sub {}); };
1877 warn $@ if $@;
1878 }
1879
1880 my $cmd = ['/sbin/vgchange', '-aly', $scfg->{vgname}];
1881 run_command ($cmd, outfunc => sub {});
1882
1883 } elsif ($type eq 'iscsi') {
1884
1885 return if !check_iscsi_support(1);
1886
1887 $session->{iscsi_sessions} = iscsi_session_list()
1888 if !$session->{iscsi_sessions};
1889
1890 my $iscsi_sess = $session->{iscsi_sessions}->{$scfg->{target}};
1891 if (!defined ($iscsi_sess)) {
1892 eval { iscsi_login ($scfg->{target}, $scfg->{portal}); };
1893 warn $@ if $@;
1894 } else {
1895 # make sure we get all devices
1896 iscsi_session_rescan ($iscsi_sess);
1897 }
1898
1899 } else {
1900 die "implement me";
1901 }
1902
1903 my $newseq = uevent_seqnum ();
1904
1905 # only call udevsettle if there are events
1906 if ($newseq > $session->{uevent_seqnum}) {
1907 my $timeout = 30;
1908 system ("$UDEVADM settle --timeout=$timeout"); # ignore errors
1909 $session->{uevent_seqnum} = $newseq;
1910 }
1911
1912 $session->{activated}->{$storeid} = 1;
1913}
1914
1915sub activate_storage_list {
1916 my ($cfg, $storeid_list, $session) = @_;
1917
1918 $session = {} if !$session;
1919
1920 foreach my $storeid (@$storeid_list) {
1921 __activate_storage_full ($cfg, $storeid, $session);
1922 }
1923}
1924
1925sub activate_storage {
1926 my ($cfg, $storeid) = @_;
1927
1928 my $session = {};
1929
1930 __activate_storage_full ($cfg, $storeid, $session);
1931}
1932
1933sub activate_volumes {
1934 my ($cfg, $vollist) = @_;
1935
1936 my $storagehash = {};
1937 foreach my $volid (@$vollist) {
1938 my ($storeid, undef) = parse_volume_id ($volid);
1939 $storagehash->{$storeid} = 1;
1940 }
1941
1942 activate_storage_list ($cfg, [keys %$storagehash]);
1943
1944 foreach my $volid (@$vollist) {
1945 my ($storeid, $volname) = parse_volume_id ($volid);
1946
1947 my $scfg = storage_config ($cfg, $storeid);
1948
1949 my $path = path ($cfg, $volid);
1950
1951 if ($scfg->{type} eq 'lvm') {
1952 my $cmd = ['/sbin/lvchange', '-aly', $path];
1953 eval { run_command ($cmd); };
1954 warn $@ if $@;
1955 }
1956
1957 # check is volume exists
1958 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
1959 die "volume '$volid' does not exist\n" if ! -f $path;
1960 } else {
1961 die "volume '$volid' does not exist\n" if ! -b $path;
1962 }
1963 }
1964}
1965
1966sub deactivate_volumes {
1967 my ($cfg, $vollist) = @_;
1968
1969 my $lvs = lvm_lvs ();
1970
1971 foreach my $volid (@$vollist) {
1972 my ($storeid, $volname) = parse_volume_id ($volid);
1973
1974 my $scfg = storage_config ($cfg, $storeid);
1975
1976 if ($scfg->{type} eq 'lvm') {
1977 my ($name) = parse_volname_lvm ($volname);
1978
1979 if ($lvs->{$scfg->{vgname}}->{$name}) {
1980 my $path = path ($cfg, $volid);
1981 my $cmd = ['/sbin/lvchange', '-aln', $path];
1982 eval { run_command ($cmd); };
1983 warn $@ if $@;
1984 }
1985 }
1986 }
1987}
1988
1989sub deactivate_storage {
1990 my ($cfg, $storeid) = @_;
1991
1992 my $iscsi_sessions;
1993
1994 my $scfg = storage_config ($cfg, $storeid);
1995
1996 my $type = $scfg->{type};
1997
1998 if ($type eq 'dir') {
1999 # nothing to do
2000 } elsif ($type eq 'nfs') {
2001 my $mountdata = read_proc_mounts();
2002 my $server = $scfg->{server};
2003 my $export = $scfg->{export};
2004 my $path = $scfg->{path};
2005
2006 my $cmd = ['/bin/umount', $path];
2007
2008 run_command ($cmd) if nfs_is_mounted ($server, $export, $path, $mountdata);
2009 } elsif ($type eq 'lvm') {
2010 my $cmd = ['/sbin/vgchange', '-aln', $scfg->{vgname}];
2011 run_command ($cmd);
2012 } elsif ($type eq 'iscsi') {
2013 my $portal = $scfg->{portal};
2014 my $target = $scfg->{target};
2015
2016 my $iscsi_sessions = iscsi_session_list();
2017 iscsi_logout ($target, $portal)
2018 if defined ($iscsi_sessions->{$target});
2019
2020 } else {
2021 die "implement me";
2022 }
2023}
2024
2025sub storage_info {
2026 my ($cfg, $content) = @_;
2027
2028 my $ids = $cfg->{ids};
2029
2030 my $info = {};
2031 my $stypes = {};
2032
2033 my $slist = [];
2034 foreach my $storeid (keys %$ids) {
2035
2036 next if $content && !$ids->{$storeid}->{content}->{$content};
2037
2038 next if !storage_check_enabled($cfg, $storeid, undef, 1);
2039
2040 my $type = $ids->{$storeid}->{type};
2041
2042 $info->{$storeid} = {
2043 type => $type,
2044 total => 0,
2045 avail => 0,
2046 used => 0,
04a2e4f3 2047 shared => $ids->{$storeid}->{shared} ? 1 : 0,
b6cf0a66
DM
2048 content => content_hash_to_string($ids->{$storeid}->{content}),
2049 active => 0,
2050 };
2051
2052 $stypes->{$type} = 1;
2053
2054 push @$slist, $storeid;
2055 }
2056
2057 my $session = {};
2058 my $mountdata = '';
2059 my $iscsi_sessions = {};
2060 my $vgs = {};
2061
2062 if ($stypes->{lvm}) {
2063 $session->{vgs} = lvm_vgs();
2064 $vgs = $session->{vgs};
2065 }
2066 if ($stypes->{nfs}) {
2067 $mountdata = read_proc_mounts();
2068 $session->{mountdata} = $mountdata;
2069 }
2070 if ($stypes->{iscsi}) {
2071 $iscsi_sessions = iscsi_session_list();
2072 $session->{iscsi_sessions} = $iscsi_sessions;
2073 }
2074
2075 eval { activate_storage_list ($cfg, $slist, $session); };
2076
2077 foreach my $storeid (keys %$ids) {
2078 my $scfg = $ids->{$storeid};
2079
2080 next if !$info->{$storeid};
2081
2082 my $type = $scfg->{type};
2083
2084 if ($type eq 'dir' || $type eq 'nfs') {
2085
2086 my $path = $scfg->{path};
2087
2088 if ($type eq 'nfs') {
2089 my $server = $scfg->{server};
2090 my $export = $scfg->{export};
2091
2092 next if !nfs_is_mounted ($server, $export, $path, $mountdata);
2093 }
2094
2095 my $timeout = 2;
2096 my $res = PVE::Tools::df($path, $timeout);
2097
2098 next if !$res || !$res->{total};
2099
2100 $info->{$storeid}->{total} = $res->{total};
2101 $info->{$storeid}->{avail} = $res->{avail};
2102 $info->{$storeid}->{used} = $res->{used};
2103 $info->{$storeid}->{active} = 1;
2104
2105 } elsif ($type eq 'lvm') {
2106
2107 my $vgname = $scfg->{vgname};
2108
2109 my $total = 0;
2110 my $free = 0;
2111
2112 if (defined ($vgs->{$vgname})) {
2113 $total = $vgs->{$vgname}->{size};
2114 $free = $vgs->{$vgname}->{free};
2115
2116 $info->{$storeid}->{total} = $total;
2117 $info->{$storeid}->{avail} = $free;
2118 $info->{$storeid}->{used} = $total - $free;
2119 $info->{$storeid}->{active} = 1;
2120 }
2121
2122 } elsif ($type eq 'iscsi') {
2123
2124 $info->{$storeid}->{total} = 0;
2125 $info->{$storeid}->{avail} = 0;
2126 $info->{$storeid}->{used} = 0;
2127 $info->{$storeid}->{active} =
2128 defined ($iscsi_sessions->{$scfg->{target}});
2129
2130 } else {
2131 die "implement me";
2132 }
2133 }
2134
2135 return $info;
2136}
2137
2138sub resolv_server {
2139 my ($server) = @_;
2140
2141 my $packed_ip = gethostbyname($server);
2142 if (defined $packed_ip) {
2143 return inet_ntoa($packed_ip);
2144 }
2145 return undef;
2146}
2147
2148sub scan_nfs {
2149 my ($server_in) = @_;
2150
2151 my $server;
2152 if (!($server = resolv_server ($server_in))) {
2153 die "unable to resolve address for server '${server_in}'\n";
2154 }
2155
2156 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
2157
2158 my $res = {};
2159 run_command ($cmd, outfunc => sub {
2160 my $line = shift;
2161
2162 # note: howto handle white spaces in export path??
2163 if ($line =~ m!^(/\S+)\s+(.+)$!) {
2164 $res->{$1} = $2;
2165 }
2166 });
2167
2168 return $res;
2169}
2170
2171sub resolv_portal {
2172 my ($portal, $noerr) = @_;
2173
2174 if ($portal =~ m/^([^:]+)(:(\d+))?$/) {
2175 my $server = $1;
2176 my $port = $3;
2177
2178 if (my $ip = resolv_server($server)) {
2179 $server = $ip;
2180 return $port ? "$server:$port" : $server;
2181 }
2182 }
2183 return undef if $noerr;
2184
2185 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
2186}
2187
2188# idea is from usbutils package (/usr/bin/usb-devices) script
2189sub __scan_usb_device {
2190 my ($res, $devpath, $parent, $level) = @_;
2191
2192 return if ! -d $devpath;
2193 return if $level && $devpath !~ m/^.*[-.](\d+)$/;
2194 my $port = $level ? int($1 - 1) : 0;
2195
2196 my $busnum = int(file_read_firstline("$devpath/busnum"));
2197 my $devnum = int(file_read_firstline("$devpath/devnum"));
2198
2199 my $d = {
2200 port => $port,
2201 level => $level,
2202 busnum => $busnum,
2203 devnum => $devnum,
2204 speed => file_read_firstline("$devpath/speed"),
2205 class => hex(file_read_firstline("$devpath/bDeviceClass")),
2206 vendid => file_read_firstline("$devpath/idVendor"),
2207 prodid => file_read_firstline("$devpath/idProduct"),
2208 };
2209
2210 if ($level) {
2211 my $usbpath = $devpath;
2212 $usbpath =~ s|^.*/\d+\-||;
2213 $d->{usbpath} = $usbpath;
2214 }
2215
2216 my $product = file_read_firstline("$devpath/product");
2217 $d->{product} = $product if $product;
2218
2219 my $manu = file_read_firstline("$devpath/manufacturer");
2220 $d->{manufacturer} = $manu if $manu;
2221
2222 my $serial => file_read_firstline("$devpath/serial");
2223 $d->{serial} = $serial if $serial;
2224
2225 push @$res, $d;
2226
2227 foreach my $subdev (<$devpath/$busnum-*>) {
2228 next if $subdev !~ m|/$busnum-[0-9]+(\.[0-9]+)*$|;
2229 __scan_usb_device($res, $subdev, $devnum, $level + 1);
2230 }
2231
2232};
2233
2234sub scan_usb {
2235
2236 my $devlist = [];
2237
2238 foreach my $device (</sys/bus/usb/devices/usb*>) {
2239 __scan_usb_device($devlist, $device, 0, 0);
2240 }
2241
2242 return $devlist;
2243}
2244
2245sub scan_iscsi {
2246 my ($portal_in) = @_;
2247
2248 my $portal;
2249 if (!($portal = resolv_portal ($portal_in))) {
2250 die "unable to parse/resolve portal address '${portal_in}'\n";
2251 }
2252
2253 return iscsi_discovery($portal);
2254}
2255
2256sub storage_default_format {
2257 my ($cfg, $storeid) = @_;
2258
2259 my $scfg = storage_config ($cfg, $storeid);
2260
2261 my $def = $default_config->{$scfg->{type}};
2262
2263 my $def_format = 'raw';
2264 my $valid_formats = [ $def_format ];
2265
2266 if (defined ($def->{format})) {
2267 $def_format = $scfg->{format} || $def->{format}->[1];
2268 $valid_formats = [ sort keys %{$def->{format}->[0]} ];
2269 }
2270
2271 return wantarray ? ($def_format, $valid_formats) : $def_format;
2272}
2273
2274sub vgroup_is_used {
2275 my ($cfg, $vgname) = @_;
2276
2277 foreach my $storeid (keys %{$cfg->{ids}}) {
2278 my $scfg = storage_config ($cfg, $storeid);
2279 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
2280 return 1;
2281 }
2282 }
2283
2284 return undef;
2285}
2286
2287sub target_is_used {
2288 my ($cfg, $target) = @_;
2289
2290 foreach my $storeid (keys %{$cfg->{ids}}) {
2291 my $scfg = storage_config ($cfg, $storeid);
2292 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
2293 return 1;
2294 }
2295 }
2296
2297 return undef;
2298}
2299
2300sub volume_is_used {
2301 my ($cfg, $volid) = @_;
2302
2303 foreach my $storeid (keys %{$cfg->{ids}}) {
2304 my $scfg = storage_config ($cfg, $storeid);
2305 if ($scfg->{base} && $scfg->{base} eq $volid) {
2306 return 1;
2307 }
2308 }
2309
2310 return undef;
2311}
2312
2313sub storage_is_used {
2314 my ($cfg, $storeid) = @_;
2315
2316 foreach my $sid (keys %{$cfg->{ids}}) {
2317 my $scfg = storage_config ($cfg, $sid);
2318 next if !$scfg->{base};
2319 my ($st) = parse_volume_id ($scfg->{base});
2320 return 1 if $st && $st eq $storeid;
2321 }
2322
2323 return undef;
2324}
2325
2326sub foreach_volid {
2327 my ($list, $func) = @_;
2328
2329 return if !$list;
2330
2331 foreach my $sid (keys %$list) {
2332 foreach my $info (@{$list->{$sid}}) {
2333 my $volid = $info->{volid};
2334 my ($sid1, $volname) = parse_volume_id ($volid, 1);
2335 if ($sid1 && $sid1 eq $sid) {
2336 &$func ($volid, $sid, $info);
2337 } else {
2338 warn "detected strange volid '$volid' in volume list for '$sid'\n";
2339 }
2340 }
2341 }
2342}
2343
23441;