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