Net/Statsd/Server/Backend/Elasticsearch.pm untested

filter: Statementstmt 0.0% 0 / 149 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 32 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 213 SCAR 47.0
CC
10
Cov
0%
flush
56.0
bulk_insert
20.0
post_stats
2.0
CRAP 110.0
1 #
2 # Flush stats to ElasticSearch (http://www.elasticsearch.org/)
3 #
4 # To enable this backend, include 'elasticsearch' in the backends
5 # configuration array:
6 #
7 # backends: ['./backends/elasticsearch']
8 # (if the config file is in the statsd folder)
9 #
10 # A sample configuration can be found in exampleElasticConfig.js
11 #
12 # This backend supports the following config options:
13 #
14 # host: hostname or IP of ElasticSearch server
15 # port: port of Elastic Search Server
16 # path: http path of Elastic Search Server (default: '/')
17 # indexPrefix: Prefix of the dynamic index to be created (default: 'statsd')
18 # indexType: The dociment type of the saved stat (default: 'stat')
19 #
20  
21 package Net::Statsd::Server::Backend::Elasticsearch;
22  
23 use 5.008;
24 use strict;
25 use warnings;
26 use base qw(Net::Statsd::Server::Backend);
27  
28 our $VERSION = '0.01';
29  
30 use HTTP::Request ();
31 use LWP::UserAgent ();
32  
33 my $debug;
34 my $flushInterval;
35 my $elasticFilter;
36 my $elasticHost;
37 my $elasticPort;
38 my $elasticPath;
39 my $elasticIndex;
40 my $elasticCountType;
41 my $elasticTimerType;
42 my $elasticStats = {};
43 my $statsdIndex;
44  
45 sub bulk_insert {
46 my ($self, $listCounters, $listTimers, $listTimerData) = @_;
47  
48 my @utc_date = gmtime();
49 my $utc_date = sprintf("%04d.%02d.%02d", $utc_date[5] + 1900, $utc_date[4] + 1, $utc_date[3]);
50  
51 $statsdIndex = $elasticIndex . '-' . $utc_date;
52 my $payload = '';
53  
54 my $key = 0;
55 for (@{ $listCounters }) {
56 $payload .= '{"index":{"_index":"' . $statsdIndex . '","_type":"' . $elasticCountType . '"}}' . "\n";
57 $payload .= '{';
58 my $innerPayload = '';
59 for my $statKey (keys %{ $listCounters->[$key] }) {
60 if ($innerPayload) { $innerPayload .= ',' }
61 $innerPayload .= '"' . $statKey . '":"' . $listCounters->[$key]->{$statKey} . '"';
62 }
63 $payload .= $innerPayload . '}' . "\n";
64 $key++;
65 }
66  
67 $key = 0;
68 for (@{ $listTimers }) {
69 $payload .= '{"index":{"_index":"' . $statsdIndex . '","_type":"' . $elasticTimerType . '"}}' . "\n";
70 $payload .= '{';
71 my $innerPayload = '';
72 for my $statKey (keys %{ $listTimers->[$key] }) {
73 if ($innerPayload) { $innerPayload .= ',' }
74 $innerPayload .= '"' . $statKey . '":"' . $listTimers->[$key]->{$statKey} . '"';
75 }
76 $payload .= $innerPayload . '}' . "\n";
77 $key++;
78 }
79  
80 $key = 0;
81 for (@{ $listTimerData }) {
82 $payload .= '{"index":{"_index":"' . $statsdIndex . '","_type":"' . $elasticTimerType . '_stats"}}' . "\n";
83 $payload += '{';
84 my $innerPayload = '';
85 for my $statKey (keys %{ $listTimerData->[$key] }) {
86 if ($innerPayload) { $innerPayload .= ','; }
87 $innerPayload .= '"' . $statKey . '":"' . $listTimerData->[$key]->{$statKey} . '"';
88 }
89 $payload .= $innerPayload . '}' . "\n";
90 $key++;
91 }
92  
93 return $payload;
94 }
95  
96 sub post_stats {
97 my ($self, $payload) = @_;
98  
99 my $optionsPost = {
100 host => $elasticHost,
101 port => $elasticPort,
102 path => $elasticPath . $statsdIndex . '/_bulk',
103 method => 'POST',
104 headers => {
105 'Content-Type' => 'application/json',
106 'Content-Length' => length($payload),
107 }
108 };
109  
110 my $req = HTTP::Request->new();
111 $req->method($optionsPost->{method});
112 $req->uri("http://" . $optionsPost->{host} . ":" . ($optionsPost->{port} || 80) . $optionsPost->{path});
113 while (my ($name, $value) = each %{ $optionsPost->{headers} }) {
114 $req->header($name => $value);
115 }
116 $req->content($payload);
117 warn "-------------- Sending to Elasticsearch:\n$payload\n\n";
118 my $lwp = LWP::UserAgent->new();
119 $lwp->agent("Net::Statsd::Server::Backend::ElasticSearch/$VERSION");
120 return $lwp->request($req);
121 }
122  
123 sub flush {
124 my ($self, $timestamp, $metrics) = @_;
125  
126 my $statString = '';
127 my $numStats = 0;
128 my $key;
129 my @counts;
130 my @timers;
131 my @timer_data;
132  
133 $timestamp *= 1000;
134  
135 for my $key (keys %{ $metrics->{counters} }) {
136 #my @keys = split m{\.}, $key;
137 if (defined $elasticFilter && $key !~ $elasticFilter) {
138 next;
139 }
140 my $value = $metrics->{counters}->{$key};
141 #push @counts, {
142 # ns => $keys[0] || '',
143 # grp => $keys[1] || '',
144 # tgt => $keys[2] || '',
145 # act => $keys[3] || '',
146 # val => $value,
147 #};
148 push @counts, {
149 key => $key,
150 counter => $value,
151 '@timestamp' => $timestamp,
152 };
153 $numStats++;
154 }
155  
156 for my $key (keys %{ $metrics->{timers} }) {
157 my @keys = split m{\.}, $key;
158 my $series = $metrics->{timers}->{$key};
159 if (defined $elasticFilter && $key !~ $elasticFilter) {
160 next;
161 }
162 for my $keyTimer (keys %{ $series }) {
163 my $value = $series->{$keyTimer};
164 push @timers, {
165 key => $key,
166 timer => $value,
167 '@timestamp' => $timestamp,
168 };
169 # push @timers, {
170 # ns => $keys[0] || '',
171 # grp => $keys[1] || '',
172 # tgt => $keys[2] || '',
173 # act => $keys[3] || '',
174 # val => $value,
175 # '@timestamp' => $timestamp,
176 # };
177 }
178 }
179  
180 for my $key (keys %{ $metrics->{timer_data} }) {
181 my @keys = split m{\.}, $key;
182 if (defined $elasticFilter && $key !~ $elasticFilter) {
183 next;
184 }
185 my $value = $metrics->{timer_data}->{$key};
186 $value->{'@timestamp'} = $timestamp;
187 $value->{key} = $key;
188 if (defined $value->{histogram}) {
189 for my $keyH (keys %{ $value->{histogram} }) {
190 $value->{$keyH} = $value->{histogram}->{$keyH};
191 }
192 delete $value->{histogram};
193 }
194 push @timer_data, $value;
195 $numStats++;
196 }
197  
198 my $es_payload = $self->bulk_insert(\@counts, \@timers, \@timer_data);
199  
200 if ($numStats > 0 && $es_payload) {
201 $self->post_stats($es_payload);
202 if ($debug) {
203 warn "flushed ${numStats} stats to ElasticSearch\n";
204 }
205 }
206  
207 }
208  
209 #var elastic_backend_status = function graphite_status(writeCb) {
210 # for (stat in elasticStats) {
211 # writeCb(null, 'elastic', stat, elasticStats[stat]);
212 # }
213 #};
214  
215 sub init {
216 my ($self, $startup_time, $config, $events) = @_;
217  
218 $debug = $config->{debug};
219 my $configEs = $config->{elasticsearch} || {};
220  
221 $elasticHost = $configEs->{host} || 'localhost';
222 $elasticPort = $configEs->{port} || 9200;
223 $elasticPath = $configEs->{path} || '/';
224 $elasticIndex = $configEs->{indexPrefix} || 'statsd';
225 # Only sends stats that match the 'statsFilter' substring
226 $elasticFilter = $configEs->{statsFilter} || 'vstatd',
227 $elasticCountType = $configEs->{countType} || 'counter';
228 $elasticTimerType = $configEs->{timerType} || 'timer';
229 $elasticTimerType = $configEs->{timerDataType} || 'timer_data';
230 $flushInterval = $config->{flushInterval};
231  
232 $elasticStats->{last_flush} = $startup_time;
233 $elasticStats->{last_exception} = $startup_time;
234  
235 #events.on('flush', flush_stats);
236 #events.on('status', elastic_backend_status);
237  
238 return 1;
239 }
240  
241 1;