blib/lib/auto/share/dist/Beekeeper/dashboard/lib/Beekeeper/Service/Dashboard/Worker.pm untested

filter: Statementstmt 0.0% 0 / 287 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 37 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 442 SCAR 73.0
CC
38
Cov
0%
_consolidate
210.0
service_stats
72.0
login
56.0
CRAP 1482.0
1 package Beekeeper::Service::Dashboard::Worker;
2  
3 use strict;
4 use warnings;
5  
6 our $VERSION = '0.09';
7  
8 use Beekeeper::Worker ':log';
9 use base 'Beekeeper::Worker';
10  
11 use Beekeeper::Worker::Extension::RemoteSession;
12 use Beekeeper::Service::Supervisor;
13 use Beekeeper::Service::LogTail;
14 use Beekeeper::Config;
15  
16 use AnyEvent;
17 use JSON::XS;
18 use Scalar::Util 'weaken';
19 use Digest::SHA 'sha256_hex';
20 use Fcntl qw(:DEFAULT :flock);
21 use Time::HiRes;
22  
23 use constant AVERAGE => 0;
24 use constant MAXIMUM => 1;
25 use constant TOTAL => 2;
26 use constant COUNT => 3;
27 use constant TSTAMP => 0;
28 use constant STATS => 1;
29  
30  
31 sub authorize_request {
32 my ($self, $req) = @_;
33  
34 # Explicitly authorize the login method
35 return BKPR_REQUEST_AUTHORIZED if $req->{method} eq 'bkpr.dashboard.login';
36  
37 # Require an user logged in for any other request
38 return unless $self->get_authentication_data;
39  
40 return BKPR_REQUEST_AUTHORIZED;
41 }
42  
43 sub on_startup {
44 my ($self) = @_;
45  
46 my $config = Beekeeper::Config->read_config_file( 'dashboard.config.json' );
47 $self->{config} = $config || {};
48  
49 unless ($config) {
50 log_warn "Couldn't read config file 'dashboard.config.json'";
51 }
52  
53 unless ($config && $config->{users} && %{$config->{users}}) {
54 log_warn "No users defined into config file 'dashboard.config.json'";
55 }
56  
57 $self->accept_remote_calls(
58 'bkpr.dashboard.login' => 'login',
59 'bkpr.dashboard.services' => 'service_stats',
60 'bkpr.dashboard.logs' => 'log_tail',
61 );
62  
63 $self->_init_collector;
64  
65 log_info "Ready";
66 }
67  
68 sub on_shutdown {
69 my ($self) = @_;
70  
71 $self->_save_state;
72  
73 log_info "Stopped";
74 }
75  
76 sub stop_working {
77 my ($self) = @_;
78  
79 delete $self->{collect_tmr};
80 delete $self->{consolidate_5s_tmr};
81 delete $self->{consolidate_1m_tmr};
82  
83 $self->SUPER::stop_working;
84 }
85  
86 sub login {
87 my ($self, $params) = @_;
88  
89 my $username = $params->{username};
90 my $password = $params->{password};
91  
92 AUTH: {
93  
94 last unless defined $username;
95 last unless defined $password;
96  
97 my $users_cfg = $self->{config}->{users};
98 my $pwd_hash = sha256_hex('Dashboard'.$username.$password);
99  
100 last unless $users_cfg;
101 last unless $users_cfg->{$username};
102 last unless $users_cfg->{$username}->{'password'};
103 last unless $users_cfg->{$username}->{'password'} eq $pwd_hash;
104  
105 # Set authentication data and assign an address to the user
106 $self->set_authentication_data( $username );
107 $self->bind_remote_session( address => "frontend.dashboard-$username" );
108  
109 return 1;
110 }
111  
112 Beekeeper::JSONRPC::Error->request_not_authenticated;
113 }
114  
115 sub service_stats {
116 my ($self, $params) = @_;
117  
118 my $resol = $params->{'resolution'} || '1s';
119 my $count = $params->{'count'} || 1;
120 my $class = $params->{'class'};
121 my $after = $params->{'after'};
122  
123 my $stats = $self->{"services_$resol"} or die "Invalid resolution";
124  
125 my $idx = @$stats - $count;
126 $idx = 0 if $idx < 0;
127  
128 if ($after) {
129 my $min = $idx;
130 my $new_data;
131 for (my $i = @$stats - 1; $i >= 0; $i--) {
132 last if $stats->[$i]->[TSTAMP] <= $after;
133 last if $i < $min;
134 $new_data = $i;
135 }
136 return [] unless $new_data;
137 $idx = $new_data;
138 }
139  
140 unless ($class) {
141 return [ @$stats[$idx..(@$stats - 1)] ];
142 }
143  
144 my @svc_stats;
145  
146 foreach my $st (@$stats[$idx..(@$stats - 1)]) {
147 next unless exists $st->[STATS]->{$class};
148 push @svc_stats, [ $st->[TSTAMP], $st->[STATS]->{$class} ];
149 }
150  
151 return \@svc_stats;
152 }
153  
154 sub log_tail {
155 my ($self, $params, $req) = @_;
156  
157 my %filters;
158  
159 foreach my $filter (qw'service count level after host pool message') {
160 next unless $params->{$filter};
161 $filters{$filter} = $params->{$filter};
162 }
163  
164 $req->async_response;
165  
166 Beekeeper::Service::LogTail->tail_async(
167 %filters,
168 on_success => sub {
169 my ($resp) = @_;
170 $req->send_response( $resp->result );
171 },
172 on_error => sub {
173 my ($resp) = @_;
174 $req->send_response( $resp );
175 },
176 );
177 }
178  
179  
180 sub _init_collector {
181 my ($self) = @_;
182 weaken($self);
183  
184 $self->_load_state;
185  
186 $self->{services_1s} ||= [];
187 $self->{services_5s} ||= [];
188 $self->{services_2m} ||= [];
189 $self->{services_15m} ||= [];
190 $self->{services_1h} ||= [];
191  
192 my $now = Time::HiRes::time;
193 my $msec = $now - int($now);
194  
195 my $offs_1s = $msec;
196 my $offs_5s = $now % 5 + $msec;
197 my $offs_1m = $now % 60 + $msec;
198  
199 $self->{collect_tmr} = AnyEvent->timer(
200 after => 1 - $offs_1s,
201 interval => 1,
202 cb => sub {
203 Beekeeper::Service::Supervisor->get_services_status_async(
204 on_success => sub {
205 my ($resp) = @_;
206 $self->_collect_stats( $resp->result );
207 },
208 on_error => sub {
209 my ($error) = @_;
210 log_warn $error->message;
211 },
212 );
213 },
214 );
215  
216 $self->{consolidate_5s_tmr} = AnyEvent->timer(
217 after => 5 - $offs_5s,
218 interval => 5,
219 cb => sub {
220  
221 # 1 hour in 5 sec resolution
222 $self->_consolidate(
223 from => $self->{services_1s},
224 into => $self->{services_5s},
225 period => 5,
226 keep => 60 * 60/5, # 720
227 );
228 },
229 );
230  
231 $self->{consolidate_1m_tmr} = AnyEvent->timer(
232 after => 60 - $offs_1m,
233 interval => 60,
234 cb => sub {
235  
236 # 1 day in 2 min resolution
237 $self->_consolidate(
238 from => $self->{services_5s},
239 into => $self->{services_2m},
240 period => 2 * 60,
241 keep => 24 * 60/2, # 720
242 );
243  
244 # 1 week in 15 min resolution
245 $self->_consolidate(
246 from => $self->{services_2m},
247 into => $self->{services_15m},
248 period => 15 * 60,
249 keep => 7 * 24 * 60/15, # 672
250 );
251  
252 # 1 month in 1 hour resolution
253 $self->_consolidate(
254 from => $self->{services_15m},
255 into => $self->{services_1h},
256 period => 60 * 60,
257 keep => 31 * 24, # 744
258 );
259 },
260 );
261 }
262  
263 sub _collect_stats {
264 my ($self, $stats) = @_;
265  
266 my $now = int( time );
267 my $global = { load => 0 };
268  
269 foreach my $class (keys %$stats) {
270 foreach my $metric (keys %{$stats->{$class}}) {
271  
272 my $val = $stats->{$class}->{$metric};
273  
274 $stats->{$class}->{$metric} = [ $val, $val ];
275  
276 if ($metric eq 'load') {
277 # Global load is the load of the most stressed service
278 next unless $global->{load} < $val;
279 $global->{load} = $val;
280 }
281 else {
282 $global->{$metric} += $val;
283 }
284 }
285 }
286  
287 foreach my $metric (keys %$global) {
288 my $val = sprintf("%.2f", $global->{$metric});
289 $global->{$metric} = [ $val, $val ];
290 }
291  
292 $stats->{'_global'} = $global;
293  
294 my $services_1s = $self->{services_1s};
295 push @$services_1s, [ $now, $stats ];
296  
297 # 10 min in 1 sec resolution
298 shift @$services_1s if (@$services_1s >= 10 * 60);
299 }
300  
301 sub _consolidate {
302 my ($self, %args) = @_;
303  
304 my $stats_src = $args{'from'};
305 my $stats_dest = $args{'into'};
306 my $period = $args{'period'};
307 my $keep = $args{'keep'};
308 my $since;
309  
310 if (@$stats_dest) {
311 # Update last consolidated period
312 $since = $stats_dest->[-1]->[TSTAMP];
313 return if $stats_src->[-1]->[TSTAMP] < $since;
314 pop @$stats_dest;
315 }
316 elsif (@$stats_src) {
317 # Consolidate all data available
318 $since = $stats_src->[0]->[TSTAMP];
319 $since -= $since % $period;
320 }
321 else {
322 return;
323 }
324  
325 my $since_idx;
326 my $now = int( time );
327  
328 for (my $i = @$stats_src - 1; $i >= 0; $i--) {
329 last if $stats_src->[$i]->[TSTAMP] < $since;
330 $since_idx = $i;
331 }
332  
333 for (my $start = $since; $start <= $now; $start += $period) {
334  
335 my $end = $start + $period - 1;
336 $end = $now if ($end > $now);
337  
338 my $cons = {};
339  
340 for (my $i = $since_idx; $i < @$stats_src; $i++) {
341  
342 my $data_point = $stats_src->[$i];
343  
344 if ($data_point->[TSTAMP] < $start) {
345 next;
346 }
347 if ($data_point->[TSTAMP] > $end) {
348 last;
349 }
350  
351 my $stats = $data_point->[STATS];
352  
353 foreach my $class (keys %$stats) {
354 foreach my $metric (keys %{$stats->{$class}}) {
355  
356 my $src = $stats->{$class}->{$metric};
357 my $dest = $cons->{$class}->{$metric} ||= [];
358  
359 $dest->[TOTAL] += $src->[AVERAGE];
360 $dest->[COUNT]++;
361  
362 $dest->[MAXIMUM] = 0 unless defined $dest->[MAXIMUM];
363 if ($src->[MAXIMUM] > $dest->[MAXIMUM]) {
364 $dest->[MAXIMUM] = $src->[MAXIMUM];
365 }
366 }
367 }
368 }
369  
370 foreach my $class (keys %$cons) {
371 foreach my $metric (keys %{$cons->{$class}}) {
372  
373 my $dest = $cons->{$class}->{$metric};
374  
375 my ($total, $count) = splice(@$dest, TOTAL, COUNT);
376  
377 $dest->[MAXIMUM] = sprintf("%.2f", $dest->[MAXIMUM]);
378 $dest->[AVERAGE] = sprintf("%.2f", $total / $count);
379 }
380 }
381  
382 $cons->{global}->{load}->[MAXIMUM] = 0;
383 $cons->{global}->{load}->[AVERAGE] = 0;
384  
385 foreach my $class (keys %$cons) {
386  
387 next if ($class eq '_global');
388  
389 if ($cons->{global}->{load}->[MAXIMUM] < $cons->{$class}->{load}->[MAXIMUM]) {
390 $cons->{global}->{load}->[MAXIMUM] = $cons->{$class}->{load}->[MAXIMUM];
391 }
392 if ($cons->{global}->{load}->[AVERAGE] < $cons->{$class}->{load}->[AVERAGE]) {
393 $cons->{global}->{load}->[AVERAGE] = $cons->{$class}->{load}->[AVERAGE];
394 }
395 }
396  
397 push @$stats_dest, [ $start, $cons ];
398 }
399  
400 if (@$stats_dest > $keep) {
401 # Discard old data
402 shift @$stats_dest;
403 }
404 }
405  
406 sub _save_state {
407 my ($self) = @_;
408  
409 my $pool_id = $self->{_WORKER}->{pool_id};
410 ($pool_id) = ($pool_id =~ m/^([\w-]+)$/); # untaint
411 my $tmp_file = "/tmp/beekeeper-dashboard-$pool_id-stats.dump";
412  
413 # Avoid stampede when several workers are exiting simultaneously
414 return if (-e $tmp_file && (stat($tmp_file))[9] == time());
415  
416 # Lock file because several workers may try to write simultaneously to it
417 sysopen(my $fh, $tmp_file, O_RDWR|O_CREAT) or return;
418 flock($fh, LOCK_EX | LOCK_NB) or return;
419 truncate($fh, 0) or return;
420  
421 print $fh encode_json([
422 $self->{services_1s},
423 $self->{services_5s},
424 $self->{services_2m},
425 $self->{services_15m},
426 $self->{services_1h},
427 ]);
428  
429 close($fh);
430 }
431  
432 sub _load_state {
433 my ($self) = @_;
434  
435 my $pool_id = $self->{_WORKER}->{pool_id};
436 ($pool_id) = ($pool_id =~ m/^([\w-]+)$/); # untaint
437 my $tmp_file = "/tmp/beekeeper-dashboard-$pool_id-stats.dump";
438  
439 return unless (-e $tmp_file);
440  
441 local($/);
442 open(my $fh, '<', $tmp_file) or die "Couldn't read $tmp_file: $!";
443 my $data = <$fh>;
444 close($fh);
445  
446 local $@;
447 my $dump = eval { decode_json($data) };
448 return if $@;
449  
450 $self->{services_1s} = $dump->[0];
451 $self->{services_5s} = $dump->[1];
452 $self->{services_2m} = $dump->[2];
453 $self->{services_15m} = $dump->[3];
454 $self->{services_1h} = $dump->[4];
455 }
456  
457 1;
458  
459 __END__