b18b974d48a4a428cf8c03d9f685aab2a46ce2d6
[scpubgit/Object-Remote.git] / lib / Object / Remote / Connection.pm
1 package Object::Remote::Connection;
2
3 use Object::Remote::Logging qw (:log :dlog);
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   #this will reap child processes as soon
22   #as they are done executing so the process
23   #table cleans up as fast as possible but
24   #anything that needs to call waitpid()
25   #in the future to get the exit value of
26   #a child will get trash results if
27   #the signal handler was running. 
28   #If creating a child and getting the
29   #exit value is required then set
30   #a localized version of the signal
31   #handler for CHLD to be 'IGNORE'
32   #in the smallest block possible
33   #and outside the block send
34   #the process a CHLD signal
35   #to reap anything that may
36   #have exited while blocked
37   #in waitpid() 
38   $SIG{CHLD} = sub { 
39     my $kid; 
40     log_trace { "CHLD signal handler is executing" };
41     do {
42       $kid = waitpid(-1, WNOHANG);
43       log_debug { "waitpid() returned '$kid'" };
44     } while $kid > 0;
45     log_trace { "CHLD signal handler is done" };
46   };
47   
48   $SIG{PIPE} = sub { log_debug { "Got a PIPE signal" } };      
49 }
50
51 END {
52   log_debug { "Killing all child processes in the process group" };
53     
54   #send SIGINT to the process group for our children
55   kill(1, -2);
56 }
57
58 our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
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     __remote_tied_hash__ => sub {
180       my %tied_hash;
181       tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
182       return \%tied_hash;
183     }
184   )->filter_json_single_key_object(
185     __remote_tied_array__ => sub {
186       my @tied_array;
187       tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
188       return \@tied_array;
189     }
190   ); 
191 }
192
193 sub _load_if_possible {
194   my ($class) = @_; 
195
196   eval "require $class"; 
197
198   if ($@) {
199     log_debug { "Attempt at loading '$class' failed with '$@'" };
200   }
201
202 }
203
204 BEGIN {
205   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
206   map _load_if_possible($_), qw(
207     Object::Remote::Connector::Local
208     Object::Remote::Connector::LocalSudo
209     Object::Remote::Connector::SSH
210     Object::Remote::Connector::UNIX
211   ); 
212 }
213
214 sub conn_from_spec {
215   my ($class, $spec, @args) = @_;
216   foreach my $poss (do { our @Guess }) {
217     if (my $conn = $poss->($spec, @args)) {
218       return $conn;
219     }
220   }
221   
222   return undef;
223 }
224
225 sub new_from_spec {
226   my ($class, $spec) = @_;
227   return $spec if blessed $spec;
228   my $conn = $class->conn_from_spec($spec); 
229   
230   die "Couldn't figure out what to do with ${spec}"
231     unless defined $conn;
232     
233   return $conn->maybe::start::connect;  
234 }
235
236 sub remote_object {
237   my ($self, @args) = @_;
238   Object::Remote::Handle->new(
239     connection => $self, @args
240   )->proxy;
241 }
242
243 sub connect {
244   my ($self, $to) = @_;
245   Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
246   return await_future(
247     $self->send_class_call(0, 'Object::Remote', connect => $to)
248   );
249 }
250
251 sub remote_sub {
252   my ($self, $sub) = @_;
253   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
254   Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
255   return await_future($self->send_class_call(0, $pkg, can => $name));
256 }
257
258 sub send_class_call {
259   my ($self, $ctx, @call) = @_;
260   Dlog_trace { "Sending a class call for connection $_" } $self->_id;
261   $self->send(call => class_call_handler => $ctx => call => @call);
262 }
263
264 sub register_class_call_handler {
265   my ($self) = @_;
266   $self->local_objects_by_id->{'class_call_handler'} ||= do {
267     my $o = $self->new_class_call_handler;
268     $self->_local_object_to_id($o);
269     $o;
270   };
271 }
272
273 sub new_class_call_handler {
274   Object::Remote::CodeContainer->new(
275     code => sub {
276       my ($class, $method) = (shift, shift);
277       use_module($class)->$method(@_);
278     }
279   );
280 }
281
282 sub register_remote {
283   my ($self, $remote) = @_;
284   Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
285   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
286   return $remote;
287 }
288
289 sub send_free {
290   my ($self, $id) = @_;
291   Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
292   delete $self->remote_objects_by_id->{$id};
293   $self->_send([ free => $id ]);
294 }
295
296 sub send {
297   my ($self, $type, @call) = @_;
298
299   my $future = CPS::Future->new;
300   my $remote = $self->remote_objects_by_id->{$call[0]};
301
302   unshift @call, $type => $self->_local_object_to_id($future);
303
304   my $outstanding = $self->outstanding_futures;
305   $outstanding->{$future} = $future;
306   $future->on_ready(sub {
307     undef($remote);
308     delete $outstanding->{$future}
309   });
310
311   $self->_send(\@call);
312
313   return $future;
314 }
315
316 sub send_discard {
317   my ($self, $type, @call) = @_;
318
319   unshift @call, $type => 'NULL';
320
321   $self->_send(\@call);
322 }
323
324 sub _send {
325   my ($self, $to_send) = @_;
326   my $fh = $self->send_to_fh;
327   Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
328   my $serialized = $self->_serialize($to_send)."\n";
329   Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
330   my $ret; 
331   eval { 
332     #TODO this should be converted over to a non-blocking ::WriteChannel class
333     die "filehandle is not open" unless openhandle($fh);
334     log_trace { "file handle has passed openhandle() test; printing to it" };
335     $ret = print $fh $serialized;
336     die "print was not successful: $!" unless defined $ret
337   };
338     
339   if ($@) {
340     Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
341     my $error = $@; chomp($error);
342     $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
343     return; 
344   }
345       
346   return $ret; 
347 }
348
349 sub _serialize {
350   my ($self, $data) = @_;
351   local our @New_Ids = (-1);
352   return eval {
353     my $flat = $self->_encode($self->_deobjectify($data));
354     warn "$$ >>> ${flat}\n" if $DEBUG;
355     $flat;
356   } || do {
357     my $err = $@; # won't get here if the eval doesn't die
358     # don't keep refs to new things
359     delete @{$self->local_objects_by_id}{@New_Ids};
360     die "Error serializing: $err";
361   };
362 }
363
364 sub _local_object_to_id {
365   my ($self, $object) = @_;
366   my $id = refaddr($object);
367   $self->local_objects_by_id->{$id} ||= do {
368     push our(@New_Ids), $id if @New_Ids;
369     $object;
370   };
371   return $id;
372 }
373
374 sub _deobjectify {
375   my ($self, $data) = @_;
376   if (blessed($data)) {
377     return +{ __remote_object__ => $self->_local_object_to_id($data) };
378   } elsif (my $ref = ref($data)) {
379     if ($ref eq 'HASH') {
380       my $tied_to = tied(%$data);
381       if(defined($tied_to)) {
382         return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)}; 
383       } else {
384         return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
385       }
386     } elsif ($ref eq 'ARRAY') {
387       my $tied_to = tied(@$data);
388       if (defined($tied_to)) {
389         return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)}; 
390       } else {
391         return [ map $self->_deobjectify($_), @$data ];
392       }
393     } elsif ($ref eq 'CODE') {
394       my $id = $self->_local_object_to_id(
395                  Object::Remote::CodeContainer->new(code => $data)
396                );
397       return +{ __remote_code__ => $id };
398     } elsif ($ref eq 'SCALAR') {
399       return +{ __scalar_ref__ => $$data };
400     } elsif ($ref eq 'GLOB') {
401       return +{ __glob_ref__ => $self->_local_object_to_id(
402         Object::Remote::GlobContainer->new(handle => $data)
403       ) };
404     } else {
405       die "Can't collapse reftype $ref";
406     }
407   }
408   return $data; # plain scalar
409 }
410
411 sub _receive {
412   my ($self, $flat) = @_;
413   warn "$$ <<< $flat\n" if $DEBUG;
414   Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
415   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
416     or do { warn "Deserialize failed for ${flat}: $@"; return };
417   Dlog_trace { "deserialization complete for connection $_" } $self->_id;
418   eval { $self->${\"receive_${type}"}(@rest); 1 }
419     or do { warn "Receive failed for ${flat}: $@"; return };
420   return;
421 }
422
423 sub receive_free {
424   my ($self, $id) = @_;
425   Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
426   delete $self->local_objects_by_id->{$id}
427     or warn "Free: no such object $id";
428   return;
429 }
430
431 sub receive_call {
432   my ($self, $future_id, $id, @rest) = @_;
433   Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
434   my $future = $self->_id_to_remote_object($future_id);
435   $future->{method} = 'call_discard_free';
436   my $local = $self->local_objects_by_id->{$id}
437     or do { $future->fail("No such object $id"); return };
438   $self->_invoke($future, $local, @rest);
439 }
440
441 sub receive_call_free {
442   my ($self, $future, $id, @rest) = @_;
443   Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
444   $self->receive_call($future, $id, undef, @rest);
445   $self->receive_free($id);
446 }
447
448 sub _invoke {
449   my ($self, $future, $local, $ctx, $method, @args) = @_;
450   Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
451   if ($method =~ /^start::/) {
452     my $f = $local->$method(@args);
453     $f->on_done(sub { undef($f); $future->done(@_) });
454     return unless $f;
455     $f->on_fail(sub { undef($f); $future->fail(@_) });
456     return;
457   }
458   my $do = sub { $local->$method(@args) };
459   eval {
460     $future->done(
461       defined($ctx)
462         ? ($ctx ? $do->() : scalar($do->()))
463         : do { $do->(); () }
464     );
465     1;
466   } or do { $future->fail($@); return; };
467   return;
468 }
469
470 1;
471
472 =head1 NAME
473
474 Object::Remote::Connection - An underlying connection for L<Object::Remote>
475
476 =head1 LAME
477
478 Shipping prioritised over writing this part up. Blame mst.
479
480 =cut