summaryrefslogtreecommitdiffstats
path: root/lib/Smokeping/Master.pm
blob: 4a5cd909fa86082eebdad61f7b532fc7a6bae746 (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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# -*- perl -*-
package Smokeping::Master;
use Data::Dumper;
use Storable qw(nstore dclone retrieve);
use strict;
use warnings;
use Fcntl qw(:flock);
use Digest::MD5 qw(md5_base64);

=head1 NAME

Smokeping::Master - Master Functionality for Smokeping

=head1 OVERVIEW

This module handles all special functionality required by smokeping running
in master mode.

=head2 IMPLEMENTATION

=head3 slave_cfg=extract_config(cfg,slave)

Extract the relevant configuration information for the selected slave. The
configuration will only contain the information that is relevant for the
slave. Any parameters overwritten in the B<Slaves> section of the configuration
file will be patched for the slave.

=cut

sub get_targets;
sub get_targets {
    my $trg = shift;
    my $slave = shift;
    my %return;
    my $ok;
    foreach my $key (keys %{$trg}){
        # dynamic hosts can only be queried from the
        # master
        next if $key eq 'host' and $trg->{$key} eq 'DYNAMIC';
        next if $key eq 'host' and $trg->{$key} =~ m|^/|; # skip multi targets
        next if $key eq 'host' and not ( defined $trg->{slaves} and $trg->{slaves} =~ /\b${slave}\b/);
        if (ref $trg->{$key} eq 'HASH'){
            $return{$key} = get_targets ($trg->{$key},$slave);
            $ok = 1 if defined $return{$key};
        } else {
            $ok = 1 if $key eq 'host';
            $return{$key} = $trg->{$key};
        }
    }    
    return ($ok ? \%return : undef);
}
    
sub extract_config {
    my $cfg = shift;
    my $slave = shift;
    # get relevant Targets
    my %slave_config;
    $slave_config{Database} = dclone $cfg->{Database}; 
    $slave_config{General}  = dclone $cfg->{General};
    $slave_config{Probes}   = dclone $cfg->{Probes};
    $slave_config{Targets}  = get_targets($cfg->{Targets},$slave);
    $slave_config{__last}   = $cfg->{__last};
    if ($cfg->{Slaves} and $cfg->{Slaves}{$slave} and $cfg->{Slaves}{$slave}{override}){
        for my $override (keys %{$cfg->{Slaves}{$slave}{override}}){
            my $node = \%slave_config;
            my @keys = split /\./, $override;
            my $last_key = pop @keys;
            for my $key (@keys){
                $node->{$key} = {}
                    unless $node->{$key} and ref $node->{$key} eq 'HASH';
                $node = $node->{$key};
            }
            $node->{$last_key} = $cfg->{Slaves}{$slave}{override}{$override};
        }
    }
    if ($slave_config{Targets}){
        return Dumper \%slave_config;
    } else {
        return undef;
    }
}

=head3 save_updates (updates)

When the cgi gets updates from a client, these updates are saved away, for
each 'target' so that the updates can be integrated into the relevant rrd
database by the rrd daemon as the next round of updates is processed. This
two stage process is chosen so that all results flow through the same code
path in the daemon.

=cut

sub save_updates {
    my $cfg = shift;
    my $slave = shift;
    my $updates = shift;
    # name\ttime\tupdatestring
    # name\ttime\tupdatestring
    for my $update (split /\n/, $updates){
        my ($name, $time, $updatestring) = split /\t/, $update;
        my $file = $cfg->{General}{datadir}."/${name}.slave_cache";
        if ( ! -f $cfg->{General}{datadir}."/${name}.rrd" ){
            warn "Skipping update for ${name}.slave_cache since ".
                 "$cfg->{General}{datadir}/${name}.rrd  does not exist ".
                 " in the local data structure. Make sure you run the ".
                 "smokeping daemon. ($cfg->{General}{datadir})\n";
        } 
        elsif ( open (my $lock, '>>' , "$file.lock") ) {
            for (my $i = 10; $i > 0; $i--){
                if ( flock $lock, LOCK_EX ){
                    my $existing = [];
	            if ( -r $file ){
                        my $in = eval { retrieve $file };
                        if ($@) { #error
                            warn "Loading $file: $@";
                        } else {
		            $existing = $in;
			};
                    };
                    push @{$existing}, [ $slave, $time, $updatestring];
                    nstore($existing, $file);		    
                    last;
                } else {
                    warn "Could not lock $file. Trying again for $i rounds.\n";
                    sleep rand(3);
                }
            }
            close $lock;
        } else {
            warn "Could not update $file: $!";
        }
    }         
};

=head3 get_slaveupdates

Read in all updates provided by slaves and return an array reference.

=cut

sub get_slaveupdates {
    my $name = shift;
    my $file = $name.".slave_cache";
    my $data;
    if ( -r $file and open (my $lock, '>>', "$file.lock") ) {
        if ( flock $lock, LOCK_EX ){
            eval { $data = retrieve $file };
            unlink $file;
            if ($@) { #error
                warn "Loading $file: $@";  
                return undef;
            }
        } else {
            warn "Could not lock $file. Will skip and try again in the next round. No harm done!\n";
        }
        close $lock;        
        return $data;
    }
    return;
}


=head3 get_secret

Read the secrtes file and figure the secret for the slave which is talking to us.

=cut

sub get_secret {
    my $cfg = shift;
    my $slave = shift;
    if (open my $hand, "<", $cfg->{Slaves}{secrets}){
        while (<$hand>){
            next unless /^${slave}:(\S+)/;
            close $hand;
            return $1;
        }
    } 
    warn "WARNING: Opening $cfg->{Slaves}{secrets}: $!\n";    
    return;
}

=head3 answer_slave

Answer the requests from the slave by accepting the data, verifying the secrets
and providing updated config information if necessary.

=cut

sub answer_slave {
    my $cfg = shift;
    my $q = shift;
    my $slave = $q->param('slave');
    my $secret = get_secret($cfg,$slave);
    if (not $secret){
        print "Content-Type: text/plain\n\n";
        print "WARNING: No secret found for slave ${slave}\n";       
        return;
    }
    my $key = $q->param('key');
    my $data = $q->param('data');
    my $config_time = $q->param('config_time');
    if (not ref $cfg->{Slaves}{$slave} eq 'HASH'){
        print "Content-Type: text/plain\n\n";
        print "WARNING: I don't know the slave ${slave} ignoring it";
        return;
    }
    # lets make sure the we share a secret
    if (md5_base64($secret.$data) eq $key){
        save_updates $cfg, $slave, $data;
    } else {
        print "Content-Type: text/plain\n\n";
        print "WARNING: Data from $slave was signed with $key which does not match our expectation\n";
        return;
    }     
    # does the client need new config ?
    if ($config_time < $cfg->{__last}){
        my $config = extract_config $cfg, $slave;    
        if ($config){
            print "Content-Type: application/smokeping-config\n";
            print "Key: ".md5_base64($secret.$config)."\n\n";
            print $config;
        } else {
            print "Content-Type: text/plain\n\n";
            print "WARNING: No targets found for slave '$slave'\n";
            return;
        }
    } else {
        print "Content-Type: text/plain\n\nOK\n";
    };       
    return;
}   


1;

__END__

=head1 COPYRIGHT

Copyright 2007 by Tobias Oetiker

=head1 LICENSE

This program is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the GNU General Public License for more
details.

You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA.

=head1 AUTHOR

Tobias Oetiker E<lt>tobi@oetiker.chE<gt>

=cut