Consul.pm

filter: Statementstmt 88.0% 133 / 151 Branchbran 36.3% 8 / 22 Conditioncond 43.7% 7 / 16 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 81.8% 36 / 44 Podpod n/a totaltotal 75.7% 184 / 243 CC 18 SCAR 9.9
CC
18
Cov
78%
_api_exec
8.2
_prep_response
6.0
_prep_request
5.3
CRAP 2.7
« Consul/API/Health.pm ↑ Summary Consul/API/Catalog.pm »
1 package Consul;
2 9 $Consul::VERSION = '0.027';
3 # ABSTRACT: Client library for consul
4  
5 9 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 9 ▶use HTTP::Tiny 0.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use URI::Escape qw(uri_escape);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use JSON::MaybeXS qw(JSON);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use Hash::MultiValue;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 9 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 9 ▶use Type::Utils qw(class_type);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 9 ▶use Types::Standard qw(Str Int Bool HashRef CodeRef);
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 2 ▶has host => ( is => 'ro', isa => Str, default => sub { '127.0.0.1' } );
Subroutine __ANON__: called CC=1 SCAR=0.0
19 0 ▶has port => ( is => 'ro', isa => Int, default => sub { 8500 } );
Subroutine __ANON__: not called CC=1 SCAR=1.2
20  
21 2 ▶has ssl => ( is => 'ro', isa => Bool, default => sub { 0 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
22  
23 2 ▶has timeout => ( is => 'ro', isa => Int, default => sub { 15 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
24  
25 9 has token => ( is => 'ro', isa => Str, predicate => '_has_token' );
26  
27 9 has _http => ( is => 'lazy', isa => class_type('HTTP::Tiny') );
28 2 ▶sub _build__http { HTTP::Tiny->new(timeout => shift->timeout) };
Subroutine _build__http: called CC=1 SCAR=0.0
29  
30 2 ▶has _version_prefix => ( is => 'ro', isa => Str, default => sub { '/v1' } );
Subroutine __ANON__: called CC=1 SCAR=0.0
31  
32 9 has _url_base => ( is => 'lazy' );
33 2 ▶sub _build__url_base {
Subroutine _build__url_base: called CC=2 SCAR=7.2
34 2 my ($self) = @_;
35 2 ▶ ($self->ssl ? 'https' : 'http') .'://'.$self->host.':'.$self->port;
Branch: 1 branch
BranchTrueFalseTotal
$self->ssl ? : 0 2 2
36 }
37  
38 4 ▶sub _prep_url {
Subroutine _prep_url: called CC=3 SCAR=11.2
39 4 my ($self, $path, %args) = @_;
40 4 my $trailing = $path =~ m{/$};
41 4 my $url = $self->_url_base.join('/', map { uri_escape($_) } split('/', $path));
42 4 ▶ $url .= '/' if $trailing;
Branch: 1 branch
BranchTrueFalseTotal
if $trailing 0 4 4
43 4 ▶ $url .= '?'.$self->_http->www_form_urlencode(\%args) if %args;
Branch: 1 branch
BranchTrueFalseTotal
if %args 0 4 4
44 4 $url;
45 }
46  
47 9 my $json = JSON->new->utf8->allow_nonref;
48  
49 4 ▶sub _prep_request {
Subroutine _prep_request: called CC=4 SCAR=16.6
50 4 my $callback = pop @_;
51 4 my ($self, $path, $method, %args) = @_;
52  
53 0 ▶ my %uargs = map { m/^_/ ? () : ($_ => $args{$_}) } keys %args;
Branch: 1 branch
BranchTrueFalseTotal
/^_/ ? : 0 0 0
54  
55 4 my $headers = Hash::MultiValue->new;
56  
57 4 ▶ if ($self->_has_token()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_token) 0 4 4
58 0 $headers->set( 'X-Consul-Token', $self->token() );
59 }
60  
61 return Consul::Request->new(
62 method => $method,
63 url => $self->_prep_url($path, %uargs),
64 headers => $headers,
65 4 ▶ content => defined( $args{_content} ) ? $args{_content} : "",
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'_content'} ? : 0 4 4
66 callback => $callback,
67 args => \%uargs,
68 );
69 }
70  
71 0 ▶sub _prep_response {
Subroutine _prep_response: not called CC=2 SCAR=17.9
72 0 my ($self, $resp, %args) = @_;
73  
74 0 my $data;
75 0 ▶ $data = $json->decode($resp->content) if length $resp->content > 0;
Branch: 1 branch
BranchTrueFalseTotal
if length $resp->content > 0 0 0 0
76  
77 0 ▶ my $meta = try { Consul::Meta->new(%{$resp->headers}) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
78  
79 0 return ($data, $meta);
80 }
81  
82 9 has request_cb => ( is => 'lazy', isa => CodeRef );
83 2 ▶sub _build_request_cb {
Subroutine _build_request_cb: called CC=1 SCAR=0.0
84 4 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
85 4 my ($self, $req) = @_;
86 4 my $res = $self->_http->request($req->method, $req->url, {
87 headers => $req->headers->mixed,
88 content => $req->content,
89 });
90 4 ▶ my $rheaders = Hash::MultiValue->from_mixed(delete $res->{headers} || {});
Condition50%1/2
delete $res->{'headers'} || {}
l!l
40
MC/DC0%0/1
delete $res->{'headers'} || {}
delete $res->{'headers'}
Truth table50%1/2
A
A= delete $res->{'headers'}
Aresult
11
00
91 4 my ($rstatus, $rreason, $rcontent) = @$res{qw(status reason content)};
92 4 $req->callback->(Consul::Response->new(
93 status => $rstatus,
94 reason => $rreason,
95 headers => $rheaders,
96 content => $rcontent,
97 request => $req,
98 ));
99 }
100 2 }
101  
102 9 has error_cb => ( is => 'lazy', isa => CodeRef );
103 1 ▶sub _build_error_cb {
Subroutine _build_error_cb: called CC=1 SCAR=0.0
104 1 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
105 1 croak shift;
106 }
107 1 }
108  
109 4 ▶sub _api_exec {
Subroutine _api_exec: called CC=6 SCAR=21.1
110 0 ▶ my $resp_cb = $#_ % 2 == 1 && ref $_[$#_] eq 'CODE' ? pop @_ : sub { pop @_ };
Subroutine __ANON__: not called CC=1 SCAR=1.7
Branch: 1 branch
BranchTrueFalseTotal
$#_ % 2 == 1 && ref $_[$#_] eq 'CODE' ? : 4 0 4
Condition33%1/3
$#_ % 2 == 1 and ref $_[$#_] eq "CODE"
!ll&&!rl&&r
004
MC/DC0%0/2
$#_ % 2 == 1 and ref $_[$#_] eq "CODE"
$#_ % 2 == 1 ref $_[$#_] eq "CODE"
Truth table33%1/3
A and B
A= $#_ % 2 == 1B= ref $_[$#_] eq "CODE"
ABresult
0X0
100
111
111 4 my ($self, $path, $method, %args) = @_;
112  
113 4 my @r;
114 0 ▶ my $cli_cb = delete $args{cb} || sub { @r = @_ };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
delete $args{'cb'} || sub { @r = @_; }
l!l&&r!l&&!r
040
MC/DC0%0/2
delete $args{'cb'} || sub { @r = @_; }
delete $args{'cb'} sub { @r = @_; }
Truth table33%1/3
A || B
A= delete $args{'cb'}B= sub { @r = @_; }
ABresult
1X1
011
000
115 4 ▶ my $error_cb = delete $args{error_cb} || $self->error_cb;
Condition66%2/3
delete $args{'error_cb'} || $self->error_cb
l!l&&r!l&&!r
220
MC/DC0%0/2
delete $args{'error_cb'} || $self->error_cb
delete $args{'error_cb'} $self->error_cb
Truth table66%2/3
A || B
A= delete $args{'error_cb'}B= $self->error_cb
ABresult
1X1
011
000
116  
117 4 ▶ $self->request_cb->($self, $self->_prep_request($path, $method, %args, sub {
Subroutine __ANON__: called CC=4 SCAR=15.8
118 4 my ($resp) = @_;
119  
120 4 ▶ my $valid_cb = $args{_valid_cb} || sub { int($resp->status/100) == 2 };
Subroutine __ANON__: called CC=1 SCAR=0.6
Condition33%1/3
$args{'_valid_cb'} || sub { int $resp->status / 100 == 2; }
l!l&&r!l&&!r
040
MC/DC0%0/2
$args{'_valid_cb'} || sub { int $resp->status / 100 == 2; }
$args{'_valid_cb'} sub { int $resp->status / 100 == 2; }
Truth table33%1/3
A || B
A= $args{'_valid_cb'}B= sub { int $resp->status / 100 == 2; }
ABresult
1X1
011
000
121  
122 4 ▶ unless ($valid_cb->($resp->status)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$valid_cb($resp->status)) 4 0 4
123 4 ▶ my $content = $resp->content || "[no content]";
Condition50%1/2
$resp->content || '[no content]'
l!l
40
MC/DC0%0/1
$resp->content || '[no content]'
$resp->content
Truth table50%1/2
A
A= $resp->content
Aresult
11
00
124 4 $error_cb->(sprintf("%s %s: %s", $resp->status, $resp->reason, $content));
125 3 return;
126 }
127  
128 0 my ($data, $meta) = $self->_prep_response(@_);
129 0 $cli_cb->($resp_cb->($data), $meta);
130 4 }));
131  
132 3 ▶ return wantarray ? @r : shift @r;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 3 3
133 };
134  
135 9 with qw(
136 Consul::API::ACL
137 Consul::API::Agent
138 Consul::API::Catalog
139 Consul::API::Event
140 Consul::API::Health
141 Consul::API::KV
142 Consul::API::Session
143 Consul::API::Status
144 );
145  
146 9 ▶use Consul::Check;
Subroutine BEGIN: called CC=1 SCAR=0.0
147 9 ▶use Consul::Service;
Subroutine BEGIN: called CC=1 SCAR=0.0
148 9 ▶use Consul::Session;
Subroutine BEGIN: called CC=1 SCAR=0.0
149  
150  
151 package
152 Consul::Request; # hide from PAUSE
153  
154 9 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
155 9 ▶use Types::Standard qw(Str CodeRef HashRef);
Subroutine BEGIN: called CC=1 SCAR=0.0
156 9 ▶use Type::Utils qw(class_type);
Subroutine BEGIN: called CC=1 SCAR=0.0
157  
158 9 has method => ( is => 'ro', isa => Str, required => 1 );
159 9 has url => ( is => 'ro', isa => Str, required => 1 );
160 9 has headers => ( is => 'ro', isa => class_type('Hash::MultiValue'), required => 1 );
161 9 has content => ( is => 'ro', isa => Str, required => 1 );
162 9 has callback => ( is => 'ro', isa => CodeRef, required => 1 );
163 9 has args => ( is => 'ro', isa => HashRef, required => 1 );
164  
165  
166 package
167 Consul::Response; # hide from PAUSE
168  
169 9 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
170 9 ▶use Types::Standard qw(Str Int);
Subroutine BEGIN: called CC=1 SCAR=0.0
171 9 ▶use Type::Utils qw(class_type);
Subroutine BEGIN: called CC=1 SCAR=0.0
172  
173 9 has status => ( is => 'ro', isa => Int, required => 1 );
174 9 has reason => ( is => 'ro', isa => Str, required => 1 );
175 0 ▶has headers => ( is => 'ro', isa => class_type('Hash::MultiValue'), default => sub { Hash::MultiValue->new } );
Subroutine __ANON__: not called CC=1 SCAR=1.2
176 0 ▶has content => ( is => 'ro', isa => Str, default => sub { "" } );
Subroutine __ANON__: not called CC=1 SCAR=1.2
177 9 has request => ( is => 'ro', isa => class_type('Consul::Request'), required => 1 );
178  
179  
180 package
181 Consul::Meta; # hide from PAUSE
182  
183 9 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
184 9 ▶use Types::Standard qw(Int Bool);
Subroutine BEGIN: called CC=1 SCAR=0.0
185  
186 9 has index => ( is => 'ro', isa => Int, init_arg => 'x-consul-index', required => 1 );
187 9 has last_contact => ( is => 'ro', isa => Int, init_arg => 'x-consul-lastcontact' );
188 0 ▶has known_leader => ( is => 'ro', isa => Bool, init_arg => 'x-consul-knownleader', coerce => sub { my $r = { true => 1, false => 0 }->{$_[0]}; defined $r ? $r : $_[0] } );
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
defined $r ? : 0 0 0
189  
190  
191 9 1;
192  
193 =pod
194  
195 =encoding UTF-8
196  
197 =for markdown [![Build Status](https://secure.travis-ci.org/robn/Consul.png)](http://travis-ci.org/robn/Consul)
198  
199 =head1 NAME
200  
201 Consul - Client library for consul
202  
203 =head1 SYNOPSIS
204  
205 use Consul;
206
207 my $consul = Consul->new;
208 say $consul->status->leader;
209
210 # shortcut to single API
211 my $status = Consul->status;
212 say $status->leader;
213  
214 =head1 DESCRIPTION
215  
216 This is a client library for accessing and manipulating data in a Consul
217 cluster. It targets the Consul v1 HTTP API.
218  
219 This module is quite low-level. You're expected to have a good understanding of
220 Consul and its API to understand the methods this module provides. See L</SEE ALSO>
221 for further reading.
222  
223 =head1 WARNING
224  
225 This is still under development. The documentation isn't all there yet (in
226 particular about the return types) and a couple of APIs aren't implemented.
227 It's still very useful and I don't expect huge changes, but please take care
228 when upgrading. Open an issue if there's something you need that isn't here and
229 I'll get right on it!
230  
231 =head1 CONSTRUCTOR
232  
233 =head2 new
234  
235 my $consul = Consul->new( %args );
236  
237 This constructor returns a new Consul client object. Valid arguments include:
238  
239 =over 4
240  
241 =item *
242  
243 C<host>
244  
245 Hostname or IP address of an Consul server (default: C<127.0.0.1>)
246  
247 =item *
248  
249 C<port>
250  
251 Port where the Consul server is listening (default: C<8500>)
252  
253 =item *
254  
255 C<ssl>
256  
257 Use SSL/TLS (ie HTTPS) when talking to the Consul server (default: off)
258  
259 =item *
260  
261 C<timeout>
262  
263 Request timeout. If a request to Consul takes longer that this, the endpoint
264 method will fail (default: 15).
265  
266 =item *
267  
268 C<token>
269  
270 Consul ACL token. This is used to set the C<X-Consul-Token> HTTP header. Typically
271 Consul agents are pre-configured with a default ACL token, or ACLs are not enabled
272 at all, so this option only needs to be set in certain cases.
273  
274 =item *
275  
276 C<request_cb>
277  
278 A callback to an alternative method to make the actual HTTP request. The
279 callback is of the form:
280  
281 sub {
282 my ($self, $req) = @_;
283 ... do HTTP call
284 $req->callback->(Consul::Response->new(...));
285 }
286  
287 C<$req> is a C<Consul::Request> object, and has the following attributes:
288  
289 =over 4
290  
291 =item *
292  
293 C<method>
294  
295 The HTTP method for the request.
296  
297 =item *
298  
299 C<url>
300  
301 The complete URL to request. This is fully formed, and includes scheme, host,
302 port and query parameters. You shouldn't need to touch it.
303  
304 =item *
305  
306 C<headers>
307  
308 A L<Hash::MultiValue> object containing any headers that should be added to the
309 request.
310  
311 =item *
312  
313 C<content>
314  
315 The body content for the request.
316  
317 =item *
318  
319 C<callback>
320  
321 A callback to call when the request is completed. It takes a single
322 C<Consul::Response> object as its parameter.
323  
324 =item *
325  
326 C<args>
327  
328 A hashref containing the original arguments passed in to the endpoint method.
329  
330 =back
331  
332 The C<callback> function should be called with a C<Consul::Response> object
333 containing the values returned by the Consul server in response to the request.
334 Create one with C<new>, passing the following attributes:
335  
336 =over 4
337  
338 =item *
339  
340 C<status>
341  
342 The integer status code.
343  
344 =item *
345  
346 C<reason>
347  
348 The status reason phrase.
349  
350 =item *
351  
352 C<headers>
353  
354 A L<Hash::MultiValue> containing the response headers.
355  
356 =item *
357  
358 C<content>
359  
360 Any body content returned in the response.
361  
362 =item *
363  
364 C<request>
365  
366 The C<Consul::Request> object passed to the callback.
367  
368 =back
369  
370 Consul itself provides a default C<request_cb> that uses L<HTTP::Tiny> to make
371 calls to the server. If you provide one, you should honour the value of the
372 C<timeout> argument.
373  
374 C<request_cb> can be used in conjunction with the C<cb> option to all API method
375 endpoints to get asynchronous behaviour. It's recommended however that you
376 don't use this directly, but rather use a module like L<AnyEvent::Consul> to
377 take care of that for you.
378  
379 If you just want to use this module to make simple calls to your Consul
380 cluster, you can ignore this option entirely.
381  
382 =item *
383  
384 C<error_cb>
385  
386 A callback to an alternative method to handle internal errors (usually HTTP
387 errors). The callback is of the form:
388  
389 sub {
390 my ($err) = @_;
391 ... output $err ...
392 }
393  
394 The default callback simply calls C<croak>.
395  
396 =back
397  
398 =head1 ENDPOINTS
399  
400 Individual API endpoints are implemented in separate modules. The following
401 methods will return a context objects for the named API. Alternatively, you can
402 request an API context directly from the Consul package. In that case,
403 C<Consul-E<gt>new> is called implicitly.
404  
405 # these are equivalent
406 my $agent = Consul->new( %args )->agent;
407 my $agent = Consul->agent( %args );
408  
409 =head2 kv
410  
411 Key/value store API. See L<Consul::API::KV>.
412  
413 =head2 agent
414  
415 Agent API. See L<Consul::API::Agent>.
416  
417 =head2 catalog
418  
419 Catalog (nodes and services) API. See L<Consul::API::Catalog>.
420  
421 =head2 health
422  
423 Health check API. See L<Consul::API::Health>.
424  
425 =head2 session
426  
427 Sessions API. See L<Consul::API::Session>.
428  
429 =head2 acl
430  
431 Access control API. See L<Consul::API::ACL>.
432  
433 =head2 event
434  
435 User event API. See L<Consul::API::Event>.
436  
437 =head2 status
438  
439 System status API. See L<Consul::API::Status>.
440  
441 =head1 METHOD OPTIONS
442  
443 All API methods implemented by the endpoints can take a number of arguments.
444 Most of those are documented in the endpoint documentation. There are however
445 some that are common to all methods:
446  
447 =over 4
448  
449 =item *
450  
451 C<cb>
452  
453 A callback to call with the results of the method. Without this, the results
454 are returned from the method, but only if C<request_cb> is synchronous. If an
455 asynchronous C<request_cb> is used without a C<cb> being passed to the method, the
456 method return value is undefined.
457  
458 If you just want to use this module to make simple calls to your Consul
459 cluster, you can ignore this option entirely.
460  
461 C<error_cb>
462  
463 A callback to an alternative method to handle internal errors (usually HTTP
464 errors). errors). The callback is of the form:
465  
466 sub {
467 my ($err) = @_;
468 ... output $err ...
469 }
470  
471 The default callback calls the C<error_cb> for the API object itself, which by
472 default, simply calls croak.
473  
474 =back
475  
476 =head1 BLOCKING QUERIES
477  
478 Some Consul API endpoints support a feature called a "blocking query". These
479 endpoints allow long-polling for changes, and support some extra information
480 about the server state, including the Raft index, in the response headers.
481  
482 The corresponding endpoint methods, when called in array context, will return a
483 second value. This is an object with three methods, C<index>, C<last_contact>
484 and C<known_leader>, corresponding to the similarly-named header fields. You
485 can use these to set up state watches, CAS writes, and so on.
486  
487 See the Consul API docs for more information.
488  
489 =head1 SEE ALSO
490  
491 =over 4
492  
493 =item *
494  
495 L<AnyEvent::Consul> - a wrapper providing asynchronous operation
496  
497 =item *
498  
499 L<https://www.consul.io/docs/agent/http.html> - Consul HTTP API documentation
500  
501 =back
502  
503 =head1 SUPPORT
504  
505 =head2 Bugs / Feature Requests
506  
507 Please report any bugs or feature requests through the issue tracker
508 at L<https://github.com/robn/Consul/issues>.
509 You will be notified automatically of any progress on your issue.
510  
511 =head2 Source Code
512  
513 This is open source software. The code repository is available for
514 public review and contribution under the terms of the license.
515  
516 L<https://github.com/robn/Consul>
517  
518 git clone https://github.com/robn/Consul.git
519  
520 =head1 CONTRIBUTORS
521  
522 =over 4
523  
524 =item *
525  
526 Rob N ★ <robn@robn.io>
527  
528 =item *
529  
530 Aran Deltac <bluefeet@gmail.com>
531  
532 =item *
533  
534 Michael McClimon
535  
536 =back
537  
538 =head1 COPYRIGHT AND LICENSE
539  
540 This software is copyright (c) 2015 by Rob N ★.
541  
542 This is free software; you can redistribute it and/or modify it under
543 the same terms as the Perl 5 programming language system itself.
544  
545 =cut
« Consul/API/Health.pm ↑ Summary Consul/API/Catalog.pm »