2011-09-30 20 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