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 router()->exclude_forwarding;
23 $SIG{PIPE} = sub { log_debug { "Got a PIPE signal" } };
27 log_debug { "Killing all child processes in the process group" };
29 #send SIGINT to the process group for our children
33 has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
36 is => 'ro', required => 1,
40 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
45 is => 'ro', required => 1,
49 Dlog_trace { "trigger for read_channel has been invoked for connection $id; file handle is $_" } $ch->fh;
51 $ch->on_line_call(sub { $self->_receive(@_) });
52 $ch->on_close_call(sub {
53 log_trace { "invoking 'done' on on_close handler for connection id '$id'" };
54 $self->on_close->done(@_);
60 is => 'rw', default => sub { $_[0]->_install_future_handlers(CPS::Future->new) },
62 log_trace { "Installing handlers into future via trigger" };
63 $_[0]->_install_future_handlers($_[1])
67 has child_pid => (is => 'ro');
69 has local_objects_by_id => (
70 is => 'ro', default => sub { {} },
71 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
74 has remote_objects_by_id => (
75 is => 'ro', default => sub { {} },
76 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
79 has outstanding_futures => (is => 'ro', default => sub { {} });
84 _deserialize => 'decode',
91 my $pid = $self->child_pid;
93 unless (defined $pid) {
94 log_trace { "After BUILD invoked for connection but there was no pid" };
98 log_trace { "Setting process group of child process '$pid'" };
100 setpgrp($self->child_pid, 1);
107 my $closed = $self->on_close->is_ready;
109 log_trace { "Connection closed: $closed" };
113 sub _fail_outstanding {
114 my ($self, $error) = @_;
115 my $outstanding = $self->outstanding_futures;
118 sprintf "Failing %i outstanding futures with '$error'", scalar(keys(%$outstanding))
121 foreach(keys(%$outstanding)) {
122 log_trace { "Failing future for $_" };
123 my $future = $outstanding->{$_};
130 sub _install_future_handlers {
132 Dlog_trace { "Installing handlers into future for connection $_" } $self->_id;
135 my $pid = $self->child_pid;
136 Dlog_trace { "Executing on_done handler in future for connection $_" } $self->_id;
137 $self->_fail_outstanding("Object::Remote connection lost: " . ($f->get)[0]);
138 return unless defined $pid;
139 log_debug { "Waiting for child '$pid' to exit" };
140 my $ret = waitpid($pid, 0);
142 log_debug { "Waited for pid $pid but waitpid() returned $ret" };
145 log_warn { "Remote interpreter did not exit cleanly" };
148 my $exit_value = $? >> 8;
149 "Remote Perl interpreter exited with value '$exit_value'"
156 sub _id_to_remote_object {
157 my ($self, $id) = @_;
158 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
159 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
161 $self->remote_objects_by_id->{$id}
162 or Object::Remote::Handle->new(connection => $self, id => $id)
167 weaken(my $self = shift);
168 JSON::PP->new->filter_json_single_key_object(
169 __remote_object__ => sub {
170 $self->_id_to_remote_object(@_);
172 )->filter_json_single_key_object(
173 __remote_code__ => sub {
174 my $code_container = $self->_id_to_remote_object(@_);
175 sub { $code_container->call(@_) };
177 )->filter_json_single_key_object(
178 __scalar_ref__ => sub {
182 )->filter_json_single_key_object(
183 __glob_ref__ => sub {
184 my $glob_container = $self->_id_to_remote_object(@_);
185 my $handle = Symbol::gensym;
186 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
189 )->filter_json_single_key_object(
190 __local_object__ => sub {
191 $self->local_objects_by_id->{$_[0]}
193 )->filter_json_single_key_object(
194 __remote_tied_hash__ => sub {
196 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
199 )->filter_json_single_key_object(
200 __remote_tied_array__ => sub {
202 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
208 sub _load_if_possible {
214 log_debug { "Attempt at loading '$class' failed with '$@'" };
220 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
221 map _load_if_possible($_), qw(
222 Object::Remote::Connector::Local
223 Object::Remote::Connector::LocalSudo
224 Object::Remote::Connector::SSH
225 Object::Remote::Connector::UNIX
230 my ($class, $spec, @args) = @_;
231 foreach my $poss (do { our @Guess }) {
232 if (my $conn = $poss->($spec, @args)) {
241 my ($class, $spec) = @_;
242 return $spec if blessed $spec;
243 my $conn = $class->conn_from_spec($spec);
245 die "Couldn't figure out what to do with ${spec}"
246 unless defined $conn;
248 return $conn->maybe::start::connect;
252 my ($self, @args) = @_;
253 Object::Remote::Handle->new(
254 connection => $self, @args
259 my ($self, $to) = @_;
260 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
262 $self->send_class_call(0, 'Object::Remote', connect => $to)
267 my ($self, $sub) = @_;
268 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
269 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
270 return await_future($self->send_class_call(0, $pkg, can => $name));
273 sub send_class_call {
274 my ($self, $ctx, @call) = @_;
275 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
276 $self->send(call => class_call_handler => $ctx => call => @call);
279 sub register_class_call_handler {
281 $self->local_objects_by_id->{'class_call_handler'} ||= do {
282 my $o = $self->new_class_call_handler;
283 $self->_local_object_to_id($o);
288 sub new_class_call_handler {
289 Object::Remote::CodeContainer->new(
291 my ($class, $method) = (shift, shift);
292 use_module($class)->$method(@_);
297 sub register_remote {
298 my ($self, $remote) = @_;
299 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
300 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
305 my ($self, $id) = @_;
306 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
307 #TODO this shows up some times when a remote side dies in the middle of a remote
308 #method invocation - possibly only when the object is being constructed?
309 #(in cleanup) Use of uninitialized value $id in delete at ../Object-Remote/lib/Object/Remote/Connection.
310 delete $self->remote_objects_by_id->{$id};
311 $self->_send([ free => $id ]);
315 my ($self, $type, @call) = @_;
317 my $future = CPS::Future->new;
318 my $remote = $self->remote_objects_by_id->{$call[0]};
320 unshift @call, $type => $self->_local_object_to_id($future);
322 my $outstanding = $self->outstanding_futures;
323 $outstanding->{$future} = $future;
324 $future->on_ready(sub {
326 delete $outstanding->{$future}
329 $self->_send(\@call);
335 my ($self, $type, @call) = @_;
337 unshift @call, $type => 'NULL';
339 $self->_send(\@call);
343 my ($self, $to_send) = @_;
344 my $fh = $self->send_to_fh;
346 unless ($self->is_valid) {
347 croak "Attempt to invoke _send on a connection that is not valid";
350 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
351 my $serialized = $self->_serialize($to_send)."\n";
352 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
355 #TODO this should be converted over to a non-blocking ::WriteChannel class
356 die "filehandle is not open" unless openhandle($fh);
357 log_trace { "file handle has passed openhandle() test; printing to it" };
358 $ret = print $fh $serialized;
359 die "print was not successful: $!" unless defined $ret
363 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
366 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
374 my ($self, $data) = @_;
375 local our @New_Ids = (-1);
377 my $flat = $self->_encode($self->_deobjectify($data));
380 my $err = $@; # won't get here if the eval doesn't die
381 # don't keep refs to new things
382 delete @{$self->local_objects_by_id}{@New_Ids};
383 die "Error serializing: $err";
387 sub _local_object_to_id {
388 my ($self, $object) = @_;
389 my $id = refaddr($object);
390 $self->local_objects_by_id->{$id} ||= do {
391 push our(@New_Ids), $id if @New_Ids;
398 my ($self, $data) = @_;
399 if (blessed($data)) {
401 $data->isa('Object::Remote::Proxy')
402 and $data->{remote}->connection == $self
404 return +{ __local_object__ => $data->{remote}->id };
406 return +{ __remote_object__ => $self->_local_object_to_id($data) };
408 } elsif (my $ref = ref($data)) {
409 if ($ref eq 'HASH') {
410 my $tied_to = tied(%$data);
411 if(defined($tied_to)) {
412 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
414 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
416 } elsif ($ref eq 'ARRAY') {
417 my $tied_to = tied(@$data);
418 if (defined($tied_to)) {
419 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
421 return [ map $self->_deobjectify($_), @$data ];
423 } elsif ($ref eq 'CODE') {
424 my $id = $self->_local_object_to_id(
425 Object::Remote::CodeContainer->new(code => $data)
427 return +{ __remote_code__ => $id };
428 } elsif ($ref eq 'SCALAR') {
429 return +{ __scalar_ref__ => $$data };
430 } elsif ($ref eq 'GLOB') {
431 return +{ __glob_ref__ => $self->_local_object_to_id(
432 Object::Remote::GlobContainer->new(handle => $data)
435 die "Can't collapse reftype $ref";
438 return $data; # plain scalar
442 my ($self, $flat) = @_;
443 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
444 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
445 or do { warn "Deserialize failed for ${flat}: $@"; return };
446 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
447 eval { $self->${\"receive_${type}"}(@rest); 1 }
448 or do { warn "Receive failed for ${flat}: $@"; return };
453 my ($self, $id) = @_;
454 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
455 delete $self->local_objects_by_id->{$id}
456 or warn "Free: no such object $id";
461 my ($self, $future_id, $id, @rest) = @_;
462 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
463 my $future = $self->_id_to_remote_object($future_id);
464 $future->{method} = 'call_discard_free';
465 my $local = $self->local_objects_by_id->{$id}
466 or do { $future->fail("No such object $id"); return };
467 $self->_invoke($future, $local, @rest);
470 sub receive_call_free {
471 my ($self, $future, $id, @rest) = @_;
472 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
473 $self->receive_call($future, $id, undef, @rest);
474 $self->receive_free($id);
478 my ($self, $future, $local, $ctx, $method, @args) = @_;
479 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
480 if ($method =~ /^start::/) {
481 my $f = $local->$method(@args);
482 $f->on_done(sub { undef($f); $future->done(@_) });
484 $f->on_fail(sub { undef($f); $future->fail(@_) });
487 my $do = sub { $local->$method(@args) };
491 ? ($ctx ? $do->() : scalar($do->()))
495 } or do { $future->fail($@); return; };
503 Object::Remote::Connection - An underlying connection for L<Object::Remote>
507 Shipping prioritised over writing this part up. Blame mst.