2005-03-08 20:59:45 +01:00
|
|
|
# $Id: TimeoutSocket.pm,v 1.2 2005/02/02 20:44:35 msergeant Exp $
|
|
|
|
|
|
|
|
package Danga::TimeoutSocket;
|
|
|
|
|
|
|
|
use base 'Danga::Socket';
|
|
|
|
use fields qw(alive_time create_time);
|
|
|
|
|
|
|
|
our $last_cleanup = 0;
|
|
|
|
|
2005-06-22 21:40:57 +02:00
|
|
|
Danga::Socket->AddTimer(15, \&_do_cleanup);
|
|
|
|
|
2005-03-08 20:59:45 +01:00
|
|
|
sub new {
|
|
|
|
my Danga::TimeoutSocket $self = shift;
|
|
|
|
my $sock = shift;
|
|
|
|
$self = fields::new($self) unless ref($self);
|
|
|
|
$self->SUPER::new($sock);
|
|
|
|
|
|
|
|
my $now = time;
|
|
|
|
$self->{alive_time} = $self->{create_time} = $now;
|
|
|
|
|
|
|
|
return $self;
|
|
|
|
}
|
|
|
|
|
2005-05-09 15:43:40 +02:00
|
|
|
# overload these in a subclass
|
|
|
|
sub max_idle_time { 0 }
|
|
|
|
sub max_connect_time { 0 }
|
|
|
|
|
2005-03-08 20:59:45 +01:00
|
|
|
sub _do_cleanup {
|
2005-06-22 21:40:57 +02:00
|
|
|
my $now = time;
|
|
|
|
|
|
|
|
Danga::Socket->AddTimer(15, \&_do_cleanup);
|
|
|
|
|
2005-03-08 20:59:45 +01:00
|
|
|
my $sf = __PACKAGE__->get_sock_ref;
|
|
|
|
|
|
|
|
my %max_age; # classname -> max age (0 means forever)
|
2005-05-09 15:43:40 +02:00
|
|
|
my %max_connect; # classname -> max connect time
|
2005-03-08 20:59:45 +01:00
|
|
|
my @to_close;
|
|
|
|
while (my $k = each %$sf) {
|
|
|
|
my Danga::TimeoutSocket $v = $sf->{$k};
|
|
|
|
my $ref = ref $v;
|
|
|
|
next unless $v->isa('Danga::TimeoutSocket');
|
|
|
|
unless (defined $max_age{$ref}) {
|
2005-05-09 15:43:40 +02:00
|
|
|
$max_age{$ref} = $ref->max_idle_time || 0;
|
|
|
|
$max_connect{$ref} = $ref->max_connect_time || 0;
|
|
|
|
}
|
|
|
|
if (my $t = $max_connect{$ref}) {
|
|
|
|
if ($v->{create_time} < $now - $t) {
|
|
|
|
push @to_close, $v;
|
|
|
|
next;
|
|
|
|
}
|
2005-03-08 20:59:45 +01:00
|
|
|
}
|
2005-05-09 15:43:40 +02:00
|
|
|
if (my $t = $max_age{$ref}) {
|
|
|
|
if ($v->{alive_time} < $now - $t) {
|
|
|
|
push @to_close, $v;
|
|
|
|
}
|
2005-03-08 20:59:45 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
$_->close("Timeout") foreach @to_close;
|
|
|
|
}
|
|
|
|
|
|
|
|
1;
|