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