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