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