found location of hang; make annotations; added more log lines
[scpubgit/Object-Remote.git] / lib / Object / Remote / Connection.pm
1 package Object::Remote::Connection;
2
3 use Object::Remote::Future;
4 use Object::Remote::Null;
5 use Object::Remote::Handle;
6 use Object::Remote::CodeContainer;
7 use Object::Remote::GlobProxy;
8 use Object::Remote::GlobContainer;
9 use Object::Remote::Logging qw (:log :dlog);
10 use Object::Remote;
11 use Symbol;
12 use IO::Handle;
13 use Module::Runtime qw(use_module);
14 use Scalar::Util qw(weaken blessed refaddr);
15 use JSON::PP qw(encode_json);
16 use Moo;
17
18 our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
19
20 has send_to_fh => (
21   is => 'ro', required => 1,
22   trigger => sub { $_[1]->autoflush(1) },
23 );
24
25 has read_channel => (
26   is => 'ro', required => 1,
27   trigger => sub {
28     my ($self, $ch) = @_;
29     weaken($self);
30     $ch->on_line_call(sub { $self->_receive(@_) });
31     $ch->on_close_call(sub { $self->on_close->done(@_) });
32   },
33 );
34
35 has on_close => (
36   is => 'ro', default => sub { CPS::Future->new },
37   trigger => sub { 
38     my ($self, $f) = @_;
39     weaken($self);
40     $f->on_done(sub {
41       $self->_fail_outstanding("Connection lost: ".($f->get)[0]);
42     });
43   }
44 );
45
46 has child_pid => (is => 'ro');
47
48 has local_objects_by_id => (
49   is => 'ro', default => sub { {} },
50   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
51 );
52
53 has remote_objects_by_id => (
54   is => 'ro', default => sub { {} },
55   coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
56 );
57
58 has outstanding_futures => (is => 'ro', default => sub { {} });
59
60 sub _fail_outstanding {
61   my ($self, $error) = @_;
62   my $outstanding = $self->outstanding_futures;
63   $_->fail($error) for values %$outstanding;
64   %$outstanding = ();
65   return;
66 }
67
68 has _json => (
69   is => 'lazy',
70   handles => {
71     _deserialize => 'decode',
72     _encode => 'encode',
73   },
74 );
75
76 sub _id_to_remote_object {
77   my ($self, $id) = @_;
78   return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
79   (
80     $self->remote_objects_by_id->{$id}
81     or Object::Remote::Handle->new(connection => $self, id => $id)
82   )->proxy;
83 }
84
85 sub _build__json {
86   weaken(my $self = shift);
87   JSON::PP->new->filter_json_single_key_object(
88     __remote_object__ => sub {
89       $self->_id_to_remote_object(@_);
90     }
91   )->filter_json_single_key_object(
92     __remote_code__ => sub {
93       my $code_container = $self->_id_to_remote_object(@_);
94       sub { $code_container->call(@_) };
95     }
96   )->filter_json_single_key_object(
97     __scalar_ref__ => sub {
98       my $value = shift;
99       return \$value;
100     }
101   )->filter_json_single_key_object(
102     __glob_ref__ => sub {
103       my $glob_container = $self->_id_to_remote_object(@_);
104       my $handle = Symbol::gensym;
105       tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
106       return $handle;
107     }
108   )->filter_json_single_key_object(
109     __local_object__ => sub {
110       $self->local_objects_by_id->{$_[0]}
111     }
112   );
113 }
114
115 BEGIN {
116   unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
117   eval { require Object::Remote::Connector::Local };
118   eval { require Object::Remote::Connector::LocalSudo };
119   eval { require Object::Remote::Connector::SSH };
120   eval { require Object::Remote::Connector::UNIX };
121 }
122
123 sub new_from_spec {
124   my ($class, $spec) = @_;
125   return $spec if blessed $spec;
126   foreach my $poss (do { our @Guess }) {
127     if (my $conn = $poss->($spec)) {
128       return $conn->maybe::start::connect;
129     }
130   }
131   die "Couldn't figure out what to do with ${spec}";
132 }
133
134 sub remote_object {
135   my ($self, @args) = @_;
136   Object::Remote::Handle->new(
137     connection => $self, @args
138   )->proxy;
139 }
140
141 sub connect {
142   my ($self, $to) = @_;
143   Dlog_debug { "Creating connection to remote node $_" } $to;
144   return await_future(
145     $self->send_class_call(0, 'Object::Remote', connect => $to)
146   );
147 }
148
149 sub remote_sub {
150   my ($self, $sub) = @_;
151   my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
152   log_debug { "Invoking remote sub '$sub'" };
153   return await_future($self->send_class_call(0, $pkg, can => $name));
154 }
155
156 sub send_class_call {
157   my ($self, $ctx, @call) = @_;
158   log_trace { "Sending a non-blocking class call" };
159   $self->send(call => class_call_handler => $ctx => call => @call);
160 }
161
162 sub register_class_call_handler {
163   my ($self) = @_;
164   $self->local_objects_by_id->{'class_call_handler'} ||= do {
165     my $o = $self->new_class_call_handler;
166     $self->_local_object_to_id($o);
167     $o;
168   };
169 }
170
171 sub new_class_call_handler {
172   Object::Remote::CodeContainer->new(
173     code => sub {
174       my ($class, $method) = (shift, shift);
175       use_module($class)->$method(@_);
176     }
177   );
178 }
179
180 sub register_remote {
181   my ($self, $remote) = @_;
182   log_trace { my $i = $remote->id; "Registered a remote object with id of '$i'" };
183   weaken($self->remote_objects_by_id->{$remote->id} = $remote);
184   return $remote;
185 }
186
187 sub send_free {
188   my ($self, $id) = @_;
189   log_debug { "sending request to free object '$id'" };
190   delete $self->remote_objects_by_id->{$id};
191   $self->_send([ free => $id ]);
192 }
193
194 sub send {
195   my ($self, $type, @call) = @_;
196
197   my $future = CPS::Future->new;
198   my $remote = $self->remote_objects_by_id->{$call[0]};
199
200   unshift @call, $type => $self->_local_object_to_id($future);
201
202   my $outstanding = $self->outstanding_futures;
203   $outstanding->{$future} = $future;
204   $future->on_ready(sub {
205     undef($remote);
206     delete $outstanding->{$future}
207   });
208
209   $self->_send(\@call);
210
211   return $future;
212 }
213
214 sub send_discard {
215   my ($self, $type, @call) = @_;
216
217   unshift @call, $type => 'NULL';
218
219   $self->_send(\@call);
220 }
221
222 sub _send {
223   my ($self, $to_send) = @_;
224   my $fh = $self->send_to_fh;
225   my $serialized = $self->_serialize($to_send)."\n";
226   Dlog_debug { my $l = length($serialized); "Sending '$l' characters of serialized data to $_" } $fh;
227   #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
228   #logic it could easily do short-writes to the remote side
229   my $ret = print $fh $serialized;
230   Dlog_trace { my $r = defined $ret ? $ret : 'undef'; "print() returned $r with $_" } $fh;
231   #TODO hrm reason print's return value was ignored?
232   die "could not write to filehandle: $!" unless $ret;
233   return $ret; 
234 }
235
236 sub _serialize {
237   my ($self, $data) = @_;
238   local our @New_Ids = (-1);
239   return eval {
240     my $flat = $self->_encode($self->_deobjectify($data));
241     warn "$$ >>> ${flat}\n" if $DEBUG;
242     $flat;
243   } || do {
244     my $err = $@; # won't get here if the eval doesn't die
245     # don't keep refs to new things
246     delete @{$self->local_objects_by_id}{@New_Ids};
247     die "Error serializing: $err";
248   };
249 }
250
251 sub _local_object_to_id {
252   my ($self, $object) = @_;
253   my $id = refaddr($object);
254   $self->local_objects_by_id->{$id} ||= do {
255     push our(@New_Ids), $id if @New_Ids;
256     $object;
257   };
258   return $id;
259 }
260
261 sub _deobjectify {
262   my ($self, $data) = @_;
263   if (blessed($data)) {
264     if (
265       $data->isa('Object::Remote::Proxy')
266       and $data->{remote}->connection == $self
267     ) {
268       return +{ __local_object__ => $data->{remote}->id };
269     } else {
270       return +{ __remote_object__ => $self->_local_object_to_id($data) };
271     }
272   } elsif (my $ref = ref($data)) {
273     if ($ref eq 'HASH') {
274       return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
275     } elsif ($ref eq 'ARRAY') {
276       return [ map $self->_deobjectify($_), @$data ];
277     } elsif ($ref eq 'CODE') {
278       my $id = $self->_local_object_to_id(
279                  Object::Remote::CodeContainer->new(code => $data)
280                );
281       return +{ __remote_code__ => $id };
282     } elsif ($ref eq 'SCALAR') {
283       return +{ __scalar_ref__ => $$data };
284     } elsif ($ref eq 'GLOB') {
285       return +{ __glob_ref__ => $self->_local_object_to_id(
286         Object::Remote::GlobContainer->new(handle => $data)
287       ) };
288     } else {
289       die "Can't collapse reftype $ref";
290     }
291   }
292   return $data; # plain scalar
293 }
294
295 sub _receive {
296   my ($self, $flat) = @_;
297   warn "$$ <<< $flat\n" if $DEBUG;
298   my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
299     or do { warn "Deserialize failed for ${flat}: $@"; return };
300   eval { $self->${\"receive_${type}"}(@rest); 1 }
301     or do { warn "Receive failed for ${flat}: $@"; return };
302   return;
303 }
304
305 sub receive_free {
306   my ($self, $id) = @_;
307   delete $self->local_objects_by_id->{$id}
308     or warn "Free: no such object $id";
309   return;
310 }
311
312 sub receive_call {
313   my ($self, $future_id, $id, @rest) = @_;
314   my $future = $self->_id_to_remote_object($future_id);
315   $future->{method} = 'call_discard_free';
316   my $local = $self->local_objects_by_id->{$id}
317     or do { $future->fail("No such object $id"); return };
318   $self->_invoke($future, $local, @rest);
319 }
320
321 sub receive_call_free {
322   my ($self, $future, $id, @rest) = @_;
323   $self->receive_call($future, $id, undef, @rest);
324   $self->receive_free($id);
325 }
326
327 sub _invoke {
328   my ($self, $future, $local, $ctx, $method, @args) = @_;
329   if ($method =~ /^start::/) {
330     my $f = $local->$method(@args);
331     $f->on_done(sub { undef($f); $future->done(@_) });
332     return unless $f;
333     $f->on_fail(sub { undef($f); $future->fail(@_) });
334     return;
335   }
336   my $do = sub { $local->$method(@args) };
337   eval {
338     $future->done(
339       defined($ctx)
340         ? ($ctx ? $do->() : scalar($do->()))
341         : do { $do->(); () }
342     );
343     1;
344   } or do { $future->fail($@); return; };
345   return;
346 }
347
348 1;
349
350 =head1 NAME
351
352 Object::Remote::Connection - An underlying connection for L<Object::Remote>
353
354 =head1 LAME
355
356 Shipping prioritised over writing this part up. Blame mst.
357
358 =cut