Client.pm

filter: Statementstmt 98.5% 133 / 135 Branchbran 95.2% 40 / 42 Conditioncond 81.8% 9 / 11 MC/DCmcdc 66.6% 4 / 6 Subroutinesub 100% 23 / 23 Podpod 84.6% 11 / 13 totaltotal 95.6% 220 / 230 CC 30 SCAR 13.7
CC
30
Cov
97%
request
6.0
every
6.0
_lc_merge
5.3
CRAP 4.0
« Client/Response.pm ↑ Summary Client/Auth.pm »
1 #
2 # Copyright (c) 2019 cPanel, L.L.C.
3 # All rights reserved.
4 # http://cpanel.net/
5 #
6 # Distributed under the terms of the MIT license. See the LICENSE file for
7 # further details.
8 #
9 package OpenStack::Client;
10  
11 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 2 ▶use HTTP::Request ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use LWP::UserAgent ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 2 ▶use JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use URI::Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 2 ▶use OpenStack::Client::Response ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 2 our $VERSION = '1.0006';
23  
24 =encoding utf8
25  
26 =head1 NAME
27  
28 OpenStack::Client - A cute little client to OpenStack services
29  
30 =head1 SYNOPSIS
31  
32 #
33 # First, connect to an API endpoint via the Keystone
34 # authorization service
35 #
36 use OpenStack::Client::Auth ();
37  
38 my $endpoint = 'http://openstack.foo.bar:5000/v2.0';
39  
40 my $auth = OpenStack::Client::Auth->new($endpoint,
41 'tenant' => $ENV{'OS_TENANT_NAME'},
42 'username' => $ENV{'OS_USERNAME'},
43 'password' => $ENV{'OS_PASSWORD'}
44 );
45  
46 my $glance = $auth->service('image',
47 'region' => $ENV{'OS_REGION_NAME'}
48 );
49  
50 my @images = $glance->all('/v2/images', 'images');
51  
52 #
53 # Or, connect directly to an API endpoint by URI
54 #
55 use OpenStack::Client ();
56  
57 my $endpoint = 'http://glance.foo.bar:9292';
58  
59 my $glance = OpenStack::Client->new($endpoint,
60 'token' => {
61 'id' => 'foo'
62 }
63 );
64  
65 my @images = $glance->all('/v2/images', 'images');
66  
67 =head1 DESCRIPTION
68  
69 C<OpenStack::Client> is a no-frills OpenStack API client which provides generic
70 access to OpenStack APIs with minimal remote service discovery facilities; with
71 a minimal client, the key understanding of the remote services are primarily
72 predicated on an understanding of the authoritative OpenStack API documentation:
73  
74 http://developer.openstack.org/api-ref.html
75  
76 Authorization, authentication, and access to OpenStack services such as the
77 OpenStack Compute and Networking APIs is made convenient by
78 L<OpenStack::Client::Auth>. Further, some small handling of response body data
79 such as obtaining the full resultset of a paginated response is handled for
80 convenience.
81  
82 Ordinarily, a client can be obtained conveniently by using the C<services()>
83 method on a L<OpenStack::Client::Auth> object.
84  
85 =head1 INSTANTIATION
86  
87 =over
88  
89 =item C<OpenStack::Client-E<gt>new(I<$endpoint>, I<%opts>)>
90  
91 Create a new C<OpenStack::Client> object connected to the specified
92 I<$endpoint>. The following values may be specified in I<%opts>:
93  
94 =over
95  
96 =item * B<token>
97  
98 A token obtained from a L<OpenStack::Client::Auth> object.
99  
100 =back
101  
102 =cut
103  
104 sub new ($%) {
105 60 ▶ my ($class, $endpoint, %opts) = @_;
Subroutine new: called CC=5 SCAR=16.1
Pod documented
106  
107 60 ▶ die 'No API endpoint provided' unless $endpoint;
Branch: 1 branch
BranchTrueFalseTotal
unless $endpoint 1 59 60
108  
109 59 ▶ $opts{'package_ua'} ||= 'LWP::UserAgent';
Condition100%2/2
$opts{"package_ua"} ||= "LWP::UserAgent"
l!l
572
MC/DC100%1/1
$opts{"package_ua"} ||= "LWP::UserAgent"
$opts{"package_ua"}
Truth table100%2/2
A
A= $opts{"package_ua"}
Aresult
11
00
110 59 ▶ $opts{'package_request'} ||= 'HTTP::Request';
Condition100%2/2
$opts{"package_request"} ||= "HTTP::Request"
l!l
572
MC/DC100%1/1
$opts{"package_request"} ||= "HTTP::Request"
$opts{"package_request"}
Truth table100%2/2
A
A= $opts{"package_request"}
Aresult
11
00
111 59 ▶ $opts{'package_response'} ||= 'OpenStack::Client::Response';
Condition100%2/2
$opts{"package_response"} ||= "OpenStack::Client::Response"
l!l
572
MC/DC100%1/1
$opts{"package_response"} ||= "OpenStack::Client::Response"
$opts{"package_response"}
Truth table100%2/2
A
A= $opts{"package_response"}
Aresult
11
00
112  
113 59 my $ua = $opts{'package_ua'}->new(
114 'ssl_opts' => {
115 'verify_hostname' => 0
116 }
117 );
118  
119 return bless {
120 'package_ua' => $opts{'package_ua'},
121 'package_request' => $opts{'package_request'},
122 'package_response' => $opts{'package_response'},
123 'ua' => $ua,
124 'endpoint' => $endpoint,
125 59 'token' => $opts{'token'}
126 }, $class;
127 }
128  
129 =back
130  
131 =head1 INSTANCE METHODS
132  
133 These methods are useful for identifying key attributes of an OpenStack service
134 endpoint client.
135  
136 =over
137  
138 =item C<$client-E<gt>endpoint()>
139  
140 Return the absolute HTTP URI to the endpoint this client provides access to.
141  
142 =cut
143  
144 sub endpoint ($) {
145 13 ▶ shift->{'endpoint'};
Subroutine endpoint: called CC=1 SCAR=0.0
Pod documented
146 }
147  
148 =item C<$client-E<gt>token()>
149  
150 If a token object was specified when creating C<$client>, then return it.
151  
152 =cut
153  
154 sub token ($) {
155 50 ▶ shift->{'token'};
Subroutine token: called CC=1 SCAR=0.0
Pod documented
156 }
157  
158 sub uri ($$) {
159 52 ▶ my ($self, $path) = @_;
Subroutine uri: called CC=1 SCAR=0.0
Pod undocumented
160  
161 return join '/', map {
162 104 my $part = $_;
163  
164 104 $part =~ s/^\///;
165 104 $part =~ s/\/$//;
166 104 $part
167 52 } $self->{'endpoint'}, $path;
168 }
169  
170 =back
171  
172 =head1 PERFORMING REMOTE CALLS
173  
174 =over
175  
176 =cut
177  
178 sub request {
179 49 ▶ my ($self, %args) = @_;
Subroutine request: called CC=6 SCAR=17.9
Pod undocumented
180  
181 49 ▶ $args{'headers'} ||= {};
Condition100%2/2
$args{"headers"} ||= {}
l!l
3613
MC/DC100%1/1
$args{"headers"} ||= {}
$args{"headers"}
Truth table100%2/2
A
A= $args{"headers"}
Aresult
11
00
182  
183 my $request = $self->{'package_request'}->new(
184 49 $args{'method'} => $self->uri($args{'path'})
185 );
186  
187 49 my @headers = $self->_get_headers_list($args{'headers'});
188  
189 49 my $count = scalar @headers;
190  
191 49 ▶ for (my $i=0; $i<$count; $i+=2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $count) 198 49 247
192 198 my $name = $headers[$i];
193 198 my $value = $headers[$i+1];
194  
195 198 $request->header($name => $value);
196 }
197  
198 49 ▶ if (defined $args{'body'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"body"}) 26 23 49
199 #
200 # Allow the request body to be supplied by a subroutine reference
201 # which, when called, will supply a chunk of data returned as per the
202 # behavior of LWP::UserAgent. This is useful for uploading arbitrary
203 # amounts of data in a request body.
204 #
205 26 ▶ if (ref($args{'body'}) =~ /CODE/) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref($args{'body'}) =~ /CODE/) { } 1 25 26
206 1 $request->content($args{'body'});
207 } else {
208 25 $request->content(JSON::encode_json($args{'body'}));
209 }
210 }
211  
212 return bless $self->{'ua'}->request($request,
213 defined $args{'handler'}? $args{'handler'}: ()),
214 49 ▶ $self->{'package_response'};
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'handler'} ? : 1 48 49
215 }
216  
217 =item C<$client-E<gt>call(I<$args>)>
218  
219 Perform a call to the service endpoint using named arguments in the hash. The
220 following arguments are required:
221  
222 =over
223  
224 =item C<method> - Request method
225  
226 =item C<path> - Resource path
227  
228 =back
229  
230 The following arguments are optional:
231  
232 =over
233  
234 =item C<headers> - Request headers
235  
236 Headers are case I<insensitive>; if duplicate header values are declared under
237 different cases, it is undefined which headers shall take precedence. The
238 following headers are sent by default:
239  
240 =over
241  
242 =item Accept
243  
244 Defaults to C<application/json, text/plain>.
245  
246 =item Accept-Encoding
247  
248 Defaults to C<identity, gzip, deflate, compress>.
249  
250 =item Content-Type
251  
252 Defaults to C<application/json>, although some API calls (e.g., a PATCH)
253 expect a different type; the case of an image update, the expected
254 type is C<application/openstack-images-v2.1-json-patch> or some version
255 thereof.
256  
257 =back
258  
259 Except for C<X-Auth-Token>, any additional token will be added to the request.
260  
261 =item C<body> - Request body
262  
263 This may be a scalar reference to a data structure to be encoded to JSON, or a
264 CODE reference to a subroutine which, when called, will return a chunk of data
265 to be supplied to the API endpoint; the stream is ended when the supplied
266 subroutine returns an empty string or undef.
267  
268 =item C<handler> - Response body handler function
269  
270 When specified, this function will be called with two arguments; the first
271 argument is a scalar value containing a chunk of data in the response body, and
272 the second is a scalar reference to a L<HTTP::Response> object representing the
273 current response. This is useful for retrieving very large resources without
274 having to store the entire response body in memory at once for parsing.
275  
276 =back
277  
278 All forms of this method may return the following:
279  
280 =over
281  
282 =item * For B<application/json>: A decoded JSON object
283  
284 =item * For other response types: The unmodified response body
285  
286 =back
287  
288 In exceptional conditions (such as when the service returns a 4xx or 5xx HTTP
289 response), the client will die with the raw text response from the HTTP
290 service, indicating the nature of the service-side failure to service the
291 current call.
292  
293 =item C<$client-E<gt>call(I<$method>, I<$path>, I<$body>)>
294  
295 Perform a call to the service endpoint using the HTTP method I<$method>,
296 accessing the resource I<$path> (relative to the absolute endpoint URI),
297 passing an arbitrary value in I<$body>.
298  
299 =item C<$client-E<gt>call(I<$method>, I<$headers>, I<$path>, I<$body>)>
300  
301 Perform a call to the service endpoint using the HTTP method I<$method>,
302 accessing the resource I<$path> (relative to the absolute endpoint URI),
303 specifying the headers in I<$headers>, passing an arbitrary value in I<$body>.
304  
305 =back
306  
307 =head1 EXAMPLES
308  
309 The following shows how one may update image metadata using the PATCH method
310 supported by version 2 of the Image API. C<@image_updates> is an array of hash
311 references of the structure defined by the PATCH RFC (6902) governing
312 "JavaScript Object Notation (JSON) Patch"; i.e., operations consisting of
313 C<add>, C<replace>, or C<delete>.
314  
315 my $headers = {
316 'Content-Type' => 'application/openstack-images-v2.1-json-patch'
317 };
318  
319 my $response = $glance->call({
320 'method' => 'PATCH',
321 'headers' => $headers,
322 'path' => qq[/v2/images/$image->{id}],
323 'body' => \@image_updates
324 );
325  
326 =cut
327  
328 sub call {
329 73 ▶ my $self = shift;
Subroutine call: called CC=5 SCAR=16.2
Pod documented
330  
331 73 ▶ if (scalar @_ == 4) {
Branch: 4 branches
BranchTrueFalseTotal
if (scalar @_ == 4) { } 3 70 73
elsif (scalar @_ == 3) { } 11 59 70
elsif (scalar @_ == 2) { } 22 37 59
elsif (scalar @_ != 1) { } 0 37 37
332 3 return $self->call({
333 'method' => $_[0],
334 'headers' => $_[1],
335 'path' => $_[2],
336 'body' => $_[3]
337 });
338 } elsif (scalar @_ == 3) {
339 11 return $self->call({
340 'method' => $_[0],
341 'headers' => {},
342 'path' => $_[1],
343 'body' => $_[2],
344 });
345 } elsif (scalar @_ == 2) {
346 22 return $self->call({
347 'method' => $_[0],
348 'headers' => {},
349 'path' => $_[1],
350 'body' => undef
351 });
352 } elsif (scalar @_ != 1) {
353 0 die "Invalid number of arguments: @_";
354 }
355  
356 37 my ($args) = @_;
357  
358 37 return $self->request(%{$args})->decode_json;
359 }
360  
361 sub _lc_merge {
362 98 ▶ my ($a, $b, %opts) = @_;
Subroutine _lc_merge: called CC=5 SCAR=16.6
363  
364 my %lc_keys_a = map {
365 155 lc $_ => $_
366 98 } keys %{$a};
367  
368 98 foreach my $key_b (keys %{$b}) {
369 196 my $key_a = $lc_keys_a{lc $key_b};
370  
371 196 ▶ if (!defined($key_a)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $key_a) { } 192 4 196
elsif (exists $a->{$key_a} and $opts{'replace'}) { } 0 4 4
372 192 $a->{$key_b} = $b->{$key_b};
373 ▶ } elsif (exists $a->{$key_a} && $opts{'replace'}) {
Condition33%1/3
exists $a->{$key_a} and $opts{"replace"}
!ll&&!rl&&r
040
MC/DC0%0/2
exists $a->{$key_a} and $opts{"replace"}
exists $a->{$key_a} $opts{"replace"}
Truth table33%1/3
A and B
A= exists $a->{$key_a}B= $opts{"replace"}
ABresult
0X0
100
111
374 0 $a->{$key_a} = $b->{$key_b};
375 }
376 }
377  
378 98 return;
379 }
380  
381 #
382 # Internal method for call() to process headers; returns a list of header name
383 # and value pairs
384 #
385 sub _get_headers_list {
386 49 ▶ my ($self, $headers) = @_;
Subroutine _get_headers_list: called CC=1 SCAR=0.0
387  
388 49 my %DEFAULTS = (
389 'Accept' => 'application/json, text/plain',
390 'Accept-Encoding' => 'identity, gzip, deflate, compress',
391 'Content-Type' => 'application/json'
392 );
393  
394 #
395 # The client should be not adding X-Auth-Token explicitly, so force it to
396 # the one received during authentication
397 #
398 49 my %OVERRIDES = (
399 'X-Auth-Token' => $self->token
400 );
401  
402 49 my %new_headers = %{$headers};
403  
404 49 _lc_merge(\%new_headers, \%DEFAULTS);
405 49 _lc_merge(\%new_headers, \%OVERRIDES, 'replace' => 1);
406  
407 49 return %new_headers;
408 }
409  
410 =head1 FETCHING REMOTE RESOURCES
411  
412 =over
413  
414 =item C<$client-E<gt>get(I<$path>, I<%opts>)>
415  
416 Issue an HTTP GET request for resource I<$path>. The keys and values
417 specified in I<%opts> will be URL encoded and appended to I<$path> when forming
418 the request. Response bodies are decoded as per C<$client-E<gt>call()>.
419  
420 =cut
421  
422 sub get ($$%) {
423 15 ▶ my ($self, $path, %opts) = @_;
Subroutine get: called CC=5 SCAR=16.1
Pod documented
424  
425 15 my $params;
426  
427 15 foreach my $name (sort keys %opts) {
428 9 my $value = $opts{$name};
429  
430 9 ▶ $params .= "&" if defined $params;
Branch: 1 branch
BranchTrueFalseTotal
if defined $params 2 7 9
431  
432 $params .= sprintf "%s=%s", map {
433 9 URI::Encode::uri_encode($_)
434 } $name, $value;
435 }
436  
437 15 ▶ if (defined $params) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params) 7 8 15
438 #
439 # $path might already have request parameters; if so, just append
440 # subsequent values with a & rather than ?.
441 #
442 7 ▶ if ($path =~ /\?/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /\?/) { } 1 6 7
443 1 $path .= "&$params";
444 } else {
445 6 $path .= "?$params";
446 }
447 }
448  
449 15 return $self->call('GET' => $path);
450 }
451  
452 =item C<$client-E<gt>each(I<$path>, I<$opts>, I<$callback>)>
453  
454 =item C<$client-E<gt>each(I<$path>, I<$callback>)>
455  
456 Issue an HTTP GET request for the resource I<$path>, while passing each
457 decoded response object to I<$callback> in a single argument. I<$opts> is taken
458 to be a HASH reference containing zero or more key-value pairs to be URL encoded
459 as parameters to each GET request made.
460  
461 =cut
462  
463 sub each ($$@) {
464 4 ▶ my ($self, $path, @args) = @_;
Subroutine each: called CC=4 SCAR=13.9
Pod documented
465  
466 4 my $opts = {};
467 4 my $callback;
468  
469 4 ▶ if (scalar @args == 2) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @args == 2) { } 1 3 4
elsif (scalar @args == 1) { } 1 2 3
470 1 ($opts, $callback) = @args;
471 } elsif (scalar @args == 1) {
472 1 ($callback) = @args;
473 } else {
474 2 die 'Invalid number of arguments';
475 }
476  
477 2 ▶ while (defined $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path) 2 2 4
478 2 my $result = $self->get($path, %{$opts});
479  
480 2 $callback->($result);
481  
482 2 $path = $result->{'next'};
483 }
484  
485 2 return;
486 }
487  
488 =item C<$client-E<gt>every(I<$path>, I<$attribute>, I<$opts>, I<$callback>)>
489  
490 =item C<$client-E<gt>every(I<$path>, I<$attribute>, I<$callback>)>
491  
492 Perform a series of HTTP GET request for the resource I<$path>, decoding the
493 result set and passing each value within each physical JSON response object's
494 attribute named I<$attribute>, to the callback I<$callback> as a single
495 argument. I<$opts> is taken to be a HASH reference containing zero or more
496 key-value pairs to be URL encoded as parameters to each GET request made.
497  
498 =cut
499  
500 sub every ($$$@) {
501 7 ▶ my ($self, $path, $attribute, @args) = @_;
Subroutine every: called CC=6 SCAR=17.9
Pod documented
502  
503 7 my $opts = {};
504 7 my $callback;
505  
506 7 ▶ if (scalar @args == 2) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @args == 2) { } 3 4 7
elsif (scalar @args == 1) { } 2 2 4
507 3 ($opts, $callback) = @args;
508 } elsif (scalar @args == 1) {
509 2 ($callback) = @args;
510 } else {
511 2 die 'Invalid number of arguments';
512 }
513  
514 5 ▶ while (defined $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path) 8 4 12
515 8 my $result = $self->get($path, %{$opts});
516  
517 8 ▶ unless (defined $result->{$attribute}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $result->{$attribute}) 1 7 8
518 1 my $keys = join( ', ', sort keys %$result );
519 1 die "Response from $path does not contain attribute '$attribute', possible options are " . $keys;
520 }
521  
522 7 foreach my $item (@{$result->{$attribute}}) {
523 12 $callback->($item);
524 }
525  
526 7 $path = $result->{'next'};
527 }
528  
529 4 return;
530 }
531  
532 =item C<$client-E<gt>all(I<$path>, I<$attribute>, I<$opts>)>
533  
534 =item C<$client-E<gt>all(I<$path>, I<$attribute>)>
535  
536 Perform a series of HTTP GET requests for the resource I<$path>, decoding the
537 result set and returning a list of all items found within each response body's
538 attribute named I<$attribute>. I<$opts> is taken to be a HASH reference
539 containing zero or more key-value pairs to be URL encoded as parameters to each
540 GET request made.
541  
542 =cut
543  
544 sub all ($$$@) {
545 2 ▶ my ($self, $path, $attribute, $opts) = @_;
Subroutine all: called CC=1 SCAR=0.0
Pod documented
546  
547 2 my @items;
548  
549 $self->every($path, $attribute, $opts, sub {
550 6 ▶ my ($item) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
551  
552 6 push @items, $item;
553 2 });
554  
555 2 return @items;
556 }
557  
558 =back
559  
560 =head1 CREATING AND UPDATING REMOTE RESOURCES
561  
562 =over
563  
564 =item C<$client-E<gt>put(I<$path>, I<$body>)>
565  
566 Issue an HTTP PUT request to the resource at I<$path>, in the form of a JSON
567 encoding of the contents of I<$body>.
568  
569 =cut
570  
571 sub put ($$$) {
572 1 ▶ my ($self, $path, $body) = @_;
Subroutine put: called CC=1 SCAR=0.0
Pod documented
573  
574 1 return $self->call('PUT' => $path, $body);
575 }
576  
577 =item C<$client-E<gt>post(I<$path>, I<$body>)>
578  
579 Issue an HTTP POST request to the resource at I<$path>, in the form of a
580 JSON encoding of the contents of I<$body>.
581  
582 =cut
583  
584 sub post ($$$) {
585 1 ▶ my ($self, $path, $body) = @_;
Subroutine post: called CC=1 SCAR=0.0
Pod documented
586  
587 1 return $self->call('POST' => $path, $body);
588 }
589  
590 =back
591  
592 =head1 DELETING REMOTE RESOURCES
593  
594 =over
595  
596 =item C<$client-E<gt>delete(I<$path>)>
597  
598 Issue an HTTP DELETE request of the resource at I<$path>.
599  
600 =cut
601  
602 sub delete ($$) {
603 1 ▶ my ($self, $path) = @_;
Subroutine delete: called CC=1 SCAR=0.0
Pod documented
604  
605 1 return $self->call('DELETE' => $path);
606 }
607  
608 =back
609  
610 =head1 SEE ALSO
611  
612 =over
613  
614 =item L<OpenStack::Client::Auth>
615  
616 The OpenStack Keystone authentication and authorization interface
617  
618 =back
619  
620 =head1 AUTHOR
621  
622 Written by Alexandra Hrefna Maheu <xan@cpanel.net>
623  
624 =head1 CONTRIBUTORS
625  
626 =over
627  
628 =item Brett Estrade <brett@cpanel.net>
629  
630 =back
631  
632 =head1 COPYRIGHT
633  
634 Copyright (c) 2019 cPanel, L.L.C. Released under the terms of the MIT license.
635 See LICENSE for further details.
636  
637 =cut
638  
639 2 1;
« Client/Response.pm ↑ Summary Client/Auth.pm »