Your IP : 216.73.216.21


Current Path : /pkg/zhost/1.0/bin.old/
Upload File :
Current File : //pkg/zhost/1.0/bin.old/zz-web-quota-scan

#!/cmd/perl

# TODO:
# - notify when 100% is reached
# - do not assume mount point /dev/sdc !
#
# customer panel
#
# settings (webmasters)
# system (storage,memory,traffic,customer)
# files (elfinder)
# logs (tail)
# database (mariadb)

use strict;
use Quota;
use Email::Sender;
use Email::Sender::Simple qw(sendmail);
use Email::Simple;
use Email::Simple::Creator;
use Email::Sender::Transport::SMTP qw();

# main routine ========================================================

# TODO:
# notify help desk if no quota is configured
# notify help desk rather than only fail
# track rate of change of quota for further warnings

my $DEBUG = 0;
my $NOTIFY = 1; # 0=off, 1=customers and admin, 2=admin only

# TODO: move these to config files

my $SUPPORT_EMAIL = 'help@zootzone.com';
my $SMTP_SERVER = 'smtp.zootzone.com';
my $SMTP_PORT = 587;
my $SMTP_USERNAME = 'robot@zootzone.com';
my $SMTP_PASSWORD = 'kAWmCiVq3CBWh';

my $BASE = '/srv/web';
my $CONF = '/etc/zoot/web';

my $HOSTNAME = read_entry("/etc/HOSTNAME");
error('fail', "/etc/HOSTNAME read error")
    unless (defined($HOSTNAME));

my @WEBMASTERS = read_list("$CONF/webmasters");
error('fail', "$CONF/webmasters read error")
    unless (defined($WEBMASTERS[0]));

my $STORAGE = read_entry("$CONF/storage");
error('fail', "$CONF/storage read error")
    unless (defined($STORAGE));

my @TRIGGERS = read_list("$CONF/storage_triggers");
error('fail', "$CONF/storage_triggers read error")
    unless (defined($TRIGGERS[0]));

my $web = '';

# TODO: tidy this up
# use 'all' to scan all
if ($ARGV[0] ne '') {
	$web = $ARGV[0] unless ($ARGV[0] eq 'all');
}
if ($ARGV[1] eq 'nosend') {
	$DEBUG = 1;
	$NOTIFY = 2;
}

$| = 1;

# scan single web
if ($web) {
    if ((-f "/etc/nginx/vhosts/$web") || (-f "/etc/nginx/vhosts.hold/$web")) {
        if (-d "$BASE/$web") {
            if (!-d "$BASE/$web/.svc") {
                error('warn', "$BASE/$web/.svc missing");
            }
		    scan($web) unless (-f "$BASE/$web/.no_quota_scan");
	    }
	    else {
		    error('fail', "$BASE/$web does not exist");
	    }
	}
    else {
        error('fail', "missing vhost $web");
    }
}
# scan all webs
else {

    my @webs = ();

    opendir(BASE, $BASE)
	    or error('fail', "cannot read $BASE");

    while (my $web = readdir(BASE)) {
		next unless ($web =~ /^w/);
        if ((-f "/etc/nginx/vhosts/$web") || (-f "/etc/nginx/vhosts.hold/$web")) {
			if (-d "$BASE/$web") {
                if (!-d "$BASE/$web/.svc") {
                    error('warn', "$BASE/$web/.svc missing");
	            }
                push (@webs, $web);
		    }
			else {
                error('warn', "$BASE/$web does not exist");
			}
        }
		else {
            error('warn', "missing vhost $web");
	    }
    }
    closedir(BASE);

    foreach my $web (@webs) {
		# TODO: code here, rather than calling bash script
        system("/cmd/zz-web-hosts-write", "$web");
		scan($web) unless (-f "$BASE/$web/.no_quota_scan");
    }
}

# subroutines =========================================================

