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