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