root/trunk/perl/lib/Cornea/Config.pm

Revision 9, 1.9 kB (checked in by jesus, 5 years ago)

nodes appear to work

Line 
1 package Cornea::Config;
2 use strict;
3 use YAML;
4 use POSIX qw/uname/;
5 use Carp;
6
7 sub default_config_file { '/etc/cornea${host}.conf' }
8
9 {
10   my %_g_Config = ();
11   sub _g_Config {
12     my $key = shift;
13     $_g_Config{$key} = shift if @_;
14     $_g_Config{$key};
15   }
16   sub _g_Config_unset { my $key = shift; delete $_g_Config{$key}; }
17   sub _g_Config_isset { my $key = shift; exists $_g_Config{$key}; }
18 }
19
20 sub new {
21     my $class = shift;
22     $class->_init(@_) unless _g_Config_isset('config_file');
23     return bless sub { die "Illegal access"; }, __PACKAGE__;
24 }
25
26 sub _init {
27     my $class = shift;
28     my $config_file = shift || $class->default_config_file;
29     my @uname = POSIX::uname();
30     my $i = 0;
31     foreach (qw/sysname nodename release version machine/) {
32       _g_Config("sysinfo::$_", $uname[$i++]);
33     }
34
35     eval {
36         my $host = ".$uname[1]";
37         my $file = eval "\"$config_file\"";
38         $class->read_config($file);
39     };
40     return unless $@;
41
42     # There was an error, use the default config
43     my $host = '';
44     my $file = eval "\"$config_file\"";
45     $class->read_config($file);
46     return;
47 }
48
49 sub read_config {
50     my ($class, $file) = @_;
51     open(CONF, "<$file") || confess "Could not read config file: $file";
52     while(<CONF>) {
53         next if /^\s*[;#]/;
54         if(/^\s*([^\s=]+)\s*=\s*\[\s*(.*)\]\s*$/) {
55           my $key = lc($1);
56           (my $val = $2) =~ s/\s+$//;
57           _g_Config($key, [split /\s+/, $val]);
58         }
59         elsif(/^\s*([^\s=]+)\s*=\s*(.*)$/) {
60           my $key = lc($1);
61           (my $val = $2) =~ s/\s+$//;
62           _g_Config($key, $val);
63         }
64     }
65     close(CONF);
66     _g_Config('config_file', $file);
67 }
68
69 sub get { my $v = _g_Config(lc($_[1])); return (ref $v eq 'ARRAY') ? $v->[0] : $v; }
70 sub get_list { my $v = _g_Config(lc($_[1])); return (ref $v eq 'ARRAY') ? $v : [$v]; }
71 sub set { _g_Config(lc($_[1]), $_[2]); }
72 sub unset { _g_Config_unset(lc($_[1])); }
73 sub isset { _g_Config_isset(lc($_[1])); }
74
75 1;
76 1;
Note: See TracBrowser for help on using the browser.