lilalo
view l3-agent @ 119:71bd999bcb04
Исправлено несколько багов:
* выполняется корректная привязка diff'ов
* правильно запоминается raw_start и проч raw_*
* временно отключен вывод признака нажатия ctrl-c (он ставился неверно)
* в приглашение добавлен случайный nonce (для правильной отработки tab)
* выполняется корректная привязка diff'ов
* правильно запоминается raw_start и проч raw_*
* временно отключен вывод признака нажатия ctrl-c (он ставился неверно)
* в приглашение добавлен случайный nonce (для правильной отработки tab)
| author | igor | 
|---|---|
| date | Thu Mar 13 12:19:42 2008 +0200 (2008-03-13) | 
| parents | 9e6359b7ad55 | 
| children | 42d9af3c851c | 
 line source
     1 #!/usr/bin/perl -w
     3 #
     4 # (c) Igor Chubin, igor@chub.in, 2004-2008
     5 #
     7 use strict;
     8 use POSIX;
     9 use Term::VT102;
    10 use Text::Iconv;
    11 use Time::Local 'timelocal_nocheck';
    12 use IO::Socket;
    14 use lib "/etc/lilalo";
    15 use l3config;
    17 our @Command_Lines;
    18 our @Command_Lines_Index;
    19 our %Diffs;
    20 our %Sessions;
    22 our %Script_Files;  # Информация о позициях в скрипт-файлах, 
    23                     # до которых уже выполнен разбор
    24                     # и информация о времени модификации файла
    25                     #   $Script_Files{$file}->{size}
    26                     #   $Script_Files{$file}->{tell}
    28 our $Killed =0;     # В режиме демона -- процесс получил сигнал о завершении
    30 sub init_variables;
    31 sub main;
    33 sub load_diff_files;
    34 sub bind_diff;
    35 sub extract_commands_from_cline;
    36 sub load_command_lines;
    37 sub sort_command_lines;
    38 sub print_command_lines;
    39 sub printq;
    41 sub save_cache_stat;
    42 sub load_cache_stat;
    43 sub print_session;
    45 sub load_diff_files
    46 {
    47     my @pathes = @_;
    49     for my $path (@pathes) {
    50         my $template = "*.diff";
    51         my @files = <$path/$template>;
    52         my $i=0;
    53         for my $file (@files) {
    55             next if defined($Diffs{$file});
    56             my %diff;
    58 # Старый формат имени diff-файла
    59 # DEPRECATED
    60             if ($file=~m@/(D?[0-9][0-9]?[0-9]?)[^/]*?([0-9]*):([0-9]*):?([0-9]*)@) {
    61                 $diff{"day"}=$1 || "";
    62                 $diff{"hour"}=$2;
    63                 $diff{"min"}=$3;
    64                 $diff{"sec"}=$4 || 0;
    66                 $diff{"uid"} = 0 if $path =~ m@/root/@; 
    68             print "diff loaded: $diff{day} $diff{hour}:$diff{min}:$diff{sec}\n";
    70             }
    71 # Новый формат имени diff-файла
    72             elsif ($file =~ m@.*/([^_]*)_([0-9]+)(.*)@) {
    73                 $diff{"local_session_id"} = $1;
    74                 $diff{"time"} = $2;
    75                 $diff{"filename"} = $3;
    76                 $diff{"filename"} =~ s@_@/@g;
    77                 $diff{"filename"} =~ s@//@_@g;
    79                 print "diff loaded: $diff{filename} (time=$diff{time},session=$diff{local_session_id})\n";
    80             }
    81             else {
    82                 next;
    83             }
    85 # Чтение и изменение кодировки содержимого diff-файла
    86             local $/;
    87             open (F, "$file")
    88                 or return "Can't open file $file ($_[0]) for reading";
    89             my $text = <F>;
    90             if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i) {
    91                 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8");
    92                 $text = $converter->convert($text);
    93             }
    94             close(F);   
    95             $diff{"text"}=$text;
    97             $diff{"path"}=$path;
    98             $diff{"bind_to"}="";
    99             $diff{"time_range"}=-1;
   100             $diff{"index"}=$i;
   102             $Diffs{$file} = \%diff;
   103             $i++;
   104         }
   105     }   
   106 }
   109 sub bind_diff
   110 {
   111     print "Trying to bind diff...\n";
   113     my $cl = shift;
   114     my $hour = $cl->{"hour"};
   115     my $min = $cl->{"min"};
   116     my $sec = $cl->{"sec"};
   118     my $min_dt = 10000;
   120     if (defined($cl->{"diff"})) {    
   121         print STDERR "Command ".$cl->{time}." is already bound";
   122         return;
   123     }
   125 # Загружаем новые diff-файлы
   126 # Это нужно делать непосредственно перед привязкой, поскольку diff'ы могли образоваться только что
   127     for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
   128         load_diff_files($lab_log);
   129     }
   131     my $diff_to_bind;
   132     for my $diff_key (keys %Diffs) {
   133         my $diff = $Diffs{$diff_key};
   134         next if ($diff->{"local_session_id"} 
   135                 && $cl->{"local_session_id"} 
   136                 && ($cl->{"local_session_id"} ne $diff->{"local_session_id"}));
   138         next if ($diff->{"day"} && $cl->{"day"} && ($cl->{"day"} ne $diff->{"day"}));
   140         my $dt;
   141         if (not $diff->{"time"}) {
   142             print STDERR "diff time is 0"; 
   143             print STDERR join(" ", keys(%$diff));
   144             print STDERR $diff->{text};
   145         }
   146         if (not $cl->{"time"}) {
   147             print STDERR "cl time is 0"; 
   148         }
   149         if ($diff->{"time"} && $cl->{"time"}) {
   150             $dt = $diff->{"time"} - $cl->{"time"}
   151         }
   152         else {
   153             $dt=($diff->{"hour"}-$hour)*3600 +($diff->{"min"}-$min)*60 + ($diff->{"sec"}-$sec);
   154         }
   155         if ($dt >=0 && $dt < $min_dt && !$diff->{"bind_to"}) {
   156              $min_dt = $dt;  
   157              $diff_to_bind = $diff_key;
   158         }
   159     }
   160     if ($diff_to_bind) {
   161         print "Approppriate diff found: dt=$min_dt\n";
   162         $Diffs{$diff_to_bind}->{"bind_to"}=$cl;
   163         $cl->{"diff"} = $diff_to_bind;
   164     }
   165     else {
   166         print STDERR "Diff not found\n";
   167         print STDERR "cl{time}",$cl->{time},"\n";
   168     }
   169 }
   172 sub extract_commands_from_cline
   173 # Разобрать командную строку $_[1] и возвратить хэш, содержащий 
   174 # номер первого появление команды в строке:
   175 #   команда => первая позиция
   176 {
   177     my $cline = $_[0];
   178     my @lists = split /\;/, $cline;
   181     my @commands = ();
   182     for my $list (@lists) {
   183         push @commands, split /\|/, $list;
   184     }
   186     my %commands;
   187     my %files;
   188     my $i=0;
   189     for my $command (@commands) {
   190         $command =~ /\s*(\S+)\s*(.*)/;
   191         if ($1 && $1 eq "sudo" ) {
   192             $commands{"$1"}=$i++;
   193             $command =~ s/\s*sudo\s+//;
   194         }
   195         $command =~ /\s*(\S+)\s*(.*)/;
   196         if ($1 && !defined $commands{"$1"}) {
   197                 $commands{"$1"}=$i++;
   198         };  
   199     }
   200     return %commands;
   201 }
   203 sub load_command_lines
   204 {
   205     my $lab_scripts_path = $_[0];
   206     my $lab_scripts_mask = $_[1];
   208     my $cline_re_base = qq'
   209             (
   210             (?:\\^?([0-9]*C?))          # exitcode
   211             (?:_([0-9]+)_)?             # uid
   212             (?:_([0-9]+)_)              # pid
   213             (...?)                  # day
   214             (.?.?)                  # lab
   215             \\s                 # space separator
   216             ([0-9][0-9]):([0-9][0-9]):([0-9][0-9])  # time
   217             .\\[50D.\\[K                # killing symbols
   218             (.*?([\$\#]\\s?))           # prompt
   219             (.*)                    # command line
   220             )
   221             ';
   222     my $cline_re = qr/$cline_re_base/sx;
   223     my $cline_re2 = qr/$cline_re_base$/sx;
   225     my $cline_re_v2_base = qq'
   226             (
   227             v2[\#]                      # version
   228             ([0-9]+)[\#]                # history line number
   229             ([0-9]+)[\#]                # exitcode
   230             ([0-9]+)[\#]                # uid
   231             ([0-9]+)[\#]                # pid
   232             ([0-9]+)[\#]                # time
   233             (.*?)[\#]                   # pwd
   234             .\\[1024D.\\[K              # killing symbols
   235             (.*?([\$\#]\\s?))           # prompt
   236             (.*)                        # command line
   237             )
   238             ';
   240     my $cline_re_v2 = qr/$cline_re_v2_base/sx;
   241     my $cline_re2_v2 = qr/$cline_re_v2_base$/sx;
   243     my $cline_re_v3_base = qq'
   244             (
   245             v3[\#]                      # version
   246             .*
   247             )
   248             ';
   249     my $cline_re_v3 = qr/$cline_re_v3_base/sx;
   251     my $cline_re2_v3_base = qq'
   252             (
   253             v3[\#]                      # version
   254             ([0-9]+)[\#]                # history line number
   255             ([0-9]+)[\#]                # exitcode
   256             ([0-9]+)[\#]                # uid
   257             ([0-9]+)[\#]                # pid
   258             ([0-9]+)[\#]                # time
   259             (.*?)[\#]                   # pwd
   260             (.*?)[\#]                   # nonce
   261             (.*?([\$\#]\\s?))           # prompt
   262             (.*)                        # command line
   263             )
   264             ';
   265     my $cline_re2_v3 = qr/$cline_re2_v3_base$/sx;
   268     my %vt;     # Хэш виртуальных терминалов. По одному на каждый сеанс
   269     my $cline_vt = Term::VT102->new (
   270                                 'cols' => $Config{"terminal_width"}, 
   271                                 'rows' => $Config{"terminal_height"});
   273     my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8")
   274         if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i);
   276     print "Parsing lab scripts...\n" if $Config{"verbose"} =~ /y/;
   278     my $file;
   279     my $skip_info;
   281     my $commandlines_loaded =0;
   282     my $commandlines_processed =0;
   284     my @lab_scripts = <$lab_scripts_path/$lab_scripts_mask>;
   285     for $file (@lab_scripts){
   287         # Пропускаем файл, если он не изменялся со времени нашего предудущего прохода
   288         my $size = (stat($file))[7];
   289         next if ($Script_Files{$file} && $Script_Files{$file}->{size} && $Script_Files{$file}->{size} >= $size);
   292         my $local_session_id;
   293         # Начальное значение идентификатора текущего сеанса определяем из имени скрипта
   294         # Впоследствии оно может быть уточнено
   295         $file =~ m@.*/([^/]*)\.script$@;
   296         $local_session_id = $1;
   298         if (not defined($vt{$local_session_id})) {
   299             $vt{$local_session_id} = Term::VT102->new ( 
   300                                         'cols' => $Config{"terminal_width"}, 
   301                                         'rows' => $Config{"terminal_height"});
   302         }
   304         #Если файл только что появился, 
   305         #пытаемся найти и загрузить информацию о соответствующей ему сессии
   306         if (!$Script_Files{$file}) {
   307             my $session_file = $file;
   308             $session_file =~ s/\.script/.info/;
   309             if (open(SESSION, $session_file)) {
   310                 local $/;
   311                 my $data = <SESSION>;
   312                 close(SESSION);
   314                 for my $session_data ($data =~ m@<session>(.*?)</session>@sg) {
   315                     my %session;
   316                     while ($session_data =~ m@<([^>]*?)>(.*?)</\1>@sg) {
   317                         $session{$1} = $2;
   318                     }
   319                     $local_session_id = $session{"local_session_id"} if $session{"local_session_id"};
   320                     $Sessions{$local_session_id}=\%session;
   321                 }
   323                 #Загруженную информацию сразу же отправляем в поток
   324                 print_session($Config{cache}, $local_session_id);
   325             }
   326             else {
   327                 die "can't open session file";
   328             }
   329         }
   331         open (FILE, "$file");
   332         binmode FILE;
   334         # Переходим к тому месту, где мы окончили разбор
   335         seek (FILE, $Script_Files{$file}->{tell}, 0) if $Script_Files{$file}->{tell};
   336         $Script_Files{$file}->{size} = $size;
   337         $Script_Files{$file}->{tell} = 0 unless $Script_Files{$file}->{tell};
   339         $file =~ m@.*/(.*?)-.*@;
   341         print "\n+- processing file $file\n|   " 
   342             if $Config{"verbose"} =~/y/;
   344         my $tty = $1;
   345         my $first_pass = 1;
   346         my %cl;
   347         my $last_output_length=0;
   348         while (<FILE>) {
   349             $commandlines_processed++;
   351             next if s/^Script started on.*?\n//s;
   353             if (/[0-9][0-9]:[0-9][0-9]:[0-9][0-9].\[[0-9][0-9]D.\[K/ && m/$cline_re/) {
   354                 s/.*\x0d(?!\x0a)//;
   355                 m/$cline_re2/gs;
   357                 $commandlines_loaded++;
   358                 $last_output_length=0;
   360                 # Previous command
   361                 my %last_cl = %cl;
   362                 my $this_line = $1;
   363                 my $err = $2 || "";
   365                 $cl{"local_session_id"} = $local_session_id;
   366                 # Parse new command 
   367                 $cl{"uid"} = $3;
   368                 #$cl{"euid"} = $cl{"uid"};   # Если в команде обнаружится sudo, euid поменяем на 0
   369                 $cl{"pid"} = $4;
   370                 $cl{"day"} = $5;
   371                 $cl{"lab"} = $6;
   372                 $cl{"hour"} = $7;
   373                 $cl{"min"} = $8;
   374                 $cl{"sec"} = $9;
   375                 #$cl{"fullprompt"} = $10;
   376                 $cl{"prompt"} = $11;
   377                 $cl{"raw_cline"} = $12; 
   379                 {
   380                 use bytes;
   381                 $cl{"raw_start"} = tell (FILE) - length($this_line);
   382                 $cl{"raw_output_start"} = tell FILE;
   383                 }
   384                 $cl{"raw_file"} = $file;
   386                 $cl{"err"} = 0;
   387                 $cl{"output"} = "";
   388                 $cl{"tty"} = $tty;
   390                 $cline_vt->process($cl{"raw_cline"}."\n");
   391                 $cl{"cline"} = $cline_vt->row_plaintext (1);
   392                 $cl{"cline"} =~ s/\s*$//;
   393                 $cl{"cline"} =~ s/.*?[\#\$]\s*//;
   394                 $cline_vt->reset();
   396                 my %commands = extract_commands_from_cline($cl{"cline"});
   397                 #$cl{"euid"}=0 if defined $commands{"sudo"};
   398                 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands; 
   399                 $cl{"last_command"} = $comms[$#comms] || ""; 
   401                 if (
   402                     $Config{"suppress_editors"} =~ /^y/i 
   403                         && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}}) 
   404                     || $Config{"suppress_pagers"}  =~ /^y/i 
   405                         && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}}) 
   406                     || $Config{"suppress_terminal"}=~ /^y/i 
   407                         && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
   408                 ) {
   409                     $cl{"suppress_output"} = "1";
   410                 }
   411                 else {
   412                     $cl{"suppress_output"} = "0";
   413                 }
   414                 $skip_info = 0;
   417                 print " ",$cl{"last_command"};
   419                 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
   420                     bind_diff(\%last_cl);
   421                 }
   423                 # Processing previous command line
   424                 #if ($first_pass) {
   425                 #    $first_pass = 0;
   426                 #    next;
   427                 #}
   429                 # Error code
   430                 $last_cl{"raw_end"} = $cl{"raw_start"};
   431                 $last_cl{"err"}=$err;
   432                 $last_cl{"err"}=130 if $err eq "^C";
   435                 # Output
   436                 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
   437                     for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
   438                         my $line= $vt{$local_session_id}->row_plaintext($i);
   439                         next if !defined ($line) ; #|| $line =~ /^\s*$/;
   440                         $line =~ s/\s*$//;
   441                         $line .= "\n" unless $line =~ /^\s*$/;
   442                         $last_cl{"output"} .= $line;
   443                     }
   444                 }
   445                 else {
   446                     $last_cl{"output"}= "";
   447                 }
   449                 $vt{$local_session_id}->reset();
   452                 # Save 
   453                 if (!$Config{"lab"} || $cl{"lab"} eq $Config{"lab"}) {
   454                     # Changing encoding 
   455                     for (keys %last_cl) {
   456                         next if /raw/;
   457                         $last_cl{$_} = $converter->convert($last_cl{$_})
   458                             if ($Config{"encoding"} && 
   459                             $Config{"encoding"} !~ /^utf-8$/i);
   460                     }
   461                     push @Command_Lines, \%last_cl; 
   463                     # Сохранение позиции в файле, до которой выполнен
   464                     # успешный разбор
   465                     $Script_Files{$file}->{tell} = $last_cl{raw_end};
   466                 }   
   467                 next;
   468             }
   470             elsif (m/$cline_re_v2/ || m/$cline_re_v3/) {
   471 # Разбираем командную строку версии 2
   472                 my $before=$_;
   473                 s/.*\x0d(?!\x0a)//;
   475                 my $re;
   476                 if (m/$cline_re_v2/) {
   477                     $re=$cline_re2_v2;
   478                 }
   479                 else {
   480                     s/.\[1K.\[10D//gs;
   481                     $re=$cline_re2_v3;
   482                     print STDERR "... $_ ...\n";
   483                 }
   485                 $commandlines_loaded++;
   486                 $last_output_length=0;
   488                 # Previous command
   489                 my %last_cl = %cl;
   491                 $cl{"local_session_id"} = $local_session_id;
   492                 # Parse new command 
   493                 my $this_line = $1;
   494                 $cl{"history"}  = $2;
   495                 my $err         = $3;
   496                 $cl{"uid"}      = $4;
   497                 #$cl{"euid"}     = $cl{"uid"};   # Если в команде обнаружится sudo, euid поменяем на 0
   498                 $cl{"pid"}      = $5;
   499                 $cl{"time"}     = $6;
   500                 $cl{"pwd"}      = $7;
   501                 $cl{"nonce"}    = $8;
   502                 #$cl{"fullprompt"} = $8;
   503                 $cl{"prompt"}   = $10;
   504                 #$cl{"raw_cline"}= $10; 
   505                 $cl{"raw_cline"}= $before; 
   507                 {
   508                 use bytes;
   509                 $cl{"raw_start"} = tell (FILE) - length($before);
   510                 $cl{"raw_output_start"} = tell FILE;
   511                 }
   512                 $cl{"raw_file"} = $file;
   514                 $cl{"err"}      = 0;
   515                 $cl{"output"}   = "";
   516                 #$cl{"tty"}     = $tty;
   518                 $cline_vt->process($cl{"raw_cline"}."\n");
   519                 $cl{"cline"}    = $cline_vt->row_plaintext (1);
   520                 $cl{"cline"}    =~ s/\s*$//;
   521                 $cl{"cline"} =~ s/.*?[\#\$]\s*//;
   522                 $cline_vt->reset();
   523                 print STDERR "cline=".$cl{"cline"}."<<\n";
   525                 my %commands    = extract_commands_from_cline($cl{"cline"});
   526                 #$cl{"euid"}     = 0 if defined $commands{"sudo"};
   527                 my @comms       = sort { $commands{$a} cmp $commands{$b} } keys %commands; 
   528                 $cl{"last_command"} 
   529                                 = $comms[$#comms] || ""; 
   531                 print STDERR "last_command=".$cl{"last_command"}."<<\n";
   533                 if (
   534                     $Config{"suppress_editors"} =~ /^y/i 
   535                         && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}}) 
   536                     || $Config{"suppress_pagers"}  =~ /^y/i 
   537                         && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}}) 
   538                     || $Config{"suppress_terminal"}=~ /^y/i 
   539                         && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
   540                 ) {
   541                     $cl{"suppress_output"} = "1";
   542                 }
   543                 else {
   544                     $cl{"suppress_output"} = "0";
   545                 }
   546                 $skip_info = 0;
   548                 if ($Config{verbose} =~ /y/i) {
   549                     print "\n|   " if $commandlines_loaded % 5 == 1;
   550                     print " ",$cl{"last_command"};
   551                 }
   553                 if (defined($last_cl{time}) 
   554                     && grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
   555                        bind_diff(\%last_cl);
   556                 }
   558                 # Error code
   559                 $last_cl{"err"}=$err;
   560                 $last_cl{"raw_end"} = $cl{"raw_start"};
   562                 # Output
   563                 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
   564                     for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
   565                         my $line= $vt{$local_session_id}->row_plaintext($i);
   566                         next if !defined ($line) ; #|| $line =~ /^\s*$/;
   567                         $line =~ s/\s*$//;
   568                         $line .= "\n" unless $line =~ /^\s*$/;
   569                         $last_cl{"output"} .= $line;
   570                     }
   571                 }
   572                 else {
   573                     $last_cl{"output"}= "";
   574                 }
   576                 $vt{$local_session_id}->reset();
   579                 # Changing encoding 
   580                 for (keys %last_cl) {
   581                     next if /raw/;
   582                     if ($Config{"encoding"} && 
   583                         $Config{"encoding"} !~ /^utf-8$/i) {
   584                         $last_cl{$_} = $converter->convert($last_cl{$_})
   585                     }
   586                 }
   587                 if (defined($last_cl{time})) {
   588                     print STDERR "push id=".$last_cl{time}."\n";
   589                     push @Command_Lines, \%last_cl; 
   590                     # Сохранение позиции в файле, до которой выполнен
   591                     # успешный разбор
   592                     $Script_Files{$file}->{tell} = $last_cl{raw_end};
   593                 }
   594                 next;
   595             }
   597 # Иначе, это строка вывода
   599             $last_output_length+=length($_);
   600             #if (!$cl{"suppress_output"} || $last_output_length < 5000) {
   601             if ($last_output_length < 50000) {
   602                 $vt{$local_session_id}->process("$_"."\n") 
   603             }
   604             else
   605             {
   606                 if (!$skip_info && defined($cl{last_command})) {
   607                     print "($cl{last_command})";
   608                     $skip_info = 1;
   609                 }
   610             }
   611         }   
   612         close(FILE);
   614     }
   615     if ($Config{"verbose"} =~ /y/) {
   616         print "\n`- finished.\n" ;
   617         print "Lines loaded: $commandlines_processed\n";
   618         print "Command lines: $commandlines_loaded\n";
   619     }
   620 }
   625 sub sort_command_lines
   626 {
   627     print "Sorting command lines..." if $Config{"verbose"} =~ /y/;
   629     # Sort Command_Lines
   630     # Write Command_Lines to Command_Lines_Index
   632     my @index;
   633     for (my $i=0;$i<=$#Command_Lines;$i++) {
   634         $index[$i]=$i;
   635     }
   637     @Command_Lines_Index = sort {
   638            defined($Command_Lines[$index[$a]]->{"time"}) 
   639         && defined($Command_Lines[$index[$b]]->{"time"}) 
   640         ?  $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"} 
   641         :  defined($Command_Lines[$index[$a]]->{"day"})
   642            && defined($Command_Lines[$index[$b]]->{"day"})
   643            && defined($Command_Lines[$index[$a]]->{"hour"})
   644            && defined($Command_Lines[$index[$b]]->{"hour"})
   645            && defined($Command_Lines[$index[$a]]->{"min"})
   646            && defined($Command_Lines[$index[$b]]->{"min"})
   647            && defined($Command_Lines[$index[$a]]->{"sec"})
   648            && defined($Command_Lines[$index[$b]]->{"sec"})
   649            ?  $Command_Lines[$index[$a]]->{"day"} cmp $Command_Lines[$index[$b]]->{"day"} 
   650            || $Command_Lines[$index[$a]]->{"hour"} <=> $Command_Lines[$index[$b]]->{"hour"}
   651            || $Command_Lines[$index[$a]]->{"min"} <=> $Command_Lines[$index[$b]]->{"min"} 
   652            || $Command_Lines[$index[$a]]->{"sec"} <=> $Command_Lines[$index[$b]]->{"sec"}
   653            :  0
   654     } @index;
   656     print "finished\n" if $Config{"verbose"} =~ /y/;
   658 }
   660 sub printq
   661 {
   662     my $TO = shift;
   663     my $text = join "", @_;
   664     $text =~ s/&/&/g;
   665     $text =~ s/</</g;
   666     $text =~ s/>/>/g;
   667     print $TO $text;
   668 }
   671 =cut 
   672 Вывести результат обработки журнала.
   673 =cut
   675 sub print_command_lines
   676 {
   677     my $output_filename=$_[0];
   678     open(OUT, ">>", $output_filename)
   679         or die "Can't open $output_filename for writing\n";
   682     my $cl;
   683     my $in_range=0;
   684     for my $i (@Command_Lines_Index) {
   685         $cl = $Command_Lines[$i];
   687         if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
   688             $in_range=1;
   689             next;
   690         }
   691         if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
   692             $in_range=0;
   693             next;
   694         }
   695         next if ($Config{"from"} && $Config{"to"} && !$in_range) 
   696             ||
   697                 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
   698             ||
   699             ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
   700             ||
   701             ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
   703         # Вырезаем из вывода только нужное количество строк
   705         my $output="";
   707         if (!grep ($_ eq $cl->{"last_command"}, @{$Config{"full_output_commands"}})
   708             && ($Config{"head_lines"} 
   709             || $Config{"tail_lines"})) { 
   710             # Partialy output
   711             my @lines = split '\n', $cl->{"output"};
   712             # head
   713             my $mark=1;
   714             for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
   715                 $output .= $lines[$i]."\n";
   716             }
   717             # tail
   718             my $start=$#lines-$Config{"cache_tail_lines"}+1;
   719             if ($start < 0) {
   720                 $start=0;
   721                 $mark=0;
   722             }   
   723             if ($start < $Config{"cache_head_lines"}) {
   724                 $start=$Config{"cache_head_lines"};
   725                 $mark=0;
   726             }   
   727             $output .= $Config{"skip_text"}."\n" if $mark;
   728             for ($i=$start; $i<= $#lines; $i++) {
   729                 $output .= $lines[$i]."\n";
   730             }
   731         } 
   732         else {
   733             # Full output
   734             $output .= $cl->{"output"};
   735         }   
   737         # Совместимость с labmaker
   739         # Переводим в секунды Эпохи
   740         # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
   741         # Информация о годе отсутствовала
   742         # Её можно внести: 
   743         # Декабрь 2004 год; остальные -- 2005 год.
   745         my $year = 2005;
   746         #$year = 2004 if ( $cl->{day} > 330 );
   747         $year = $Config{year} if $Config{year};
   748         # timelocal(            $sec,      $min,      $hour,      $mday,$mon,$year);
   749         $cl->{time} ||= timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
   752         # Начинаем вывод команды
   753         print OUT "<command>\n";
   754         print OUT "<l3cd>$Config{l3cd}</l3cd>\n" if $Config{"l3cd"};
   755         for my $element (qw(
   756             local_session_id
   757             history
   758             uid
   759             pid
   760             time
   761             pwd
   762             raw_start
   763             raw_output_start
   764             raw_end
   765             raw_file
   766             tty
   767             err
   768             last_command
   769             history
   770             nonce
   771             )) {
   772             next unless defined($cl->{"$element"});
   773             print OUT "<$element>".$cl->{$element}."</$element>\n";
   774         }
   775         for my $element (qw(
   776             prompt
   777             cline
   778             )) {
   779             next unless defined($cl->{"$element"});
   780             print OUT "<$element>";
   781             printq(\*OUT,$cl->{"$element"});
   782             print OUT "</$element>\n";
   783         }
   784             #note
   785             #note_title
   786         print OUT "<output>";
   787         printq(\*OUT,$output);
   788         print OUT "</output>\n";
   789         if ($cl->{"diff"}) {
   790             print OUT "<diff>";
   791             printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
   792             print OUT "</diff>\n";
   793         }
   794         print OUT "</command>\n";
   796     }
   798     close(OUT);
   799 }
   801 sub print_session
   802 {
   803     my $output_filename = $_[0];
   804     my $local_session_id = $_[1];
   805     return if not defined($Sessions{$local_session_id});
   807     print "printing session info. session id = ".$local_session_id."\n"
   808         if $Config{verbose} =~ /y/;
   810     open(OUT, ">>", $output_filename)
   811         or die "Can't open $output_filename for writing\n";
   812     print OUT "<session>\n";
   813     print OUT "<l3cd>$Config{l3cd}</l3cd>\n" if $Config{"l3cd"};
   814     my %session = %{$Sessions{$local_session_id}};
   815     for my $key (keys %session) {
   816         print OUT "<$key>".$session{$key}."</$key>\n";
   817         print "         ".$key,"\n";
   818     }
   819     print OUT "</session>\n";
   820     close(OUT);
   821 }
   823 sub send_cache
   824 {
   825     # Если в кэше что-то накопилось, 
   826     # попытаемся отправить это на сервер
   827     #
   828     my $cache_was_sent=0;
   830     if (open(CACHE, $Config{cache})) {
   831         local $/;
   832         my $cache = <CACHE>;
   833         close(CACHE);
   835         my $socket = IO::Socket::INET->new(
   836                             PeerAddr => $Config{backend_address},
   837                             PeerPort => $Config{backend_port},
   838                             proto   => "tcp",
   839                             Type    => SOCK_STREAM
   840                         );
   842         if ($socket) {
   843             print $socket $cache;
   844             close($socket);
   845             $cache_was_sent = 1;
   846         }
   847     }
   848     return $cache_was_sent;
   849 }
   851 sub save_cache_stat
   852 {
   853     open (CACHE, ">$Config{cache_stat}");
   854     for my $f (keys %Script_Files) {
   855         print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
   856     }
   857     close(CACHE);
   858 }
   860 sub load_cache_stat
   861 {
   862     if (open (CACHE, "$Config{cache_stat}")) {
   863         while(<CACHE>) {
   864             chomp;
   865             my ($f, $size, $tell) = split /\t/;
   866             $Script_Files{$f}->{size} = $size;
   867             $Script_Files{$f}->{tell} = $tell;
   868         }
   869         close(CACHE);
   870     };
   871 }
   874 main();
   876 sub process_was_killed
   877 {
   878     $Killed = 1;
   879 }
   881 sub reload
   882 {
   883     init_config;
   884 }
   886 sub main
   887 {
   889     $| = 1;
   891     init_variables();
   892     init_config();
   895     if ($Config{"mode"} ne "daemon") {
   897 #    В нормальном режиме работы нужно
   898 #    считать скрипты, обработать их и записать
   899 #    результат выполнения в результирующий файл.
   900 #    После этого завершить работу.
   902 # Очистим кэш-файл, если он существовал
   903         if (open (CACHE, ">", $Config{"cache"})) {
   904             close(CACHE);
   905         };
   906         load_command_lines($Config{"input"}, $Config{"input_mask"});
   907         sort_command_lines;
   908         #process_command_lines;
   909         print_command_lines($Config{"cache"});
   910     } 
   911     else {
   912         if (open(PIDFILE, $Config{agent_pidfile})) {
   913             my $pid = <PIDFILE>;
   914             close(PIDFILE);
   915             if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
   916                 print "Removing stale pidfile\n";
   917                 unlink $Config{agent_pidfile}
   918                     or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
   919             }
   920             elsif ($^O eq 'freebsd' && defined($pid) && $pid ne "" && not `ps axo uid,pid,command | grep '$< $pid $Config{"l3-agent"}' | grep -v grep 2> /dev/null`) {
   921                 print "Removing stale pidfile\n";
   922                 unlink $Config{agent_pidfile}
   923                     or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
   924             }
   925             elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
   926                 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
   927                 exit(0);
   928             }
   929             else {
   930                 print "Unknown operating system";
   931                 exit(0);
   932             }
   933         }
   934         if ($Config{detach} =~ /^y/i) {
   935             #$Config{verbose} = "no";
   936             my $pid = fork;
   937             exit if $pid;
   938             die "Couldn't fork: $!" unless defined ($pid);
   940             open(PIDFILE, ">", $Config{agent_pidfile})
   941                 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
   942             print PIDFILE $$;
   943             close(PIDFILE);
   945             for my $handle (*STDIN, *STDOUT, *STDERR) {
   946                 open ($handle, "+<", "/dev/null")
   947                     or die "can't reopen $handle to /dev/null: $!"
   948             }
   950             POSIX::setsid()
   951                 or die "Can't start a new session: $!";
   953             $0 = $Config{"l3-agent"};
   955             $SIG{INT} = $SIG{TERM} = \&process_was_killed;
   956             $SIG{HUP} = \&reload;
   958         }
   959         while (not $Killed) {
   960             @Command_Lines = ();
   961             @Command_Lines_Index = ();
   962             load_cache_stat();
   963             load_command_lines($Config{"input"}, $Config{"input_mask"});
   964             if (@Command_Lines) {
   965                 sort_command_lines;
   966                 #process_command_lines;
   967                 print_command_lines($Config{"cache"});
   968             }
   969             save_cache_stat();
   970             if (-e $Config{cache} && (stat($Config{cache}))[7]) {
   971                 send_cache() && unlink($Config{cache});
   972             }
   973             sleep($Config{"daemon_sleep_interval"} || 1);
   974         }
   976         unlink $Config{agent_pidfile};
   977     }
   979 }
   981 sub init_variables
   982 {
   983 }
