implement optional watchdog for remote connections
[scpubgit/Object-Remote.git] / lib / Object / Remote / Connection.pm
CommitLineData
9e72f0cf 1package Object::Remote::Connection;
2
c824fdf3 3use Object::Remote::Logging qw (:log :dlog);
dc28afe8 4use Object::Remote::Future;
9d804009 5use Object::Remote::Null;
676438a1 6use Object::Remote::Handle;
fe6c9a7f 7use Object::Remote::CodeContainer;
ed5a8a8e 8use Object::Remote::GlobProxy;
9use Object::Remote::GlobContainer;
7790ca36 10use Object::Remote::Tied;
9e72f0cf 11use Object::Remote;
ed5a8a8e 12use Symbol;
9e72f0cf 13use IO::Handle;
c824fdf3 14use POSIX ":sys_wait_h";
9e72f0cf 15use Module::Runtime qw(use_module);
f8080c1c 16use Scalar::Util qw(weaken blessed refaddr openhandle);
9e72f0cf 17use JSON::PP qw(encode_json);
18use Moo;
19
c824fdf3 20BEGIN {
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_debug { "CHLD signal handler is executing" };
41 do {
42 $kid = waitpid(-1, WNOHANG);
43 log_trace { "waitpid() returned '$kid'" };
44 } while $kid > 0;
45 log_trace { "CHLD signal handler is done" };
46 };
47}
48
49END {
50 log_debug { "Killing all child processes in the process group" };
51
52 #send SIGINT to the process group for our children
53 kill(1, -2);
54}
55
56
6db5156c 57our $DEBUG = !!$ENV{OBJECT_REMOTE_DEBUG};
9031635d 58#numbering each connection allows it to be
59#tracked along with file handles in
60#the logs
c824fdf3 61
9031635d 62has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
ad4f54b2 63
9e72f0cf 64has send_to_fh => (
65 is => 'ro', required => 1,
90115979 66 trigger => sub {
67 my $self = $_[0];
68 $_[1]->autoflush(1);
69 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
70 },
9e72f0cf 71);
72
c824fdf3 73#TODO see if this is another case of the same bug below
74#where trigger never fires because the attribute isn't
75#actually set at any time
12fb4a80 76has read_channel => (
9e72f0cf 77 is => 'ro', required => 1,
78 trigger => sub {
12fb4a80 79 my ($self, $ch) = @_;
f8080c1c 80 my $id = $self->_id;
81 Dlog_trace { "trigger for read_channel has been invoked for connection $id; file handle is $_" } $ch->fh;
9e72f0cf 82 weaken($self);
12fb4a80 83 $ch->on_line_call(sub { $self->_receive(@_) });
f8080c1c 84 $ch->on_close_call(sub {
85 log_trace { "invoking 'done' on on_close handler for connection id '$id'" };
86 $self->on_close->done(@_);
87 });
9e72f0cf 88 },
89);
90
f8080c1c 91#TODO properly fix this bug -
92#trigger can't ever be invoked with a default
93#value and the on_close attribute is read only....
94#the future never gets the on_done handler
95#installed
c824fdf3 96sub BUILD {
f8080c1c 97 my ($self) = @_;
c824fdf3 98 $self->on_close(CPS::Future->new);
f8080c1c 99}
100
c824fdf3 101after BUILD => sub {
102 my ($self) = @_;
103
104 return unless defined $self->child_pid;
105
106 log_debug { "Setting process group of child process" };
107
108 setpgrp($self->child_pid, 1);
109};
110
111
112
12fb4a80 113has on_close => (
f8080c1c 114 is => 'rw', default => sub { CPS::Future->new },
9031635d 115 trigger => sub {
12fb4a80 116 my ($self, $f) = @_;
9031635d 117 Dlog_trace { "trigger for on_close has been invoked for connection $_" } $self->_id;
12fb4a80 118 weaken($self);
119 $f->on_done(sub {
f8080c1c 120 Dlog_trace { "failing all of the outstanding futures for connection $_" } $self->_id;
c824fdf3 121 $self->_fail_outstanding("Object::Remote connection lost: " . ($f->get)[0]);
12fb4a80 122 });
123 }
124);
ad4f54b2 125
47c83a13 126has child_pid => (is => 'ro');
127
11dbd4a0 128has local_objects_by_id => (
129 is => 'ro', default => sub { {} },
130 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
131);
9e72f0cf 132
11dbd4a0 133has remote_objects_by_id => (
134 is => 'ro', default => sub { {} },
135 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
136);
9e72f0cf 137
a980b0b8 138has outstanding_futures => (is => 'ro', default => sub { {} });
139
12fb4a80 140sub _fail_outstanding {
141 my ($self, $error) = @_;
9031635d 142 Dlog_debug { "Failing outstanding futures with '$error' for connection $_" } $self->_id;
12fb4a80 143 my $outstanding = $self->outstanding_futures;
144 $_->fail($error) for values %$outstanding;
145 %$outstanding = ();
146 return;
147}
148
9e72f0cf 149has _json => (
150 is => 'lazy',
151 handles => {
152 _deserialize => 'decode',
153 _encode => 'encode',
154 },
155);
156
fe6c9a7f 157sub _id_to_remote_object {
158 my ($self, $id) = @_;
9031635d 159 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
fe6c9a7f 160 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
161 (
162 $self->remote_objects_by_id->{$id}
163 or Object::Remote::Handle->new(connection => $self, id => $id)
164 )->proxy;
165}
166
9e72f0cf 167sub _build__json {
168 weaken(my $self = shift);
9e72f0cf 169 JSON::PP->new->filter_json_single_key_object(
170 __remote_object__ => sub {
fe6c9a7f 171 $self->_id_to_remote_object(@_);
172 }
173 )->filter_json_single_key_object(
174 __remote_code__ => sub {
175 my $code_container = $self->_id_to_remote_object(@_);
176 sub { $code_container->call(@_) };
9e72f0cf 177 }
6ed5d580 178 )->filter_json_single_key_object(
179 __scalar_ref__ => sub {
180 my $value = shift;
181 return \$value;
182 }
ed5a8a8e 183 )->filter_json_single_key_object(
184 __glob_ref__ => sub {
185 my $glob_container = $self->_id_to_remote_object(@_);
186 my $handle = Symbol::gensym;
187 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
188 return $handle;
189 }
6163a5aa 190 )->filter_json_single_key_object(
191 __local_object__ => sub {
192 $self->local_objects_by_id->{$_[0]}
193 }
7790ca36 194 )->filter_json_single_key_object(
195 __remote_tied_hash__ => sub {
196 my %tied_hash;
197 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
198 return \%tied_hash;
199 }
200 )->filter_json_single_key_object(
201 __remote_tied_array__ => sub {
202 my @tied_array;
203 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
204 return \@tied_array;
205 }
206 );
9e72f0cf 207}
208
c824fdf3 209sub _load_if_possible {
210 my ($class) = @_;
211
212 eval "require $class";
213
214 if ($@) {
215 log_debug { "Attempt at loading '$class' failed with '$@'" };
216 }
217
218}
219
84b04178 220BEGIN {
221 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
c824fdf3 222 map _load_if_possible($_), qw(
223 Object::Remote::Connector::Local
224 Object::Remote::Connector::LocalSudo
225 Object::Remote::Connector::SSH
226 Object::Remote::Connector::UNIX
227 );
84b04178 228}
229
c824fdf3 230sub conn_from_spec {
231 my ($class, $spec, @args) = @_;
84b04178 232 foreach my $poss (do { our @Guess }) {
c824fdf3 233 if (my $conn = $poss->($spec, @args)) {
234 return $conn;
fbd3b8ec 235 }
84b04178 236 }
c824fdf3 237
238 return undef;
239}
240
241sub new_from_spec {
242 my ($class, $spec) = @_;
243 return $spec if blessed $spec;
244 my $conn = $class->conn_from_spec($spec);
245
246 die "Couldn't figure out what to do with ${spec}"
247 unless defined $conn;
248
249 return $conn->maybe::start::connect;
84b04178 250}
251
11dbd4a0 252sub remote_object {
e144d525 253 my ($self, @args) = @_;
254 Object::Remote::Handle->new(
255 connection => $self, @args
256 )->proxy;
257}
258
4c17fea5 259sub connect {
260 my ($self, $to) = @_;
9031635d 261 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
deb77aaf 262 return await_future(
263 $self->send_class_call(0, 'Object::Remote', connect => $to)
264 );
4c17fea5 265}
266
11dbd4a0 267sub remote_sub {
c6fe6fbd 268 my ($self, $sub) = @_;
269 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
9031635d 270 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
deb77aaf 271 return await_future($self->send_class_call(0, $pkg, can => $name));
272}
273
274sub send_class_call {
275 my ($self, $ctx, @call) = @_;
9031635d 276 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
deb77aaf 277 $self->send(call => class_call_handler => $ctx => call => @call);
278}
279
280sub register_class_call_handler {
281 my ($self) = @_;
3687a42d 282 $self->local_objects_by_id->{'class_call_handler'} ||= do {
c5736e1c 283 my $o = $self->new_class_call_handler;
3687a42d 284 $self->_local_object_to_id($o);
285 $o;
286 };
c6fe6fbd 287}
288
c5736e1c 289sub new_class_call_handler {
290 Object::Remote::CodeContainer->new(
291 code => sub {
292 my ($class, $method) = (shift, shift);
293 use_module($class)->$method(@_);
294 }
295 );
296}
297
9e72f0cf 298sub register_remote {
299 my ($self, $remote) = @_;
9031635d 300 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
9e72f0cf 301 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
302 return $remote;
303}
304
305sub send_free {
306 my ($self, $id) = @_;
7790ca36 307 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
9e72f0cf 308 delete $self->remote_objects_by_id->{$id};
309 $self->_send([ free => $id ]);
310}
311
312sub send {
313 my ($self, $type, @call) = @_;
314
deb77aaf 315 my $future = CPS::Future->new;
a2d43709 316 my $remote = $self->remote_objects_by_id->{$call[0]};
deb77aaf 317
318 unshift @call, $type => $self->_local_object_to_id($future);
9e72f0cf 319
a980b0b8 320 my $outstanding = $self->outstanding_futures;
321 $outstanding->{$future} = $future;
a2d43709 322 $future->on_ready(sub {
323 undef($remote);
324 delete $outstanding->{$future}
325 });
a980b0b8 326
9e72f0cf 327 $self->_send(\@call);
328
329 return $future;
330}
331
9d804009 332sub send_discard {
333 my ($self, $type, @call) = @_;
334
deb77aaf 335 unshift @call, $type => 'NULL';
9d804009 336
337 $self->_send(\@call);
338}
339
9e72f0cf 340sub _send {
341 my ($self, $to_send) = @_;
9d64d2d9 342 my $fh = $self->send_to_fh;
9031635d 343 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
9d64d2d9 344 my $serialized = $self->_serialize($to_send)."\n";
6b7b2732 345 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
9d64d2d9 346 #TODO this is very risky for deadlocks unless it's set to non-blocking and then with out extra
7790ca36 347 #logic it could easily do short-writes to the remote side - how about taking this entire buffer
348 #and having the run loop send it to the file handle so this doesn't block while the sending
349 #is happening?
f8080c1c 350 my $ret;
351 eval {
352 local($SIG{PIPE}) = 'IGNORE';
353 die "filehandle is not open" unless openhandle($fh);
354 log_trace { "file handle has passed openhandle() test; printing to it" };
355 $ret = print $fh $serialized;
356 die "print was not successful: $!" unless defined $ret
357 };
c824fdf3 358
f8080c1c 359 if ($@) {
360 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
361 my $error = $@; chomp($error);
362 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
363 return;
364 }
365
9d64d2d9 366 return $ret;
9e72f0cf 367}
368
369sub _serialize {
370 my ($self, $data) = @_;
3687a42d 371 local our @New_Ids = (-1);
9d804009 372 return eval {
ad4f54b2 373 my $flat = $self->_encode($self->_deobjectify($data));
374 warn "$$ >>> ${flat}\n" if $DEBUG;
375 $flat;
70a578ac 376 } || do {
9d804009 377 my $err = $@; # won't get here if the eval doesn't die
378 # don't keep refs to new things
379 delete @{$self->local_objects_by_id}{@New_Ids};
380 die "Error serializing: $err";
381 };
9e72f0cf 382}
383
a76f2f60 384sub _local_object_to_id {
385 my ($self, $object) = @_;
386 my $id = refaddr($object);
387 $self->local_objects_by_id->{$id} ||= do {
3687a42d 388 push our(@New_Ids), $id if @New_Ids;
a76f2f60 389 $object;
390 };
391 return $id;
392}
393
9e72f0cf 394sub _deobjectify {
395 my ($self, $data) = @_;
396 if (blessed($data)) {
6163a5aa 397 if (
398 $data->isa('Object::Remote::Proxy')
399 and $data->{remote}->connection == $self
400 ) {
401 return +{ __local_object__ => $data->{remote}->id };
402 } else {
403 return +{ __remote_object__ => $self->_local_object_to_id($data) };
404 }
9e72f0cf 405 } elsif (my $ref = ref($data)) {
406 if ($ref eq 'HASH') {
7790ca36 407 my $tied_to = tied(%$data);
408 if(defined($tied_to)) {
409 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
410 } else {
411 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
412 }
9e72f0cf 413 } elsif ($ref eq 'ARRAY') {
7790ca36 414 my $tied_to = tied(@$data);
415 if (defined($tied_to)) {
416 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
417 } else {
418 return [ map $self->_deobjectify($_), @$data ];
419 }
fe6c9a7f 420 } elsif ($ref eq 'CODE') {
421 my $id = $self->_local_object_to_id(
422 Object::Remote::CodeContainer->new(code => $data)
423 );
424 return +{ __remote_code__ => $id };
6ed5d580 425 } elsif ($ref eq 'SCALAR') {
426 return +{ __scalar_ref__ => $$data };
ed5a8a8e 427 } elsif ($ref eq 'GLOB') {
428 return +{ __glob_ref__ => $self->_local_object_to_id(
429 Object::Remote::GlobContainer->new(handle => $data)
430 ) };
9e72f0cf 431 } else {
432 die "Can't collapse reftype $ref";
433 }
434 }
435 return $data; # plain scalar
436}
437
9e72f0cf 438sub _receive {
ad4f54b2 439 my ($self, $flat) = @_;
440 warn "$$ <<< $flat\n" if $DEBUG;
9031635d 441 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
ad4f54b2 442 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
443 or do { warn "Deserialize failed for ${flat}: $@"; return };
9031635d 444 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
9e72f0cf 445 eval { $self->${\"receive_${type}"}(@rest); 1 }
ad4f54b2 446 or do { warn "Receive failed for ${flat}: $@"; return };
9e72f0cf 447 return;
448}
449
450sub receive_free {
451 my ($self, $id) = @_;
9031635d 452 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
9d804009 453 delete $self->local_objects_by_id->{$id}
454 or warn "Free: no such object $id";
9e72f0cf 455 return;
456}
457
458sub receive_call {
deb77aaf 459 my ($self, $future_id, $id, @rest) = @_;
9031635d 460 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
deb77aaf 461 my $future = $self->_id_to_remote_object($future_id);
8131a88a 462 $future->{method} = 'call_discard_free';
9e72f0cf 463 my $local = $self->local_objects_by_id->{$id}
464 or do { $future->fail("No such object $id"); return };
465 $self->_invoke($future, $local, @rest);
466}
467
8131a88a 468sub receive_call_free {
469 my ($self, $future, $id, @rest) = @_;
9031635d 470 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
84b04178 471 $self->receive_call($future, $id, undef, @rest);
8131a88a 472 $self->receive_free($id);
473}
474
9e72f0cf 475sub _invoke {
84b04178 476 my ($self, $future, $local, $ctx, $method, @args) = @_;
9031635d 477 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
dc28afe8 478 if ($method =~ /^start::/) {
479 my $f = $local->$method(@args);
480 $f->on_done(sub { undef($f); $future->done(@_) });
3f1f1e66 481 return unless $f;
dc28afe8 482 $f->on_fail(sub { undef($f); $future->fail(@_) });
483 return;
484 }
84b04178 485 my $do = sub { $local->$method(@args) };
486 eval {
487 $future->done(
488 defined($ctx)
489 ? ($ctx ? $do->() : scalar($do->()))
490 : do { $do->(); () }
491 );
492 1;
493 } or do { $future->fail($@); return; };
9e72f0cf 494 return;
495}
496
9e72f0cf 4971;
b9a9982d 498
499=head1 NAME
500
501Object::Remote::Connection - An underlying connection for L<Object::Remote>
502
503=head1 LAME
504
505Shipping prioritised over writing this part up. Blame mst.
506
507=cut