Despite its lofty martial-arts name, Tie::CHI is a simple module that allows you to tie a hash to a persistent CHI cache, using any of CHI’s backends.
I hardly ever choose Tie interfaces — too much magic — but occasionally they do produce pretty code. In this case, we have a watchdog script that sends USR2 signals to httpd processes that grow too large (so that they’ll log their call stack). Sometimes these processes stick around for a while, so I only want to send a certain number of signals per process.
my %kill_count;
...
if ( $vsize > $max_vsize ) {
if ( $kill_count{$pid} < $max_kills ) {
kill( 'USR2', $pid );
$kill_count{$pid}++;
$log->warn(sprintf( "pid %d vsize %dmb > %dmb, sending USR2",
$pid, $vsize, $max_vsize ));
}
}
Then it occurred to me that the watchdog restarts frequently, so I need to keep the kill counts persistent; and I should only limit on an hourly basis, because the same pid will eventually come around again. We already have a custom CHI subclass that we use for caching all over our application, so it was easy to plug it in:
use Tie::CHI;
my $cache = HM::Cache->new
(namespace => 'watchdog/kill_count', expires_in => '1 hour');
my %kill_count;
tie %kill_count, 'Tie::CHI', $cache;
And voila, %kill_count is persistent, and its values decay after an hour.