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