sub scan {

	my $web = shift;

	print "$web " if ($DEBUG);

    my $base = "$BASE/$web";
    my $conf = "$base/etc";

	# TODO: don't hardcode device
    my %quota = read_quota($web, '/dev/sdc');

	if (defined($quota{error})) {
        print "$quota{error}" if ($DEBUG);
    }
	else {
		if ($DEBUG) {
	        print "$quota{used}";
	        print "/$quota{limit} ($quota{percent}%)" if (defined $quota{limit});
	    }
	}
	# possibly create system status directory
    if (! -f "$base/sys/storage") {

        build_path( { base   => "$base",
                      dirs   => 'sys',
                      users  => 'root/root',
                      groups => "$web/$web",
                      modes  => '0750/0750' } );
    }
	# update storage status file
    write_entry("$quota{used}/$quota{limit} ($quota{percent}%)", "$base/sys/storage");

	my @triggers = sort { $b <=> $a } @TRIGGERS;
	
	my $admin = join(',', @WEBMASTERS);
    my @webmasters = read_list("$conf/notify/webmasters");

	my $notify = 0;
	my $tag = '';

	my $min = 0;
	my $max = 100;

	foreach my $trigger (@triggers) {

	    $min = $trigger;

	    if ($quota{percent} > $min && $quota{percent} <= $max) {

			print " [$min-$max]" if ($DEBUG);

			if (new_trigger_range($web, $min, $max)) {

			    $notify = $NOTIFY if ($NOTIFY);
                $tag = 'ALERT';

				print " $tag" if ($DEBUG);
			}
	        last;
	    }
	    $max = $trigger;
	}
	# first quota scan, or range returned to level below triggers
	if ($quota{percent} <= $min) {

        print " [0-$min]" if ($DEBUG);

	    if (new_trigger_range($web, 0, $min)) {

			$notify = $NOTIFY if ($NOTIFY);
            $tag = 'INFO';

			print " $tag" if ($DEBUG);
        }
    }
	if ($notify) {
        my $subject = "$tag: Disk quota $quota{percent}% - $web\@$HOSTNAME";
		my $message = '';
		my $recipients = '';
        if (defined($webmasters[0])) {
            $message = message($web, $quota{used}, $quota{limit}, $quota{percent});
		    $recipients = join(',', @webmasters);
		    notify($recipients, $subject, $message) if ($notify == 1);
		}
		# always notify admin
        $message = message($web, $quota{used}, $quota{limit}, $quota{percent}, $recipients);
        notify($admin, $subject, $message);
    }
	print "\n" if ($DEBUG);
}

sub error {

    my $mode = shift;
    my $message = shift;

    print "WARN: " if ($mode eq 'warn');
    print "FAIL: " if ($mode eq 'fail');

    print "$message\n";

    exit 1 if ($mode eq 'fail');
}

sub build_path {

    my $ref  = shift;
    my %path = %$ref;

    chdir($path{base});

    my @dirs   = split('/', $path{dirs});
    my @users  = split('/', $path{users});
    my @groups = split('/', $path{groups});
    my @modes  = split('/', $path{modes});

    foreach my $dir (@dirs) {

	    mkdir($dir) unless (-d $dir);

	    my $user  = shift @users;
	    my $group = shift @groups;
	    my $mode  = shift @modes;

	    #print "$dir = $user:$group ($mode)\n";

	    my $uid   = getpwnam $user;
	    my $gid   = getgrnam $group;

	    chown($uid, $gid, $dir);

	    chmod(oct($mode), $dir);

	    chdir($dir);
    }
}

