| 1 | package App::MadEye::Plugin::Agent::Gearmand; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use App::MadEye::Plugin::Agent::Base; | ||
| 5 | |||
| 6 | use Gearman::Util; | ||
| 7 | use Socket qw(IPPROTO_TCP TCP_NODELAY SOL_SOCKET SOCK_STREAM); | ||
| 8 | use IO::Socket::INET; | ||
| 9 | use IO::Select; | ||
| 10 | |||
| 11 | my $MSG = "WATCHINGWATCHING"; | ||
| 12 | |||
| 13 | sub is_dead { | ||
| 14 | my ( $self, $host ) = @_; | ||
| 15 | |||
| 16 | my $conf = $self->config->{config}; | ||
| 17 | my $port = $conf->{port} || 7003; | ||
| 18 | my $connect_timeout = $conf->{connect_timeout} || 10; | ||
| 19 | my $select_timeout = $conf->{select_timeout} || 10; | ||
| 20 | |||
| 21 | my $sock = IO::Socket::INET->new( | ||
| 22 | PeerAddr => $host, | ||
| 23 | PeerPort => $port, | ||
| 24 | Timeout => $connect_timeout, | ||
| 25 | ); | ||
| 26 | unless ($sock) { | ||
| 27 | return "Cannot open Socket to $host:$port\n$!"; | ||
| 28 | } | ||
| 29 | $sock->blocking(0); | ||
| 30 | setsockopt( $sock, IPPROTO_TCP, TCP_NODELAY, pack( "l", 1 ) ) or die; | ||
| 31 | $sock->autoflush(1); | ||
| 32 | |||
| 33 | my $req = Gearman::Util::pack_req_command( 'echo_req', $MSG ); | ||
| 34 | Gearman::Util::send_req( $sock, \$req ); | ||
| 35 | $sock->flush; | ||
| 36 | |||
| 37 | my $select = IO::Select->new; | ||
| 38 | $select->add($sock); | ||
| 39 | |||
| 40 | my ( $can_read, ) = $select->can_read($select_timeout); | ||
| 41 | unless ($can_read) { | ||
| 42 | $sock->close; | ||
| 43 | return "gearmand connection timeout : $host"; | ||
| 44 | } | ||
| 45 | |||
| 46 | my $err; | ||
| 47 | my $res = Gearman::Util::read_res_packet( $sock, \$err ); | ||
| 48 | if ( $res && $res->{type} eq "error" ) { | ||
| 49 | die "Error packet from server after get_status: ${$res->{blobref}}\n"; | ||
| 50 | } | ||
| 51 | |||
| 52 | if ( $res && $res->{type} eq 'echo_res' && ${ $res->{blobref} } eq $MSG ) { | ||
| 53 | $sock->close(); | ||
| 54 | return; # alive | ||
| 55 | } | ||
| 56 | else { | ||
| 57 | $sock->close(); | ||
| 58 | return "gearmand response is invaild : $res->{type}"; | ||
| 59 | } | ||
| 60 | } | ||
| 61 | |||
| 62 | 1; | ||
| 63 | __END__ |