Remote/Connection.pm

filter: Statementstmt 33.3% 1 / 3 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 1 / 1 Podpod n/a totaltotal 50.0% 2 / 4 CC 1 SCAR 2.6
CC
1
Cov
33%
BEGIN
1.3
CRAP 1.3
« Remote.pm ↑ Summary Remote/FromData.pm »
1 package Object::Remote::Connection;
2  
3 0 ▶use Object::Remote::Logging qw (:log :dlog router);
Subroutine BEGIN: called CC=1 SCAR=2.6
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;
11 use Object::Remote;
12 use Symbol;
13 use IO::Handle;
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);
18 use Future;
19 use Carp qw(croak);
20 use Moo;
21  
22 BEGIN { router()->exclude_forwarding }
23  
24 END {
25 our %child_pids;
26  
27 log_trace { "END handler is being invoked in " . __PACKAGE__ };
28  
29 foreach(keys(%child_pids)) {
30 log_debug { "Killing child process '$_'" };
31 kill('TERM', $_);
32 }
33 }
34  
35 has _id => ( is => 'ro', required => 1, default => sub { our $NEXT_CONNECTION_ID++ } );
36  
37 has send_to_fh => (
38 is => 'ro', required => 1,
39 trigger => sub {
40 my $self = $_[0];
41 $_[1]->autoflush(1);
42 Dlog_trace { my $id = $self->_id; "connection had send_to_fh set to $_" } $_[1];
43 },
44 );
45  
46 has read_channel => (
47 is => 'ro', required => 1,
48 trigger => sub {
49 my ($self, $ch) = @_;
50 my $id = $self->_id;
51 Dlog_trace { "trigger for read_channel has been invoked for connection $id; file handle is $_" } $ch->fh;
52 weaken($self);
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(@_)
57 unless $self->on_close->is_ready;
58 });
59 },
60 );
61  
62 has on_close => (
63 is => 'rw', default => sub { $_[0]->_install_future_handlers(Object::Remote->current_loop->new_future) },
64 trigger => sub {
65 log_trace { "Installing handlers into future via trigger" };
66 $_[0]->_install_future_handlers($_[1])
67 },
68 );
69  
70 has child_pid => (is => 'ro');
71  
72 has local_objects_by_id => (
73 is => 'ro', default => sub { {} },
74 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
75 );
76  
77 has remote_objects_by_id => (
78 is => 'ro', default => sub { {} },
79 coerce => sub { +{ %{$_[0]} } }, # shallow clone on the way in
80 );
81  
82 has outstanding_futures => (is => 'ro', default => sub { {} });
83  
84 has _json => (
85 is => 'lazy',
86 handles => {
87 _deserialize => 'decode',
88 _encode => 'encode',
89 },
90 );
91  
92 after BUILD => sub {
93 my ($self) = @_;
94 my $pid = $self->child_pid;
95 our %child_pids;
96 return unless defined $pid;
97 $child_pids{$pid} = 1;
98 return;
99 };
100  
101 sub BUILD { }
102  
103 sub is_valid {
104 my ($self) = @_;
105 my $valid = ! $self->on_close->is_ready;
106  
107 log_trace {
108 my $id = $self->_id;
109 my $text;
110 if ($valid) {
111 $text = 'yes';
112 } else {
113 $text = 'no';
114 }
115 "Connection '$id' is valid: '$text'"
116 };
117  
118 return $valid;
119 }
120  
121 sub _fail_outstanding {
122 my ($self, $error) = @_;
123 my $outstanding = $self->outstanding_futures;
124  
125 Dlog_debug {
126 sprintf "Failing %i outstanding futures with '$error'", scalar(keys(%$outstanding))
127 };
128  
129 foreach(keys(%$outstanding)) {
130 log_trace { "Failing future for $_" };
131 my $future = $outstanding->{$_};
132 $future->fail("$error\n");
133 }
134  
135 %$outstanding = ();
136 return;
137 }
138  
139 sub _install_future_handlers {
140 my ($self, $f) = @_;
141 our %child_pids;
142 Dlog_trace { "Installing handlers into future for connection $_" } $self->_id;
143 weaken($self);
144 $f->on_done(sub {
145 my $pid = $self->child_pid;
146 Dlog_trace { "Executing on_done handler in future for connection $_" } $self->_id;
147 $self->_fail_outstanding("Object::Remote connection lost: " . ($f->get)[0]);
148 return unless defined $pid;
149 log_debug { "Waiting for child '$pid' to exit" };
150 my $ret = waitpid($pid, 0);
151 if ($ret != $pid) {
152 log_debug { "Waited for pid $pid but waitpid() returned $ret" };
153 return;
154 } elsif ($? & 127) {
155 log_warn { "Remote interpreter did not exit cleanly" };
156 } else {
157 log_verbose {
158 my $exit_value = $? >> 8;
159 "Remote Perl interpreter exited with value '$exit_value'"
160 };
161 }
162  
163 delete $child_pids{$pid};
164 });
165 return $f;
166 };
167  
168 sub _id_to_remote_object {
169 my ($self, $id) = @_;
170 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
171 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
172 (
173 $self->remote_objects_by_id->{$id}
174 or Object::Remote::Handle->new(connection => $self, id => $id)
175 )->proxy;
176 }
177  
178 sub _build__json {
179 weaken(my $self = shift);
180 JSON::PP->new->filter_json_single_key_object(
181 __remote_object__ => sub {
182 $self->_id_to_remote_object(@_);
183 }
184 )->filter_json_single_key_object(
185 __remote_code__ => sub {
186 my $code_container = $self->_id_to_remote_object(@_);
187 sub { $code_container->call(@_) };
188 }
189 )->filter_json_single_key_object(
190 __scalar_ref__ => sub {
191 my $value = shift;
192 return \$value;
193 }
194 )->filter_json_single_key_object(
195 __glob_ref__ => sub {
196 my $glob_container = $self->_id_to_remote_object(@_);
197 my $handle = Symbol::gensym;
198 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
199 return $handle;
200 }
201 )->filter_json_single_key_object(
202 __local_object__ => sub {
203 $self->local_objects_by_id->{$_[0]}
204 }
205 )->filter_json_single_key_object(
206 __remote_tied_hash__ => sub {
207 my %tied_hash;
208 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
209 return \%tied_hash;
210 }
211 )->filter_json_single_key_object(
212 __remote_tied_array__ => sub {
213 my @tied_array;
214 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
215 return \@tied_array;
216 }
217 );
218 }
219  
220 sub _load_if_possible {
221 my ($class) = @_;
222  
223 use_module($class);
224  
225 if ($@) {
226 log_debug { "Attempt at loading '$class' failed with '$@'" };
227 }
228  
229 }
230  
231 BEGIN {
232 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
233 map _load_if_possible($_), qw(
234 Object::Remote::Connector::Local
235 Object::Remote::Connector::LocalSudo
236 Object::Remote::Connector::SSH
237 Object::Remote::Connector::UNIX
238 Object::Remote::Connector::INET
239 );
240 }
241  
242 sub conn_from_spec {
243 my ($class, $spec, @args) = @_;
244 foreach my $poss (do { our @Guess }) {
245 if (my $conn = $poss->($spec, @args)) {
246 return $conn;
247 }
248 }
249  
250 return undef;
251 }
252  
253 sub new_from_spec {
254 my ($class, $spec, @args) = @_;
255 return $spec if blessed $spec;
256 my $conn = $class->conn_from_spec($spec, @args);
257  
258 die "Couldn't figure out what to do with ${spec}"
259 unless defined $conn;
260  
261 return $conn->maybe::start::connect;
262 }
263  
264 sub remote_object {
265 my ($self, @args) = @_;
266 Object::Remote::Handle->new(
267 connection => $self, @args
268 )->proxy;
269 }
270  
271 sub connect {
272 my ($self, $to) = @_;
273 Dlog_debug { "Creating connection to remote node '$to' for connection $_" } $self->_id;
274 return await_future(
275 $self->send_class_call(0, 'Object::Remote', connect => $to)
276 );
277 }
278  
279 sub remote_sub {
280 my ($self, $sub) = @_;
281 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
282 Dlog_debug { "Invoking remote sub '$sub' for connection '$_'" } $self->_id;
283 return await_future($self->send_class_call(0, $pkg, can => $name));
284 }
285  
286 sub send_class_call {
287 my ($self, $ctx, @call) = @_;
288 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
289 $self->send(call => class_call_handler => $ctx => call => @call);
290 }
291  
292 sub register_class_call_handler {
293 my ($self) = @_;
294 $self->local_objects_by_id->{'class_call_handler'} ||= do {
295 my $o = $self->new_class_call_handler;
296 $self->_local_object_to_id($o);
297 $o;
298 };
299 }
300  
301 sub new_class_call_handler {
302 Object::Remote::CodeContainer->new(
303 code => sub {
304 my ($class, $method) = (shift, shift);
305 use_module($class)->$method(@_);
306 }
307 );
308 }
309  
310 sub register_remote {
311 my ($self, $remote) = @_;
312 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
313 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
314 return $remote;
315 }
316  
317 sub send_free {
318 my ($self, $id) = @_;
319 $id = '' unless defined $id;
320 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
321 #TODO this shows up some times when a remote side dies in the middle of a remote
322 #method invocation - possibly only when the object is being constructed?
323 #(in cleanup) Use of uninitialized value $id in delete at ../Object-Remote/lib/Object/Remote/Connection.
324 delete $self->remote_objects_by_id->{$id};
325 $self->_send([ free => $id ]);
326 }
327  
328 sub send {
329 my ($self, $type, @call) = @_;
330  
331 my $future = Object::Remote->current_loop->new_future;
332 my $remote = $self->remote_objects_by_id->{$call[0]};
333  
334 unshift @call, $type => $self->_local_object_to_id($future);
335  
336 my $outstanding = $self->outstanding_futures;
337 $outstanding->{$future} = $future;
338 $future->on_ready(sub {
339 undef($remote);
340 delete $outstanding->{$future}
341 });
342  
343 $self->_send(\@call);
344  
345 return $future;
346 }
347  
348 sub send_discard {
349 my ($self, $type, @call) = @_;
350  
351 unshift @call, $type => 'NULL';
352  
353 $self->_send(\@call);
354 }
355  
356 sub _send {
357 my ($self, $to_send) = @_;
358 my $fh = $self->send_to_fh;
359  
360 unless ($self->is_valid) {
361 croak "Attempt to invoke _send on a connection that is not valid";
362 }
363  
364 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
365 my $serialized = $self->_serialize($to_send)."\n";
366 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
367 my $ret;
368 eval {
369 #TODO this should be converted over to a non-blocking ::WriteChannel class
370 die "filehandle is not open" unless openhandle($fh);
371 log_trace { "file handle has passed openhandle() test; printing to it" };
372 $ret = print $fh $serialized;
373 die "print was not successful: $!" unless defined $ret
374 };
375  
376 if ($@) {
377 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
378 my $error = $@;
379 chomp($error);
380 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
381 return;
382 }
383  
384 return $ret;
385 }
386  
387 sub _serialize {
388 my ($self, $data) = @_;
389 local our @New_Ids = (-1);
390 return eval {
391 my $flat = $self->_encode($self->_deobjectify($data));
392 $flat;
393 } || do {
394 my $err = $@; # won't get here if the eval doesn't die
395 # don't keep refs to new things
396 delete @{$self->local_objects_by_id}{@New_Ids};
397 die "Error serializing: $err";
398 };
399 }
400  
401 sub _local_object_to_id {
402 my ($self, $object) = @_;
403 my $id = refaddr($object);
404 $self->local_objects_by_id->{$id} ||= do {
405 push our(@New_Ids), $id if @New_Ids;
406 $object;
407 };
408 return $id;
409 }
410  
411 sub _deobjectify {
412 my ($self, $data) = @_;
413 if (blessed($data)) {
414 if (
415 $data->isa('Object::Remote::Proxy')
416 and $data->{remote}->connection == $self
417 ) {
418 return +{ __local_object__ => $data->{remote}->id };
419 } else {
420 return +{ __remote_object__ => $self->_local_object_to_id($data) };
421 }
422 } elsif (my $ref = ref($data)) {
423 if ($ref eq 'HASH') {
424 my $tied_to = tied(%$data);
425 if(defined($tied_to)) {
426 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
427 } else {
428 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
429 }
430 } elsif ($ref eq 'ARRAY') {
431 my $tied_to = tied(@$data);
432 if (defined($tied_to)) {
433 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
434 } else {
435 return [ map $self->_deobjectify($_), @$data ];
436 }
437 } elsif ($ref eq 'CODE') {
438 my $id = $self->_local_object_to_id(
439 Object::Remote::CodeContainer->new(code => $data)
440 );
441 return +{ __remote_code__ => $id };
442 } elsif ($ref eq 'SCALAR') {
443 return +{ __scalar_ref__ => $$data };
444 } elsif ($ref eq 'GLOB') {
445 return +{ __glob_ref__ => $self->_local_object_to_id(
446 Object::Remote::GlobContainer->new(handle => $data)
447 ) };
448 } else {
449 die "Can't collapse reftype $ref";
450 }
451 }
452 return $data; # plain scalar
453 }
454  
455 sub _receive {
456 my ($self, $flat) = @_;
457 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
458 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
459 or do { warn "Deserialize failed for ${flat}: $@"; return };
460 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
461 eval { $self->${\"receive_${type}"}(@rest); 1 }
462 or do { warn "Receive failed for ${flat}: $@"; return };
463 return;
464 }
465  
466 sub receive_free {
467 my ($self, $id) = @_;
468 $id = '' unless defined $id;
469 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
470 delete $self->local_objects_by_id->{$id}
471 or warn "Free: no such object $id";
472 return;
473 }
474  
475 sub receive_call {
476 my ($self, $future_id, $id, @rest) = @_;
477 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
478 my $future = $self->_id_to_remote_object($future_id);
479 $future->{method} = 'call_discard_free';
480 my $local = $self->local_objects_by_id->{$id}
481 or do { $future->fail("No such object $id"); return };
482 $self->_invoke($future, $local, @rest);
483 }
484  
485 sub receive_call_free {
486 my ($self, $future, $id, @rest) = @_;
487 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
488 $self->receive_call($future, $id, undef, @rest);
489 $self->receive_free($id);
490 }
491  
492 sub _invoke {
493 my ($self, $future, $local, $ctx, $method, @args) = @_;
494 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
495 if ($method =~ /^start::/) {
496 my $f = $local->$method(@args);
497 $f->on_done(sub { undef($f); $future->done(@_) });
498 return unless $f;
499 $f->on_fail(sub { undef($f); $future->fail(@_) });
500 return;
501 }
502 my $do = sub { $local->$method(@args) };
503 eval {
504 $future->done(
505 defined($ctx)
506 ? ($ctx ? $do->() : scalar($do->()))
507 : do { $do->(); () }
508 );
509 1;
510 } or do { $future->fail($@); return; };
511 return;
512 }
513  
514 sub DEMOLISH {
515 my ($self, $in_global_destruction) = @_;
516  
517 return if $in_global_destruction;
518  
519 my $child_pid = $self->child_pid;
520 return unless $child_pid;
521  
522 unless ($self->on_close->is_ready) {
523 kill('TERM', $child_pid);
524 $self->on_close->done('No more references to connection');
525 }
526 }
527  
528 1;
529  
530 =head1 NAME
531  
532 Object::Remote::Connection - An underlying connection for L<Object::Remote>
533  
534 use Object::Remote;
535  
536 my $local = Object::Remote->connect('-');
537 my $remote = Object::Remote->connect('myserver');
538 my $remote_user = Object::Remote->connect('user@myserver');
539 my $local_sudo = Object::Remote->connect('user@');
540  
541 #$remote can be any other connection object
542 my $hostname = Sys::Hostname->can::on($remote, 'hostname');
543  
544 =head1 DESCRIPTION
545  
546 This is the class that supports connections to remote objects.
547  
548 =head1 SEE ALSO
549  
550 =over 4
551  
552 =item C<Object::Remote::Role::Connector::PerlInterpreter>
553  
554 =item C<Object::Remote>
555  
556 =back
557  
558 =cut
« Remote.pm ↑ Summary Remote/FromData.pm »