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