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