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

filter: Statementstmt 0.0% 0 / 139 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 207 SCAR 56.1
CC
16
Cov
0%
send_req
90.0
init_cli_client
30.0
normalize_filespec
12.0
CRAP 272.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.280
74  
75 =cut
76  
77 our $VERSION = '0.280';
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 => 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 foreach my $target ( File::ShareDir::dist_dir( $ARGS{'distro'} ), $ARGS{'sitedir'} ) {
159 if ( $target ) {
160 print "Loading configuration files from $target\n";
161 my $status = $CELL->load( verbose => 1, sitedir => $target );
162 die Dumper( $status ) unless $status->ok;
163 }
164 }
165  
166 # initialize the LWP::UserAgent object
167 init_ua();
168  
169 return $CELL->status_ok( 'MREST_CLI_INIT_OK' );
170 }
171  
172  
173 =head2 normalize_filespec
174  
175 Given a filename (path) which might be relative or absolute, return an absolute
176 version. If the path was relative, it will be anchored to the home directory of
177 the user we are running as.
178  
179 =cut
180  
181 sub normalize_filespec {
182 my $fs = shift;
183 confess "normalize_filespec(): missing argument!" unless $fs;
184 my $is_absolute = File::Spec->file_name_is_absolute( $fs );
185 if ( $is_absolute ) {
186 return $fs;
187 }
188 return File::Spec->catfile( File::HomeDir->my_home, $fs );
189 }
190  
191  
192 =head2 init_ua
193  
194 Initialize the LWP::UserAgent singleton object.
195  
196 =cut
197  
198 sub init_ua {
199 my $cookie_jar = $site->MREST_CLI_COOKIE_JAR;
200 if ( $cookie_jar ) {
201 $cookie_jar = normalize_filespec( $cookie_jar );
202 print( "Cookie jar: $cookie_jar\n" );
203 } else {
204 die "UFGaRAL! MREST_CLI_COOKIE_JAR site param undefined!";
205 }
206 $ua->cookie_jar( { file => $cookie_jar } );
207 return;
208 }
209  
210  
211 =head2 cookie_jar
212  
213 Return the cookie_jar associated with our user agent.
214  
215 =cut
216  
217 sub cookie_jar { $ua->cookie_jar };
218  
219  
220 =head2 send_req
221  
222 Send a request to the server, get the response, convert it from JSON, and
223 return it to caller. Die on unexpected errors.
224  
225 =cut
226  
227 sub send_req {
228 no strict 'refs';
229 # process arguments
230 my ( $method, $path, $body_data ) = validate_pos( @_,
231 { type => SCALAR },
232 { type => SCALAR },
233 { type => SCALAR|UNDEF, optional => 1 },
234 );
235 $log->debug( "Entering " . __PACKAGE__ . "::send_req with $method $path" );
236 if ( ! defined( $body_data ) ) {
237 # HTTP::Message 6.10 complains if request content is undefined
238 $log->debug( "No request content given; setting to empty string" );
239 $body_data = '';
240 }
241  
242 # initialize suppressed headers hash %sh
243 map {
244 $log->debug( "Suppressing header $_" );
245 $sh{ lc $_ } = '';
246 } @{ $site->MREST_CLI_SUPPRESSED_HEADERS } unless %sh;
247  
248 $path = "/$path" unless $path =~ m/^\//;
249 $log->debug("send_req: path is $path");
250  
251 # convert body data to UTF-8
252 my $encoded_body_data = encode( "UTF-8", $body_data );
253  
254 # assemble request
255 my $url = $meta->MREST_CLI_URI_BASE || 'http://localhost:5000';
256 $url .= uri_escape( $path, '%' );
257 $log->debug( "Encoded URI is $url" );
258 my $r = $methods{$method}->(
259 $url,
260 Accept => 'application/json',
261 Content_Type => 'application/json',
262 Content => $body_data,
263 );
264  
265 # add basic auth
266 my $user = $meta->CURRENT_EMPLOYEE_NICK || 'demo';
267 my $password = $meta->CURRENT_EMPLOYEE_PASSWORD || 'demo';
268 $log->debug( "send_req: basic auth user $user / pass $password" );
269 $r->authorization_basic( $user, $password );
270  
271 # send request, get response
272 my $response = $ua->request( $r );
273 $log->debug( "Response is " . Dumper( $response ) );
274 my $code = $response->code;
275  
276 # process response entity
277 my $status;
278 my $content = $response->content;
279 #$log->debug( "Response entity is " . Dumper( $content ) );
280 if ( $content ) {
281 #my $unicode_content = decode( "UTF-8", $content );
282  
283 # if the content is a bare string, enclose it in double quotes
284 if ( $content =~ m/^[^\{].*[^\}]$/s ) {
285 $content =~ s/\n//g;
286 $log->debug( "Adding double quotes to bare JSON string" );
287 $content = '"' . $content . '"';
288 }
289  
290 my $perl_scalar = $JSON->decode( $content );
291  
292 if ( ref( $perl_scalar ) ) {
293 # if it's a hash, we have faith that it will bless into a status object
294 $status = bless $perl_scalar, 'App::CELL::Status';
295 } elsif ( $perl_scalar eq 'Unauthorized' ) {
296 $status = $CELL->status_err(
297 'MREST_CLI_UNAUTHORIZED',
298 payload => $response->code . ' ' . $response->message
299 );
300 $log->error("Unauthorized");
301 } else {
302 $status = $CELL->status_err( 'MREST_OTHER_ERROR_REPORT_THIS_AS_A_BUG', payload => $perl_scalar );
303 $log->error("Unexpected HTTP response ->$perl_scalar<-" );
304 }
305 } else {
306 $status = $CELL->status_warn( 'MREST_CLI_HTTP_REQUEST_OK_NODATA' );
307 }
308 $status->{'http_status'} = $response->code . ' ' . $response->message;
309  
310 # load up headers
311 $status->{'headers'} = {};
312 $response->headers->scan( sub {
313 my ( $h, $v ) = @_;
314 $status->{'headers'}->{$h} = $v unless exists $sh{ lc $h };
315 } );
316 return $status;
317 }
318  
319 1;