# init_ | read_ | write_
sub read_quota {
	# success | no quota | error
	my $user = shift;
	my $dev  = shift;

	my %quota = ();

    my $uid = getpwnam($user);

	unless (defined($uid)) {
		$quota{error} = "Invalid user: $user";
		return %quota;
	}	
	unless (defined($dev)) {
		$quota{error} = "Missing device argument";
		return %quota;
	}	
	my $error = '';

	my ($bytes, $soft, $hard) = Quota::query($dev, $uid);

	my $error = Quota::strerr();

	if (defined($bytes)) {
	    $quota{used} = sprintf("%.2f", $bytes/1024/1024);
		if ($hard > 0) {
	        $quota{limit} = sprintf("%.2f", $hard/1024/1024);
	    }
	    if ($hard > 0) {
	        $quota{percent} = sprintf("%.0f", ($bytes/$hard)*100);
	    }
    }
	else {
		$quota{error} = $error;
	}
	return %quota;
}

sub edit_quota {
	# success | no quota | error
	my $user = shift;
	my $gigabytes = shift;
	my $dev = shift;

	my %quota = ();

    my $uid = getpwnam($user);

	unless (defined($uid)) {
		$quota{error} = "Invalid user: $user";
		return %quota;
	}	
	unless (defined($dev)) {
		$quota{error} = "Missing device argument";
		return %quota;
	}	

	my $bytes = sprintf("%.0f", ($gigabytes*1024*1024));

	my $bytes_soft = $bytes;
	my $bytes_hard = $bytes;

	my $inode_soft = 0;
	my $inode_hard = 0;

	if (Quota::setqlim($dev, $uid, $bytes_soft, $bytes_hard, $inode_soft, $inode_hard))
	{
	    my $error = Quota::strerr();
		$quota{error} = $error;
	}
    else {
        %quota = read_quota($user, $dev);
	}
    return %quota;
}

sub init_quota {

	my $web = shift;

    my $default_quota = 0.25;

    my $result = read_entry("$BASE/$web/sys/storage");

	unless ($result) {

        build_path( { base   => "$BASE/$web",
                      dirs   => 'sys',
                      users  => 'root',
                      groups => "$web",
                      modes  => '0750' } );

        write_item($default_quota, "$BASE/$web/sys/storage");
	}
}

sub read_entry {

	my $file = shift;
	my $regex = shift;

	open(F, "<$file") or return undef;
	my $value = <F>;
	chomp($value);
	close(F) or return undef;
	if (defined($regex)) {
        return undef unless ($value =~ m/$regex/);
    }
	return "$value";
}

sub write_entry {

	my $item = shift;
	my $file = shift;

	open(F, ">$file") or return 0;
	print F "$item";
	close(F) or return 0;
	return 1;
}

sub read_list {

	my $file = shift;
	my $regex = shift;

	my @list = ();

	open(F, "<$file") or return undef;

	while (my $line = <F>) {
		chomp($line);
	    if (defined($regex)) {
            return undef unless ($line =~ m/$regex/);
        }
		push(@list, $line);
	}
	close(F) or return undef;

	return undef if (@list == 0);
	return @list;
}

sub new_trigger_range {

    my $web = shift;
    my $min = shift;
    my $max = shift;

    my $this_range = "$min-$max";

	if (! -d "$BASE/$web/var/quota") {

        build_path( { base   => "$BASE/$web",
                      dirs   => 'var/quota',
                      users  => 'root/root',
                      groups => "$web/$web",
                      modes  => '0750/0750' } );
    }
	my $last_range = '';
	if (-f "$BASE/$web/var/quota/trigger") {
	    my $range = read_entry("$BASE/$web/var/quota/trigger");
		$last_range = $range if (defined($range));
	}
    if ($this_range ne $last_range) {
		write_entry("$this_range", "$BASE/$web/var/quota/trigger");
        return 1;
    }
	return 0;
}

sub notify {

	my $recipients = shift;
	my $subject = shift;
	my $message = shift;

	my $transport = Email::Sender::Transport::SMTP->new({
	    host => 'smtp.zootzone.com',
		port => 465,
		ssl => 1,
		helo => "$HOSTNAME",
		sasl_username => "$SMTP_USERNAME",
		sasl_password => "$SMTP_PASSWORD"
    });

    my $email = Email::Simple->create(
        header => [
            To      => "$recipients",
            From    => "$SUPPORT_EMAIL",
            Subject => "$subject",
        ],
        body => "$message\n",
    );

    unless (sendmail($email, { transport => $transport })) {
		my $error = Email::Sender::Failure->message;
		print "email failed; $error\n";
	}
}

