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);
21 router()->exclude_forwarding;
22 $SIG{PIPE} = sub { log_debug { "Got a PIPE signal" } };
26 log_debug { "Killing all child processes in the process group" };
28 #send SIGINT to the process group for our children
32 has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
35 is => 'ro', required => 1,
39 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
44 is => 'ro', required => 1,
48 Dlog_trace { "trigger for read_channel has been invoked for connection $id; file handle is $_" } $ch->fh;
50 $ch->on_line_call(sub { $self->_receive(@_) });
51 $ch->on_close_call(sub {
52 log_trace { "invoking 'done' on on_close handler for connection id '$id'" };
53 $self->on_close->done(@_);
59 is => 'rw', default => sub { $_[0]->_install_future_handlers(CPS::Future->new) },
61 log_trace { "Installing handlers into future via trigger" };
62 $_[0]->_install_future_handlers($_[1])
66 has child_pid => (is => 'ro');
68 has local_objects_by_id => (
69 is => 'ro', default => sub { {} },
70 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
73 has remote_objects_by_id => (
74 is => 'ro', default => sub { {} },
75 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
78 has outstanding_futures => (is => 'ro', default => sub { {} });
83 _deserialize => 'decode',
90 my $pid = $self->child_pid;
92 unless (defined $pid) {
93 log_trace { "After BUILD invoked for connection but there was no pid" };
97 log_trace { "Setting process group of child process '$pid'" };
99 setpgrp($self->child_pid, 1);
104 sub _fail_outstanding {
105 my ($self, $error) = @_;
106 Dlog_debug { "$$ Failing outstanding futures with '$error' for connection $_" } $self->_id;
107 my $outstanding = $self->outstanding_futures;
108 $_->fail("$error\n") for values %$outstanding;
113 sub _install_future_handlers {
115 Dlog_trace { "Installing handlers into future for connection $_" } $self->_id;
118 my $pid = $self->child_pid;
119 Dlog_trace { "Executing on_done handler in future for connection $_" } $self->_id;
120 $self->_fail_outstanding("Object::Remote connection lost: " . ($f->get)[0]);
121 return unless defined $pid;
122 log_debug { "Waiting for child '$pid' to exit" };
123 my $ret = waitpid($pid, 0);
125 log_debug { "Waited for pid $pid but waitpid() returned $ret" };
128 log_warn { "Remote interpreter did not exit cleanly" };
131 my $exit_value = $? >> 8;
132 "Remote Perl interpreter exited with value '$exit_value'"
139 sub _id_to_remote_object {
140 my ($self, $id) = @_;
141 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
142 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
144 $self->remote_objects_by_id->{$id}
145 or Object::Remote::Handle->new(connection => $self, id => $id)
150 weaken(my $self = shift);
151 JSON::PP->new->filter_json_single_key_object(
152 __remote_object__ => sub {
153 $self->_id_to_remote_object(@_);
155 )->filter_json_single_key_object(
156 __remote_code__ => sub {
157 my $code_container = $self->_id_to_remote_object(@_);
158 sub { $code_container->call(@_) };
160 )->filter_json_single_key_object(
161 __scalar_ref__ => sub {
165 )->filter_json_single_key_object(
166 __glob_ref__ => sub {
167 my $glob_container = $self->_id_to_remote_object(@_);
168 my $handle = Symbol::gensym;
169 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
172 )->filter_json_single_key_object(
173 __remote_tied_hash__ => sub {
175 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
178 )->filter_json_single_key_object(
179 __remote_tied_array__ => sub {
181 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
187 sub _load_if_possible {
193 log_debug { "Attempt at loading '$class' failed with '$@'" };
199 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
200 map _load_if_possible($_), qw(
201 Object::Remote::Connector::Local
202 Object::Remote::Connector::LocalSudo
203 Object::Remote::Connector::SSH
204 Object::Remote::Connector::UNIX
209 my ($class, $spec, @args) = @_;
210 foreach my $poss (do { our @Guess }) {
211 if (my $conn = $poss->($spec, @args)) {
220 my ($class, $spec) = @_;
221 return $spec if blessed $spec;
222 my $conn = $class->conn_from_spec($spec);
224 die "Couldn't figure out what to do with ${spec}"
225 unless defined $conn;
227 return $conn->maybe::start::connect;
231 my ($self, @args) = @_;
232 Object::Remote::Handle->new(
233 connection => $self, @args
238 my ($self, $to) = @_;
239 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
241 $self->send_class_call(0, 'Object::Remote', connect => $to)
246 my ($self, $sub) = @_;
247 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
248 Dlog_debug { "Invoking remote sub '$sub' for connection $_" } $self->_id;
249 return await_future($self->send_class_call(0, $pkg, can => $name));
252 sub send_class_call {
253 my ($self, $ctx, @call) = @_;
254 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
255 $self->send(call => class_call_handler => $ctx => call => @call);
258 sub register_class_call_handler {
260 $self->local_objects_by_id->{'class_call_handler'} ||= do {
261 my $o = $self->new_class_call_handler;
262 $self->_local_object_to_id($o);
267 sub new_class_call_handler {
268 Object::Remote::CodeContainer->new(
270 my ($class, $method) = (shift, shift);
271 use_module($class)->$method(@_);
276 sub register_remote {
277 my ($self, $remote) = @_;
278 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
279 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
284 my ($self, $id) = @_;
285 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
286 #TODO this shows up some times when a remote side dies in the middle of a remote
287 #method invocation - possibly only when the object is being constructed?
288 #(in cleanup) Use of uninitialized value $id in delete at ../Object-Remote/lib/Object/Remote/Connection.
289 delete $self->remote_objects_by_id->{$id};
290 $self->_send([ free => $id ]);
294 my ($self, $type, @call) = @_;
296 my $future = CPS::Future->new;
297 my $remote = $self->remote_objects_by_id->{$call[0]};
299 unshift @call, $type => $self->_local_object_to_id($future);
301 my $outstanding = $self->outstanding_futures;
302 $outstanding->{$future} = $future;
303 $future->on_ready(sub {
305 delete $outstanding->{$future}
308 $self->_send(\@call);
314 my ($self, $type, @call) = @_;
316 unshift @call, $type => 'NULL';
318 $self->_send(\@call);
322 my ($self, $to_send) = @_;
323 my $fh = $self->send_to_fh;
324 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
325 my $serialized = $self->_serialize($to_send)."\n";
326 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
329 #TODO this should be converted over to a non-blocking ::WriteChannel class
330 die "filehandle is not open" unless openhandle($fh);
331 log_trace { "file handle has passed openhandle() test; printing to it" };
332 $ret = print $fh $serialized;
333 die "print was not successful: $!" unless defined $ret
337 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
340 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
348 my ($self, $data) = @_;
349 local our @New_Ids = (-1);
351 my $flat = $self->_encode($self->_deobjectify($data));
354 my $err = $@; # won't get here if the eval doesn't die
355 # don't keep refs to new things
356 delete @{$self->local_objects_by_id}{@New_Ids};
357 die "Error serializing: $err";
361 sub _local_object_to_id {
362 my ($self, $object) = @_;
363 my $id = refaddr($object);
364 $self->local_objects_by_id->{$id} ||= do {
365 push our(@New_Ids), $id if @New_Ids;
372 my ($self, $data) = @_;
373 if (blessed($data)) {
374 return +{ __remote_object__ => $self->_local_object_to_id($data) };
375 } elsif (my $ref = ref($data)) {
376 if ($ref eq 'HASH') {
377 my $tied_to = tied(%$data);
378 if(defined($tied_to)) {
379 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
381 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
383 } elsif ($ref eq 'ARRAY') {
384 my $tied_to = tied(@$data);
385 if (defined($tied_to)) {
386 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
388 return [ map $self->_deobjectify($_), @$data ];
390 } elsif ($ref eq 'CODE') {
391 my $id = $self->_local_object_to_id(
392 Object::Remote::CodeContainer->new(code => $data)
394 return +{ __remote_code__ => $id };
395 } elsif ($ref eq 'SCALAR') {
396 return +{ __scalar_ref__ => $$data };
397 } elsif ($ref eq 'GLOB') {
398 return +{ __glob_ref__ => $self->_local_object_to_id(
399 Object::Remote::GlobContainer->new(handle => $data)
402 die "Can't collapse reftype $ref";
405 return $data; # plain scalar
409 my ($self, $flat) = @_;
410 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
411 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
412 or do { warn "Deserialize failed for ${flat}: $@"; return };
413 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
414 eval { $self->${\"receive_${type}"}(@rest); 1 }
415 or do { warn "Receive failed for ${flat}: $@"; return };
420 my ($self, $id) = @_;
421 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
422 delete $self->local_objects_by_id->{$id}
423 or warn "Free: no such object $id";
428 my ($self, $future_id, $id, @rest) = @_;
429 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
430 my $future = $self->_id_to_remote_object($future_id);
431 $future->{method} = 'call_discard_free';
432 my $local = $self->local_objects_by_id->{$id}
433 or do { $future->fail("No such object $id"); return };
434 $self->_invoke($future, $local, @rest);
437 sub receive_call_free {
438 my ($self, $future, $id, @rest) = @_;
439 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
440 $self->receive_call($future, $id, undef, @rest);
441 $self->receive_free($id);
445 my ($self, $future, $local, $ctx, $method, @args) = @_;
446 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
447 if ($method =~ /^start::/) {
448 my $f = $local->$method(@args);
449 $f->on_done(sub { undef($f); $future->done(@_) });
451 $f->on_fail(sub { undef($f); $future->fail(@_) });
454 my $do = sub { $local->$method(@args) };
458 ? ($ctx ? $do->() : scalar($do->()))
462 } or do { $future->fail($@); return; };
470 Object::Remote::Connection - An underlying connection for L<Object::Remote>
474 Shipping prioritised over writing this part up. Blame mst.