| 1 | package Zed::SSHPool; | ||
| 2 | |||
| 3 | use Zed::Config::Env; | ||
| 4 | use Zed::Config::Space; | ||
| 5 | use Zed::Output; | ||
| 6 | |||
| 7 | use Net::OpenSSH; | ||
| 8 | use strict; | ||
| 9 | |||
| 10 | =head1 NAME | ||
| 11 | |||
| 12 | Zed::SSHPool - manage ssh connection. | ||
| 13 | |||
| 14 | =head1 SYNOPSIS | ||
| 15 | |||
| 16 | use Zed::SSHPool; | ||
| 17 | |||
| 18 | Zed::SSHPool::run(\@host => 'cmd', @cmd); | ||
| 19 | Zed::SSHPool::run(\@host => 'get', { %OPT }, @files); | ||
| 20 | Zed::SSHPool::run(\@host => 'put', { %OPT }, @files); | ||
| 21 | |||
| 22 | =cut | ||
| 23 | |||
| 24 | our %OPT = | ||
| 25 | ( | ||
| 26 | async => 1, | ||
| 27 | expand_vars => 1, | ||
| 28 | master_stderr_discard => 1, | ||
| 29 | master_stdout_discard => 1, | ||
| 30 | master_opts => [-o => "ConnectTimeout=3", -o => "StrictHostKeyChecking=no"], | ||
| 31 | ); | ||
| 32 | |||
| 33 | my %ssh; | ||
| 34 | |||
| 35 | sub get_ssh { $ssh{ $_[0] } } | ||
| 36 | |||
| 37 | sub connect | ||
| 38 | { | ||
| 39 | my(%error, $user, $pwd); | ||
| 40 | |||
| 41 | $user = env("username"); | ||
| 42 | $pwd = passwd(); | ||
| 43 | |||
| 44 | for my $host(@_) | ||
| 45 | { | ||
| 46 | $ssh{$host} && !$ssh{$host}->check_master && delete $ssh{$host}; | ||
| 47 | $ssh{$host} ||= Net::OpenSSH->new( $host, user => $user, password => $pwd, %OPT); | ||
| 48 | } | ||
| 49 | |||
| 50 | for my $host(@_) | ||
| 51 | { | ||
| 52 | $ssh{$host}->wait_for_master(0); | ||
| 53 | |||
| 54 | if($ssh{$host}->error) | ||
| 55 | { | ||
| 56 | $error{$host} = $ssh{$host}->error; | ||
| 57 | delete $ssh{$host}; | ||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | wantarray ? %error : \%error; | ||
| 62 | } | ||
| 63 | |||
| 64 | sub run | ||
| 65 | { | ||
| 66 | my($hosts, $type, @params) = @_; | ||
| 67 | |||
| 68 | my(%result, @fail, @suc, $count) = Zed::SSHPool::connect(@$hosts); | ||
| 69 | |||
| 70 | for my $host(@$hosts) | ||
| 71 | { | ||
| 72 | $count += 1; | ||
| 73 | my($c_str, $ssh, $output) = "$count/". scalar @$hosts; | ||
| 74 | |||
| 75 | if( $result{$host} ) | ||
| 76 | { | ||
| 77 | result($c_str, 0, "$host done.."); | ||
| 78 | push @fail, $host; | ||
| 79 | next; | ||
| 80 | } | ||
| 81 | |||
| 82 | $ssh = Zed::SSHPool::get_ssh( $host ); | ||
| 83 | |||
| 84 | if($type eq 'cmd') | ||
| 85 | { | ||
| 86 | |||
| 87 | $output = $ssh->capture( @params ); | ||
| 88 | $result{$host} = $output; | ||
| 89 | |||
| 90 | }elsif($type eq 'get'){ | ||
| 91 | |||
| 92 | $ssh->scp_get( @params ); | ||
| 93 | |||
| 94 | }elsif($type eq 'put'){ | ||
| 95 | |||
| 96 | $ssh->scp_put( @params ); | ||
| 97 | } | ||
| 98 | |||
| 99 | result($c_str, !$ssh->error, "$host done.."); | ||
| 100 | $ssh->error ? push @fail, $host | ||
| 101 | : push @suc, $host; | ||
| 102 | } | ||
| 103 | |||
| 104 | (\@suc, \@fail, \%result); | ||
| 105 | |||
| 106 | } | ||
| 107 | |||
| 108 | |||
| 109 | 1; | ||
| 110 | |||
| 111 | __END__ |