File Coverage

blib/lib/Object/Remote/Connection.pm
Criterion Covered Total %
statement 236 313 75.4
branch 46 70 65.7
condition 6 15 40.0
subroutine 54 82 65.8
pod 0 16 0.0
total 342 496 68.9


line stmt bran cond sub pod time code
1             package Object::Remote::Connection;
2              
3 11     11   109553 use Object::Remote::Logging qw (:log :dlog router);
  11         33  
  11         156  
4 11     11   578 use Object::Remote::Future;
  11         29  
  11         1110  
5 11     11   8468 use Object::Remote::Null;
  11         42  
  11         472  
6 11     11   357 use Object::Remote::Handle;
  11         22  
  11         399  
7 11     11   6037 use Object::Remote::CodeContainer;
  11         35  
  11         496  
8 11     11   5511 use Object::Remote::GlobProxy;
  11         38  
  11         482  
9 11     11   5787 use Object::Remote::GlobContainer;
  11         46  
  11         553  
10 11     11   5896 use Object::Remote::Tied;
  11         57  
  11         489  
11 11     11   483 use Object::Remote;
  11         29  
  11         298  
12 11     11   75 use Symbol;
  11         124  
  11         872  
13 11     11   60 use IO::Handle;
  11         23  
  11         471  
14 11     11   5610 use POSIX ":sys_wait_h";
  11         83276  
  11         106  
15 11     11   19395 use Module::Runtime qw(use_module);
  11         28  
  11         107  
16 11     11   882 use Scalar::Util qw(weaken blessed refaddr openhandle);
  11         26  
  11         863  
17 11     11   849 use JSON::PP qw(encode_json);
  11         14734  
  11         948  
18 11     11   97 use Future;
  11         32  
  11         455  
19 11     11   56 use Carp qw(croak);
  11         83  
  11         552  
20 11     11   55 use Moo;
  11         19  
  11         86  
