lib/Command/Interactive.pm

filter: Statementstmt 98.5% 135 / 137 Branchbran 86.3% 57 / 66 Conditioncond 83.3% 10 / 12 MC/DCmcdc 75.0% 6 / 8 Subroutinesub 100% 15 / 15 Podpod 100% 1 / 1 totaltotal 93.7% 224 / 239 CC 39 SCAR 26.6
CC
39
Cov
94%
_run_via_expect
26.2
run
8.0
_show_output
3.0
CRAP 14.3
↑ Summary lib/Command/Interactive/Interaction.pm »
1 package Command::Interactive;
2 # ABSTRACT: handles interactive (and non-interactive) process invocation
3  
4 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 8 our $VERSION = '1.21';
8  
9 8 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =head1 NAME
12  
13 Command::Interactive- handles interactive (and non-interactive) process invocation through a reliable and easily configured interface.
14  
15 =head1 SYNOPSIS
16  
17 This module can be used to invoke both interactive and non-interactive commands with predicatable results.
18  
19 use Command::Interactive;
20 use Carp;
21  
22 # Simple, non-interactive usage
23 my $result = Command::Interactive->new->run("cp foo /tmp/");
24 croak "Could not copy foo to /tmp/: $result!" if($result);
25  
26 # Interactive usage supports output parsing
27 # and automated responses to discovered strings
28 my $password_prompt = Command::Interactive::Interaction->new({
29 expected_string => 'Please enter your password:',
30 response => 'secret',
31 });
32  
33 my $my_logging_fh;
34 my $command = Command::Interactive->new({
35 echo_output => 1,
36 output_stream => $my_logging_fh,
37 interactions => [ $password_prompt ],
38 });
39 my $restart_result = $command->run("ssh user\@somehost 'service apachectl restart'");
40 if($restart_result)
41 {
42 warn "Couldn't restart server!";
43 }
44  
45 =cut
46  
47 8 ▶use Command::Interactive::Interaction;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 8 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 8 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 8 ▶use Expect;
Subroutine BEGIN: called CC=1 SCAR=0.0
51  
52 =head1 FIELDS
53  
54 =head2 always_use_expect (DEFAULT: FALSE)
55  
56 Whether to use the C<Expect> module to execute system commands. By default, Expect is only used if one or more interactions() are specified.
57  
58 =cut
59  
60 8 has always_use_expect => (
61 is => 'rw',
62 isa => 'Bool',
63 default => 0,
64 );
65  
66 =head2 debug_logfile (DEFAULT: undef)
67  
68 The name of a file to which lots of debugging information should be written. Typically useful only for maintainers. If you want to see what your command is doing, use echo_output() and a debugging filehandle (or just STDOUT).
69  
70 =cut
71  
72 8 has debug_logfile => (
73 is => 'rw',
74 isa => 'Str',
75 );
76  
77 =head2 echo_output (DEFAULT: FALSE)
78  
79 Whether to echo output to the specified output_stream(). This allows users of
80 Command::Interactive to see what is going on, but it also can clutter an interface with lots of superfluous command output. Use it wisely.
81  
82 See web_format() for a discussion about how to format command output for web interfaces.
83  
84 =cut
85  
86 8 has echo_output => (
87 is => 'rw',
88 isa => 'Bool',
89 default => 0,
90 );
91  
92 =head2 interactions (DEFAULT: [], the empty arrayref)
93  
94 An array reference of Command::Interactive::Interaction objects that specify the
95 interactions that may (or must) occur during the execution of the command. See
96 C<Command::Interactive::Interaction> for more information on specifying rules about command interactions.
97  
98 =cut
99  
100 has interactions => (
101 is => 'rw',
102 isa => 'ArrayRef',
103 3 ▶ default => sub { [] }, # References are not allowed as defaults
Subroutine __ANON__: called CC=1 SCAR=0.0
104 8 );
105  
106 =head2 output_stream (DEFAULT: STDOUT)
107  
108 The stream object to which output should be sent when echo_output() is enabled. This is any object with a print() method; it needn't have a full C<IO>-compliant interface.
109  
110 =cut
111  
112 8 has output_stream => (
113 is => 'rw',
114 default => *STDOUT,
115 );
116  
117 =head2 timeout (DEFAULT: undef)
118  
119 If defined, represents the timeout (in seconds) that Command::Interactive will wait for output when run() is called.
120  
121 =cut
122  
123 8 has timeout => (
124 is => 'rw',
125 isa => 'Int',
126 );
127  
128 =head2 web_format (DEFAULT: FALSE)
129  
130 Whether to format strings for web output when print command output as a result of echo_output(). If this is true, \r, \n, and \r\n will be replaced with "<br/>\n".
131  
132 =cut
133  
134 8 has web_format => (
135 is => 'rw',
136 isa => 'Bool',
137 default => 0,
138 );
139  
140 =head1 METHODS
141  
142 =head2 run($command)
143  
144 This method does the heavy lifting of Command::Interactive. If one or more interactions() are specified (or if always_use_expect() is true), then the heavy lifting is dispatched to _run_via_expect(); otherwise this method uses traditional perl C<open("$command |")> approach.
145  
146 $command is expected to be a scalar (string), properly escaped, that could be
147 executed (e.g.) via system() or ``. No matter what command you provide, the bash
148 file descriptors for stdout and stderr are tied together using '2>&1' unless you
149 have done so already. This allows Command::Interactive to capture and react to both regular output and errors using the same mechanism.
150  
151 run() returns undef if the command is successful, otherwise it returns a string describing why the command failed (or was thought to have failed).
152  
153 The command you pass in via $command is expected to exit with status code 0 on
154 success. If it returns something different, Command::Interactive will incorrectly conclude that the command failed and will return a message to that effect.
155  
156 =cut
157  
158 20 ▶sub run {
Subroutine run: called CC=8 SCAR=20.8
Pod documented
159 20 my $self = shift;
160 20 my $command = shift;
161  
162 20 ▶ confess "No command provided" unless ($command);
Branch: 1 branch
BranchTrueFalseTotal
unless $command 1 19 20
163  
164 19 my $result;
165 19 ▶ if ($self->always_use_expect or @{$self->interactions}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->always_use_expect or @{$self->interactions;}) { } 14 5 19
Condition100%3/3
$self->always_use_expect or @{$self->interactions;}
l!l&&r!l&&!r
685
MC/DC100%2/2
$self->always_use_expect or @{$self->interactions;}
$self->always_use_expect @{$self->interactions;}
Truth table100%3/3
A or B
A= $self->always_use_expectB= @{$self->interactions;}
ABresult
1X1
011
000
166 # We'll to use Expect to handle this,
167 # which means that we will be able to
168 # respond to input requests
169 14 $result = $self->_run_via_expect($command);
170 } else {
171 5 my $use_command = $self->_fixup_command_to_catch_stderr($command);
172 5 $self->_log("Executing $use_command");
173 4 my $cfh = IO::File->new("$use_command|");
174 4 ▶ if ($cfh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfh) { } 2 2 4
175 2 ▶ while (my $output = <$cfh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $output = readline $cfh)) 1 2 3
176 1 $self->_log("open() returned output: $output");
177 1 $self->_show_output($output);
178 }
179 2 $cfh->close;
180 2 ▶ $result = ($? >> 8) ? "Error executing $command: $!" : undef;
Branch: 1 branch
BranchTrueFalseTotal
$? >> 8 ? : 1 1 2
181 } else {
182 2 $result = "Could not execute $command: $!";
183 }
184 }
185  
186 18 ▶ $self->_log($result ? "Returning result: $result for command $command" : "Returning undef result, signifying success");
Branch: 1 branch
BranchTrueFalseTotal
$result ? : 9 9 18
187 18 return $result;
188 }
189  
190 =head2 _show_output($chunk_of_output)
191  
192 If echo_output() is true, this command prints any output from $command to the chosen output_stream(). If web_format() is true, the output is first formatted for HTML by replacing end-of-line characters with "<br/>\n".
193  
194 =cut
195  
196 22 ▶sub _show_output {
Subroutine _show_output: called CC=3 SCAR=11.0
197 22 my $self = shift;
198 22 my $output = shift;
199  
200 22 ▶ return unless ($self->echo_output);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->echo_output 20 2 22
201  
202 2 ▶ $output =~ s/[\r\n]+/<br\/>\n/g if ($self->web_format);
Branch: 1 branch
BranchTrueFalseTotal
if $self->web_format 1 1 2
203 2 $self->_log("Stream output: $output");
204 2 return $self->output_stream->print($output);
205 }
206  
207 =head2 _run_via_expect($command)
208  
209 This method handles running commands with one or more interactions() (or for which always_use_expect() is true) via the Perl module C<Expect>.
210  
211 The return semantics of _run_via_expect() are identical to those of run().
212  
213 =cut
214  
215 14 ▶sub _run_via_expect {
Subroutine _run_via_expect: called CC=25 SCAR=32.7
216 14 my $self = shift;
217 14 my $command = shift;
218  
219 14 my $use_command = $self->_fixup_command_to_catch_stderr($command);
220  
221 14 $self->_log("Using Expect to spawn command: $use_command");
222  
223 14 my $exp = Expect->new;
224 14 $exp->raw_pty(1);
225 14 $exp->log_stdout(0);
226  
227 14 my $e = $exp->spawn($use_command);
228 14 ▶ return "Could not start $command: $!" unless ($e);
Branch: 1 branch
BranchTrueFalseTotal
unless $e 0 14 14
229  
230 14 my ($expect_array, $indexed_interactions) = $self->_generate_interaction_list;
231  
232 14 my $result;
233  
234 14 my ($match_position, $error, $matched_string, $before, $after);
235  
236 14 my $occurrences = [];
237  
238 14 my $already_closed = 0;
239  
240 EXPECT_READ:
241 14 ▶ while (!$error) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error) 20 0 20
242 20 ($match_position, $error, $matched_string, $before, $after) = $e->expect($self->timeout, @$expect_array);
243 20 ▶ if ($match_position) {
Branch: 2 branches
BranchTrueFalseTotal
if ($match_position) { } 8 12 20
elsif ($error) { } 12 0 12
244 # Collapse this all into string just in case
245 # you have a f-ing retarded value of $/ or an
246 # overridden version of CORE::print() that puts
247 # newlines at the end of each print call
248 8 my $show;
249 8 ▶ $show .= $before if (length($before));
Branch: 1 branch
BranchTrueFalseTotal
if length $before 3 5 8
250 8 $show .= $matched_string;
251 8 ▶ $show .= $after if (length($after));
Branch: 1 branch
BranchTrueFalseTotal
if length $after 8 0 8
252 8 $self->_show_output($show);
253  
254 # Determine whether this was an interactive
255 # request for a response, or an error
256 8 $match_position -= 1;
257 8 my $i = $indexed_interactions->[$match_position];
258 8 my $type = $i->type;
259 8 ▶ $occurrences->[$match_position] = 0 unless ($occurrences->[$match_position]);
Branch: 1 branch
BranchTrueFalseTotal
unless $occurrences->[$match_position] 7 1 8
260 8 $occurrences->[$match_position]++;
261 8 ▶ if ($i->is_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i->is_error) 1 7 8
262 1 $result = "Got error string '$matched_string', which matched error detection $type '" . $i->expected_string . "'";
263 1 last EXPECT_READ;
264 }
265  
266 7 ▶ if ($occurrences->[$match_position] > $i->max_allowed_occurrences) {
Branch: 1 branch
BranchTrueFalseTotal
if ($occurrences->[$match_position] > $i->max_allowed_occurrences) 1 6 7
267 1 $result =
268 "Got string '$matched_string', which matched expected $type '"
269 . $i->expected_string
270 . "'. This was occurrence #"
271 . $occurrences->[$match_position]
272 . ", which exceeds the specified limit of "
273 . $i->max_allowed_occurrences
274 . " occurrence(s) set for this $type";
275 1 last EXPECT_READ;
276 }
277 6 ▶ if ($i->response) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i->response) 1 5 6
278 1 $self->_log("Stream send: " . $i->response);
279 1 $e->send($i->actual_response_to_send);
280 }
281 } elsif ($error) {
282 12 ▶ if (($error eq '2:EOF') or $error =~ /3:Child PID (\d+) exited with/) {
Branch: 4 branches
BranchTrueFalseTotal
if ($error eq '2:EOF' or $error =~ /3:Child PID (\d+) exited with/) { } 11 1 12
elsif ($error eq '1:TIMEOUT') { } 1 0 1
elsif ($error =~ /^3: (.+)/) { } 0 0 0
elsif ($error =~ /^4:(.+)/) { } 0 0 0
Condition66%2/3
$error eq "2:EOF" or $error =~ /3:Child PID (\d+) exited with/
l!l&&r!l&&!r
0111
MC/DC50%1/2
$error eq "2:EOF" or $error =~ /3:Child PID (\d+) exited with/
$error eq "2:EOF" $error =~ /3:Child PID (\d+) exited with/
Truth table66%2/3
A or B
A= $error eq "2:EOF"B= $error =~ /3:Child PID (\d+) exited with/
ABresult
1X1
011
000
283 # Let's see if there were any required
284 # interactions that failed to occur
285 11 ▶ for (my $count = 0; $count < scalar(@$indexed_interactions); $count++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count < scalar @$indexed_interactions) 7 11 18
286 7 my $i = $indexed_interactions->[$count];
287 7 ▶ if ($i->is_required and not $occurrences->[$count]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i->is_required and not $occurrences->[$count]) 2 5 7
Condition66%2/3
$i->is_required and not $occurrences->[$count]
!ll&&!rl&&r
052
MC/DC50%1/2
$i->is_required and not $occurrences->[$count]
$i->is_required not $occurrences->[$count]
Truth table66%2/3
A and not(B)
A= $i->is_requiredB= not $occurrences->[$count]
ABresult
0X0
100
111
288 2 $result = "Failed to encounter required " . $i->type . " '" . $i->expected_string . "' before exit";
289 }
290 }
291 } elsif ($error eq '1:TIMEOUT') {
292 1 $result = "Got TIMEOUT from Expect (timeout=" . $self->timeout . " seconds)";
293 1 $e->hard_close;
294 1 $already_closed = 1;
295 } elsif ($error =~ /^3: (.+)/) # uncoverable
296 {
297 0 $result = "Failure on command: $1";
298 } elsif ($error =~ /^4:(.+)/) # uncoverable
299 {
300 0 $result = "Got error reading command filehandle: $1";
301 }
302 12 last EXPECT_READ;
303 }
304 }
305  
306 # Need to capture any remaining output
307 14 ▶ $self->_show_output($e->exp_before) if ($e->exp_before);
Branch: 1 branch
BranchTrueFalseTotal
if $e->exp_before 11 3 14
308 14 ▶ $e->expect(0) unless ($already_closed);
Branch: 1 branch
BranchTrueFalseTotal
unless $already_closed 13 1 14
309 # In case the call to expect(0) caught any remaining output
310 14 ▶ $self->_show_output($e->exp_before) if ($e->exp_before);
Branch: 1 branch
BranchTrueFalseTotal
if $e->exp_before 2 12 14
311 14 ▶ $e->soft_close unless ($already_closed);
Branch: 1 branch
BranchTrueFalseTotal
unless $already_closed 13 1 14
312  
313 14 ▶ if ($e->exitstatus and not defined($result)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($e->exitstatus and not defined $result) 1 13 14
Condition100%3/3
$e->exitstatus and not defined $result
!ll&&!rl&&r
1211
MC/DC100%2/2
$e->exitstatus and not defined $result
$e->exitstatus not defined $result
Truth table100%3/3
A and not(B)
A= $e->exitstatusB= not defined $result
ABresult
0X0
100
111
314 1 $result = 'Got back return value ' . $e->exitstatus . " from $command";
315 }
316  
317 14 return $result;
318 }
319  
320 =head2 _generate_instruction_list()
321  
322 This method returns information to be passed to C<Expect>'s expect() method, as well as a bookkeeping array using for tracking number of times a given interaction has occurred.
323  
324 =cut
325  
326 14 ▶sub _generate_interaction_list {
Subroutine _generate_interaction_list: called CC=3 SCAR=11.0
327 14 my $self = shift;
328  
329 14 my $expect_array = [];
330 14 my $indexed_interactions = [];
331  
332 14 foreach my $i (@{$self->interactions}) {
333 10 ▶ push @$expect_array, '-re' if ($i->expected_string_is_regex);
Branch: 1 branch
BranchTrueFalseTotal
if $i->expected_string_is_regex 2 8 10
334 10 push @$expect_array, $i->expected_string;
335 10 push @$indexed_interactions, $i;
336 }
337  
338 14 return ($expect_array, $indexed_interactions);
339  
340 }
341  
342 =head2 _fixup_command_to_catch_stderr($original_command)
343  
344 This method appends '2>&1' to the end of any command submitted to run(), except when that filehandle-tying string is already present in the command.
345  
346 Returns the modified version of $original_command.
347  
348 =cut
349  
350 19 ▶sub _fixup_command_to_catch_stderr {
Subroutine _fixup_command_to_catch_stderr: called CC=2 SCAR=6.9
351 19 my $self = shift;
352 19 my $original_command = shift;
353  
354 19 my $use_command = $original_command;
355 19 ▶ $use_command .= " 2>&1" unless ($use_command =~ m#2>&1#);
Branch: 1 branch
BranchTrueFalseTotal
unless $use_command =~ /2>&1/ 18 1 19
356 19 return $use_command;
357 }
358  
359 =head2 _log($line_to_log)
360  
361 Used for internal logging purposes when debug_logfile() is defined. See the
362 discussion of debug_logfile() for a better way to debug YOUR command's
363 execution; this method is intended for consumption by developers of
364 Command::Interactive.
365  
366 =cut
367  
368 41 ▶sub _log {
Subroutine _log: called CC=3 SCAR=11.0
369 41 my $self = shift;
370 41 my $message = shift;
371  
372 41 ▶ if ($self->debug_logfile) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->debug_logfile) 3 38 41
373 3 my $f = IO::File->new(">>" . $self->debug_logfile);
374 3 ▶ croak("Could not open debugging log file " . $self->debug_logfile) unless ($f);
Branch: 1 branch
BranchTrueFalseTotal
unless $f 1 2 3
375 2 $f->print(map { POSIX::strftime("[%Y-%m-%dT%H:%M:%SZ] $_\n", gmtime) } split(/[\r\n]/, $message));
376 2 $f->close;
377 }
378  
379 40 return;
380 }
381  
382 8 ▶no Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
383 8 __PACKAGE__->meta->make_immutable;
384  
385 8 1;
386  
387 =head1 AUTHOR
388  
389 Binary.com, <perl@binary.com>
390  
391 =head1 LICENSE
392  
393 This module is free software; you can redistribute it and/or modify it under the
394 same terms as Perl itself.
395  
396 =cut
397  
↑ Summary lib/Command/Interactive/Interaction.pm »