| 1 | package Net::OpenSSH::ConnectionCache; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Net::OpenSSH; | ||
| 7 | use Net::OpenSSH::Constants qw(:error); | ||
| 8 | |||
| 9 | use Data::Dumper; | ||
| 10 | use Scalar::Util qw(weaken); | ||
| 11 | |||
| 12 | our $MAX_SIZE = 20; | ||
| 13 | our %cache; | ||
| 14 | |||
| 15 | sub _factory { | ||
| 16 | my $class = shift; | ||
| 17 | my %opts = @_; | ||
| 18 | my $dump = Data::Dumper->new([\%opts], ['s']); | ||
| 19 | $dump->Indent(0); | ||
| 20 | $dump->Sortkeys(1); | ||
| 21 | $dump->Deepcopy(1); | ||
| 22 | my $signature = $dump->Dump; | ||
| 23 | my $ssh = $cache{$signature}; | ||
| 24 | if ($ssh and $ssh->error != OSSH_MASTER_FAILED) { | ||
| 25 | if ($opts{async} or $ssh->wait_for_master) { | ||
| 26 | return $cache{$signature} = $ssh; | ||
| 27 | } | ||
| 28 | } | ||
| 29 | if ($MAX_SIZE <= keys %cache) { | ||
| 30 | for (keys %cache) { | ||
| 31 | $ssh = $cache{$_}; | ||
| 32 | $ssh or $ssh->error != OSSH_MASTER_FAILED or delete $cache{$_} | ||
| 33 | } | ||
| 34 | for (keys %cache) { | ||
| 35 | last if ($MAX_SIZE <= keys %cache); | ||
| 36 | weaken $cache{$_}; | ||
| 37 | if (defined $cache{$_}) { | ||
| 38 | $cache{$_} = $cache{$_}; # unweaken | ||
| 39 | } | ||
| 40 | else { | ||
| 41 | delete $cache{$_}; | ||
| 42 | } | ||
| 43 | } | ||
| 44 | } | ||
| 45 | local $Net::OpenSSH::FACTORY; | ||
| 46 | $cache{$signature} = $class->new(@_); | ||
| 47 | } | ||
| 48 | |||
| 49 | $Net::OpenSSH::FACTORY = \&_factory; | ||
| 50 | |||
| 51 | sub clean_cache { %cache = () } | ||
| 52 | |||
| 53 | END { %cache = () } | ||
| 54 | |||
| 55 | 1; | ||
| 56 | |||
| 57 | __END__ |