summaryrefslogtreecommitdiff
path: root/lib/Loadbars/Config.pm
blob: 365d8c6fc76e43baaf32566bcfe93beb2abb690c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package Loadbars::Config;

use strict;
use warnings;

use Loadbars::Utils;
use Loadbars::Shared;

sub read () {
    return unless -f Loadbars::Constants->CONFFILE;

    display_info(
        "Reading configuration from " . Loadbars::Constants->CONFFILE );
    open my $conffile, Loadbars::Constants->CONFFILE
      or die "$!: " . Loadbars::Constants->CONFFILE . "\n";

    while (<$conffile>) {
        chomp;
        s/[\t\s]*?#.*//;

        next unless length;

        my ( $key, $val ) = split '=';

        unless ( defined $val ) {
            display_warn("Could not parse config line: $_");
            next;
        }

        trim($key);
        trim($val);

        if ( not exists $C{$key} ) {
            display_warn("There is no such config key: $key, ignoring");

        }
        else {
            display_info(
"Setting $key=$val, it might be overwritten by command line params."
            );
            $C{$key} = $val;
        }
    }

    close $conffile;
}

sub write () {
    display_warn( "Overwriting config file " . Loadbars::Constants->CONFFILE )
      if -f Loadbars::Constants->CONFFILE;

    open my $conffile, '>', Loadbars::Constants->CONFFILE or do {
        display_warn( "$!: " . Loadbars::Constants->CONFFILE );

        return undef;
    };

    for ( grep !/title/, keys %C ) {
        print $conffile "$_=$C{$_}\n";
    }

    close $conffile;
}

# Recursuve function
sub get_cluster_hosts ($;$);

sub get_cluster_hosts ($;$) {
    my ( $cluster, $recursion ) = @_;

    unless ( defined $recursion ) {
        $recursion = 1;

    }
    elsif ( $recursion > Loadbars::Constants->CSSH_MAX_RECURSION ) {
        error(  "CSSH_MAX_RECURSION reached. Infinite circle loop in "
              . Loadbars::Constants->CSSH_CONFFILE
              . "?" );
    }

    open my $fh, Loadbars::Constants->CSSH_CONFFILE
      or error( "$!: " . Loadbars::Constants->CSSH_CONFFILE );
    my $hosts;

    while (<$fh>) {
        if (/^$cluster\s*(.*)/) {
            $hosts = $1;
            last;
        }
    }

    close $fh;

    unless ( defined $hosts ) {
        error(  "No such cluster in "
              . Loadbars::Constants->CSSH_CONFFILE
              . ": $cluster" )
          unless defined $recursion;

        return ($cluster);
    }

    my @hosts;
    push @hosts, get_cluster_hosts $_, ( $recursion + 1 )
      for ( split /\s+/, $hosts );

    return @hosts;
}

1;