first attempt at fixing ssh/sh escaping problem with perl_command - works but isn...
[scpubgit/Object-Remote.git] / lib / Object / Remote / Role / Connector / PerlInterpreter.pm
1 package Object::Remote::Role::Connector::PerlInterpreter;
2
3 use IPC::Open2;
4 use IPC::Open3; 
5 use IO::Handle;
6 use Object::Remote::Logging qw( :log :dlog );
7 use Object::Remote::ModuleSender;
8 use Object::Remote::Handle;
9 use Object::Remote::Future;
10 use Scalar::Util qw(blessed weaken);
11 use Moo::Role;
12 use Symbol; 
13
14 with 'Object::Remote::Role::Connector';
15
16 has module_sender => (is => 'lazy');
17
18 #if no child_stderr file handle is specified then stderr
19 #of the child will be connected to stderr of the parent
20 has stderr => ( is => 'rw', default => sub { undef } );
21
22 sub _build_module_sender {
23   my ($hook) =
24     grep {blessed($_) && $_->isa('Object::Remote::ModuleLoader::Hook') }
25       @INC;
26   return $hook ? $hook->sender : Object::Remote::ModuleSender->new;
27 }
28
29 has perl_command => (is => 'lazy');
30 has watchdog_timeout => ( is => 'ro', required => 1, default => sub { 0 } );
31
32 #TODO convert nice value into optional feature enabled by
33 #setting value of attribute
34 #ulimit of ~500 megs of v-ram
35 #TODO only works with ssh with quotes but only works locally
36 #with out quotes
37 sub _build_perl_command {[ 'sh -c "ulimit -v 200000; nice -n 15 perl -"' ] }
38 #sub _build_perl_command { [ 'perl', '-' ] }
39 #sub _build_perl_command { [ 'cat' ] }
40
41 around connect => sub {
42   my ($orig, $self) = (shift, shift);
43   my $f = $self->$start::start($orig => @_);
44   return future {
45     $f->on_done(sub {
46       my ($conn) = $f->get;
47       $self->_setup_watchdog_reset($conn); 
48       my $sub = $conn->remote_sub('Object::Remote::Logging::init_logging_forwarding');
49       $sub->('Object::Remote::Logging', Object::Remote::Logging->arg_router);
50       Object::Remote::Handle->new(
51         connection => $conn,
52         class => 'Object::Remote::ModuleLoader',
53         args => { module_sender => $self->module_sender }
54       )->disarm_free;
55       require Object::Remote::Prompt;
56       Object::Remote::Prompt::maybe_set_prompt_command_on($conn);
57     });
58     $f;
59   } 2;
60 };
61
62 sub final_perl_command { shift->perl_command }
63
64 sub _start_perl {
65   my $self = shift;
66   my $given_stderr = $self->stderr;
67   my $foreign_stderr;
68  
69   Dlog_debug { "invoking connection to perl interpreter using command line: $_" } @{$self->final_perl_command};
70     
71   if (defined($given_stderr)) {
72       #if the stderr data goes to an existing file handle
73       #an need an anonymous file handle is required
74       #as the other half of a pipe style file handle pair
75       #so the file handles can go into the run loop
76       $foreign_stderr = gensym();
77   } else {
78       #if no file handle has been specified
79       #for the child's stderr then connect
80       #the child stderr to the parent stderr
81       $foreign_stderr = ">&STDERR";
82   }
83   
84   my $pid = open3(
85     my $foreign_stdin,
86     my $foreign_stdout,
87     $foreign_stderr,
88     @{$self->final_perl_command},
89   ) or die "Failed to run perl at '$_[0]': $!";
90   
91   if (defined($given_stderr)) {   
92       log_warn { "using experimental cat for child stderr" };
93         
94       #TODO refactor if this solves the problem
95       Object::Remote->current_loop
96                     ->watch_io(
97                         handle => $foreign_stderr,
98                         on_read_ready => sub {
99                           my $buf = ''; 
100                           my $len = sysread($foreign_stderr, $buf, 32768);
101                           if (!defined($len) or $len == 0) {
102                             log_trace { "Got EOF or error on child stderr, removing from watcher" };
103                             $self->stderr(undef);
104                             Object::Remote->current_loop
105                                           ->unwatch_io(
106                                               handle => $foreign_stderr,
107                                               on_read_ready => 1
108                                             );
109                           } else {
110                               Dlog_trace { "got $len characters of stderr data for connection" };
111                               print $given_stderr $buf or die "could not send stderr data: $!";
112                           }
113                          } 
114                       );     
115   }
116       
117   return ($foreign_stdin, $foreign_stdout, $pid);
118 }
119
120 sub _open2_for {
121   my $self = shift;
122   my ($foreign_stdin, $foreign_stdout, $pid) = $self->_start_perl(@_);
123   my $to_send = $self->fatnode_text;
124   log_debug { my $len = length($to_send); "Sending contents of fat node to remote node; size is '$len' characters"  };
125   Object::Remote->current_loop
126                 ->watch_io(
127                     handle => $foreign_stdin,
128                     on_write_ready => sub {
129                       my $len = syswrite($foreign_stdin, $to_send, 32768);
130                       if (defined $len) {
131                         substr($to_send, 0, $len) = '';
132                       }
133                       # if the stdin went away, we'll never get Shere
134                       # so it's not a big deal to simply give up on !defined
135                       if (!defined($len) or 0 == length($to_send)) {
136                         log_trace { "Got EOF or error when writing fatnode data to filehandle, unwatching it" };
137                         Object::Remote->current_loop
138                                       ->unwatch_io(
139                                           handle => $foreign_stdin,
140                                           on_write_ready => 1
141                                         );
142                       } else {
143                           log_trace { "Sent $len bytes of fatnode data to remote side" };
144                       }
145                     }
146                   );
147   return ($foreign_stdin, $foreign_stdout, $pid);
148 }
149
150 sub _setup_watchdog_reset {
151     my ($self, $conn) = @_;
152     my $timer_id; 
153     
154     return unless $self->watchdog_timeout; 
155         
156     Dlog_trace { "Creating Watchdog management timer for connection id $_" } $conn->_id;
157
158     $timer_id = Object::Remote->current_loop->watch_time(
159         every => $self->watchdog_timeout / 3,
160         code => sub {
161             unless(defined($conn)) {
162                 log_trace { "Weak reference to connection in Watchdog was lost, terminating update timer $timer_id" };
163                 Object::Remote->current_loop->unwatch_time($timer_id);
164                 return;  
165             }
166             
167             Dlog_debug { "Reseting Watchdog for connection id $_" } $conn->_id;
168             #we do not want to block in the run loop so send the
169             #update off and ignore any result, we don't need it
170             #anyway
171             $conn->send_class_call(0, 'Object::Remote::WatchDog', 'reset');
172         }
173     );
174     
175     $conn->on_close->on_done(sub { Object::Remote->current_loop->unwatch_time($timer_id) });
176 }
177
178 sub fatnode_text {
179   my ($self) = @_;
180   my $text = '';
181
182   require Object::Remote::FatNode;
183   
184   $text = "my \$WATCHDOG_TIMEOUT = '" . $self->watchdog_timeout . "';\n";
185   
186   if (my $duration = $self->watchdog_timeout) {
187     $text .= "alarm(\$WATCHDOG_TIMEOUT);\n";    
188   }
189
190   $text .= 'BEGIN { $ENV{OBJECT_REMOTE_DEBUG} = 1 }'."\n"
191     if $ENV{OBJECT_REMOTE_DEBUG};
192   $text .= <<'END';
193 $INC{'Object/Remote/FatNode.pm'} = __FILE__;
194 $Object::Remote::FatNode::DATA = <<'ENDFAT';
195 END
196   $text .= do { no warnings 'once'; $Object::Remote::FatNode::DATA };
197   $text .= "ENDFAT\n";
198   $text .= <<'END';
199 eval $Object::Remote::FatNode::DATA;
200 die $@ if $@;
201 END
202   
203   $text .= "__END__\n";
204   return $text;
205 }
206
207 1;