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