File Coverage

blib/lib/Object/Remote/Connection.pm
Criterion Covered Total %
statement 238 315 75.5
branch 49 74 66.2
condition 6 15 40.0
subroutine 54 82 65.8
pod 0 16 0.0
total 347 502 69.1


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