The OpenNET Project / Index page

[ новости /+++ | форум | теги | ]



Индекс форумов
Составление сообщения

Исходное сообщение
"Скрипт для обработки store.log"
Отправлено mic, 09-Дек-04 07:42 
Задался я както вопросом чего это в кэше лежит на данный момент.
Скриптик написал.
Запускаю раз в сутки по крону.
Делает файл .ini куда пишет кол-во обработанных байт из лога. В след. раз продолжает с этого места.
Работает и под виндой, кстати.
На выходе строка вида:
размер имя_файла_в_кэше дата_время ссылка
Выводит только файлы более 10 000 байт.
--------------------------------------------------
#!/usr/bin/perl

use FileHandle;
autoflush STDOUT 1;

$times = times;

use integer;

# Куда пишем результат
$file_log = "cache.log";
$cache_store_log = "/usr/local/squid/var/logs/store.log";

$_ = $0; if (s/([\\\/])([^\/\\]+)\.[^\/\\]*$/$1/) { $script_name = $2; $dir = $_; }
$win = 1 if ($ENV{OS}); $term = 1 if ($ENV{TERM}); $browser = 1 if $ENV{REMOTE_ADDR}; $cron = !($term or $browser or $win);
print "\n\n" if $browser;

print "Read config\n" unless $cron;

&read_config("$dir$script_name.ini");

if (-f $file_log) {

    print "Read old log ..." unless $cron;

    open(C,"<$file_log") || print "Can't open $file_log!\n";
    $_ = <C>; chomp; my ($f,$l) = split if ($_ ne "");
    $first_time = $f if ($f && ($f < $first_time));
    $last_time = $f if ($l && ($l > $last_time));

    while(<C>) { chomp;
        next if /^[#\x0a\x0d]/o;
        ($byte,$file,$_) = split(' ',$_,3);
        next if $file eq '';
        $site{$file} = "$byte $_";
    }
    close C;
    print " done\n" unless $cron;
}

open(C,"<$cache_store_log") || die "Can't open $cache_store_log!\n";

$cache_seek = 0 if ((-s $cache_store_log) < $cache_seek);
seek(C,$cache_seek,0);

print "Read new log..." unless $cron;

while(<C>) {
    next if (/^[#\x0a\x0d]/o); chomp;

#1091289709.998 RELEASE -1 FFFFFFFF BBB9140F6150263E98C4E2F2F408F112  407 1091289709
#         0 1091289709 text/html 1371/1695 GET http://sa.secure-firewall.com/binaries/info.htm

    @m = split(' ', $_, 13);


    ($time) =     split('\.',$m[0],2);    #next if $time < 1049130000; # Apr 1 00:00:00 2003
    $first_time=$day_time = $time if ((not $first_time) || ($time < $first_time));
    $last_time  = $time if ($time > $last_time);
    $act =        $m[1];    #action
    $file =        $m[3]; #file number
    next if ($file =~ /^F+$/o);
    $cod =        $m[5];
    if ($cod eq '?') { delete $site{$file}; next; }
    $exp =        $m[6]; #Expiries
    $exp1 =     $m[7];
    $exp2 =     $m[8];
    $type =        $m[9];
    ($m,$byte)= split('\/',$m[10],2);
    if ($byte < 10000) { delete $site{$file}; next; }
    $GET =         $m[11];
    $href =     $m[12]; #$href =~ s/%([0-9A-H]{2})/pack('C',hex($1))/ge;

    if    ($act eq 'SWAPOUT') {
        $site{$file} = "$byte $time $href";
    }
    elsif ($act eq 'RELEASE') {
        delete $site{$file};
    }

print "\x0d",$.," lines read" if (!($cron) and ($. > 9999) and ($.=~/0000$/o));
}

$cache_seek = tell(C);
close C;

print " done\n" unless $cron;

push @ini,("cache_seek    $cache_seek\n") if ($cache_seek > 0);

print "Format...\n" unless $cron;
@ooo = ();
while (($file, $value) = each %site){
    ($byte,$o) = split(' ',$value,2);
    $byte = substr('0'x12 .$byte,-12);
    push @ooo,"$byte $file $o\n";
}
    #Вывод результата в файл
    $t_file_log = "$tmp_dir$file_log.tmp";
    open(C,">$t_file_log") || die "Can't open $t_file_log to write!\n";

print "Write new log...\n" unless $cron;

    print C "$first_time $last_time\n",reverse(sort(@ooo));
    close C;

    if (($t_file_log ne "") and ($file_log ne "")) {
        if ($term or $cron) {`mv $t_file_log $file_log`;}
        elsif ($win) {
            `del /Q $file_log >nul` if (-f $file_log);
            `ren $t_file_log $file_log`;}
    }
@ooo = ();
undef %site;

#Save new stat into conf
print "Save stat.\n" unless $cron;

&saveconf("$script_name.ini");

no integer;
print "OK. ",times-$times,"sec\n" unless $cron;

sub read_config{
    my ($file) = @_; return unless $file; my $i;
    return unless (-f $file);
    open(C,"<$file") || print "Can't open $file!\n";
    while(<C>) { next if /^[#\x0a\x0d]/; chomp;
        s/#[^"]*$//; s/[ \x09]+$//g;
        ($i,$_) = split(" ",$_,2); s/\"//g; $$i = "$_";
    }
    close C;
}

sub saveconf {
    my ($file) = @_; return unless $file; my $i;
    my $t_file = "$tmp_dir$file.tmp";
    open(C,">$t_file") || print "Can't open $file to write!\n";
    print C @ini;close C;

    if ($term or $cron) {`cp -p $file $file.bak; mv $t_file $file`;}
    elsif ($win)        {`copy $file $file.bak & del /Q $file & ren $t_file $file`;}
}
-------------------------------------------------

PS. Кстати, львинная доля - порнуха. Ужас!
PPS. Скриптик для просмотра тоже есть. Но он поболее весом :)
ICQ: 1978_9_1024

 

Ваше сообщение
Имя*:
EMail:
Для отправки ответов на email укажите знак ! перед адресом, например, !user@host.ru (!! - не показывать email).
Более тонкая настройка отправки ответов производится в профиле зарегистрированного участника форума.
Заголовок*:
Сообщение*:
  Введите код, изображенный на картинке: КОД
 
При общении не допускается: неуважительное отношение к собеседнику, хамство, унизительное обращение, ненормативная лексика, переход на личности, агрессивное поведение, обесценивание собеседника, провоцирование флейма голословными и заведомо ложными заявлениями. Не отвечайте на сообщения, явно нарушающие правила - удаляются не только сами нарушения, но и все ответы на них. Лог модерирования.



Партнёры:
PostgresPro
Inferno Solutions
Hosting by Hoster.ru
Хостинг:

Закладки на сайте
Проследить за страницей
Created 1996-2024 by Maxim Chirkov
Добавить, Поддержать, Вебмастеру