sub message {

	my $web = shift;
	my $used = shift;
	my $limit = shift;
	my $percent = shift;
	my $recipients = shift || 0;


	my @list = read_list("$BASE/$web/etc/nginx/hosts");

	my $hosts = '';
	if (defined($list[0])) {
		$hosts = "\nHosts:\n\n" . join("\n", @list) . "\n";
	}
	my $rcpts = '';
	if ($recipients) {
		my @array = split(',', $recipients);
		$rcpts = "\nRecipients:\n\n" . join("\n", @array) . "\n";
	}

    return "Hello,
	
This message was generated automatically.

You're listed as a webmaster for the web hosting account below.

Disk quota change notification:

Account: $web\@$HOSTNAME
Storage: $used/$limit GB ($percent%)
$hosts$rcpts
Respond to request a storage upgrade.

--
help\@zootzone.com
"
}

https://nalibali.org/post-sitemap.xml 2026-11-20T09:00:00+00:00 https://nalibali.org/page-sitemap.xml 2026-11-18T09:24:11+00:00 https://nalibali.org/stories-sitemap.xml 2026-05-05T06:48:38+00:00 https://nalibali.org/stories-sitemap2.xml 2026-05-05T06:48:38+00:00 https://nalibali.org/audio_stories-sitemap.xml 2026-03-27T06:53:13+00:00 https://nalibali.org/story_cards-sitemap.xml 2025-06-06T10:27:48+00:00 https://nalibali.org/story_seeds-sitemap.xml 2025-05-19T07:35:43+00:00 https://nalibali.org/rhymes-sitemap.xml 2025-06-17T07:43:10+00:00 https://nalibali.org/activity_sheets-sitemap.xml 2025-05-16T09:16:43+00:00 https://nalibali.org/printables-sitemap.xml 2025-05-16T09:28:40+00:00 https://nalibali.org/posters_bookmarks-sitemap.xml 2025-05-16T10:20:22+00:00 https://nalibali.org/team_member-sitemap.xml 2025-05-28T09:40:43+00:00 https://nalibali.org/video_stories-sitemap.xml 2025-06-23T08:48:28+00:00 https://nalibali.org/guides-sitemap.xml 2025-06-17T09:38:41+00:00 https://nalibali.org/story_supplements-sitemap.xml 2025-09-16T12:22:20+00:00 https://nalibali.org/vacancies-sitemap.xml 2026-09-17T07:05:01+00:00 https://nalibali.org/category-sitemap.xml 2026-11-20T09:00:00+00:00 https://nalibali.org/post_tag-sitemap.xml 2026-11-06T00:00:00+00:00 https://nalibali.org/test-sitemap.xml 2025-06-13T09:36:28+00:00 https://nalibali.org/story_categories-sitemap.xml 2026-05-05T06:48:38+00:00 https://nalibali.org/activity_sheets_categories-sitemap.xml 2025-05-16T09:16:43+00:00 https://nalibali.org/printables_categories-sitemap.xml 2025-05-16T09:28:40+00:00 https://nalibali.org/posters_bookmarks_categories-sitemap.xml 2025-05-16T10:20:22+00:00 https://nalibali.org/single_audio-sitemap.xml 2026-03-27T06:53:13+00:00 https://nalibali.org/rhyme_categories-sitemap.xml 2025-06-17T07:43:10+00:00 https://nalibali.org/guide_categories-sitemap.xml 2025-06-17T09:38:41+00:00 https://nalibali.org/author-sitemap.xml 2026-01-22T07:26:07+00:00