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