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