blib/lib/Web/MREST/CLI.pm untested

filter: Statementstmt 0.0% 0 / 148 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 222 SCAR 59.4
CC
19
Cov
0%
send_req
90.0
init_cli_client
72.0
normalize_filespec
12.0
CRAP 380.0
1 # *************************************************************************
2 # Copyright (c) 2014-2015, SUSE LLC
3 #
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in the
14 # documentation and/or other materials provided with the distribution.
15 #
16 # 3. Neither the name of SUSE LLC nor the names of its contributors may be
17 # used to endorse or promote products derived from this software without
18 # specific prior written permission.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 # POSSIBILITY OF SUCH DAMAGE.
31 # *************************************************************************
32  
33 # ------------------------
34 # Model module
35 # ------------------------
36  
37 package Web::MREST::CLI;
38  
39 use 5.012;
40 use strict;
41 use warnings;
42  
43 use App::CELL qw( $CELL $log $site $meta );
44 use App::CELL::Test qw( _touch );
45 use Carp qw( confess );
46 use Data::Dumper;
47 use Encode;
48 use Exporter qw( import ); # Exporter was first released with perl 5
49 use File::HomeDir; # File::HomeDir was not in CORE (or so I think)
50 use File::Spec; # File::Spec was first released with perl 5.00405
51 use HTTP::Request::Common qw( GET PUT POST DELETE );
52 use JSON;
53 use Log::Any::Adapter;
54 use LWP::UserAgent;
55 use LWP::Protocol::https;
56 #print "LWP::UserAgent: ".LWP::UserAgent->VERSION,"\n";
57 #print "LWP::Protocol::https: ".LWP::Protocol::https->VERSION,"\n";
58 use Params::Validate qw( :all );
59 use URI::Escape;
60  
61  
62  
63  
64 =head1 NAME
65  
66 Web::MREST::CLI - CLI components for Web::MEST-based applications
67  
68  
69  
70  
71 =head1 VERSION
72  
73 Version 0.283
74  
75 =cut
76  
77 our $VERSION = '0.283';
78  
79  
80  
81  
82 =head1 DESCRIPTION
83  
84 Top-level module of the L<Web::MREST::CLI> distribution. Exports some
85 "generalized" functions that are used internally and might also be useful for
86 writing CLI clients in general.
87  
88 =cut
89  
90  
91  
92 =head1 EXPORTS
93  
94 =cut
95  
96 our @EXPORT_OK = qw( init_cli_client normalize_filespec send_req );
97  
98  
99  
100  
101 =head1 PACKAGE VARIABLES
102  
103 =cut
104  
105 # user agent
106 my $ua = LWP::UserAgent->new(
107 ssl_opts => {
108 verify_hostname => 1,
109 }
110 );
111  
112 # dispatch table with references to HTTP::Request::Common functions
113 my %methods = (
114 GET => \&GET,
115 PUT => \&PUT,
116 POST => \&POST,
117 DELETE => \&DELETE,
118 );
119  
120 my %sh;
121 our $JSON = JSON->new->allow_nonref->convert_blessed->utf8->pretty;
122  
123  
124  
125  
126 =head1 FUNCTIONS
127  
128  
129 =head2 init_cli_client
130  
131 Takes PARAMHASH containing possible parameters C<distro>, C<sitedir>,
132 and C<debug_mode>. Initializes CLI client and returns a status object.
133  
134 The C<distro> string should use hyphens instead of double-colons, i.e.
135 C<Foo-Bar> instead of C<Foo::Bar>.
136  
137 =cut
138  
139 sub init_cli_client {
140 my ( %ARGS ) = validate( @_, {
141 distro => { type => SCALAR },
142 sitedir => { type => ARRAYREF|SCALAR|UNDEF, optional => 1 },
143 early_debug => { type => SCALAR|UNDEF, optional => 1 },
144 } );
145  
146 my $tf = $ARGS{'early_debug'};
147 if ( $tf ) {
148 _touch $tf;
149 if ( -r $tf and -w $tf ) {
150 unlink $tf;
151 Log::Any::Adapter->set( 'File', $tf );
152 $log->debug( __PACKAGE__ . "::init_cli_client activating early debug logging to $tf" );
153 } else {
154 print "Given unreadable/unwritable early debugging filespec $tf\n";
155 }
156 }
157  
158 my @targets;
159 if ( defined( $ARGS{'sitedir'} ) ) {
160 if ( ref( $ARGS{'sitedir'} ) eq 'ARRAY' ) {
161 @targets = @{ $ARGS{'sitedir'} };
162 }
163 if ( ref( $ARGS{'sitedir'} ) eq '' ) {
164 @targets = ( $ARGS{'sitedir'} );
165 }
166 }
167 my $target = File::ShareDir::dist_dir( $ARGS{'distro'} );
168 my $status = $CELL->load( verbose => 1, sitedir => $target );
169 die $status->text unless $status->ok;
170 foreach my $target ( @targets ) {
171 print "Loading configuration files from $target\n";
172 $status = $CELL->load( verbose => 1, sitedir => $target );
173 print "WARNING: " . $status->text . "\n" unless $status->ok;
174 }
175  
176 # initialize the LWP::UserAgent object
177 init_ua();
178  
179 return $CELL->status_ok( 'MREST_CLI_INIT_OK' );
180 }
181  
182  
183 =head2 normalize_filespec
184  
185 Given a filename (path) which might be relative or absolute, return an absolute
186 version. If the path was relative, it will be anchored to the home directory of
187 the user we are running as.
188  
189 =cut
190  
191 sub normalize_filespec {
192 my $fs = shift;
193 confess "normalize_filespec(): missing argument!" unless $fs;
194 my $is_absolute = File::Spec->file_name_is_absolute( $fs );
195 if ( $is_absolute ) {
196 return $fs;
197 }
198 return File::Spec->catfile( File::HomeDir->my_home, $fs );
199 }
200  
201  
202 =head2 init_ua
203  
204 Initialize the LWP::UserAgent singleton object.
205  
206 =cut
207  
208 sub init_ua {
209 my $cookie_jar = $site->MREST_CLI_COOKIE_JAR;
210 if ( $cookie_jar ) {
211 $cookie_jar = normalize_filespec( $cookie_jar );
212 print( "Cookie jar: $cookie_jar\n" );
213 } else {
214 die "UFGaRAL! MREST_CLI_COOKIE_JAR site param undefined!";
215 }
216 $ua->cookie_jar( { file => $cookie_jar } );
217 return;
218 }
219  
220  
221 =head2 cookie_jar
222  
223 Return the cookie_jar associated with our user agent.
224  
225 =cut
226  
227 sub cookie_jar { $ua->cookie_jar };
228  
229  
230 =head2 send_req
231  
232 Send a request to the server, get the response, convert it from JSON, and
233 return it to caller. Die on unexpected errors.
234  
235 =cut
236  
237 sub send_req {
238 no strict 'refs';
239 # process arguments
240 my ( $method, $path, $body_data ) = validate_pos( @_,
241 { type => SCALAR },
242 { type => SCALAR },
243 { type => SCALAR|UNDEF, optional => 1 },
244 );
245 $log->debug( "Entering " . __PACKAGE__ . "::send_req with $method $path" );
246 if ( ! defined( $body_data ) ) {
247 # HTTP::Message 6.10 complains if request content is undefined
248 $log->debug( "No request content given; setting to empty string" );
249 $body_data = '';
250 }
251  
252 # initialize suppressed headers hash %sh
253 map {
254 $log->debug( "Suppressing header $_" );
255 $sh{ lc $_ } = '';
256 } @{ $site->MREST_CLI_SUPPRESSED_HEADERS } unless %sh;
257  
258 $path = "/$path" unless $path =~ m/^\//;
259 $log->debug("send_req: path is $path");
260  
261 # convert body data to UTF-8
262 my $encoded_body_data = encode( "UTF-8", $body_data );
263  
264 # assemble request
265 my $url = $meta->MREST_CLI_URI_BASE || 'http://localhost:5000';
266 $url .= uri_escape( $path, '%' );
267 $log->debug( "Encoded URI is $url" );
268 my $r = $methods{$method}->(
269 $url,
270 Accept => 'application/json',
271 Content_Type => 'application/json',
272 Content => $body_data,
273 );
274  
275 # add basic auth
276 my $user = $meta->CURRENT_EMPLOYEE_NICK || 'demo';
277 my $password = $meta->CURRENT_EMPLOYEE_PASSWORD || 'demo';
278 $log->debug( "send_req: basic auth user $user / pass $password" );
279 $r->authorization_basic( $user, $password );
280  
281 # send request, get response
282 my $response = $ua->request( $r );
283 $log->debug( "Response is " . Dumper( $response ) );
284 my $code = $response->code;
285  
286 # process response entity
287 my $status;
288 my $content = $response->content;
289 #$log->debug( "Response entity is " . Dumper( $content ) );
290 if ( $content ) {
291 #my $unicode_content = decode( "UTF-8", $content );
292  
293 # if the content is a bare string, enclose it in double quotes
294 if ( $content =~ m/^[^\{].*[^\}]$/s ) {
295 $content =~ s/\n//g;
296 $log->debug( "Adding double quotes to bare JSON string" );
297 $content = '"' . $content . '"';
298 }
299  
300 my $perl_scalar = $JSON->decode( $content );
301  
302 if ( ref( $perl_scalar ) ) {
303 # if it's a hash, we have faith that it will bless into a status object
304 $status = bless $perl_scalar, 'App::CELL::Status';
305 } elsif ( $perl_scalar eq 'Unauthorized' ) {
306 $status = $CELL->status_err(
307 'MREST_CLI_UNAUTHORIZED',
308 payload => $response->code . ' ' . $response->message
309 );
310 $log->error("Unauthorized");
311 } else {
312 $status = $CELL->status_err( 'MREST_OTHER_ERROR_REPORT_THIS_AS_A_BUG', payload => $perl_scalar );
313 $log->error("Unexpected HTTP response ->$perl_scalar<-" );
314 }
315 } else {
316 $status = $CELL->status_warn( 'MREST_CLI_HTTP_REQUEST_OK_NODATA' );
317 }
318 $status->{'http_status'} = $response->code . ' ' . $response->message;
319  
320 # load up headers
321 $status->{'headers'} = {};
322 $response->headers->scan( sub {
323 my ( $h, $v ) = @_;
324 $status->{'headers'}->{$h} = $v unless exists $sh{ lc $h };
325 } );
326 return $status;
327 }
328  
329 1;