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