3832bfab0b3054b8579ccda7f7e3e019d267eee8
[scpubgit/Object-Remote.git] / lib / Object / Remote / Connection.pm
1 package Object::Remote::Connection;
2
3 use Object::Remote::Logging qw (:log :dlog router);
4 use Object::Remote::Future;
5 use Object::Remote::Null;
6 use Object::Remote::Handle;
7 use Object::Remote::CodeContainer;
8 use Object::Remote::GlobProxy;
9 use Object::Remote::GlobContainer;
10 use Object::Remote::Tied;
11 use Object::Remote;
12 use Symbol;
13 use IO::Handle;
14 use POSIX ":sys_wait_h";
15 use Module::Runtime qw(use_module);
16 use Scalar::Util qw(weaken blessed refaddr openhandle);
17 use JSON::PP qw(encode_json);
18 use Moo;
19
20 BEGIN { 
21   router()->exclude_forwarding;
22   $SIG{PIPE} = sub { log_debug { "Got a PIPE signal" } };
23 }
24
25 END {
26   log_debug { "Killing all child processes in the process group" };
27     
28   #send SIGINT to the process group for our children
29   kill(1, -2);
30 }
31
32 has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
33
34 has send_to_fh => (
35   is => 'ro', required => 1,
36   trigger => sub {
37       my $self = $_[0];
38       $_[1]->autoflush(1);
39       Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_"  } $_[1];
40   },
41 );
42
43 has read_channel => (
44   is => 'ro', required => 1,
45   trigger => sub {
46     my ($self, $ch) = @_;
47     my $id = $self->_id; 
48     Dlog_trace { "trigger for read_channel has been invoked for connection $id; file handle is $_" } $ch->fh;
49     weaken($self);
50     $ch->on_line_call(sub { $self->_receive(@_) });
51     $ch->on_close_call(sub { 
52       log_trace { "invoking 'done' on on_close handler for connection id '$id'" };
53       $self->on_close->done(@_);
54     });
55   },
56 );
57
58 has on_close => (
59   is => 'rw', default => sub { $_[0]->_install_future_handlers(CPS::Future->new) },
60   trigger => sub {
61       log_trace { "Installing handlers into future via trigger" };
62       $_[0]->_install_future_handlers($_[1])
63   },
64 );
65
66 has child_pid => (is => 'ro');
67
68 has local_objects_by_id => (
69   is => 'ro', default => sub { {} },
70   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
71 );
72
73 has remote_objects_by_id => (
74   is => 'ro', default => sub { {} },
75   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
76 );
77
78 has outstanding_futures => (is => 'ro', default => sub { {} });
79
80 has _json => (
81   is => 'lazy',
82   handles => {
83     _deserialize => 'decode',
84     _encode => 'encode',
85   },
86 );
87
88 after BUILD => sub {
89   my ($self) = @_;
90   my $pid = $self->child_pid;
91   
92   unless (defined $pid) {
93       log_trace { "After BUILD invoked for connection but there was no pid" };
94       return;
95   }
96     
97   log_trace { "Setting process group of child process '$pid'" };
98   
99   setpgrp($self->child_pid, 1);
100 };
101
102 sub BUILD { }
103
104 sub _fail_outstanding {
105   my ($self, $error) = @_;
106   Dlog_debug { "$$ Failing outstanding futures with '$error' for connection $_" } $self->_id;
107   my $outstanding = $self->outstanding_futures;
108   $_->fail("$error\n") for values %$outstanding;
109   %$outstanding = ();
110   return;
111 }
112
113 sub _install_future_handlers {
114     my ($self, $f) = @_;
115     Dlog_trace { "Installing handlers into future for connection $_" } $self->_id;
116     weaken($self);
117     $f->on_done(sub {
118       my $pid = $self->child_pid;
119       Dlog_trace { "Executing on_done handler in future for connection $_" } $self->_id;
120       $self->_fail_outstanding("Object::Remote connection lost: " . ($f->get)[0]);
121       return unless defined $pid;
122       log_debug { "Waiting for child '$pid' to exit" };
123       my $ret = waitpid($pid, 0);
124       if ($ret != $pid) {
125         log_debug { "Waited for pid $pid but waitpid() returned $ret" };
126         return;
127       } elsif ($? & 127) {
128           log_warn { "Remote interpreter did not exit cleanly" };
129       } else {
130         log_verbose {
131           my $exit_value = $? >> 8;
132           "Remote Perl interpreter exited with value '$exit_value'"
133         };
134       }
135     });
136     return $f; 
137 };
138
139 sub _id_to_remote_object {
140   my ($self, $id) = @_;
141   Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
142   return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
143   (
144     $self->remote_objects_by_id->{$id}
145     or Object::Remote::Handle->new(connection => $self, id => $id)
146   )->proxy;
147 }
148
149 sub _build__json {
150   weaken(my $self = shift);
151   JSON::PP->new->filter_json_single_key_object(
152     __remote_object__ => sub {
153       $self->_id_to_remote_object(@_);
154     }
155   )->filter_json_single_key_object(
156     __remote_code__ => sub {
157       my $code_container = $self->_id_to_remote_object(@_);
158       sub { $code_container->call(@_) };
159     }
160   )->filter_json_single_key_object(
161     __scalar_ref__ => sub {
162       my $value = shift;
163       return \$value;
164     }
165   )->filter_json_single_key_object(
166     __glob_ref__ => sub {
167       my $glob_container = $self->_id_to_remote_object(@_);
168       my $handle = Symbol::gensym;
169       tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
170       return $handle;
171     }
172   )->filter_json_single_key_object(
173     __local_object__ => sub {
174       $self->local_objects_by_id->{$_[0]}
175     }
176   )->filter_json_single_key_object(
177     __remote_tied_hash__ => sub {
178       my %tied_hash;
179       tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
180       return \%tied_hash;
181     }
182   )->filter_json_single_key_object(
183     __remote_tied_array__ => sub {
184       my @tied_array;
185       tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
186       return \@tied_array;
187     }
188   ); 
189 }
190
191 sub _load_if_possible {
192   my ($class) = @_; 
193
194   use_module($class); 
195
196   if ($@) {
197     log_debug { "Attempt at loading '$class' failed with '$@'" };
198   }
199
200 }
201
202 BEGIN {
203   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
204   map _load_if_possible($_), qw(
205     Object::Remote::Connector::Local
206     Object::Remote::Connector::LocalSudo
207     Object::Remote::Connector::SSH
208     Object::Remote::Connector::UNIX
209   ); 
210 }
211
212 sub conn_from_spec {
213   my ($class, $spec, @args) = @_;
214   foreach my $poss (do { our @Guess }) {
215     if (my $conn = $poss->($spec, @args)) {
216       return $conn;
217     }
218   }
219   
220   return undef;
221 }
222
223 sub new_from_spec {
224   my ($class, $spec) = @_;
225   return $spec if blessed $spec;
226   my $conn = $class->conn_from_spec($spec); 
227   
228   die "Couldn't figure out what to do with ${spec}"
229     unless defined $conn;
230     
231   return $conn->maybe::start::connect;  
232 }
233
234 sub remote_object {
235   my ($self, @args) = @_;
236   Object::Remote::Handle->new(
237     connection => $self, @args
238   )->proxy;
239 }
240
241 sub connect {
242   my ($self, $to) = @_;
243   Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
244   return await_future(
245     $self->send_class_call(0, 'Object::Remote', connect => $to)
246   );
247 }
248
249 sub remote_sub {
250   my ($self, $sub) = @_;
251   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
252   Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
253   return await_future($self->send_class_call(0, $pkg, can => $name));
254 }
255
256 sub send_class_call {
257   my ($self, $ctx, @call) = @_;
258   Dlog_trace { "Sending a class call for connection $_" } $self->_id;
259   $self->send(call => class_call_handler => $ctx => call => @call);
260 }
261
262 sub register_class_call_handler {
263   my ($self) = @_;
264   $self->local_objects_by_id->{'class_call_handler'} ||= do {
265     my $o = $self->new_class_call_handler;
266     $self->_local_object_to_id($o);
267     $o;
268   };
269 }
270
271 sub new_class_call_handler {
272   Object::Remote::CodeContainer->new(
273     code => sub {
274       my ($class, $method) = (shift, shift);
275       use_module($class)->$method(@_);
276     }
277   );
278 }
279
280 sub register_remote {
281   my ($self, $remote) = @_;
282   Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
283   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
284   return $remote;
285 }
286
287 sub send_free {
288   my ($self, $id) = @_;
289   Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
290   #TODO this shows up some times when a remote side dies in the middle of a remote
291   #method invocation - possibly only when the object is being constructed?
292   #(in cleanup) Use of uninitialized value $id in delete at ../Object-Remote/lib/Object/Remote/Connection.
293   delete $self->remote_objects_by_id->{$id};
294   $self->_send([ free => $id ]);
295 }
296
297 sub send {
298   my ($self, $type, @call) = @_;
299
300   my $future = CPS::Future->new;
301   my $remote = $self->remote_objects_by_id->{$call[0]};
302
303   unshift @call, $type => $self->_local_object_to_id($future);
304
305   my $outstanding = $self->outstanding_futures;
306   $outstanding->{$future} = $future;
307   $future->on_ready(sub {
308     undef($remote);
309     delete $outstanding->{$future}
310   });
311
312   $self->_send(\@call);
313
314   return $future;
315 }
316
317 sub send_discard {
318   my ($self, $type, @call) = @_;
319
320   unshift @call, $type => 'NULL';
321
322   $self->_send(\@call);
323 }
324
325 sub _send {
326   my ($self, $to_send) = @_;
327   my $fh = $self->send_to_fh;
328   Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
329   my $serialized = $self->_serialize($to_send)."\n";
330   Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
331   my $ret; 
332   eval { 
333     #TODO this should be converted over to a non-blocking ::WriteChannel class
334     die "filehandle is not open" unless openhandle($fh);
335     log_trace { "file handle has passed openhandle() test; printing to it" };
336     $ret = print $fh $serialized;
337     die "print was not successful: $!" unless defined $ret
338   };
339     
340   if ($@) {
341     Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
342     my $error = $@;
343     chomp($error);
344     $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
345     return; 
346   }
347       
348   return $ret; 
349 }
350
351 sub _serialize {
352   my ($self, $data) = @_;
353   local our @New_Ids = (-1);
354   return eval {
355     my $flat = $self->_encode($self->_deobjectify($data));
356     $flat;
357   } || do {
358     my $err = $@; # won't get here if the eval doesn't die
359     # don't keep refs to new things
360     delete @{$self->local_objects_by_id}{@New_Ids};
361     die "Error serializing: $err";
362   };
363 }
364
365 sub _local_object_to_id {
366   my ($self, $object) = @_;
367   my $id = refaddr($object);
368   $self->local_objects_by_id->{$id} ||= do {
369     push our(@New_Ids), $id if @New_Ids;
370     $object;
371   };
372   return $id;
373 }
374
375 sub _deobjectify {
376   my ($self, $data) = @_;
377   if (blessed($data)) {
378     if (
379       $data->isa('Object::Remote::Proxy')
380       and $data->{remote}->connection == $self
381     ) {
382       return +{ __local_object__ => $data->{remote}->id };
383     } else {
384       return +{ __remote_object__ => $self->_local_object_to_id($data) };
385     }
386   } elsif (my $ref = ref($data)) {
387     if ($ref eq 'HASH') {
388       my $tied_to = tied(%$data);
389       if(defined($tied_to)) {
390         return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)}; 
391       } else {
392         return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
393       }
394     } elsif ($ref eq 'ARRAY') {
395       my $tied_to = tied(@$data);
396       if (defined($tied_to)) {
397         return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)}; 
398       } else {
399         return [ map $self->_deobjectify($_), @$data ];
400       }
401     } elsif ($ref eq 'CODE') {
402       my $id = $self->_local_object_to_id(
403                  Object::Remote::CodeContainer->new(code => $data)
404                );
405       return +{ __remote_code__ => $id };
406     } elsif ($ref eq 'SCALAR') {
407       return +{ __scalar_ref__ => $$data };
408     } elsif ($ref eq 'GLOB') {
409       return +{ __glob_ref__ => $self->_local_object_to_id(
410         Object::Remote::GlobContainer->new(handle => $data)
411       ) };
412     } else {
413       die "Can't collapse reftype $ref";
414     }
415   }
416   return $data; # plain scalar
417 }
418
419 sub _receive {
420   my ($self, $flat) = @_;
421   Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
422   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
423     or do { warn "Deserialize failed for ${flat}: $@"; return };
424   Dlog_trace { "deserialization complete for connection $_" } $self->_id;
425   eval { $self->${\"receive_${type}"}(@rest); 1 }
426     or do { warn "Receive failed for ${flat}: $@"; return };
427   return;
428 }
429
430 sub receive_free {
431   my ($self, $id) = @_;
432   Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
433   delete $self->local_objects_by_id->{$id}
434     or warn "Free: no such object $id";
435   return;
436 }
437
438 sub receive_call {
439   my ($self, $future_id, $id, @rest) = @_;
440   Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
441   my $future = $self->_id_to_remote_object($future_id);
442   $future->{method} = 'call_discard_free';
443   my $local = $self->local_objects_by_id->{$id}
444     or do { $future->fail("No such object $id"); return };
445   $self->_invoke($future, $local, @rest);
446 }
447
448 sub receive_call_free {
449   my ($self, $future, $id, @rest) = @_;
450   Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
451   $self->receive_call($future, $id, undef, @rest);
452   $self->receive_free($id);
453 }
454
455 sub _invoke {
456   my ($self, $future, $local, $ctx, $method, @args) = @_;
457   Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
458   if ($method =~ /^start::/) {
459     my $f = $local->$method(@args);
460     $f->on_done(sub { undef($f); $future->done(@_) });
461     return unless $f;
462     $f->on_fail(sub { undef($f); $future->fail(@_) });
463     return;
464   }
465   my $do = sub { $local->$method(@args) };
466   eval {
467     $future->done(
468       defined($ctx)
469         ? ($ctx ? $do->() : scalar($do->()))
470         : do { $do->(); () }
471     );
472     1;
473   } or do { $future->fail($@); return; };
474   return;
475 }
476
477 1;
478
479 =head1 NAME
480
481 Object::Remote::Connection - An underlying connection for L<Object::Remote>
482
483 =head1 LAME
484
485 Shipping prioritised over writing this part up. Blame mst.
486
487 =cut