21              
22 11     11   9142 BEGIN { router()->exclude_forwarding }
23              
24             END {
25 11     11   19598 our %child_pids;
26              
27 11         136 log_trace { "END handler is being invoked in " . __PACKAGE__ };
  0         0  
28              
29 11         226 foreach(keys(%child_pids)) {
30 18         196 log_debug { "Killing child process '$_'" };
  0         0  
31 18         1278 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(Future->new) },
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 5086 my ($self) = @_;
104 312         7897 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         6321 };
116              
117 312         6135 return $valid;
118             }
119              
120             sub _fail_outstanding {
121 1     1   31 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   62 log_trace { "Failing future for $_" };
  0         0  
130 4         65 my $future = $outstanding->{$_};
131 4         43 $future->fail("$error\n");
132             }
133              
134 1         25 %$outstanding = ();
135 1         5 return;
136             }
137              
138             sub _install_future_handlers {
139 19     19   437 my ($self, $f) = @_;
140 19         39 our %child_pids;
141 19     0   457 Dlog_trace { "Installing handlers into future for connection $_" } $self->_id;
  0         0  
142 19         1529 weaken($self);
143             $f->on_done(sub {
144 1     1   107 my $pid = $self->child_pid;
145 1         16 Dlog_trace { "Executing on_done handler in future for connection $_" } $self->_id;
  0         0  
146 1         27 $self->_fail_outstanding("Object::Remote connection lost: " . ($f->get)[0]);
147 1 50       6 return unless defined $pid;
148 1         10 log_debug { "Waiting for child '$pid' to exit" };
  0         0  
149 1         8189 my $ret = waitpid($pid, 0);
150 1 50       16 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         21 };
160             }
161              
162 1         22 delete $child_pids{$pid};
163 19         342 });
164 19         1315 return $f;
165             };
166              
167             sub _id_to_remote_object {
168 242     242   780 my ($self, $id) = @_;
169 242     0   2070 Dlog_trace { "fetching proxy for remote object with id '$id' for connection $_" } $self->_id;
  0         0  
170 242 100       5104 return bless({}, 'Object::Remote::Null') if $id eq 'NULL';
171             (
172 90   66     5926 $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   709 weaken(my $self = shift);
179             JSON::PP->new->filter_json_single_key_object(
180             __remote_object__ => sub {
181 42     42   53935 $self->_id_to_remote_object(@_);
182             }
183             )->filter_json_single_key_object(
184             __remote_code__ => sub {
185 21     21   23410 my $code_container = $self->_id_to_remote_object(@_);
186 21         216 sub { $code_container->call(@_) };
  21         424  
187             }
188             )->filter_json_single_key_object(
189             __scalar_ref__ => sub {
190 2     2   2161 my $value = shift;
191 2         9 return \$value;
192             }
193             )->filter_json_single_key_object(
194             __glob_ref__ => sub {
195 4     4   4394 my $glob_container = $self->_id_to_remote_object(@_);
196 4         39 my $handle = Symbol::gensym;
197 4         272 tie *$handle, 'Object::Remote::GlobProxy', $glob_container;
198 4         23 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   1206 my %tied_hash;
207 1         8 tie %tied_hash, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
208 1         6 return \%tied_hash;
209             }
210             )->filter_json_single_key_object(
211             __remote_tied_array__ => sub {
212 1     1   3640 my @tied_array;
213 1         8 tie @tied_array, 'Object::Remote::Tied', $self->_id_to_remote_object(@_);
214 1         5 return \@tied_array;
215             }
216 19         509 );
217             }
218              
219             sub _load_if_possible {
220 55     55   156 my ($class) = @_;
221              
222 55         231 use_module($class);
223              
224 55 50       34897 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   94 unshift our @Guess, sub { blessed($_[0]) ? $_[0] : undef };
  18         126  
232 11         71 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 71 my ($class, $spec, @args) = @_;
243 18         37 foreach my $poss (do { our @Guess }) {
  18         154  
244 36 100       200 if (my $conn = $poss->($spec, @args)) {
245 18         118 return $conn;
246             }
247             }
248              
249 0         0 return undef;
250             }
251              
252             sub new_from_spec {
253 28     28 0 98 my ($class, $spec, @args) = @_;
254 28 100       133 return $spec if blessed $spec;
255 18         141 my $conn = $class->conn_from_spec($spec, @args);
256              
257 18 50       86 die "Couldn't figure out what to do with ${spec}"
258             unless defined $conn;
259              
260 18         204 return $conn->maybe::start::connect;
261             }
262              
263             sub remote_object {
264 20     20 0 172 my ($self, @args) = @_;
265 20         479 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 84 my ($self, $sub) = @_;
280 21         220 my ($pkg, $name) = $sub =~ m/^(.*)::([^:]+)$/;
281 21     0   265 Dlog_debug { "Invoking remote sub '$sub' for connection '$_'" } $self->_id;
  0         0  
282 21         540 return await_future($self->send_class_call(0, $pkg, can => $name));
283             }
284              
285             sub send_class_call {
286 64     64 0 334 my ($self, $ctx, @call) = @_;
287 64     0   653 Dlog_trace { "Sending a class call for connection $_" } $self->_id;
  0         0  
288 64         1343 $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 370 my ($self, $remote) = @_;
311 128     0   1323 Dlog_trace { my $i = $remote->id; "Registered a remote object with id of '$i' for connection $_" } $self->_id;
  0         0  
  0         0  
312 128         3172 weaken($self->remote_objects_by_id->{$remote->id} = $remote);
313 128         1284 return $remote;
314             }
315              
316             sub send_free {
317 19     19 0 78 my ($self, $id) = @_;
318 19     0   320 Dlog_trace { "sending request to free object '$id' for connection $_" } $self->_id;
  0         0  
319             #TODO this shows up some times when a remote side dies in the middle of a remote
320             #method invocation - possibly only when the object is being constructed?
321             #(in cleanup) Use of uninitialized value $id in delete at ../Object-Remote/lib/Object/Remote/Connection.
322 19         475 delete $self->remote_objects_by_id->{$id};
323 19         127 $self->_send([ free => $id ]);
324             }
325              
326             sub send {
327 156     156 0 789 my ($self, $type, @call) = @_;
328              
329 156         832 my $future = Future->new;
330 156         1931 my $remote = $self->remote_objects_by_id->{$call[0]};
331              
332 156         964 unshift @call, $type => $self->_local_object_to_id($future);
333              
334 156         632 my $outstanding = $self->outstanding_futures;
335 156         820 $outstanding->{$future} = $future;
336             $future->on_ready(sub {
337 156     156   12231 undef($remote);
338 156         1190 delete $outstanding->{$future}
339 156         1422 });
340              
341 156         6145 $self->_send(\@call);
342              
343 156         1446 return $future;
344             }
345              
346             sub send_discard {
347 21     21 0 128 my ($self, $type, @call) = @_;
348              
349 21         83 unshift @call, $type => 'NULL';
350              
351 21         111 $self->_send(\@call);
352             }
353              
354             sub _send {
355 196     196   657 my ($self, $to_send) = @_;
356 196         746 my $fh = $self->send_to_fh;
357              
358 196 100       787 unless ($self->is_valid) {
359 1         296 croak "Attempt to invoke _send on a connection that is not valid";
360             }
361              
362 195     0   1800 Dlog_trace { "Starting to serialize data in argument to _send for connection $_" } $self->_id;
  0         0  
363 195         3687 my $serialized = $self->_serialize($to_send)."\n";
364 195     0   1664 Dlog_trace { my $l = length($serialized); "serialization is completed; sending '$l' characters of serialized data to $_" } $fh;
  0         0  
  0         0  
365 195         3441 my $ret;
366 195         491 eval {
367             #TODO this should be converted over to a non-blocking ::WriteChannel class
368 195 50       1250 die "filehandle is not open" unless openhandle($fh);
369 195     0   1193 log_trace { "file handle has passed openhandle() test; printing to it" };
  0         0  
370 195         33788 $ret = print $fh $serialized;
371 195 50       1035 die "print was not successful: $!" unless defined $ret
372             };
373              
374 195 50       629 if ($@) {
375 0     0   0 Dlog_debug { "exception encountered when trying to write to file handle $_: $@" } $fh;
  0         0  
376 0         0 my $error = $@;
377 0         0 chomp($error);
378 0 0       0 $self->on_close->done("could not write to file handle: $error") unless $self->on_close->is_ready;
379 0         0 return;
380             }
381              
382 195         637 return $ret;
383             }
384              
385             sub _serialize {
386 195     195   576 my ($self, $data) = @_;
387 195         793 local our @New_Ids = (-1);
388             return eval {
389             my $flat = $self->_encode($self->_deobjectify($data));
390             $flat;
391 195   33     443 } || do {
392             my $err = $@; # won't get here if the eval doesn't die
393             # don't keep refs to new things
394             delete @{$self->local_objects_by_id}{@New_Ids};
395             die "Error serializing: $err";
396             };
397             }
398              
399             sub _local_object_to_id {
400 200     200   5594 my ($self, $object) = @_;
401 200         481 my $id = refaddr($object);
402 200   33     2084 $self->local_objects_by_id->{$id} ||= do {
403 200 100       691 push our(@New_Ids), $id if @New_Ids;
404 200         839 $object;
405             };
406 200         1546 return $id;
407             }
408              
409             sub _deobjectify {
410 1452     1452   3060 my ($self, $data) = @_;
411 1452 100       5087 if (blessed($data)) {
    100          
412 39 100 66     686 if (
413             $data->isa('Object::Remote::Proxy')
414             and $data->{remote}->connection == $self
415             ) {
416 1         55 return +{ __local_object__ => $data->{remote}->id };
417             } else {
418 38         147 return +{ __remote_object__ => $self->_local_object_to_id($data) };
419             }
420             } elsif (my $ref = ref($data)) {
421 206 100       999 if ($ref eq 'HASH') {
    100          
    100          
    100          
    50          
422 3         5 my $tied_to = tied(%$data);
423 3 50       10 if(defined($tied_to)) {
424 0         0 return +{__remote_tied_hash__ => $self->_local_object_to_id($tied_to)};
425             } else {
426 3         14 return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data };
427             }
428             } elsif ($ref eq 'ARRAY') {
429 195         547 my $tied_to = tied(@$data);
430 195 50       535 if (defined($tied_to)) {
431 0         0 return +{__remote_tied_array__ => $self->_local_object_to_id($tied_to)};
432             } else {
433 195         998 return [ map $self->_deobjectify($_), @$data ];
434             }
435             } elsif ($ref eq 'CODE') {
436 5         197 my $id = $self->_local_object_to_id(
437             Object::Remote::CodeContainer->new(code => $data)
438             );
439 5         187 return +{ __remote_code__ => $id };
440             } elsif ($ref eq 'SCALAR') {
441 2         78 return +{ __scalar_ref__ => $$data };
442             } elsif ($ref eq 'GLOB') {
443 1         26 return +{ __glob_ref__ => $self->_local_object_to_id(
444             Object::Remote::GlobContainer->new(handle => $data)
445             ) };
446             } else {
447 0         0 die "Can't collapse reftype $ref";
448             }
449             }
450 1207         8028 return $data; # plain scalar
451             }
452              
453             sub _receive {
454 173     173   724 my ($self, $flat) = @_;
455 173     0   2072 Dlog_trace { my $l = length($flat); "Starting to deserialize $l characters of data for connection $_" } $self->_id;
  0         0  
  0         0  
456 173         382 my ($type, @rest) = eval { @{$self->_deserialize($flat)} }
  173         4830  
457 173 50       3456 or do { warn "Deserialize failed for ${flat}: $@"; return };
  0         0  
  0         0  
458 173     0   98478 Dlog_trace { "deserialization complete for connection $_" } $self->_id;
  0         0  
459 173         531 eval { $self->${\"receive_${type}"}(@rest); 1 }
  173         1453  
  173         1428  
460 173 50       3181 or do { warn "Receive failed for ${flat}: $@"; return };
  0         0  
  0         0  
461 173         2533 return;
462             }
463              
464             sub receive_free {
465 152     152 0 489 my ($self, $id) = @_;
466 152     0   1366 Dlog_trace { "got a receive_free for object '$id' for connection $_" } $self->_id;
  0         0  
467 152 50       3164 delete $self->local_objects_by_id->{$id}
468             or warn "Free: no such object $id";
469 152         475 return;
470             }
471              
472             sub receive_call {
473 173     173 0 1405 my ($self, $future_id, $id, @rest) = @_;
474 173     0   1440 Dlog_trace { "got a receive_call for object '$id' for connection $_" } $self->_id;
  0         0  
475 173         3187 my $future = $self->_id_to_remote_object($future_id);
476 173         753 $future->{method} = 'call_discard_free';
477             my $local = $self->local_objects_by_id->{$id}
478 173 50       1597 or do { $future->fail("No such object $id"); return };
  0         0  
  0         0  
479 173         764 $self->_invoke($future, $local, @rest);
480             }
481              
482             sub receive_call_free {
483 152     152 0 622 my ($self, $future, $id, @rest) = @_;
484 152     0   1383 Dlog_trace { "got a receive_call_free for object '$id' for connection $_" } $self->_id;
  0         0  
485 152         3394 $self->receive_call($future, $id, undef, @rest);
486 152         640 $self->receive_free($id);
487             }
488              
489             sub _invoke {
490 173     173   761 my ($self, $future, $local, $ctx, $method, @args) = @_;
491 173     0   1384 Dlog_trace { "got _invoke for a method named '$method' for connection $_" } $self->_id;
  0         0  
492 173 50       2996 if ($method =~ /^start::/) {
493 0         0 my $f = $local->$method(@args);
494 0     0   0 $f->on_done(sub { undef($f); $future->done(@_) });
  0         0  
  0         0  
495 0 0       0 return unless $f;
496 0     0   0 $f->on_fail(sub { undef($f); $future->fail(@_) });
  0         0  
  0         0  
497 0         0 return;
498             }
499 173     173   874 my $do = sub { $local->$method(@args) };
  173         3397  
500             eval {
501             $future->done(
502             defined($ctx)
503             ? ($ctx ? $do->() : scalar($do->()))
504 173 50       1220 : do { $do->(); () }
  157 100       466  
  157         4008500  
505             );
506 172         1168 1;
507 173 100       449 } or do { $future->fail($@); return; };
  1         42  
  1         38  
508 172         2005 return;
509             }
510              
511             1;
512              
513             =head1 NAME
514              
515             Object::Remote::Connection - An underlying connection for L
516              
517             use Object::Remote;
518              
519             my $local = Object::Remote->connect('-');
520             my $remote = Object::Remote->connect('myserver');
521             my $remote_user = Object::Remote->connect('user@myserver');
522             my $local_sudo = Object::Remote->connect('user@');
523              
524             #$remote can be any other connection object
525             my $hostname = Sys::Hostname->can::on($remote, 'hostname');
526              
527             =head1 DESCRIPTION
528              
529             This is the class that supports connections to remote objects.
530              
531             =head1 SEE ALSO
532              
533             =over 4
534              
535             =item C
536              
537             =item C
538              
539             =back
540              
541             =cut