Net/Statsd/Server.pm

filter: Statementstmt 19.6% 75 / 381 Branchbran 8.5% 8 / 94 Conditioncond 6.6% 4 / 60 MC/DCmcdc 0.0% 0 / 34 Subroutinesub 38.0% 19 / 50 Podpod 0.0% 0 / 23 totaltotal 16.5% 106 / 642 CC 93 SCAR 48.0
CC
93
Cov
16%
handle_client_packet
420.0
handle_manager_command
342.0
clear_metrics
90.0
CRAP 121.1
↑ Summary Net/Statsd/Server/Backend/File.pm »
1 # ABSTRACT: a Perl port of Etsy's statsd *server*
2  
3 package Net::Statsd::Server;
4  
5 # Use statements {{{
6  
7 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 #se warnings;
9  
10 3 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Socket qw(SOL_SOCKET SO_RCVBUF);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 3 ▶use AnyEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 3 ▶use AnyEvent::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use AnyEvent::Handle::UDP;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use AnyEvent::Log;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 3 ▶use AnyEvent::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 3 ▶use Net::Statsd::Server::Backend;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 3 ▶use Net::Statsd::Server::Metrics;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 # }}}
24  
25 # Constants and global variables {{{
26  
27 3 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
28 3 DEBUG => 0,
29 DEFAULT_CONFIG_FILE => 'localConfig.js',
30 DEFAULT_FLUSH_INTERVAL => 10_000,
31 DEFAULT_LOG_LEVEL => 'info',
32 RECEIVE_BUFFER_MB => 8, # 0 = setsockopt disabled
33 3 };
34  
35 3 our $VERSION = '0.17';
36 3 our $logger;
37  
38 # }}}
39  
40 1 ▶sub new {
Subroutine new: called CC=4 SCAR=14.3
Pod undocumented
41 1 my ($class, $opt) = @_;
42 1 ▶ $opt ||= {};
Condition50%1/2
$opt ||= {}
l!l
10
MC/DC0%0/1
$opt ||= {}
$opt
Truth table50%1/2
A
A= $opt
Aresult
11
00
43 1 ▶ $class = ref $class || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
010
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
44  
45 1 my $startup_time = time();
46  
47 # Initialize data structures with defaults for statsd stats
48 my $self = {
49  
50 startup_time => $startup_time,
51 start_time_hi => [Time::HiRes::gettimeofday],
52  
53 server => undef,
54 mgmtServer => undef,
55  
56 config_file => $opt->{config_file},
57 1 config => undef,
58 stats => {
59 messages => {
60 "last_msg_seen" => $startup_time,
61 "bad_lines_seen" => 0,
62 }
63 },
64 metrics => undef,
65  
66 debugInt => undef,
67 flushInterval => undef,
68  
69 backends => [],
70 logger => $logger,
71 };
72  
73 $self->{$_} = $opt->{$_}
74 1 for keys %{ $opt };
75  
76 1 bless $self, $class;
77 }
78  
79 # Flatten JSON booleans to avoid calls to JSON::XS::bool
80 # in the performance-critical code paths
81 1 ▶sub _flatten_bools {
Subroutine _flatten_bools: called CC=2 SCAR=6.9
82 1 my ($self, $conf_hash) = @_;
83 1 for (qw(dumpMessages debug)) {
84 2 $conf_hash->{$_} = !! $conf_hash->{$_};
85 }
86 1 return $conf_hash;
87 }
88  
89 0 ▶sub _json_emitter {
Subroutine _json_emitter: not called CC=1 SCAR=6.9
90 0 my ($self) = @_;
91 0 my $js = JSON::XS->new()
92 ->utf8(1)
93 ->shrink(1)
94 ->space_before(0)
95 ->space_after(1)
96 ->indent(0);
97 0 return $js;
98 }
99  
100 0 ▶sub _start_time_hi {
Subroutine _start_time_hi: not called CC=1 SCAR=6.9
101 0 return $_[0]->{start_time_hi};
102 }
103  
104 1 ▶sub config_defaults {
Subroutine config_defaults: called CC=1 SCAR=0.0
Pod undocumented
105 return {
106 1 "debug" => 0,
107 "debugInterval" => 10000, # ms
108 "graphitePort" => 2003,
109 "port" => 8125,
110 "address" => "0.0.0.0",
111 "mgmt_port" => 8126,
112 "mgmt_address" => "0.0.0.0",
113 "flushInterval" => DEFAULT_FLUSH_INTERVAL, # ms
114 #"keyFlush" => {
115 # "interval" => 10, # s
116 # "percent" => 100,
117 # "log" => "",
118 #},
119 "log" => {
120 "backend" => "stdout",
121 "level" => "LOG_INFO",
122 },
123  
124 "prefixStats" => "statsd",
125 "dumpMessages" => 0,
126  
127 "deleteIdleStats" => 0,
128 #"deleteCounters" => 0,
129 #"deleteGauges" => 0,
130 #"deleteSets" => 0,
131 #"deleteTimers" => 0,
132  
133 "percentThreshold" => [ 90 ],
134  
135 "backends" => [
136 "Console",
137 ],
138 };
139 }
140  
141 1 ▶sub config {
Subroutine config: called CC=8 SCAR=22.4
Pod undocumented
142 1 my ($self, $config_file) = @_;
143  
144 1 ▶ if (exists $self->{config} && defined $self->{config}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"config"} and defined $self->{"config"}) 0 1 1
Condition33%1/3
exists $self->{"config"} and defined $self->{"config"}
!ll&&!rl&&r
010
MC/DC0%0/2
exists $self->{"config"} and defined $self->{"config"}
exists $self->{"config"} defined $self->{"config"}
Truth table33%1/3
A and B
A= exists $self->{"config"}B= defined $self->{"config"}
ABresult
0X0
100
111
145 0 return $self->{config};
146 }
147  
148 1 ▶ $config_file ||= $self->config_file();
Condition33%1/3
$config_file ||= $self->config_file
l!l&&r!l&&!r
010
MC/DC0%0/2
$config_file ||= $self->config_file
$config_file $self->config_file
Truth table33%1/3
A ||= B
A= $config_fileB= $self->config_file
ABresult
1X1
011
000
149  
150 1 ▶ if (! -e $config_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $config_file) 0 1 1
151 0 return;
152 }
153  
154 1 my $defaults = $self->config_defaults();
155  
156 1 ▶ open my $conf_fh, '<', $config_file
Branch: 1 branch
BranchTrueFalseTotal
open my $conf_fh, "<", $config_file or return $defaults 1 0 1
157 or return $defaults;
158  
159 1 my $conf_json = join("", <$conf_fh>);
160 1 close $conf_fh;
161  
162 1 my $json = JSON::XS->new->relaxed->utf8;
163 1 my $conf_hash = $json->decode($conf_json);
164  
165 1 $conf_hash = $self->_flatten_bools($conf_hash);
166  
167 # Poor man's Hash::Merge
168 1 for (keys %{ $defaults }) {
169 14 ▶ if (! exists $conf_hash->{$_}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $conf_hash->{$_}) 4 10 14
170 4 $conf_hash->{$_} = $defaults->{$_};
171 }
172 }
173  
174 1 return $self->{config} = $conf_hash;
175 }
176  
177 0 ▶sub clear_metrics {
Subroutine clear_metrics: not called CC=9 SCAR=45.0
Pod undocumented
178 0 my ($self) = @_;
179  
180 0 my $conf = $self->config;
181  
182 0 my $del_counters = $conf->{deleteCounters};
183 0 my $del_gauges = $conf->{deleteGauges};
184 0 my $del_sets = $conf->{deleteSets};
185 0 my $del_timers = $conf->{deleteTimers};
186  
187 # Metrics that are not seen in the interval won't
188 # be sent anymore. Enable this with 'deleteIdleStats'
189 0 my $del_idle = _defined_or($conf->{deleteIdleStats}, 0);
190  
191 0 ▶ if ($del_idle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($del_idle) 0 0 0
192 0 $del_counters = _defined_or($del_counters, 1);
193 0 $del_gauges = _defined_or($del_gauges, 1);
194 0 $del_timers = _defined_or($del_timers, 1);
195 0 $del_sets = _defined_or($del_sets, 1);
196 }
197  
198 # Whether to just reset them to zero or to wipe them
199 0 my $metrics = $self->{metrics};
200 0 ▶ if ($del_counters) {
Branch: 1 branch
BranchTrueFalseTotal
if ($del_counters) { } 0 0 0
201 0 $metrics->{counters} = {};
202 0 $metrics->{counter_rates} = {};
203 }
204 else {
205 0 my $counters = $metrics->{counters};
206 0 my $counter_rates = $metrics->{counter_rates};
207 0 $_ = 0 for
208 0 values %{ $counters },
209 0 values %{ $counter_rates };
210 }
211  
212 0 ▶ if ($del_timers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($del_timers) { } 0 0 0
213 0 $metrics->{timers} = {};
214 0 $metrics->{timer_data} = {};
215 }
216 else {
217 0 my $timers = $metrics->{timers};
218 0 my $timer_data = $metrics->{timer_data};
219 0 $_ = [] for
220 0 values %{ $timers },
221 0 values %{ $timer_data };
222 }
223  
224 0 ▶ if ($del_gauges) {
Branch: 1 branch
BranchTrueFalseTotal
if ($del_gauges) 0 0 0
225 0 $metrics->{gauges} = {};
226 }
227  
228 0 ▶ if ($del_sets) {
Branch: 1 branch
BranchTrueFalseTotal
if ($del_sets) { } 0 0 0
229 0 $metrics->{sets} = {};
230 }
231 else {
232 0 my $sets = $metrics->{sets};
233 0 $_ = {} for values %{ $sets };
234 }
235  
236 0 return;
237 }
238  
239 1 ▶sub config_file {
Subroutine config_file: called CC=1 SCAR=0.0
Pod undocumented
240 1 _defined_or($_[0]->{config_file}, DEFAULT_CONFIG_FILE);
241 }
242  
243 0 ▶sub flush_metrics {
Subroutine flush_metrics: not called CC=1 SCAR=6.9
Pod undocumented
244 0 my ($self) = @_;
245 0 my $flush_start_time = time;
246 0 $logger->(notice => "flushing metrics");
247 0 my $flush_interval = $self->config->{flushInterval};
248 0 my $metrics = $self->metrics->process($flush_interval);
249 0 ▶ $self->foreach_backend(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
250 0 $_[0]->flush($flush_start_time, $metrics);
251 0 });
252 0 $self->clear_metrics();
253 0 return;
254 }
255  
256 # This is the performance-critical section of Net::Statsd::Server.
257 # Everything below has been optimised for performance rather than
258 # legibility or transparency. Be careful.
259  
260 0 ▶sub handle_client_packet {
Subroutine handle_client_packet: not called CC=20 SCAR=60.4
Pod undocumented
261 0 my ($self, $request) = @_;
262  
263 0 my $config = $self->{config};
264 0 my $metrics = $self->{metrics};
265 0 my $counters = $metrics->{counters};
266 0 my $stats = $self->{stats};
267 0 my $g_pref = $config->{prefixStats};
268  
269 0 $counters->{"${g_pref}.packets_received"}++;
270  
271 # TODO backendEvents.emit('packet', msg, rinfo);
272  
273 0 my @metrics = split("\n", $request);
274  
275 0 my $dump_messages = $config->{dumpMessages};
276 my $must_count_keys = exists $config->{keyFlush}
277 0 ▶ && $config->{keyFlush}->{interval};
Condition0%0/3
exists $config->{'keyFlush'} && $config->{'keyFlush'}{'interval'}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $config->{'keyFlush'} && $config->{'keyFlush'}{'interval'}
exists $config->{'keyFlush'} $config->{'keyFlush'}{'interval'}
Truth table0%0/3
A && B
A= exists $config->{'keyFlush'}B= $config->{'keyFlush'}{'interval'}
ABresult
0X0
100
111
278  
279 0 for my $m (@metrics) {
280  
281 0 ▶ $logger->(debug => $m) if $dump_messages;
Branch: 1 branch
BranchTrueFalseTotal
if $dump_messages 0 0 0
282  
283 0 my @bits = split(":", $m);
284 0 my $key = shift @bits;
285  
286 # Keep [,=] to allow sending of tags. Handy for Influxdb integration.
287 0 $key =~ y{/ }{_-}s;
288 0 $key =~ y{a-zA-Z0-9_\-\.,=}{}cd;
289  
290 # Not very clear here. Etsy's code was doing this differently
291 0 ▶ if ($must_count_keys) {
Branch: 1 branch
BranchTrueFalseTotal
if ($must_count_keys) 0 0 0
292 0 my $key_counter = $metrics->{keyCounter};
293 0 $key_counter->{$key}++;
294 }
295  
296 0 ▶ push @bits, "1" if 0 == @bits;
Branch: 1 branch
BranchTrueFalseTotal
if 0 == @bits 0 0 0
297  
298 0 for my $i (0..$#bits) {
299  
300 0 my $sample_rate = 1;
301 0 my @fields = split(/\|/, $bits[$i]);
302  
303 0 ▶ if (! defined $fields[1] || $fields[1] eq "") {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $fields[1] or $fields[1] eq "") 0 0 0
Condition0%0/3
not defined $fields[1] or $fields[1] eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $fields[1] or $fields[1] eq ""
not defined $fields[1] $fields[1] eq ""
Truth table0%0/3
not(A) or B
A= not defined $fields[1]B= $fields[1] eq ""
ABresult
1X1
011
000
304 0 $logger->(warn => "Bad line: $bits[$i] in msg \"$m\"");
305 0 $counters->{"${g_pref}.bad_lines_seen"}++;
306 0 $stats->{"messages"}->{"bad_lines_seen"}++;
307 0 next;
308 }
309  
310 0 ▶ my $value = $fields[0] || 0;
Condition0%0/2
$fields[0] || 0
l!l
00
MC/DC0%0/1
$fields[0] || 0
$fields[0]
Truth table0%0/2
A
A= $fields[0]
Aresult
11
00
311 0 my $unit = $fields[1];
312 0 for ($unit) {
313 0 s{^\s*}{};
314 0 s{\s*$}{};
315 }
316  
317 # Timers
318 0 ▶ if ($unit eq "ms") {
Branch: 3 branches
BranchTrueFalseTotal
if ($unit eq 'ms') { } 0 0 0
elsif ($unit eq 'g') { } 0 0 0
elsif ($unit eq 's') { } 0 0 0
319 0 my $timers = $metrics->{timers};
320 0 ▶ $timers->{$key} ||= [];
Condition0%0/2
$timers->{$key} ||= []
l!l
00
MC/DC0%0/1
$timers->{$key} ||= []
$timers->{$key}
Truth table0%0/2
A
A= $timers->{$key}
Aresult
11
00
321 0 push @{ $timers->{$key} }, $value;
322 }
323  
324 # Gauges
325 elsif ($unit eq "g") {
326 0 my $gauges = $metrics->{gauges};
327 0 $gauges->{$key} = $value;
328 }
329  
330 # Sets
331 elsif ($unit eq "s") {
332 # Treat set as a normal hash with undef keys
333 # to minimize memory consumption *and* insertion speed
334 0 my $sets = $metrics->{sets};
335 0 ▶ $sets->{$key} ||= {};
Condition0%0/2
$sets->{$key} ||= {}
l!l
00
MC/DC0%0/1
$sets->{$key} ||= {}
$sets->{$key}
Truth table0%0/2
A
A= $sets->{$key}
Aresult
11
00
336 0 $sets->{$key}->{$value} = undef;
337 }
338  
339 # Counters
340 else {
341 0 ▶ if (defined $fields[2]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $fields[2]) 0 0 0
342 0 ▶ if ($fields[2] =~ m{^\@([\d\.]+)}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fields[2] =~ /^\@([\d\.]+)/) { } 0 0 0
343 0 $sample_rate = $1 + 0;
344 }
345 else {
346 0 $logger->(warn => "Bad line: $bits[$i] in msg \"$m\"; has invalid sample rate");
347 0 $counters->{"${g_pref}.bad_lines_seen"}++;
348 0 $stats->{"messages"}->{"bad_lines_seen"}++;
349 0 next;
350 }
351 }
352 0 ▶ $counters->{$key} ||= 0;
Condition0%0/2
$counters->{$key} ||= 0
l!l
00
MC/DC0%0/1
$counters->{$key} ||= 0
$counters->{$key}
Truth table0%0/2
A
A= $counters->{$key}
Aresult
11
00
353 0 ▶ $value ||= 1;
Condition0%0/2
$value ||= 1
l!l
00
MC/DC0%0/1
$value ||= 1
$value
Truth table0%0/2
A
A= $value
Aresult
11
00
354 0 $value /= $sample_rate;
355 0 $counters->{$key} += $value;
356 }
357 }
358 }
359  
360 0 $stats->{"messages"}->{"last_msg_seen"} = time();
361 }
362  
363 0 ▶sub handle_manager_command {
Subroutine handle_manager_command: not called CC=18 SCAR=58.3
Pod undocumented
364 0 my ($self, $handle, $request) = @_;
365 0 my @cmdline = split(" ", trim($request));
366 0 my $cmd = shift @cmdline;
367 0 my $reply;
368  
369 0 $logger->(notice => "Received manager command '$cmd' (req=$request)");
370  
371 0 ▶ if ($cmd eq "help") {
Branch: 10 branches
BranchTrueFalseTotal
if ($cmd eq 'help') { } 0 0 0
elsif ($cmd eq 'stats') { } 0 0 0
elsif ($cmd eq 'counters') { } 0 0 0
elsif ($cmd eq 'timers') { } 0 0 0
elsif ($cmd eq 'gauges') { } 0 0 0
elsif ($cmd eq 'sets') { } 0 0 0
elsif ($cmd eq 'delcounters') { } 0 0 0
elsif ($cmd eq 'deltimers') { } 0 0 0
elsif ($cmd eq 'delgauges') { } 0 0 0
elsif ($cmd eq 'quit') { } 0 0 0
372 0 $reply = (
373 "Commands: stats, counters, timers, gauges, delcounters, deltimers, delgauges, quit\015\012\015\012"
374 );
375 }
376 elsif ($cmd eq "stats") {
377 0 my $now = time;
378 0 my $uptime = $now - $self->{startup_time};
379 0 $reply = "uptime: $uptime\n";
380  
381 # Loop through the base stats
382 0 my $stats = $self->stats;
383  
384 0 for my $group (keys %{$stats}) {
385 0 for my $metric (keys %{$stats->{$group}}) {
386 0 my $val = $stats->{$group}->{$metric};
387 0 ▶ my $delta = $metric =~ m{^last_}
Branch: 1 branch
BranchTrueFalseTotal
$metric =~ /^last_/ ? : 0 0 0
388 ? $now - $val
389 : $val;
390 0 $reply .= "${group}.${metric}: ${delta}\n";
391 }
392 }
393  
394 0 ▶ $self->foreach_backend(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
395 0 my $backend_status = $_[0]->status;
396 0 ▶ if ($backend_status && ref $backend_status eq "HASH") {
Branch: 1 branch
BranchTrueFalseTotal
if ($backend_status and ref $backend_status eq "HASH") 0 0 0
Condition0%0/3
$backend_status and ref $backend_status eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
$backend_status and ref $backend_status eq "HASH"
$backend_status ref $backend_status eq "HASH"
Truth table0%0/3
A and B
A= $backend_statusB= ref $backend_status eq "HASH"
ABresult
0X0
100
111
397 0 for (keys %{ $backend_status }) {
398 $reply .= sprintf("%s.%s: %s\n",
399 lc($_[0]->name),
400 0 $_ => $backend_status->{$_}
401 );
402 }
403 }
404 0 });
405  
406 0 $reply .= "END\n\n";
407 }
408 elsif ($cmd eq "counters") {
409 0 my $counters = $self->{metrics}->{counters};
410 0 $reply = $self->_json_emitter()->encode($counters);
411 0 $reply .= "\nEND\n\n";
412 }
413 elsif ($cmd eq "timers") {
414 0 my $timers = $self->{metrics}->{timers};
415 0 $reply = $self->_json_emitter()->encode($timers);
416 0 $reply .= "\nEND\n\n";
417 }
418 elsif ($cmd eq "gauges") {
419 0 my $gauges = $self->{metrics}->{gauges};
420 0 $reply = $self->_json_emitter()->encode($gauges);
421 0 $reply .= "\nEND\n\n";
422 }
423 elsif ($cmd eq "sets") {
424 0 my $sets = $self->{metrics}->{sets};
425 0 my $sets_as_lists = {};
426 # FIXME Not really happy about this...
427 # if you have huge sets, it's going to suck.
428 # If you have huge sets, probably statsd is not for you anyway.
429 0 for my $set (keys %{$sets}) {
430 0 $sets_as_lists->{$set} = [ keys %{ $sets->{$set} } ];
431 }
432 0 $reply = $self->_json_emitter()->encode($sets_as_lists);
433 0 $reply .= "\nEND\n\n";
434 }
435 elsif ($cmd eq "delcounters") {
436 0 my $counters = $self->{metrics}->{counters};
437 0 for my $name (@cmdline) {
438 0 delete $counters->{$name};
439 0 $reply .= "deleted: $name\n";
440 }
441 0 $reply .= "\nEND\n\n";
442 }
443 elsif ($cmd eq "deltimers") {
444 0 my $timers = $self->{metrics}->{timers};
445 0 for my $name (@cmdline) {
446 0 delete $timers->{$name};
447 0 $reply .= "deleted: $name\n";
448 }
449 0 $reply .= "\nEND\n\n";
450 }
451 elsif ($cmd eq "delgauges") {
452 0 my $gauges = $self->{metrics}->{gauges};
453 0 for my $name (@cmdline) {
454 0 delete $gauges->{$name};
455 0 $reply .= "deleted: $name\n";
456 }
457 0 $reply .= "\nEND\n\n";
458 }
459 elsif ($cmd eq "quit") {
460 0 undef $reply;
461 0 $handle->destroy();
462 }
463 else {
464 0 $reply = "ERROR\n";
465 }
466 0 return $reply;
467 }
468  
469 0 ▶sub handle_manager_connection {
Subroutine handle_manager_connection: not called CC=2 SCAR=17.9
Pod undocumented
470 0 my ($self, $handle, $line) = @_;
471 #$logger->(notice => "Received mgmt command [$line]");
472 0 ▶ if (my $reply = $self->handle_manager_command($handle, $line)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $reply = $self->handle_manager_command($handle, $line)) { } 0 0 0
473 0 $logger->(notice => "Sending mgmt reply [$reply]");
474 0 $handle->push_write($reply);
475 # Accept a new command on the same connection
476 0 ▶ $handle->push_read(line => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
477 0 handle_manager_connection($self, @_)
478 0 });
479 }
480 else {
481 0 $logger->(notice => "Shutting down socket");
482 0 $handle->push_write("\n");
483 0 $handle->destroy;
484 }
485 }
486  
487 0 ▶sub init_backends {
Subroutine init_backends: not called CC=7 SCAR=40.3
Pod undocumented
488 0 my ($self) = @_;
489 0 my $backends = $self->config->{backends};
490 0 ▶ if (! $backends or ref $backends ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $backends or ref $backends ne "ARRAY") 0 0 0
Condition0%0/3
not $backends or ref $backends ne "ARRAY"
l!l&&r!l&&!r
000
MC/DC0%0/2
not $backends or ref $backends ne "ARRAY"
not $backends ref $backends ne "ARRAY"
Truth table0%0/3
not(A) or B
A= not $backendsB= ref $backends ne "ARRAY"
ABresult
1X1
011
000
491 0 die "At least one backend is needed in your configuration";
492 }
493 0 for my $backend (@{ $backends }) {
494  
495 # Nodejs statsd expects a relative path
496 0 ▶ if ($backend =~ m{^ \./backends/ (.+) $}x) {
Branch: 1 branch
BranchTrueFalseTotal
if ($backend =~ m[^ \./backends/ (.+) $]x) 0 0 0
497 0 $backend = $1;
498 }
499  
500 0 my $pkg = $backend;
501 0 ▶ if ($backend =~ m{^ (\w+) $}x) {
Branch: 1 branch
BranchTrueFalseTotal
if ($backend =~ /^ (\w+) $/x) 0 0 0
502 0 $pkg = ucfirst lc $pkg;
503 0 $pkg = "Net::Statsd::Server::Backend::${pkg}";
504 }
505 0 my $mod = $pkg;
506 0 $mod =~ s{::}{/}g;
507 0 $mod .= ".pm";
508 eval {
509 0 require $mod ; 1
510 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require $mod; 1 } } or do { &$Net::Statsd::Server::logger("error", "Backend $backend failed to load: $@"); next } 0 0 0
511 0 $logger->(error=>"Backend ${backend} failed to load: $@");
512 0 next;
513 };
514 0 $self->register_backend($pkg);
515 }
516 }
517  
518 0 ▶sub init_logger {
Subroutine init_logger: not called CC=7 SCAR=40.3
Pod undocumented
519 0 my ($self, $config) = @_;
520  
521 0 ▶ $config ||= {};
Condition0%0/2
$config ||= {}
l!l
00
MC/DC0%0/1
$config ||= {}
$config
Truth table0%0/2
A
A= $config
Aresult
11
00
522  
523 0 ▶ my $backend = $config->{backend} || 'stdout';
Condition0%0/2
$config->{'backend'} || 'stdout'
l!l
00
MC/DC0%0/1
$config->{'backend'} || 'stdout'
$config->{'backend'}
Truth table0%0/2
A
A= $config->{'backend'}
Aresult
11
00
524 0 ▶ my $level = lc($config->{level} || 'LOG_INFO');
Condition0%0/2
$config->{'level'} || 'LOG_INFO'
l!l
00
MC/DC0%0/1
$config->{'level'} || 'LOG_INFO'
$config->{'level'}
Truth table0%0/2
A
A= $config->{'level'}
Aresult
11
00
525 0 $level =~ s{^log_}{};
526  
527 0 ▶ if ($backend eq 'stdout') {
Branch: 2 branches
BranchTrueFalseTotal
if ($backend eq 'stdout') { } 0 0 0
elsif ($backend eq 'syslog') { } 0 0 0
528 0 $AnyEvent::Log::FILTER->level($level);
529 }
530 elsif ($backend eq 'syslog') {
531 # Syslog logging works commenting out the FILTER->level line
532 0 $AnyEvent::Log::COLLECT->attach(
533 AnyEvent::Log::Ctx->new(
534 level => $level,
535 log_to_syslog => "user",
536 )
537 );
538 }
539 0 ▶ $logger ||= sub { AE::log(shift(@_), shift(@_)) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
$Net::Statsd::Server::logger ||= sub { &AE::log(shift @_, shift @_); }
l!l&&r!l&&!r
000
MC/DC0%0/2
$Net::Statsd::Server::logger ||= sub { &AE::log(shift @_, shift @_); }
$Net::Statsd::Server::logger sub { &AE::log(shift @_, shift @_); }
Truth table0%0/3
A ||= B
A= $Net::Statsd::Server::loggerB= sub { &AE::log(shift @_, shift @_); }
ABresult
1X1
011
000
540 }
541  
542 0 ▶sub logger {
Subroutine logger: not called CC=1 SCAR=6.9
Pod undocumented
543 0 return $logger;
544 }
545  
546 0 ▶sub metrics {
Subroutine metrics: not called CC=1 SCAR=6.9
Pod undocumented
547 0 $_[0]->{metrics};
548 }
549  
550 0 ▶sub register_backend {
Subroutine register_backend: not called CC=2 SCAR=17.9
Pod undocumented
551 0 my ($self, $backend) = @_;
552 0 ▶ $self->{backends} ||= [];
Condition0%0/2
$self->{"backends"} ||= []
l!l
00
MC/DC0%0/1
$self->{"backends"} ||= []
$self->{"backends"}
Truth table0%0/2
A
A= $self->{"backends"}
Aresult
11
00
553 0 my $backend_instance = $backend->new(
554 $self->_start_time_hi, $self->config,
555 );
556 0 $logger->(notice => "Initializing $backend backend");
557 0 push @{ $self->{backends} }, $backend_instance;
558 }
559  
560 0 ▶sub foreach_backend {
Subroutine foreach_backend: not called CC=4 SCAR=30.0
Pod undocumented
561 0 my ($self, $callback) = @_;
562 0 ▶ my $backends = $self->{backends} || [];
Condition0%0/2
$self->{'backends'} || []
l!l
00
MC/DC0%0/1
$self->{'backends'} || []
$self->{'backends'}
Truth table0%0/2
A
A= $self->{'backends'}
Aresult
11
00
563 0 for my $obj (@{ $backends }) {
564 eval {
565 0 $callback->($obj); 1;
566 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$callback($obj); 1 } } or do { &$Net::Statsd::Server::logger("error", "Failed callback on $obj backend: $@") } 0 0 0
567 0 $logger->(error => "Failed callback on $obj backend: $@");
568 };
569 }
570 }
571  
572 0 ▶sub reload_config {
Subroutine reload_config: not called CC=1 SCAR=6.9
Pod undocumented
573 0 my ($self) = @_;
574 0 delete $self->{config};
575 0 $logger->(warn => "Received SIGHUP: reloading configuration");
576 0 return $self->{config} = $self->config();
577 }
578  
579 0 ▶sub setup_flush_timer {
Subroutine setup_flush_timer: not called CC=2 SCAR=17.9
Pod undocumented
580 0 my ($self) = @_;
581  
582 my $flush_interval = $self->config->{flushInterval}
583 0 ▶ || DEFAULT_FLUSH_INTERVAL;
Condition0%0/2
$self->config->{'flushInterval'} || 10000
l!l
00
MC/DC0%0/1
$self->config->{'flushInterval'} || 10000
$self->config->{'flushInterval'}
Truth table0%0/2
A
A= $self->config->{'flushInterval'}
Aresult
11
00
584  
585 0 $flush_interval = $flush_interval / 1000;
586 0 $logger->(notice => "metrics flush will happen every ${flush_interval}s");
587  
588 0 ▶ my $flush_t = AE::timer $flush_interval, $flush_interval, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
589 0 $self->flush_metrics
590 0 };
591  
592 0 return $flush_t;
593 }
594  
595 1 ▶sub _defined_or { defined $_[0] ? $_[0] : $_[1] }
Subroutine _defined_or: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 1 0 1
596  
597 0 ▶sub setup_keyflush_timer {
Subroutine setup_keyflush_timer: not called CC=3 SCAR=24.8
Pod undocumented
598 0 my ($self) = @_;
599  
600 0 my $conf_kf = $self->config->{keyFlush};
601 0 my $kf_interval = _defined_or($conf_kf->{interval}, 0);
602 0 ▶ return if $kf_interval <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $kf_interval <= 0 0 0 0
603  
604 # Always milliseconds in the config!
605 0 $kf_interval /= 1000;
606  
607 0 my $kf_pct = _defined_or($conf_kf->{percent}, 100);
608 0 my $kf_log = $conf_kf->{log};
609  
610 0 ▶ $logger->(notice => "flushing top ${kf_pct}% keys to "
Condition0%0/2
$kf_log || 'stdout'
l!l
00
MC/DC0%0/1
$kf_log || 'stdout'
$kf_log
Truth table0%0/2
A
A= $kf_log
Aresult
11
00
611 . ($kf_log || "stdout")
612 . " every ${kf_interval}s"
613 );
614  
615 0 ▶ my $kf_timer = AE::timer $kf_interval, $kf_interval, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
616 0 $self->flush_top_keys()
617 0 };
618  
619 0 return $kf_timer;
620 }
621  
622 0 ▶sub flush_top_keys {
Subroutine flush_top_keys: not called CC=6 SCAR=37.4
Pod undocumented
623 0 my ($self) = @_;
624  
625 0 my $conf_kf = _defined_or($self->config->{keyFlush}, {});
626 0 my $kf_interval = _defined_or($conf_kf->{interval}, 0);
627 0 $kf_interval /= 1000;
628  
629 0 ▶ my $kf_pct = $conf_kf->{percent} || 100;
Condition0%0/2
$conf_kf->{'percent'} || 100
l!l
00
MC/DC0%0/1
$conf_kf->{'percent'} || 100
$conf_kf->{'percent'}
Truth table0%0/2
A
A= $conf_kf->{'percent'}
Aresult
11
00
630 0 my $kf_log = $conf_kf->{log};
631  
632 0 my @sorted_keys;
633 0 my $key_counter = $self->metrics->{keyCounter};
634 0 ▶ while (my ($k, $v) = each %{ $key_counter }) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$key_counter;}) 0 0 0
635 0 push @sorted_keys, [ $k, $v ];
636 }
637  
638 0 @sorted_keys = sort { $b->[1] <=> $a->[1] } @sorted_keys;
639  
640 0 my @time = localtime;
641 0 my $time_str = sprintf "%04d-%02d-%02d %02d:%02d:%02d",
642 $time[5] + 1900, $time[4] + 1, $time[3],
643 $time[2], $time[1], $time[0];
644  
645 0 my $log_message = "";
646  
647 # Only show the top keyFlush.percent keys
648 0 my $top_pct_limit = int(scalar(@sorted_keys) * $kf_pct / 100);
649 0 for my $i (0 .. $top_pct_limit - 1) {
650 0 $log_message .= sprintf "$time_str count=%d key=%s\n",
651 $sorted_keys[$i][1], $sorted_keys[$i][0];
652 }
653  
654 0 ▶ if ($kf_log) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kf_log) { } 0 0 0
655 0 ▶ if (open my $log_fh, '>>', $kf_log) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $log_fh, ">>", $kf_log) 0 0 0
656 0 $log_fh->printflush($log_message);
657 0 $log_fh->close();
658 }
659 } else {
660 0 print $log_message;
661 }
662  
663 # Clear the counters
664 0 $self->metrics->{keyCounter} = {};
665  
666 }
667  
668 0 ▶sub init_metrics {
Subroutine init_metrics: not called CC=1 SCAR=6.9
Pod undocumented
669 0 my ($self) = @_;
670 0 my $config = $self->config;
671 0 $self->{metrics} = Net::Statsd::Server::Metrics->new($config);
672 0 return $self->{metrics};
673 }
674  
675 0 ▶sub start_server {
Subroutine start_server: not called CC=7 SCAR=40.3
Pod undocumented
676 0 my ($self, $config) = @_;
677  
678 0 ▶ if (! defined $config) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $config) 0 0 0
679 0 $config = $self->config();
680 }
681  
682 0 $self->init_logger($config->{log});
683  
684 0 ▶ my $host = $config->{address} || '0.0.0.0';
Condition0%0/2
$config->{'address'} || '0.0.0.0'
l!l
00
MC/DC0%0/1
$config->{'address'} || '0.0.0.0'
$config->{'address'}
Truth table0%0/2
A
A= $config->{'address'}
Aresult
11
00
685 0 ▶ my $port = $config->{port} || 8125;
Condition0%0/2
$config->{'port'} || 8125
l!l
00
MC/DC0%0/1
$config->{'port'} || 8125
$config->{'port'}
Truth table0%0/2
A
A= $config->{'port'}
Aresult
11
00
686  
687 0 ▶ my $mgmt_host = $config->{mgmt_address} || '0.0.0.0';
Condition0%0/2
$config->{'mgmt_address'} || '0.0.0.0'
l!l
00
MC/DC0%0/1
$config->{'mgmt_address'} || '0.0.0.0'
$config->{'mgmt_address'}
Truth table0%0/2
A
A= $config->{'mgmt_address'}
Aresult
11
00
688 0 ▶ my $mgmt_port = $config->{mgmt_port} || 8126;
Condition0%0/2
$config->{'mgmt_port'} || 8126
l!l
00
MC/DC0%0/1
$config->{'mgmt_port'} || 8126
$config->{'mgmt_port'}
Truth table0%0/2
A
A= $config->{'mgmt_port'}
Aresult
11
00
689  
690 0 $self->init_backends();
691 0 $self->init_metrics();
692  
693 # Statsd clients interface (UDP)
694 $self->{server} = AnyEvent::Handle::UDP->new(
695 bind => [$host, $port],
696 0 ▶ on_recv => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
697 0 my ($data, $ae_handle, $client_addr) = @_;
698 #$logger->(debug => "Got data=$data self=$self");
699 0 $self->handle_client_packet($data);
700 },
701 0 );
702  
703 # Bump up SO_RCVBUF on UDP socket, to buffer up incoming
704 # UDP packets, to avoid significant packet loss under load.
705 # Read more: http://bit.ly/10eeFoE
706 0 if (RECEIVE_BUFFER_MB > 0) {
707 # On some systems this could fail (cpantesters reports)
708 # Have it emit a warning instead of throwing an exception
709 0 ▶ setsockopt($self->{server}->fh, SOL_SOCKET,
Branch: 1 branch
BranchTrueFalseTotal
setsockopt $self->{"server"}->fh, 1, 8, 8388608 or warn "Couldn't set SO_RCVBUF: $!" 0 0 0
710 SO_RCVBUF, RECEIVE_BUFFER_MB * 1048576)
711 or warn "Couldn't set SO_RCVBUF: $!";
712 }
713  
714 # Management interface (TCP, for 'stats' command, etc...)
715 0 ▶ $self->{mgmtServer} = AnyEvent::Socket::tcp_server $mgmt_host, $mgmt_port, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
716 0 ▶ my ($fh, $host, $port) = @_
Branch: 1 branch
BranchTrueFalseTotal
my($fh, $host, $port) = or die "Unable to connect: $!" 0 0 0
717 or die "Unable to connect: $!";
718  
719 0 my $handle; $handle = AnyEvent::Handle->new(
720 fh => $fh,
721 0 ▶ on_error => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
722 0 AE::log error => $_[2],
723 $_[0]->destroy;
724 },
725 0 ▶ on_eof => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
726 0 $handle->destroy;
727 0 AE::log info => "Done.",
728 },
729 0 );
730  
731 0 ▶ $handle->push_read(line => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
732 0 handle_manager_connection($self, @_)
733 0 });
734 0 };
735  
736 0 $logger->(notice => "statsd server started on ${host}:${port} (v${VERSION})");
737 0 $logger->(notice => "manager interface started on ${mgmt_host}:${mgmt_port}");
738  
739 0 my $f_ti = $self->setup_flush_timer;
740 0 my $kf_ti = $self->setup_keyflush_timer;
741  
742 # This will block waiting for
743 # incoming connections (TCP) or packets (UDP)
744 0 my $cv = AE::cv;
745 0 $cv->recv();
746 }
747  
748 0 ▶sub stats {
Subroutine stats: not called CC=1 SCAR=6.9
Pod undocumented
749 0 $_[0]->{stats};
750 }
751  
752 8 ▶sub trim {
Subroutine trim: called CC=2 SCAR=6.9
Pod undocumented
753 8 my $s = shift;
754 8 ▶ return unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 1 7 8
755 7 $s =~ s{^\s+}{};
756 7 $s =~ s{\s+$}{};
757 7 return $s;
758 }
759  
760 3 1;
761  
762 __END__
↑ Summary Net/Statsd/Server/Backend/File.pm »