#!/usr/bin/perl -w

=head1 NAME

check_system_load - Is the system is too overloaded to accept new connections?

=head1 DESCRIPTION

The B<check_system_load> plugin determines whether the system load is
above a specific level, if so it rejects incoming connections.

=cut

=head1 CONFIG

The configuration of this plugin is read from the file
/etc/qpsmtpd/max_system_load, which should contain an an integar
value.

If the system load exceeds *or* equals this number then
incoming connections are denied until the load reduces.

=cut

=head1 AUTHOR

Steve Kemp
--
http://steve.org.uk/Software/qpsmtpd/


=cut


=begin doc

  Hook the pre-connection phase of the transaction - if the load is
 too high we want to know as soon as possible.

=end doc

=cut

use Sys::CpuLoad;
use Qpsmtpd::Constants;
use strict;
use warnings;


sub hook_pre_connection
{
    my ( $self, $transaction, %args ) = (@_);

    #
    #  Return if the configuration variable isn't present.
    #
    my $max_load = $self->qp->config("max_system_load");
    return DECLINED if ( !defined($max_load) );

    #
    #  Get current load.
    #
    my @loads = Sys::CpuLoad::load();
    my $load  = int( $loads[0] );

    if ( $load >= $max_load )
    {
        $self->log( LOGINFO,
                   "check_system_load $load > $max_load rejecting connection" );
        return ( DENYSOFT_DISCONNECT,
                 "System load too high ($load) please try again later" );
    }

    return DECLINED;
}