Check Disk Quota Usage By Parsing Maildirsize

In the previous article, I have explained how to check the quota usage by using perl scripts. maildir quota checking is done by using File::Find function which seems a bit slow and too much consuming I/O process. same as the find function on bash script. find function in perl perform disk usage by determining the size of all files and directories recursively. all sizes of files and directories then accumulated.

find(sub{ -f and ( $size += -s ) }, $diruser );

actually, examination of maildir quota usage is also done by imap server which is written into a file called maildirsize.  So, rather than wasting resources on the server. we can directly read the specified quota and usage on maildirsize file.

Maildir quota usage using File::Find

sub checksize {
        my $diruser = $_[0];
        trim($diruser);
        my $size;
        find(sub{ -f and ( $size += -s ) }, $diruser );
        if (defined $size) {
                $size = sprintf("%u",$size);
                return $size;
        }
        return undef;
}


Maildir quota usage by parsing maildirsize file

#!/usr/bin/perl
use strict;
use warnings;

my $username=$ARGV[0];
exit if (!defined $username);

my $home = "/path/to/postfix/maildir";

my $file=$home . "/" . $username . "/maildirsize";
open(FILE, "< $file") or die "OK $file does not exist.";
my @lines = ;
close(FILE);

my $quota = $lines[0];
$quota = substr($quota, 1, -2);

my $line=my $size=my $msgs=0;
do {
        $line++;
        (my $msgsize, my $msgcount) = split(" ", $lines[$line]);
        $size+=$msgsize; $msgs+=$msgcount;
} while ($line < $#lines); if ($size > $quota) {
        print "OVERQUOTA user: $username size: $size quota: $quota msgs: $msgs\n";
} else {
        print "OK user: $username size: $size quota: $quota msgs: $msgs\n";
}

$username represent user directory such as foo, bar etc.
$home represents the main directory of postfix maildir.
$file represents all combination of the $home + $username + maildirsize.

Example of running the perl script

$ ./quota.pl foobar
OVERQUOTA user: foobar size: 105881164 quota: 05881600 msgs: 1614

but your mileage may vary, there are advantages and disadvantages of each method.

2 Comments

  1. llattan

    syntax error at ./qmail_quota_user.pl line 12, near “= ;”

  2. llattan

    syntax error at ./qmail_quota_user.pl line 12, near “= ;”

    # perl -v

    This is perl, v5.10.0 built for x86_64-linux-thread-multi

    Copyright 1987-2007, Larry Wall

Leave a Reply

Your email address will not be published. Required fields are marked *