Commit a7333537 authored by mcramer's avatar mcramer
Browse files

Added: vlogger mysql usage to store traffic reports

Added: interface module web traffic statistics
Fixed: mail_traffic is now reported to master server instead of local
Fixed: GRANTs for slave server database user on master database
parent bb5171da
<?php
$wb['list_head_txt'] = 'Web трафик';
$wb['domain_txt'] = 'Domain';
$wb['this_month_txt'] = 'Этот месяц';
$wb['last_month_txt'] = 'Последний месяц';
$wb['this_year_txt'] = 'Этот год';
$wb['last_year_txt'] = 'Последний год';
?>
<?php
$wb['list_head_txt'] = 'Web traffic';
$wb['domain_txt'] = 'Domain';
$wb['this_month_txt'] = 'This month';
$wb['last_month_txt'] = 'Last month';
$wb['this_year_txt'] = 'This year';
$wb['last_year_txt'] = 'Last year';
?>
......@@ -76,6 +76,21 @@ $module["nav"][] = array( 'title' => 'Database',
'open' => 1,
'items' => $items);
//**** Statistics menu
$items = array();
$items[] = array( 'title' => 'Web traffic',
'target' => 'content',
'link' => 'sites/web_sites_stats.php');
$module['nav'][] = array( 'title' => 'Statistics',
'open' => 1,
'items' => $items);
// clean up
unset($items);
......
<?php
/*
Datatypes:
- INTEGER
- DOUBLE
- CURRENCY
- VARCHAR
- TEXT
- DATE
*/
// Name of the list
$liste["name"] = "web_sites_stats";
// Database table
$liste["table"] = "web_domain";
// Index index field of the database table
$liste["table_idx"] = "domain_id";
// Search Field Prefix
$liste["search_prefix"] = "search_";
// Records per page
$liste["records_per_page"] = 15;
// Script File of the list
$liste["file"] = "web_sites_stats.php";
// Script file of the edit form
$liste["edit_file"] = "web_domain_edit.php";
// Script File of the delete script
$liste["delete_file"] = "web_domain_del.php";
// Paging Template
$liste["paging_tpl"] = "templates/paging.tpl.htm";
// Enable auth
$liste["auth"] = "yes";
/*****************************************************
* Suchfelder
*****************************************************/
$liste["item"][] = array( 'field' => "domain",
'datatype' => "VARCHAR",
'formtype' => "TEXT",
'op' => "like",
'prefix' => "%",
'suffix' => "%",
'width' => "",
'value' => "");
?>
\ No newline at end of file
<h2><tmpl_var name="list_head_txt"></h2>
<p><tmpl_var name="list_desc_txt"></p>
<div class="panel panel_list_web_sites_stats">
<div class="pnl_listarea">
<fieldset><legend><tmpl_var name="list_head_txt"></legend>
<table class="list">
<thead>
<tr>
<th class="tbl_col_domain" scope="col"><tmpl_var name="domain_txt"></th>
<th class="tbl_col_this_month" scope="col"><tmpl_var name="this_month_txt"></th>
<th class="tbl_col_last_month" scope="col"><tmpl_var name="last_month_txt"></th>
<th class="tbl_col_this_year" scope="col"><tmpl_var name="this_year_txt"></th>
<th class="tbl_col_last_year" scope="col"><tmpl_var name="last_year_txt"></th>
<th class="tbl_col_buttons" scope="col">&nbsp;</th>
</tr>
<tr>
<td class="tbl_col_domain"><input type="text" name="search_domain" value="{tmpl_var name='search_domain'}" /></td>
<td class="tbl_col_this_month"></td>
<td class="tbl_col_last_month"></td>
<td class="tbl_col_this_year"></td>
<td class="tbl_col_last_year"></td>
<td class="tbl_col_buttons"><div class="buttons"><button type="button" class="icons16 icoFilter" name="Filter" id="Filter" value="{tmpl_var name="filter_txt"}" onClick="submitForm('pageForm','sites/web_sites_stats.php');"><span>{tmpl_var name="filter_txt"}</span></button></div></td>
</tr>
</thead>
<tbody>
<tmpl_loop name="records">
<tr class="tbl_row_<tmpl_if name='__EVEN__'}even<tmpl_else>uneven</tmpl_if>">
<td class="tbl_col_domain"><a href="#" onClick="loadContent('sites/web_domain_edit.php?id={tmpl_var name='id'}');">{tmpl_var name="domain"}</a></td>
<td class="tbl_col_this_month"><a href="#" onClick="loadContent('sites/web_domain_edit.php?id={tmpl_var name='id'}');">{tmpl_var name="this_month"} kB</a></td>
<td class="tbl_col_last_month"><a href="#" onClick="loadContent('sites/web_domain_edit.php?id={tmpl_var name='id'}');">{tmpl_var name="last_month"} kB</a></td>
<td class="tbl_col_this_year"><a href="#" onClick="loadContent('sites/web_domain_edit.php?id={tmpl_var name='id'}');">{tmpl_var name="this_year"} kB</a></td>
<td class="tbl_col_last_year"><a href="#" onClick="loadContent('sites/web_domain_edit.php?id={tmpl_var name='id'}');">{tmpl_var name="last_year"} kB</a></td>
<td class="tbl_col_buttons">
<div class="buttons icons16">
</div>
</td>
</tr>
</tmpl_loop>
</tbody>
<tfoot>
<tr>
<td class="tbl_footer tbl_paging" colspan="6"><tmpl_var name="paging"></td>
</tr>
</tfoot>
</table>
</fieldset>
</div>
</div>
<?php
require_once('../../lib/config.inc.php');
require_once('../../lib/app.inc.php');
/******************************************
* Begin Form configuration
******************************************/
$list_def_file = "list/web_sites_stats.list.php";
/******************************************
* End Form configuration
******************************************/
//* Check permissions for module
$app->auth->check_module_permissions('sites');
$app->load('listform_actions');
class list_action extends listform_actions {
function prepareDataRow($rec)
{
global $app;
$rec = $app->listform->decode($rec);
//* Alternating datarow colors
$this->DataRowColor = ($this->DataRowColor == '#FFFFFF') ? '#EEEEEE' : '#FFFFFF';
$rec['bgcolor'] = $this->DataRowColor;
//* Set the statistics colums
//** Traffic of the current month
$tmp_year = date('Y');
$tmp_month = date('m');
$tmp_rec = $app->db->queryOneRecord("SELECT SUM(traffic_bytes) as t FROM web_traffic WHERE hostname = '".$rec['domain']."' AND YEAR(traffic_date) = '$tmp_year' AND MONTH(traffic_date) = '$tmp_month'");
$rec['this_month'] = number_format(intval($tmp_rec['t'])/1024, 0, '.', ' ');
//** Traffic of the current year
$tmp_rec = $app->db->queryOneRecord("SELECT sum(traffic_bytes) as t FROM web_traffic WHERE hostname = '".$rec['domain']."' AND YEAR(traffic_date) = '$tmp_year'");
$rec['this_year'] = number_format(intval($tmp_rec['t'])/1024, 0, '.', ' ');
//** Traffic of the last month
$tmp_year = date('Y',mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
$tmp_month = date('m',mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
$tmp_rec = $app->db->queryOneRecord("SELECT sum(traffic_bytes) as t FROM web_traffic WHERE hostname = '".$rec['domain']."' AND YEAR(traffic_date) = '$tmp_year' AND MONTH(traffic_date) = '$tmp_month'");
$rec['last_month'] = number_format(intval($tmp_rec['t'])/1024, 0, '.', ' ');
//** Traffic of the last year
$tmp_year = date('Y',mktime(0, 0, 0, date("m"), date("d"), date("Y")-1));
$tmp_rec = $app->db->queryOneRecord("SELECT sum(traffic_bytes) as t FROM web_traffic WHERE hostname = '".$rec['domain']."' AND YEAR(traffic_date) = '$tmp_year'");
$rec['last_year'] = number_format(intval($tmp_rec['t'])/1024, 0, '.', ' ');
//* The variable "id" contains always the index variable
$rec['id'] = $rec[$this->idx_key];
return $rec;
}
}
$list = new list_action;
$list->onLoad();
?>
\ No newline at end of file
......@@ -4,7 +4,7 @@
################################################
LogFormat "%v %h %l %u %t \"%r\" %>s %B \"%{Referer}i\" \"%{User-Agent}i\"" combined_ispconfig
CustomLog "| /usr/sbin/vlogger -s access.log -t \"%Y%m%d-access.log\" /var/log/ispconfig/httpd" combined_ispconfig
CustomLog "| /usr/local/ispconfig/server/scripts/vlogger -s access.log -t \"%Y%m%d-access.log\" -d \"/etc/vlogger-dbi.conf\" /var/log/ispconfig/httpd" combined_ispconfig
<Directory /var/www/clients>
AllowOverride None
......
......@@ -68,7 +68,7 @@ foreach($records as $rec) {
$tstamp = date("Y-m");
$sql = "SELECT * FROM mail_traffic WHERE month = '$tstamp' AND mailuser_id = ".$rec["mailuser_id"];
$tr = $app->db->queryOneRecord($sql);
$tr = $app->dbmaster->queryOneRecord($sql);
$mail_traffic += $tr["traffic"];
if($tr["traffic_id"] > 0) {
......@@ -76,7 +76,7 @@ foreach($records as $rec) {
} else {
$sql = "INSERT INTO mail_traffic (month,mailuser_id,traffic) VALUES ('$tstamp',".$rec["mailuser_id"].",$mail_traffic)";
}
$app->db->query($sql);
$app->dbmaster->query($sql);
echo $sql;
}
......
#!/usr/bin/perl -T
#
# vlogger - smarter logging for apache
# steve j. kondik <shade@chemlab.org>
#
# this script will take piped logs in STDIN, break off the first component
# and log the line into the proper directory under $LOGDIR. it will roll the
# logs over at midnight on-the-fly and maintain a symlink to the most recent log.
#
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library General Public License for more details.
#
#
# CHANGELOG:
# 0.1 initial release
# 0.2 cleanups, added -e option for errorlogs, added strict stuff
# 0.3 cleanups, bugfixes, docs, added -r size rotation option
# 0.4 added dbi usage tracking option, code cleanups from cz@digitalfreaks.org
# 1.0 small bugfixes, first production release
# 1.1 bugfix release
# 1.2 support for mod_logio
# 1.3 various contributed bugfixes
#
#
# TODO:
# configurable file compression using Compress::Zlib, maybe.
#
package vlogger;
$ENV{PATH} = "/bin:/usr/bin";
my $VERSION = "1.3";
=head1 NAME
vlogger - flexible log rotation and usage tracking in perl
=head1 SYNOPSIS
vlogger [OPTIONS]... [LOGDIR]
=head1 DESCRIPTION
Vlogger is designed to make webserver log rotation simple and easy to manage.
It deals with VirtualHost logs automatically, so only one directive is required
to manage all hosts on a webserver. Vlogger takes piped output from Apache or
another webserver, splits off the first field, and writes the logs to logfiles
in subdirectories. It uses a filehandle cache to avoid resource limitations.
It will start a new logfile at the beginning of a new day, and optionally start
new files when a certain filesize is reached. It can maintain a symlink to
the most recent log for easy access. Optionally, host parsing can be disabled
for use in ErrorLog directives.
To use vlogger, you need to add a "%v" to the first part of your LogFormat:
LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
Then call it from a customlog:
CustomLog "| /usr/local/sbin/vlogger -s access.log -u www-logs -g www-logs /var/log/apache" combined
=head1 OPTIONS
Options are given in short format on the command line.
-a
Do not autoflush files. This may improve performance but may break logfile
analyzers that depend on full entries in the logs.
-e
ErrorLog mode. In this mode, the host parsing is disabled, and the file is
written out using the template under the specified LOGDIR.
-n
Disables rotation. This option disables rotation altogether.
-f MAXFILES
Maximum number of filehandles to keep open. Defaults to 100. Setting this
value too high may result in the system running out of file descriptors.
Setting it too low may affect performance.
-u UID
Change user to UID when running as root.
-g GID
Change group to GID when running as root.
-t TEMPLATE
Filename template using Date::Format codes. Default is "%m%d%Y-access.log",
or "%m%d%Y-error.log". When using the -r option, the default becomes
"%m%d%Y-%T-access.log" or "%m%d%Y-%T-error.log".
-s SYMLINK
Specifies the name of a symlink to the current file.
-r SIZE
Rotate files when they reach SIZE. SIZE is given in bytes.
-d CONFIG
Use the DBI usage tracker.
-h
Displays help.
-v
Prints version information.
=head1 DBI USAGE TRACKER
Vlogger can automatically keep track of per-virtualhost usage statistics in a
database. DBI and the relevant drivers (eg. DBD::mysql) needs to be installed for
this to work. Create a table in your database to hold the data. A "mysql_create.sql"
script is provided for using this feature with MySQL. Configure the dsn, user, pass
and dump values in the vlogger-dbi.conf file. The "dump" parameter controls how often
vlogger will dump its stats into the database (the default is 30 seconds). Copy this
file to somewhere convienient on your filesystem (like /etc/apache/vlogger-dbi.conf) and
start vlogger with "-d /etc/apache/vlogger-dbi.conf". You might want to use this feature
to easily bill customers on a daily/weekly/monthly basis for bandwidth usage.
=head1 SEE ALSO
cronolog(1), httplog(1)
=head1 BUGS
None, yet.
=head1 AUTHORS
Steve J. Kondik <shade@chemlab.org>
WWW: http://n0rp.chemlab.org/vlogger
=cut
# a couple modules we need
use strict;
no strict "refs";
use warnings;
use sigtrap qw(handler exitall HUP USR1 TERM INT PIPE);
use Date::Format;
use Getopt::Std;
use IO::Handle;
# get command line options
our %OPTS;
getopts( 'f:t:s:hu:g:aeivr:d:', \%OPTS );
# print out version
if ( $OPTS{'v'} ) {
print "VLogger $VERSION (apache logfile parser)\n";
print "Written by Steve J. Kondik <shade\@chemlab.org>\n\n";
print "This is free software; see the source for copying conditions. There is NO\n";
print "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n";
exit;
}
# print help
if ( $OPTS{'h'} || !$ARGV[0] ) {
usage();
exit;
}
# log directory
my $LOGDIR;
if ( $ARGV[0] ) {
if ( !-d $ARGV[0] ) {
print STDERR
"[vlogger] target directory $ARGV[0] does not exist - exiting.\n\n";
exit;
}
$LOGDIR = $ARGV[0];
}
$LOGDIR =~ /(.*)/;
$LOGDIR = $1;
# change uid/gid if requested (and running as root)
if ( $> == "0" ) {
if ( $OPTS{'g'} ) {
my $guid = getgrnam( $OPTS{'g'} );
if ( !defined $guid || $guid == 0 ) {
print STDERR
"[vlogger] cannot run as root or nonexistant group.\n\n";
exit;
}
$) = $guid;
$( = $guid;
if ( $) != $guid and $) != ( $guid - 2**32 ) ) {
die "fatal: setgid to gid $guid failed\n";
}
}
if ( $OPTS{'u'} ) {
my $uuid = getpwnam( $OPTS{'u'} );
if ( !defined $uuid || $uuid == 0 ) {
print STDERR
"[vlogger] cannot run as root or nonexistant user.\n\n";
exit;
}
$> = $uuid;
$< = $uuid;
if ( $> != $uuid and $> != ( $uuid - 2**32 ) ) {
die "fatal: setuid to uid $uuid failed\n";
}
}
}
# set up dbi stuffs
my $DBI_DSN;
my $DBI_USER;
my $DBI_PASS;
my $DBI_DUMP;
if ( $OPTS{'d'} ) {
if ( $OPTS{'e'} ) {
print "-d not valid with -e. exiting.\n";
exit;
}
eval "use DBI";
open CONF, $OPTS{'d'};
while (<CONF>) {
chomp;
my @conf = split (/\s/);
if ( $conf[0] eq "dsn" ) {
$DBI_DSN = $conf[1];
}
elsif ( $conf[0] eq "user" ) {
$DBI_USER = $conf[1];
}
elsif ( $conf[0] eq "pass" ) {
$DBI_PASS = $conf[1];
}
elsif ( $conf[0] eq "dump" ) {
$DBI_DUMP = $conf[1];
}
}
close CONF;
unless ( $DBI_DSN && $DBI_USER && $DBI_PASS && $DBI_DUMP ) {
print "All values for DBI configuration are not properly defined.\n\n";
exit;
}
# test the connection
my $dbh = DBI->connect( $DBI_DSN, $DBI_USER, $DBI_PASS )
or die "DBI Error: $!";
$dbh->disconnect;
# SIGALRM dumps the tracker hash
$SIG{ALRM} = \&dump_tracker;
alarm $DBI_DUMP;
}
# max files to keep open
my $MAXFILES;
if ( $OPTS{'f'} ) {
$MAXFILES = $OPTS{'f'};
}
else {
$MAXFILES = "100";
}
# filesize rotation
my $MAXSIZE;
if ( $OPTS{'r'} ) {
$MAXSIZE = $OPTS{'r'};
}
# filename template
my $TEMPLATE;
if ( $OPTS{'t'} ) {
$TEMPLATE = $OPTS{'t'};
$TEMPLATE =~ /(.*)/;
$TEMPLATE = $1;
}
elsif ( $OPTS{'e'} ) {
if ( $OPTS{'r'} ) {
$TEMPLATE = "%m%d%Y-%T-error.log";
}
else {
$TEMPLATE = "%m%d%Y-error.log";
}
}
else {
if ( $OPTS{'r'} ) {
$TEMPLATE = "%m%d%Y-%T-access.log";
}
else {
$TEMPLATE = "%m%d%Y-access.log";
}
}
# symlink
if ( $OPTS{'s'} ) {
$OPTS{'s'} =~ /(.*)/;
$OPTS{'s'} = $1;
}
# chroot to the logdir
chdir($LOGDIR);
#chroot("."); we better do not chroot as DBI requires to load a module on the fly -> error!
my %logs = ();
my %tracker = ();
my $LASTDUMP = time();
# pick a mode
if ( $OPTS{'e'} ) {
$0 = "vlogger (error log)";
# errorlog mode
open ELOG, ">>" . time2str( $TEMPLATE, time() )
or die ( "can't open $LOGDIR/" . time2str( $TEMPLATE, time() ) );
unless ( $OPTS{'a'} ) {
ELOG->autoflush(1);
}
if ( $OPTS{'s'} ) {
if ( -l $OPTS{'s'} ) {
unlink( $OPTS{'s'} );
}
symlink( time2str( $TEMPLATE, time() ), $OPTS{'s'} );
}
my $LASTWRITE = time();
while ( my $log_line = <STDIN> ) {
unless ( $OPTS{'n'} ) {
if ( time2str( "%Y%m%d", time() ) >
time2str( "%Y%m%d", $LASTWRITE ) )
{
# open a new file
close ELOG;
open_errorlog();
}
elsif ( $OPTS{'r'} ) {
# check the size
my @filesize = ELOG->stat;
print $filesize[7] . "\n";