1 package Object::Remote::Connection;
3 use Object::Remote::Logging qw (:log :dlog router);
4 use Object::Remote::Future;
5 use Object::Remote::Null;
6 use Object::Remote::Handle;
7 use Object::Remote::CodeContainer;
8 use Object::Remote::GlobProxy;
9 use Object::Remote::GlobContainer;
10 use Object::Remote::Tied;
14 use POSIX ":sys_wait_h";
15 use Module::Runtime qw(use_module);
16 use Scalar::Util qw(weaken blessed refaddr openhandle);
17 use JSON::PP qw(encode_json);
22 BEGIN { router()->exclude_forwarding }
27 log_trace { "END handler is being invoked in " . __PACKAGE__ };
29 foreach(keys(%child_pids)) {
30 log_debug { "Killing child process '$_'" };
35 has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
38 is => 'ro', required => 1,
42 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
47 is => 'ro', required => 1,
51 Dlog_trace { "trigger for read_channel has been invoked for connection $id; file handle is $_" } $ch->fh;
53 $ch->on_line_call(sub { $self->_receive(@_) });
54 $ch->on_close_call(sub {
55 log_trace { "invoking 'done' on on_close handler for connection id '$id'" };
56 $self->on_close->done(@_);
62 is => 'rw', default => sub { $_[0]->_install_future_handlers(Future->new) },
64 log_trace { "Installing handlers into future via trigger" };
65 $_[0]->_install_future_handlers($_[1])
69 has child_pid => (is => 'ro');
71 has local_objects_by_id => (
72 is => 'ro', default => sub { {} },
73 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
76 has remote_objects_by_id => (
77 is => 'ro', default => sub { {} },
78 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
81 has outstanding_futures => (is => 'ro', default => sub { {} });
86 _deserialize => 'decode',
93 my $pid = $self->child_pid;
95 return unless defined $pid;
96 $child_pids{$pid} = 1;
104 my $valid = ! $self->on_close->is_ready;
114 "Connection '$id' is valid: '$text'"
120 sub _fail_outstanding {
121 my ($self, $error) = @_;
122 my $outstanding = $self->outstanding_futures;
125 sprintf "Failing %i outstanding futures with '$error'", scalar(keys(%$outstanding))
128 foreach(keys(%$outstanding)) {
129 log_trace { "Failing future for $_" };
130 my $future = $outstanding->{$_};
131 $future->fail("$error\n");
138 sub _install_future_handlers {
141 Dlog_trace { "Installing handlers into future for connection $_" } $self->_id;
144 my $pid = $self->child_pid;
145 Dlog_trace { "Executing on_done handler in future for connection $_" } $self->_id;
146 $self->_fail_outstanding("Object::Remote connection lost: " . ($f->get)[0]);
147 return unless defined $pid;
148 log_debug { "Waiting for child '$pid' to exit" };
149 my $ret = waitpid($pid, 0);
151 log_debug { "Waited for pid $pid but waitpid() returned $ret" };
154 log_warn { "Remote interpreter did not exit cleanly" };
157 my $exit_value = $? >> 8;
158 "Remote Perl interpreter exited with value '$exit_value'"
162 delete $child_pids{$pid};
167 sub _id_to_remote_object {
168 my ($self, $id) = @_;
169 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
170 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
172 $self->remote_objects_by_id->{$id}
173 or Object::Remote::Handle->new(connection => $self, id => $id)
178 weaken(my $self = shift);
179 JSON::PP->new->filter_json_single_key_object(
180 __remote_object__ => sub {
181 $self->_id_to_remote_object(@_);
183 )->filter_json_single_key_object(
184 __remote_code__ => sub {
185 my $code_container = $self->_id_to_remote_object(@_);
186 sub { $code_container->call(@_) };
188 )->filter_json_single_key_object(
189 __scalar_ref__ => sub {
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;
200 )->filter_json_single_key_object(
201 __local_object__ => sub {
202 $self->local_objects_by_id->{$_[0]}
204 )->filter_json_single_key_object(
205 __remote_tied_hash__ => sub {
207 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
210 )->filter_json_single_key_object(
211 __remote_tied_array__ => sub {
213 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
219 sub _load_if_possible {
225 log_debug { "Attempt at loading '$class' failed with '$@'" };
231 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
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
241 my ($class, $spec, @args) = @_;
242 foreach my $poss (do { our @Guess }) {
243 if (my $conn = $poss->($spec, @args)) {
252 my ($class, $spec, @args) = @_;
253 return $spec if blessed $spec;
254 my $conn = $class->conn_from_spec($spec, @args);
256 die "Couldn't figure out what to do with ${spec}"
257 unless defined $conn;
259 return $conn->maybe::start::connect;
263 my ($self, @args) = @_;
264 Object::Remote::Handle->new(
265 connection => $self, @args
270 my ($self, $to) = @_;
271 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
273 $self->send_class_call(0, 'Object::Remote', connect => $to)
278 my ($self, $sub) = @_;
279 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
280 Dlog_debug { "Invoking remote sub '$sub' for connection '$_'" } $self->_id;
281 return await_future($self->send_class_call(0, $pkg, can => $name));
284 sub send_class_call {
285 my ($self, $ctx, @call) = @_;
286 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
287 $self->send(call => class_call_handler => $ctx => call => @call);
290 sub register_class_call_handler {
292 $self->local_objects_by_id->{'class_call_handler'} ||= do {
293 my $o = $self->new_class_call_handler;
294 $self->_local_object_to_id($o);
299 sub new_class_call_handler {
300 Object::Remote::CodeContainer->new(
302 my ($class, $method) = (shift, shift);
303 use_module($class)->$method(@_);
308 sub register_remote {
309 my ($self, $remote) = @_;
310 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
311 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
316 my ($self, $id) = @_;
317 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
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.
321 delete $self->remote_objects_by_id->{$id};
322 $self->_send([ free => $id ]);
326 my ($self, $type, @call) = @_;
328 my $future = Future->new;
329 my $remote = $self->remote_objects_by_id->{$call[0]};
331 unshift @call, $type => $self->_local_object_to_id($future);
333 my $outstanding = $self->outstanding_futures;
334 $outstanding->{$future} = $future;
335 $future->on_ready(sub {
337 delete $outstanding->{$future}
340 $self->_send(\@call);
346 my ($self, $type, @call) = @_;
348 unshift @call, $type => 'NULL';
350 $self->_send(\@call);
354 my ($self, $to_send) = @_;
355 my $fh = $self->send_to_fh;
357 unless ($self->is_valid) {
358 croak "Attempt to invoke _send on a connection that is not valid";
361 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
362 my $serialized = $self->_serialize($to_send)."\n";
363 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
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
374 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
377 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
385 my ($self, $data) = @_;
386 local our @New_Ids = (-1);
388 my $flat = $self->_encode($self->_deobjectify($data));
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";
398 sub _local_object_to_id {
399 my ($self, $object) = @_;
400 my $id = refaddr($object);
401 $self->local_objects_by_id->{$id} ||= do {
402 push our(@New_Ids), $id if @New_Ids;
409 my ($self, $data) = @_;
410 if (blessed($data)) {
412 $data->isa('Object::Remote::Proxy')
413 and $data->{remote}->connection == $self
415 return +{ __local_object__ => $data->{remote}->id };
417 return +{ __remote_object__ => $self->_local_object_to_id($data) };
419 } elsif (my $ref = ref($data)) {
420 if ($ref eq 'HASH') {
421 my $tied_to = tied(%$data);
422 if(defined($tied_to)) {
423 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
425 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
427 } elsif ($ref eq 'ARRAY') {
428 my $tied_to = tied(@$data);
429 if (defined($tied_to)) {
430 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
432 return [ map $self->_deobjectify($_), @$data ];
434 } elsif ($ref eq 'CODE') {
435 my $id = $self->_local_object_to_id(
436 Object::Remote::CodeContainer->new(code => $data)
438 return +{ __remote_code__ => $id };
439 } elsif ($ref eq 'SCALAR') {
440 return +{ __scalar_ref__ => $$data };
441 } elsif ($ref eq 'GLOB') {
442 return +{ __glob_ref__ => $self->_local_object_to_id(
443 Object::Remote::GlobContainer->new(handle => $data)
446 die "Can't collapse reftype $ref";
449 return $data; # plain scalar
453 my ($self, $flat) = @_;
454 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
455 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
456 or do { warn "Deserialize failed for ${flat}: $@"; return };
457 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
458 eval { $self->${\"receive_${type}"}(@rest); 1 }
459 or do { warn "Receive failed for ${flat}: $@"; return };
464 my ($self, $id) = @_;
465 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
466 delete $self->local_objects_by_id->{$id}
467 or warn "Free: no such object $id";
472 my ($self, $future_id, $id, @rest) = @_;
473 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
474 my $future = $self->_id_to_remote_object($future_id);
475 $future->{method} = 'call_discard_free';
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);
481 sub receive_call_free {
482 my ($self, $future, $id, @rest) = @_;
483 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
484 $self->receive_call($future, $id, undef, @rest);
485 $self->receive_free($id);
489 my ($self, $future, $local, $ctx, $method, @args) = @_;
490 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
491 if ($method =~ /^start::/) {
492 my $f = $local->$method(@args);
493 $f->on_done(sub { undef($f); $future->done(@_) });
495 $f->on_fail(sub { undef($f); $future->fail(@_) });
498 my $do = sub { $local->$method(@args) };
502 ? ($ctx ? $do->() : scalar($do->()))
506 } or do { $future->fail($@); return; };
514 Object::Remote::Connection - An underlying connection for L<Object::Remote>
518 my $local = Object::Remote->connect('-');
519 my $remote = Object::Remote->connect('myserver');
520 my $remote_user = Object::Remote->connect('user@myserver');
521 my $local_sudo = Object::Remote->connect('user@');
523 #$remote can be any other connection object
524 my $hostname = Sys::Hostname->can::on($remote, 'hostname');
528 This is the class that supports connections to remote objects.
534 =item C<Object::Remote::Role::Connector::PerlInterpreter>
536 =item C<Object::Remote>