2011-09-30 47 views
1

我在写一个快速脚本来测试负载均衡器的故障和解释流量。我希望它在无法连接到一台主机或另一台主机后继续尝试进行连接。我当前的脚本看起来不像是在执行mkcnct子版中的eval块,我不知道为什么。任何人都可以发现我做错了什么吗?eval/alarm是否正在执行?

#!/usr/bin/perl 

use strict; 
use Net::HTTP; 
use Getopt::Std; 

my %opts; 

getopts('ht:',\%opts); 

my @hostlist ("www.foo.com","www1.foo.com","www2.foo.com"); 

my $timeout; 

if ($opts{t} =~ /\d+/) { 
$timeout = $opts{t} + time(); 
} else { 
$timeout = 3600 + time(); 
} 

while ($timeout < time()) { 
foreach my $host (@hostlist) { 
    my $cnct = mkcnct($host); 
    if ($cnct) { mkreq($cnct) }; 
} 
} 

sub mkreq { 
my $cnct = shift; 
my $time = gettime(); 
my $out; 
$cnct->write_request(GET => "/index.html"); 
($out->{code},$out->{message},%{$out->{headers}}) = $cnct->read_response_headers; 
printf "%s\t%s - Size %d\tLast modified %s\n", $time, $out->{message}, $out->{headers}{'Content-Length'}, $out->{headers}{'Last-Modified'}; 
$out = ""; 
$cnct->write_request(GET => "/pki/ca.crl"); 
($out->{code},$out->{message},%{$out->{headers}}) = $cnct->read_response_headers; 
printf "%s\t%s - Size %d\tLast modified %s\n", $time, $out->{message}, $out->{headers}{'Content-Length'}, $out->{headers}{'Last-Modified'}; 
} 

sub mkcnct { 
my $host = shift; 
my $time = gettime(); 
my $cnct; 
eval{ 
    local $SIG{ALRM} = sub { print "$time\tCannot connect to $host\n"}; 
    alarm(2); 
    $cnct = Net::HTTP->new(Host => $host); 
    alarm(0); 
}; 
alarm(0); 
return($cnct); 
} 

sub gettime { 
my @time = localtime(time); 
my $out; 
$out = sprintf "%d\/%d\/%d %d:%d", ($time[4] + 1), $time[3], ($time[5] % 100), $time[2], $time[1]; 
return($out); 
} 
+0

您应该始终通过执行if($ @){print $ @;}来检查'eval'的返回值。 }之后。 – CanSpice

+0

使用[LWPx :: ParanoidAgent](http://p3rl.org/LWPx::ParanoidAgent)并设置'timeout'属性可能是更健壮的方法。 – daxim

回答

-3

尝试替换返回($ cnct);返回$ cnct;在mkcnct。您可能希望在返回的标量和列表上修复文档

+2

-1两者是相同的。比较'perl -MO = Deparse -e'return($ cnct)''和'perl -MO = deparse -e'return $ cnct''的输出。 – daxim

+0

1)子只能返回标量列表。返回标量和返回一个标量列表没有区别。 2)Parens几乎从不创建列表,这里也不例外。就像在(5 + 5)* 4'和'my @a =(1,2,3);'中一样,它们最多影响优先级。 – ikegami

+1

@daxim,你真的应该使用'-MO =简明'来检查差异。 Deparse不是100%准确的。 – ikegami