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