lilalo

view l3-agent @ 74:a10db759e587

Перешёл на новый формат приглашения.
Ура Ура Ура!

Теперь в нём есть информация
о номере строки в истории (history),
текущем каталоге (pwd),
времени появления приглашения (time)

Давно пора было!
author devi
date Thu Feb 09 18:47:04 2006 +0200 (2006-02-09)
parents 35e0d61c820d
children d28dda8ea18f
line source
1 #!/usr/bin/perl -w
3 #
4 # (c) Igor Chubin, igor@chub.in, 2004-2006
5 #
8 ## Эта строчка добавлена из блокнота Windows
9 ## Надо отдать должное, он каким-то образом научился понимать кодировку
11 use strict;
12 use POSIX;
13 use Term::VT102;
14 use Text::Iconv;
15 use Time::Local 'timelocal_nocheck';
16 use IO::Socket;
18 use lib "/usr/local/bin";
19 use l3config;
22 our @Command_Lines;
23 our @Command_Lines_Index;
24 our %Diffs;
25 our %Sessions;
27 our %Script_Files; # Информация о позициях в скрипт-файлах,
28 # до которых уже выполнен разбор
29 # и информация о времени модификации файла
30 # $Script_Files{$file}->{size}
31 # $Script_Files{$file}->{tell}
33 our $Killed =0; # В режиме демона -- процесс получил сигнал о завершении
35 sub init_variables;
36 sub main;
38 sub load_diff_files;
39 sub bind_diff;
40 sub extract_commands_from_cline;
41 sub load_command_lines;
42 sub sort_command_lines;
43 sub print_command_lines;
44 sub printq;
46 sub save_cache_stat;
47 sub load_cache_stat;
48 sub print_session;
50 sub load_diff_files
51 {
52 my @pathes = @_;
54 for my $path (@pathes) {
55 my $template = "*.diff";
56 my @files = <$path/$template>;
57 my $i=0;
58 for my $file (@files) {
60 next if defined($Diffs{$file});
62 my %diff;
64 $diff{"path"}=$path;
65 $diff{"uid"}="SET THIS";
67 # Сейчас UID определяется из названия каталога
68 # откуда берутся diff-файлы
69 # Это неправильно
70 #
71 # ВАРИАНТ:
72 # К файлам жураналам должны прилагаться ситемны файлы,
73 # мз которых и будет определяться соответствие
74 # имён пользователей их uid'ам
75 #
76 $diff{"uid"} = 0 if $path =~ m@/root/@;
78 $diff{"bind_to"}="";
79 $diff{"time_range"}=-1;
81 next if not $file=~m@/(D?[0-9][0-9]?[0-9]?)[^/]*?([0-9]*):([0-9]*):?([0-9]*)@;
82 $diff{"day"}=$1 || "";
83 $diff{"hour"}=$2;
84 $diff{"min"}=$3;
85 $diff{"sec"}=$4 || 0;
87 $diff{"index"}=$i;
89 print "diff loaded: $diff{day} $diff{hour}:$diff{min}:$diff{sec}\n";
91 local $/;
92 open (F, "$file")
93 or return "Can't open file $file ($_[0]) for reading";
94 my $text = <F>;
95 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i) {
96 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8");
97 $text = $converter->convert($text);
98 }
99 close(F);
100 $diff{"text"}=$text;
101 #print "$file loaded ($diff{day})\n";
103 #push @Diffs, \%diff;
104 $Diffs{$file} = \%diff;
105 $i++;
106 }
107 }
108 }
111 sub bind_diff
112 {
113 # my $path = shift;
114 # my $pid = shift;
115 # my $day = shift;
116 # my $lab = shift;
118 print "Trying to bind diff...\n";
120 my $cl = shift;
121 my $hour = $cl->{"hour"};
122 my $min = $cl->{"min"};
123 my $sec = $cl->{"sec"};
125 my $min_dt = 10000;
127 for my $diff_key (keys %Diffs) {
128 my $diff = $Diffs{$diff_key};
129 # Check here date, time and user
130 next if ($diff->{"day"} && $cl->{"day"} && ($cl->{"day"} ne $diff->{"day"}));
131 #next if (!$diff->{"uid"} && $cl->{"euid"} != $diff->{"uid"});
133 my $dt=($diff->{"hour"}-$hour)*3600 +($diff->{"min"}-$min)*60 + ($diff->{"sec"}-$sec);
134 if ($dt >0 && $dt < $min_dt && ($diff->{"time_range"} <0 || $dt < $diff->{"time_range"})) {
135 print "Approppriate diff found: dt=$dt\n";
136 if ($diff->{"bind_to"}) {
137 undef $diff->{"bind_to"}->{"diff"};
138 };
139 $diff->{"time_range"}=$dt;
140 $diff->{"bind_to"}=$cl;
142 $cl->{"diff"} = $diff_key;
143 $min_dt = $dt;
144 }
145 }
146 }
149 sub extract_commands_from_cline
150 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
151 # номер первого появление команды в строке:
152 # команда => первая позиция
153 {
154 my $cline = $_[0];
155 my @lists = split /\;/, $cline;
158 my @commands = ();
159 for my $list (@lists) {
160 push @commands, split /\|/, $list;
161 }
163 my %commands;
164 my %files;
165 my $i=0;
166 for my $command (@commands) {
167 $command =~ /\s*(\S+)\s*(.*)/;
168 if ($1 && $1 eq "sudo" ) {
169 $commands{"$1"}=$i++;
170 $command =~ s/\s*sudo\s+//;
171 }
172 $command =~ /\s*(\S+)\s*(.*)/;
173 if ($1 && !defined $commands{"$1"}) {
174 $commands{"$1"}=$i++;
175 };
176 }
177 return %commands;
178 }
180 sub load_command_lines
181 {
182 my $lab_scripts_path = $_[0];
183 my $lab_scripts_mask = $_[1];
185 my $cline_re_base = qq'
186 (
187 (?:\\^?([0-9]*C?)) # exitcode
188 (?:_([0-9]+)_)? # uid
189 (?:_([0-9]+)_) # pid
190 (...?) # day
191 (.?.?) # lab
192 \\s # space separator
193 ([0-9][0-9]):([0-9][0-9]):([0-9][0-9]) # time
194 .\\[50D.\\[K # killing symbols
195 (.*?([\$\#]\\s?)) # prompt
196 (.*) # command line
197 )
198 ';
199 my $cline_re = qr/$cline_re_base/sx;
200 my $cline_re2 = qr/$cline_re_base$/sx;
202 my $cline_re_v2_base = qq'
203 (
204 v2[\#] # version
205 ([0-9]+)[\#] # history line number
206 ([0-9]+)[\#] # exitcode
207 ([0-9]+)[\#] # uid
208 ([0-9]+)[\#] # pid
209 ([0-9]+)[\#] # time
210 (.*?)[\#] # pwd
211 .\\[1024D.\\[K # killing symbols
212 (.*?([\$\#]\\s?)) # prompt
213 (.*) # command line
214 )
215 ';
217 my $cline_re_v2 = qr/$cline_re_v2_base/sx;
218 my $cline_re2_v2 = qr/$cline_re_v2_base$/sx;
220 my $vt = Term::VT102->new ( 'cols' => $Config{"terminal_width"},
221 'rows' => $Config{"terminal_height"});
222 my $cline_vt = Term::VT102->new ('cols' => $Config{"terminal_width"},
223 'rows' => $Config{"terminal_height"});
225 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8")
226 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i);
228 print "Parsing lab scripts...\n" if $Config{"verbose"} =~ /y/;
230 my $file;
231 my $skip_info;
233 my $commandlines_loaded =0;
234 my $commandlines_processed =0;
236 my @lab_scripts = <$lab_scripts_path/$lab_scripts_mask>;
237 for $file (@lab_scripts){
239 # Пропускаем файл, если он не изменялся со времени нашего предудущего прохода
240 my $size = (stat($file))[7];
241 next if ($Script_Files{$file} && $Script_Files{$file}->{size} && $Script_Files{$file}->{size} >= $size);
244 my $local_session_id;
245 # Начальное значение идентификатора текущего сеанса определяем из имени скрипта
246 # Впоследствии оно может быть уточнено
247 $file =~ m@.*/([^/]*)\.script$@;
248 $local_session_id = $1;
250 #Если файл только что появился,
251 #пытаемся найти и загрузить информацию о соответствующей ему сессии
252 if (!$Script_Files{$file}) {
253 my $session_file = $file;
254 $session_file =~ s/\.script/.info/;
255 if (open(SESSION, $session_file)) {
256 local $/;
257 my $data = <SESSION>;
258 close(SESSION);
260 for my $session_data ($data =~ m@<session>(.*?)</session>@sg) {
261 my %session;
262 while ($session_data =~ m@<([^>]*?)>(.*?)</\1>@sg) {
263 $session{$1} = $2;
264 }
265 $local_session_id = $session{"local_session_id"} if $session{"local_session_id"};
266 $Sessions{$local_session_id}=\%session;
267 }
269 #Загруженную информацию сразу же отправляем в поток
270 print_session($Config{cache}, $local_session_id);
271 }
272 }
274 open (FILE, "$file");
275 binmode FILE;
277 # Переходим к тому месту, где мы окончили разбор
278 seek (FILE, $Script_Files{$file}->{tell}, 0) if $Script_Files{$file}->{tell};
279 $Script_Files{$file}->{size} = $size;
280 $Script_Files{$file}->{tell} = 0 unless $Script_Files{$file}->{tell};
282 $file =~ m@.*/(.*?)-.*@;
284 print "+- processing file $file\n" if $Config{"verbose"} =~/y/;
286 my $tty = $1;
287 my $first_pass = 1;
288 my %cl;
289 my $last_output_length=0;
290 while (<FILE>) {
291 $commandlines_processed++;
293 next if s/^Script started on.*?\n//s;
295 if (/[0-9][0-9]:[0-9][0-9]:[0-9][0-9].\[[0-9][0-9]D.\[K/ && m/$cline_re/) {
296 s/.*\x0d(?!\x0a)//;
297 m/$cline_re2/gs;
299 $commandlines_loaded++;
300 $last_output_length=0;
302 # Previous command
303 my %last_cl = %cl;
304 my $err = $2 || "";
306 $cl{"local_session_id"} = $local_session_id;
307 # Parse new command
308 $cl{"uid"} = $3;
309 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
310 $cl{"pid"} = $4;
311 $cl{"day"} = $5;
312 $cl{"lab"} = $6;
313 $cl{"hour"} = $7;
314 $cl{"min"} = $8;
315 $cl{"sec"} = $9;
316 #$cl{"fullprompt"} = $10;
317 $cl{"prompt"} = $11;
318 $cl{"raw_cline"} = $12;
320 {
321 use bytes;
322 $cl{"raw_start"} = tell (FILE) - length($1);
323 $cl{"raw_output_start"} = tell FILE;
324 }
325 $cl{"raw_file"} = $file;
327 $cl{"err"} = 0;
328 $cl{"output"} = "";
329 $cl{"tty"} = $tty;
331 $cline_vt->process($cl{"raw_cline"}."\n");
332 $cl{"cline"} = $cline_vt->row_plaintext (1);
333 $cl{"cline"} =~ s/\s*$//;
334 $cline_vt->reset();
336 my %commands = extract_commands_from_cline($cl{"cline"});
337 #$cl{"euid"}=0 if defined $commands{"sudo"};
338 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
339 $cl{"last_command"} = $comms[$#comms] || "";
341 if (
342 $Config{"suppress_editors"} =~ /^y/i
343 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
344 || $Config{"suppress_pagers"} =~ /^y/i
345 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
346 || $Config{"suppress_terminal"}=~ /^y/i
347 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
348 ) {
349 $cl{"suppress_output"} = "1";
350 }
351 else {
352 $cl{"suppress_output"} = "0";
353 }
354 $skip_info = 0;
357 print " ",$cl{"last_command"};
359 # Processing previous command line
360 if ($first_pass) {
361 $first_pass = 0;
362 next;
363 }
365 # Error code
366 $last_cl{"raw_end"} = $cl{"raw_start"};
367 $last_cl{"err"}=$err;
368 $last_cl{"err"}=130 if $err eq "^C";
370 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
371 bind_diff(\%last_cl);
372 }
374 # Output
375 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
376 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
377 my $line= $vt->row_plaintext($i);
378 next if !defined ($line) ; #|| $line =~ /^\s*$/;
379 $line =~ s/\s*$//;
380 $line .= "\n" unless $line =~ /^\s*$/;
381 $last_cl{"output"} .= $line;
382 }
383 }
384 else {
385 $last_cl{"output"}= "";
386 }
388 $vt->reset();
391 # Save
392 if (!$Config{"lab"} || $cl{"lab"} eq $Config{"lab"}) {
393 # Changing encoding
394 for (keys %last_cl) {
395 next if /raw/;
396 $last_cl{$_} = $converter->convert($last_cl{$_})
397 if ($Config{"encoding"} &&
398 $Config{"encoding"} !~ /^utf-8$/i);
399 }
400 push @Command_Lines, \%last_cl;
402 # Сохранение позиции в файле, до которой выполнен
403 # успешный разбор
404 $Script_Files{$file}->{tell} = $last_cl{raw_end};
405 }
406 next;
407 }
410 elsif (m/$cline_re_v2/) {
413 # Разбираем командную строку версии 2
416 s/.*\x0d(?!\x0a)//;
417 m/$cline_re2_v2/gs;
419 $commandlines_loaded++;
420 $last_output_length=0;
422 # Previous command
423 my %last_cl = %cl;
425 $cl{"local_session_id"} = $local_session_id;
426 # Parse new command
427 $cl{"history"} = $2;
428 my $err = $3;
429 $cl{"uid"} = $4;
430 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
431 $cl{"pid"} = $5;
432 $cl{"time"} = $6;
433 $cl{"pwd"} = $7;
434 #$cl{"fullprompt"} = $8;
435 $cl{"prompt"} = $9;
436 $cl{"raw_cline"}= $10;
438 {
439 use bytes;
440 $cl{"raw_start"} = tell (FILE) - length($1);
441 $cl{"raw_output_start"} = tell FILE;
442 }
443 $cl{"raw_file"} = $file;
445 $cl{"err"} = 0;
446 $cl{"output"} = "";
447 #$cl{"tty"} = $tty;
449 $cline_vt->process($cl{"raw_cline"}."\n");
450 $cl{"cline"} = $cline_vt->row_plaintext (1);
451 $cl{"cline"} =~ s/\s*$//;
452 $cline_vt->reset();
454 my %commands = extract_commands_from_cline($cl{"cline"});
455 #$cl{"euid"} = 0 if defined $commands{"sudo"};
456 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
457 $cl{"last_command"}
458 = $comms[$#comms] || "";
460 if (
461 $Config{"suppress_editors"} =~ /^y/i
462 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
463 || $Config{"suppress_pagers"} =~ /^y/i
464 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
465 || $Config{"suppress_terminal"}=~ /^y/i
466 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
467 ) {
468 $cl{"suppress_output"} = "1";
469 }
470 else {
471 $cl{"suppress_output"} = "0";
472 }
473 $skip_info = 0;
476 if ($Config{verbose} =~ /y/i) {
477 print "| " if $commandlines_loaded % 15 == 1;
478 print " ",$cl{"last_command"};
479 }
481 # Processing previous command line
482 if ($first_pass) {
483 $first_pass = 0;
484 next;
485 }
487 # Error code
488 $last_cl{"err"}=$err;
489 $last_cl{"raw_end"} = $cl{"raw_start"};
491 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
492 bind_diff(\%last_cl);
493 }
495 # Output
496 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
497 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
498 my $line= $vt->row_plaintext($i);
499 next if !defined ($line) ; #|| $line =~ /^\s*$/;
500 $line =~ s/\s*$//;
501 $line .= "\n" unless $line =~ /^\s*$/;
502 $last_cl{"output"} .= $line;
503 }
504 }
505 else {
506 $last_cl{"output"}= "";
507 }
509 $vt->reset();
512 # Changing encoding
513 for (keys %last_cl) {
514 next if /raw/;
515 if ($Config{"encoding"} &&
516 $Config{"encoding"} !~ /^utf-8$/i) {
517 $last_cl{$_} = $converter->convert($last_cl{$_})
518 }
519 }
520 push @Command_Lines, \%last_cl;
522 # Сохранение позиции в файле, до которой выполнен
523 # успешный разбор
524 $Script_Files{$file}->{tell} = $last_cl{raw_end};
526 next;
528 }
530 # Иначе, это строка вывода
532 $last_output_length+=length($_);
533 #if (!$cl{"suppress_output"} || $last_output_length < 5000) {
534 if ($last_output_length < 50000) {
535 $vt->process("$_"."\n")
536 }
537 else
538 {
539 if (!$skip_info) {
540 print "($cl{last_command})";
541 $skip_info = 1;
542 }
543 }
544 }
545 close(FILE);
547 }
548 if ($Config{"verbose"} =~ /y/) {
549 print "\n`- finished.\n" ;
550 print "Lines loaded: $commandlines_processed\n";
551 print "Command lines: $commandlines_loaded\n";
552 }
553 }
558 sub sort_command_lines
559 {
560 print "Sorting command lines..." if $Config{"verbose"} =~ /y/;
562 # Sort Command_Lines
563 # Write Command_Lines to Command_Lines_Index
565 my @index;
566 for (my $i=0;$i<=$#Command_Lines;$i++) {
567 $index[$i]=$i;
568 }
570 @Command_Lines_Index = sort {
571 $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"} ||
572 $Command_Lines[$index[$a]]->{"day"} cmp $Command_Lines[$index[$b]]->{"day"} ||
573 $Command_Lines[$index[$a]]->{"hour"} <=> $Command_Lines[$index[$b]]->{"hour"} ||
574 $Command_Lines[$index[$a]]->{"min"} <=> $Command_Lines[$index[$b]]->{"min"} ||
575 $Command_Lines[$index[$a]]->{"sec"} <=> $Command_Lines[$index[$b]]->{"sec"}
576 } @index;
578 print "finished\n" if $Config{"verbose"} =~ /y/;
580 }
582 sub printq
583 {
584 my $TO = shift;
585 my $text = join "", @_;
586 $text =~ s/&/&amp;/g;
587 $text =~ s/</&lt;/g;
588 $text =~ s/>/&gt;/g;
589 print $TO $text;
590 }
593 =cut
594 Вывести результат обработки журнала.
595 =cut
597 sub print_command_lines
598 {
599 my $output_filename=$_[0];
600 my $mode = ">";
601 $mode =">>" if $Config{mode} eq "daemon";
602 open(OUT, $mode, $output_filename)
603 or die "Can't open $output_filename for writing\n";
606 my $cl;
607 my $in_range=0;
608 for my $i (@Command_Lines_Index) {
609 $cl = $Command_Lines[$i];
611 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
612 $in_range=1;
613 next;
614 }
615 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
616 $in_range=0;
617 next;
618 }
619 next if ($Config{"from"} && $Config{"to"} && !$in_range)
620 ||
621 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
622 ||
623 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
624 ||
625 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
627 # Вырезаем из вывода только нужное количество строк
629 my $output="";
631 if (!grep ($_ eq $cl->{"last_command"}, @{$Config{"full_output_commands"}})
632 && ($Config{"head_lines"}
633 || $Config{"tail_lines"})) {
634 # Partialy output
635 my @lines = split '\n', $cl->{"output"};
636 # head
637 my $mark=1;
638 for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
639 $output .= $lines[$i]."\n";
640 }
641 # tail
642 my $start=$#lines-$Config{"cache_tail_lines"}+1;
643 if ($start < 0) {
644 $start=0;
645 $mark=0;
646 }
647 if ($start < $Config{"cache_head_lines"}) {
648 $start=$Config{"cache_head_lines"};
649 $mark=0;
650 }
651 $output .= $Config{"skip_text"}."\n" if $mark;
652 for ($i=$start; $i<= $#lines; $i++) {
653 $output .= $lines[$i]."\n";
654 }
655 }
656 else {
657 # Full output
658 $output .= $cl->{"output"};
659 }
661 # Совместимость с labmaker
663 # Переводим в секунды Эпохи
664 # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
665 # Информация о годе отсутствовала
666 # Её можно внести:
667 # Декабрь 2004 год; остальные -- 2005 год.
669 my $year = 2005;
670 #$year = 2004 if ( $cl->{day} > 330 );
671 $year = $Config{year} if $Config{year};
672 # timelocal( $sec, $min, $hour, $mday,$mon,$year);
673 $cl->{time} ||= timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
676 # Начинаем вывод команды
677 print OUT "<command>\n";
678 for my $element (qw(
679 local_session_id
680 history
681 uid
682 pid
683 time
684 pwd
685 raw_start
686 raw_output_start
687 raw_end
688 raw_file
689 tty
690 err
691 last_command
692 history
693 )) {
694 next unless defined($cl->{"$element"});
695 print OUT "<$element>".$cl->{$element}."</$element>\n";
696 }
697 for my $element (qw(
698 prompt
699 cline
700 )) {
701 next unless defined($cl->{"$element"});
702 print OUT "<$element>";
703 printq(\*OUT,$cl->{"$element"});
704 print OUT "</$element>\n";
705 }
706 #note
707 #note_title
708 print OUT "<output>";
709 printq(\*OUT,$output);
710 print OUT "</output>\n";
711 if ($cl->{"diff"}) {
712 print OUT "<diff>";
713 printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
714 print OUT "</diff>\n";
715 }
716 print OUT "</command>\n";
718 }
720 close(OUT);
721 }
723 sub print_session
724 {
725 my $output_filename = $_[0];
726 my $local_session_id = $_[1];
727 return if not defined($Sessions{$local_session_id});
729 open(OUT, ">>", $output_filename)
730 or die "Can't open $output_filename for writing\n";
731 print OUT "<session>\n";
732 my %session = %{$Sessions{$local_session_id}};
733 for my $key (keys %session) {
734 print OUT "<$key>".$session{$key}."</$key>\n"
735 }
736 print OUT "</session>\n";
737 close(OUT);
738 }
740 sub send_cache
741 {
742 # Если в кэше что-то накопилось,
743 # попытаемся отправить это на сервер
744 #
745 my $cache_was_sent=0;
747 if (open(CACHE, $Config{cache})) {
748 local $/;
749 my $cache = <CACHE>;
750 close(CACHE);
752 my $socket = IO::Socket::INET->new(
753 PeerAddr => $Config{backend_address},
754 PeerPort => $Config{backend_port},
755 proto => "tcp",
756 Type => SOCK_STREAM
757 );
759 if ($socket) {
760 print $socket $cache;
761 close($socket);
762 $cache_was_sent = 1;
763 }
764 }
765 return $cache_was_sent;
766 }
768 sub save_cache_stat
769 {
770 open (CACHE, ">$Config{cache_stat}");
771 for my $f (keys %Script_Files) {
772 print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
773 }
774 close(CACHE);
775 }
777 sub load_cache_stat
778 {
779 if (open (CACHE, "$Config{cache_stat}")) {
780 while(<CACHE>) {
781 chomp;
782 my ($f, $size, $tell) = split /\t/;
783 $Script_Files{$f}->{size} = $size;
784 $Script_Files{$f}->{tell} = $tell;
785 }
786 close(CACHE);
787 };
788 }
791 main();
793 sub process_was_killed
794 {
795 $Killed = 1;
796 }
798 sub main
799 {
801 $| = 1;
803 init_variables();
804 init_config();
807 if ($Config{"mode"} ne "daemon") {
809 # В нормальном режиме работы нужно
810 # считать скрипты, обработать их и записать
811 # результат выполнения в результирующий файл.
812 # После этого завершить работу.
814 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
815 load_diff_files($lab_log);
816 }
817 load_command_lines($Config{"input"}, $Config{"input_mask"});
818 sort_command_lines;
819 #process_command_lines;
820 print_command_lines($Config{"cache"});
821 }
822 else {
823 if (open(PIDFILE, $Config{agent_pidfile})) {
824 my $pid = <PIDFILE>;
825 close(PIDFILE);
826 if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
827 print "Removing stale pidfile\n";
828 unlink $Config{agent_pidfile}
829 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
830 }
831 elsif ($^O eq 'freebsd' && $pid && `ps axo uid,pid,command | grep '$<\\s*$pid\\s*$Config{"l3-agent"}' 2> /dev/null`) {
832 print "Removing stale pidfile\n";
833 unlink $Config{agent_pidfile}
834 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
835 }
836 elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
837 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
838 exit(0);
839 }
840 else {
841 print "Unknown operating system";
842 exit(0);
843 }
844 }
845 if ($Config{detach} =~ /^y/i) {
846 #$Config{verbose} = "no";
847 my $pid = fork;
848 exit if $pid;
849 die "Couldn't fork: $!" unless defined ($pid);
851 open(PIDFILE, ">", $Config{agent_pidfile})
852 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
853 print PIDFILE $$;
854 close(PIDFILE);
856 for my $handle (*STDIN, *STDOUT, *STDERR) {
857 open ($handle, "+<", "/dev/null")
858 or die "can't reopen $handle to /dev/null: $!"
859 }
861 POSIX::setsid()
862 or die "Can't start a new session: $!";
864 $0 = $Config{"l3-agent"};
866 $SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&process_was_killed;
867 }
868 while (not $Killed) {
869 @Command_Lines = ();
870 @Command_Lines_Index = ();
871 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
872 load_diff_files($lab_log);
873 }
874 load_cache_stat();
875 load_command_lines($Config{"input"}, $Config{"input_mask"});
876 if (@Command_Lines) {
877 sort_command_lines;
878 #process_command_lines;
879 print_command_lines($Config{"cache"});
880 }
881 save_cache_stat();
882 if (-e $Config{cache} && (stat($Config{cache}))[7]) {
883 send_cache() && unlink($Config{cache});
884 }
885 sleep($Config{"daemon_sleep_interval"} || 1);
886 }
888 unlink $Config{agent_pidfile};
889 }
891 }
893 sub init_variables
894 {
895 }