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