Graphite/API.pm

filter: Statementstmt 68.8% 64 / 93 Branchbran 31.8% 7 / 22 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 66.6% 16 / 24 Podpod 100% 5 / 5 totaltotal 55.0% 92 / 167 CC 17 SCAR 25.4
CC
17
Cov
55%
__construct_target_argument
56.0
metrics
8.8
__construct_target_function
6.0
CRAP 12.6
« Graphite/Draw.pm ↑ Summary Graphite/HTTPClient.pm »
1 package Net::Async::Graphite::API;
2  
3 3 our $VERSION = '0.1_1';
4  
5 =head1 NAME
6  
7 Net::Async::Graphite::API - Interface between perl and graphite.
8  
9 =head1 SYNOPSIS
10  
11 with 'Net::Async::Graphite::API';
12  
13 =head1 DESCRIPTION
14  
15 Don't use this module directly, use L<Net::Async::Graphite> and create
16 objects using its C<new> method in the normal way. Those objects will
17 include the functionality documented here.
18  
19 This role brings the capacity to transmit HTTP requests to graphite
20 and asynchronously wait for and return the response.
21  
22 It also defines a structure describing complex target paths in a perl
23 data structure.
24  
25 =head1 BUGS
26  
27 Assumes graphite-api and doesn't handle transport errors at all.
28  
29 Using Memoize may be pointles.
30  
31 =cut
32  
33 3 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 3 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 3 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
37  
38 3 ▶use Memoize qw(memoize);
Subroutine BEGIN: called CC=1 SCAR=0.0
39 3 ▶use PerlX::Maybe qw(maybe);
Subroutine BEGIN: called CC=1 SCAR=0.0
40 3 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 3 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
42  
43 =head1 ROLE
44  
45 Asynchronity is achieved by using L<Net::Async::HTTP> inside
46 L<Net::Async::Graphite::HTTPClient>.
47  
48 JSON data is decoded using a L<JSON> object handled by
49 L<Net::Async::Graphite::JSONCodec>.
50  
51 =cut
52  
53 3 with 'Net::Async::Graphite::HTTPClient';
54  
55 3 with 'Net::Async::Graphite::JSONCodec';
56  
57 =head1 ATTRIBUTES
58  
59 =over
60  
61 =item endpoint (required, read-only)
62  
63 The base of the graphite URL to which C</metrics> and C</render>
64 requests will be directed. Everything up to and B<including> the
65 trailing C</>. eg. C<https://monitoring.example.com:8080/graphite/>.
66  
67 If the trailing C</> is not included it's assumed you know what you're
68 doing so only a warning will be printed.
69  
70 =cut
71  
72 has endpoint => (
73 is => 'ro',
74 16 ▶ isa => sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
75 16 ▶ carp 'endpoint should include a trailing "/", attempting to continue'
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] =~ m[/$]u 0 16 16
76 unless $_[0] =~ /\/$/;
77 16 ▶ croak 'endpoint must include a protocol' unless $_[0] =~ /^[a-z-]+:/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] =~ /^[a-z-]+:/iu 0 16 16
78 },
79 3 required => 1,
80 );
81  
82 =back
83  
84 =head1 PUBLIC METHODS
85  
86 All of these methods return a L<Future> which will complete with the
87 indicated result (or which will die).
88  
89 =over
90  
91 =item metrics ($method, $query, [%extra])
92  
93 Perform C<$method> on/with the metrics which match C<$query>, which
94 should be a simple scalar describing the query to perform, or an
95 arrayref of such scalars if the method can handle multiple query
96 parameters. ie. this will request a URI which looks like:
97 C<< <graphite-endpoint>/metrics/<$method>?query=<$query>[&query=...] >>. If
98 arguments are supplied in C<%extra>, they are added to the generated
99 URI as encoded query parameters.
100  
101 The three methods which graphite-api exposes at this time are supported:
102  
103 =over
104  
105 =item find
106  
107 =item expand
108  
109 =item index[.json]
110  
111 C</metrics/index.json> can be requested with C<$method> of C<index> or
112 C<index.json> because requiring the C<.json> suffix is silly. Also I
113 can consider creating real methods C<find>, C<expand> and C<index>.
114  
115 =back
116  
117 The L<Future> will complete with the http content. If you want the
118 HTTP request object see the C<_download> private method, but note
119 I<private>.
120  
121 =cut
122  
123 3 my %allowed_metrics_params = (
124 expand => [qw(groupByExpr leavesOnly)],
125 find => [qw(wildcards from until position)],
126 index => [],
127 );
128 3 $allowed_metrics_params{'index.json'} = $allowed_metrics_params{index}; # FFS
129  
130 8 ▶sub metrics {
Subroutine metrics: called CC=7 SCAR=21.8
Pod documented
131 8 my $self = shift;
132 8 my ($method, $query, %extra) = @_;
133 8 ▶ $method = 'index.json' if $method eq 'index';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "index" 2 6 8
134 return Future->fail("Invalid metrics method: $method")
135 8 ▶ unless exists $allowed_metrics_params{$method};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $allowed_metrics_params{$method} 0 8 8
136 8 my $uri = URI->new($self->endpoint . "metrics/$method");
137 my %query = (
138 maybe query => $query, # No query in index
139 8 map { maybe $_ => $extra{$_} } @{ $allowed_metrics_params{$method} },
140 );
141 # Only if .../find. Is default_* stupid?
142 8 ▶ $query{from} ||= $self->default_from if $self->has_default_from;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_default_from 0 8 8
Condition0%0/3
$query{"from"} ||= $self->default_from
l!l&&r!l&&!r
000
MC/DC0%0/2
$query{"from"} ||= $self->default_from
$query{"from"} $self->default_from
Truth table0%0/3
A ||= B
A= $query{"from"}B= $self->default_from
ABresult
1X1
011
000
143 8 ▶ $query{until} ||= $self->default_until if $self->has_default_until;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_default_until 0 8 8
Condition0%0/3
$query{"until"} ||= $self->default_until
l!l&&r!l&&!r
000
MC/DC0%0/2
$query{"until"} ||= $self->default_until
$query{"until"} $self->default_until
Truth table0%0/3
A ||= B
A= $query{"until"}B= $self->default_until
ABresult
1X1
011
000
144 8 $uri->query_form(%query);
145 8 ▶ $self->_download($uri)->then(sub { Future->done($_[0]->content) });
Subroutine __ANON__: called CC=1 SCAR=0.0
146 }
147  
148 =item metrics_asperl ($method, $query, [%extra])
149  
150 Calls C<metrics()> with the same arguments and decodes the result,
151 which is assumed to be JSON text, into a perl data structure.
152  
153 =cut
154  
155 4 ▶sub metrics_asperl {
Subroutine metrics_asperl: called CC=1 SCAR=0.0
Pod documented
156 4 my $self = shift;
157 4 ▶ $self->metrics(@_)->then(sub { Future->done($self->_json->decode(shift)); });
Subroutine __ANON__: called CC=1 SCAR=0.0
158 }
159  
160 # L<http://graphite.readthedocs.io/en/latest/render_api.html>. ie. this
161  
162 =item render ($format, $target, [%extra])
163  
164 Fetch the metric data for the given C<$target>, which should be a
165 simple scalar specifying a path identifying metrics, or an arrayref of
166 such scalars, as described in the
167 L<< graphite C</render> documentation | http://graphite.readthedocs.io/en/latest/render_api.html >>
168 C<render()> will then request a URI which looks like:
169 C<< <graphite-endpoint>/render?format=<$format>&target=<$query>[&target=...] >>.
170  
171 The name of the format may also be called as a method directly,
172 without the first (C<$format>) argument:
173  
174 =over
175  
176 =item csv ($target, [%extra])
177  
178 =item dygraph ($target, [%extra])
179  
180 =item json ($target, [%extra])
181  
182 =item pdf ($target, [%extra])
183  
184 =item png ($target, [%extra])
185  
186 =item raw ($target, [%extra])
187  
188 =item rickshaw ($target, [%extra])
189  
190 =item svg ($target, [%extra])
191  
192 =back
193  
194 =cut
195  
196 8 ▶sub render {
Subroutine render: called CC=1 SCAR=0.0
Pod documented
197 8 my $self = shift;
198 8 my ($format, $target, %extra) = @_;
199 8 my $uri = URI->new($self->endpoint . 'render');
200 my %query = (
201 format => $format,
202 target => $target,
203 8 map { maybe $_ => $extra{$_} } qw(graphType jsonp maxDataPoints noNullPoints), # Many more
204 );
205 8 $uri->query_form(%query);
206 8 ▶ $self->_download($uri)->then(sub { Future->done($_[0]->content) });
Subroutine __ANON__: called CC=1 SCAR=0.0
207 }
208  
209 3 for my $format (qw(
210 csv
211 dygraph
212 json
213 pdf
214 png
215 raw
216 rickshaw
217 svg
218 )) {
219 3 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
220 0 ▶ *{$format} = sub { $_[0]->render($format => @_[1..$#_]) };
Subroutine __ANON__: not called CC=1 SCAR=0.4
221 }
222  
223 =item render_asperl ($target, [%extra])
224  
225 Calls C<render()> with the same arguments but prepended by the format
226 C<raw>, and decodes the result.
227  
228 Graphite's raw format is documented in
229 L<< graphite C</render> documentation | http://graphite.readthedocs.io/en/latest/render_api.html >>
230 but in short it's an ASCII (or UTF-8 if you're so inclined) encoded
231 file consisting of one line per metric found. Each line consists of a
232 header and the data separated by a C<|>. Within each of these each
233 datum is separated by a C<,>.
234  
235 I don't know or care if the line endings include C<\r>.
236  
237 The data is returned as a list of hashrefs containing the data broken
238 up into B<all> of its components. ie. Each datum of each metric will
239 be turned into its own perl scalar.
240  
241 Each hashref will contain five values:
242  
243 =over
244  
245 =item target
246  
247 The path of metric.
248  
249 =item start
250  
251 Unix timestamp pinpointing the beginning of the data.
252  
253 =item end
254  
255 Unix timestamp pinpointing the end of the data.
256  
257 =item step
258  
259 The time interval in seconds (probably) between each datum.
260  
261 =item data
262  
263 The data. An arrayref of however many scalars it takes.
264  
265 The data are B<not> converted from their original text form, and
266 graphite include the string C<None> in the list of returned values, so
267 not every datum will necessarily look like a number.
268  
269 =back
270  
271 =cut
272  
273 0 ▶sub render_asperl {
Subroutine render_asperl: not called CC=1 SCAR=6.9
Pod documented
274 0 my $self = shift;
275 0 ▶ $self->render(raw => @_)->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
276 my @sets = map {
277 0 chomp;
278 0 my ($head, $data) = split /\|/;
279 0 my %set;
280 0 (@set{qw(target start end step)}) = split /,/, $head;
281 0 $set{data} = [ split /,/, $data ];
282 0 \%set;
283 } split /\n/, $_[0];
284 0 Future->done(@sets);
285 0 });
286 }
287  
288 =item find_target_from_spec ($spec, ...)
289  
290 Construct strings for use by the C<target> parameter of C</render>
291 queries from the specifications in each C<$spec>, which must be a
292 plain text scalar of the metric's path or an arrayref containing 2
293 items (second optional):
294  
295 =over
296  
297 =item $function
298  
299 The name of a function as defined by the graphite API.
300  
301 =item [ @arguments ] (optional)
302  
303 An arrayref containing 0 or more arguments. Each argument may be a
304 scalar, which left alone, or an arrayref which must itself be another
305 C<$spec>-like scalar/pair.
306  
307 =back
308  
309 It sounds a lot more confusing than it is. These are valid:
310  
311 # Scalar
312  
313 'simple.metric.name'
314  
315 # Becomes "simple.metric.name"
316  
317  
318 # Function
319  
320 [ 'summarize' => [ 'simple.metric.name' ] ]
321  
322 # Becomes "summarize(simple.metric.name)"
323  
324  
325 # Function with more arguments
326  
327 [ 'summarize' => [ 'me.tr.ic', '"arg1"', 42 ] ]
328  
329 # Becomes "summarize(me.tr.ic,%52arg1%52,42)"
330  
331  
332 # Recursive function
333  
334 [
335 'summarize' => [
336 'randomize' => [
337 'pointless.metric', 'argue', 'bicker'
338 ],
339 'and-fight',
340 ]
341 ]
342  
343 # Becomes "summarize(randomize(pointless.metric,argue,bicker),and-fight)"
344  
345  
346 Any other form is not.
347  
348 Simply put, where it's not just a plain string the specification is a
349 recursive nest of function/argument-list pairs, where each argument
350 can itself be another function pair.
351  
352 The implementation of the target string construction uses L<Memoize>
353 to avoid repeatedly calling functions which return the same data. It
354 probably destroys any advantage gained by doing this by normalising
355 the function arguments with JSON first. I'll measure it some day.
356  
357 =cut
358  
359 0 ▶sub find_target_from_spec {
Subroutine find_target_from_spec: not called CC=1 SCAR=6.9
Pod documented
360 0 my $self = shift;
361 0 return map { __construct_target_argument($_) } @_;
362 }
363  
364 =back
365  
366 =head1 PRIVATE METHODS
367  
368 =over
369  
370 =item __construct_target_argument ($argument)
371  
372 This is not an object or class method.
373  
374 Compile C<$argument> into its part of the string which will build up
375 the (or a) target component of a Graphite request URI. C<$argument>
376 must be a scalar or an arrayref with exactly one or two items in
377 it. If included, the second must be an arrayref of the function's
378 arguments.
379  
380 Returns the scalar as-is or calls C<__construct_target_function> to
381 decode the arrayref.
382  
383 This function uses L<Memoize> for which it normalises its arguments
384 using L<JSON>.
385  
386 =cut
387  
388 memoize('__construct_target_argument',
389 0 ▶ NORMALIZER => sub { ref($_[0]) ? encode_json($_[0]) : $_[0] });
Subroutine __ANON__: not called CC=2 SCAR=13.0
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 0 0
390  
391 0 ▶sub __construct_target_argument {
Subroutine __construct_target_argument: not called CC=7 SCAR=40.3
392 0 my ($argument) = @_;
393 0 my $ref = ref $argument;
394 0 ▶ if (not $ref) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $ref) { } 0 0 0
elsif ($ref eq 'ARRAY' and scalar @$argument <= 2) { } 0 0 0
395 0 $argument;
396 ▶ } elsif ($ref eq 'ARRAY' and scalar @$argument <= 2) {
Condition0%0/3
$ref eq "ARRAY" and scalar @$argument <= 2
!ll&&!rl&&r
000
MC/DC0%0/2
$ref eq "ARRAY" and scalar @$argument <= 2
$ref eq "ARRAY" scalar @$argument <= 2
Truth table0%0/3
A and B
A= $ref eq "ARRAY"B= scalar @$argument <= 2
ABresult
0X0
100
111
397 0 ▶ croak 'Function arguments must be an arrayref'
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $argument->[1] or ref $argument->[1] eq "ARRAY" 0 0 0
Condition0%0/3
not defined $argument->[1] or ref $argument->[1] eq "ARRAY"
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $argument->[1] or ref $argument->[1] eq "ARRAY"
not defined $argument->[1] ref $argument->[1] eq "ARRAY"
Truth table0%0/3
not(A) or B
A= not defined $argument->[1]B= ref $argument->[1] eq "ARRAY"
ABresult
1X1
011
000
398 unless not defined $argument->[1] or ref $argument->[1] eq 'ARRAY';
399 0 ▶ __construct_target_function($argument->[0], @{ $argument->[1] || [] });
Condition0%0/2
$argument->[1] || []
l!l
00
MC/DC0%0/1
$argument->[1] || []
$argument->[1]
Truth table0%0/2
A
A= $argument->[1]
Aresult
11
00
400 } else {
401 0 croak "Unknown argument reference type: $ref";
402 }
403 }
404  
405 =item __construct_target_function ($name, [@arguments])
406  
407 This is not an object or class method.
408  
409 Compile C<$name> and C<@arguments> into their part of the string which
410 will build up the target component of a Graphite request URI. Recurses
411 back into C<__construct_target_argument> to build each argument
412 component.
413  
414 This function uses L<Memoize> for which it normalises its arguments
415 using L<JSON>.
416  
417 =cut
418  
419 memoize('__construct_target_function',
420 0 ▶ NORMALIZER => sub { encode_json({@_}) });
Subroutine __ANON__: not called CC=1 SCAR=1.2
421  
422 0 ▶sub __construct_target_function {
Subroutine __construct_target_function: not called CC=2 SCAR=17.9
423 0 my $name = shift;
424 0 ▶ croak 'Function name must be a scalar' if ref $name;
Branch: 1 branch
BranchTrueFalseTotal
if ref $name 0 0 0
425 0 my @arguments = map { __construct_target_argument($_) } @_;
426 0 $name . '(' . join(',', @arguments) . ')';
427 }
428  
429 3 1;
430  
431 =back
432  
433 =head1 SEE ALSO
434  
435 Graphite's C</render> documentation L<http://graphite.readthedocs.io/en/latest/render_api.html>
436  
437 L<Net::Async::Graphite>
438  
439 L<Net::Async::Graphite::HTTPClient>
440  
441 L<Net::Async::Graphite::JSONCodec>
442  
443 L<Future>
444  
445 L<Moo>
446  
447 L<Net::Async::HTTP>
448  
449 =head1 AUTHOR
450  
451 Matthew King <matthew.king@cloudbeds.com>
452  
453 =cut
« Graphite/Draw.pm ↑ Summary Graphite/HTTPClient.pm »