- package IO::Socket::StatusPublisher;
- use strict;
- use warnings;
- use IO::Socket;
- sub help {
- die "Usage: $0 process status [weight] [hostname]\n"
- . "\tprocess: name of process (http,dmgr,etc)\n"
- . "\tstatus: status of process (start[ed],run[ning],stop[ped],term[inated])\n"
- . "\tweight: (optional) number for size of the pie slice. defaults to 0\n"
- . "\thostname: (optional) defaults to `hostname`\n"
- }
- my $process = $ARGV[0] || help ;
- my $status = $ARGV[1] || help ;
- my $weight = $ARGV[2] || 0;
- my $hostname = $ARGV[3] || `hostname`;
- sub new {
- my ($class, %args ) = @_;
- my $self = bless ({}, ref ($class) || $class);
- my $host = $args{host};
- my $port = $args{port};
- $self->connect ( $host, $port );
- return $self;
- }
- sub connect {
- my ( $self, $host, $port ) = @_;
- $self->close;
- $self->{connection} = IO::Socket::INET->new ( PeerAddr => "$host:$port" );
- $self->{connection} && $self->{connection}->connected ||
- die "Could not connect to status dashboard $host $port" ;
- my ( $myport, $myaddr ) = sockaddr_in ( $self->{connection}->sockname );
- return ( inet_ntoa ( $myaddr ), $myport );
- }
- sub status {
- my ( $self, $process, $status, $weight, $hostname ) = @_;
- my $conn = $self->{connection};
- my $skey = "status:hostnames";
- my $hkey = "status:hostname:" . $process;
- my $zkey = "status:hostname:" . $process . ":weight";
- my $hkeyl = length $hkey;
- my $skeyl = length $skey;
- my $zkeyl = length $zkey;
- my $processl = length $process;
- my $statusl = length $status;
- my $weightl = length $weight;
- my $hostnamel = length $hostname;
- my $select = "*2\r\n\$6\r\nselect\r\n\$1\r\n9\r\n";
- my $sadd = "*3\r\n\$4\r\nsadd\r\n\$$skeyl\r\n$skey\r\n\$$hostnamel\r\n$hostname\r\n";
- my $hset = "*4\r\n\$4\r\nhset\r\n\$$hkeyl\r\n$hkey\r\n\$$processl\r\n$process\r\n\$$statusl\r\n$status\r\n";
- my $zadd = "*4\r\n\$4\r\nzadd\r\n\$$zkeyl\r\n$zkey\r\n\$$weightl\r\n$weight\r\n\$$processl\r\n$process\r\n";
- $conn->print ( $select . $sadd . $hset . $zadd );
- return $self;
- }
- sub close {
- my $self = shift;
- my $conn = $self->{connection};
- return $conn->close if $conn && $conn->connected;
- }
- IO::Socket::StatusPublisher
- ->new( ( "host", "localhost", "port", 6379 ) )
- ->status( $process, $status, $weight, chomp($hostname) )
- ->close;