lilalo

view l3-agent @ 85:3f92cd706473

* Исправлена ошибка с неверной очисткой XML-файла
с lablog'ом, при выполнении в пакетном режиме.
Он очищался, перед записью команд, а не надо было.
В результате терялась информация о сессиях.

Теперь очистка выполняется в самом самом начале
author devi
date Sat Feb 25 08:22:20 2006 +0200 (2006-02-25)
parents 2cb912bff2ea
children 3058ada85a58
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});
61 my %diff;
63 # Старый формат имени diff-файла
64 # DEPRECATED
65 if ($file=~m@/(D?[0-9][0-9]?[0-9]?)[^/]*?([0-9]*):([0-9]*):?([0-9]*)@) {
66 $diff{"day"}=$1 || "";
67 $diff{"hour"}=$2;
68 $diff{"min"}=$3;
69 $diff{"sec"}=$4 || 0;
71 $diff{"uid"} = 0 if $path =~ m@/root/@;
73 print "diff loaded: $diff{day} $diff{hour}:$diff{min}:$diff{sec}\n";
75 }
76 # Новый формат имени diff-файла
77 elsif ($file =~ m@.*/([^_]*)_([0-9]+)(.*)@) {
78 $diff{"local_session_id"} = $1;
79 $diff{"time"} = $2;
80 $diff{"filename"} = $3;
81 $diff{"filename"} =~ s@_@/@g;
82 $diff{"filename"} =~ s@//@_@g;
84 print "diff loaded: $diff{filename} (time=$diff{time},session=$diff{local_session_id})\n";
85 }
86 else {
87 next;
88 }
90 # Чтение и изменение кодировки содержимого diff-файла
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;
102 $diff{"path"}=$path;
103 $diff{"bind_to"}="";
104 $diff{"time_range"}=-1;
105 $diff{"index"}=$i;
107 $Diffs{$file} = \%diff;
108 $i++;
109 }
110 }
111 }
114 sub bind_diff
115 {
116 print "Trying to bind diff...\n";
118 my $cl = shift;
119 my $hour = $cl->{"hour"};
120 my $min = $cl->{"min"};
121 my $sec = $cl->{"sec"};
123 my $min_dt = 10000;
125 for my $diff_key (keys %Diffs) {
126 my $diff = $Diffs{$diff_key};
127 next if ($diff->{"local_session_id"}
128 && $cl->{"local_session_id"}
129 && ($cl->{"local_session_id"} ne $diff->{"local_session_id"}));
131 next if ($diff->{"day"} && $cl->{"day"} && ($cl->{"day"} ne $diff->{"day"}));
133 my $dt;
134 if ($diff->{"time"} && $cl->{"time"}) {
135 $dt = $diff->{"time"} - $cl->{"time"}
136 }
137 else {
138 $dt=($diff->{"hour"}-$hour)*3600 +($diff->{"min"}-$min)*60 + ($diff->{"sec"}-$sec);
139 }
140 if ($dt >0
141 && $dt < $min_dt
142 && ($diff->{"time_range"} <0
143 || $dt < $diff->{"time_range"})) {
144 print "Approppriate diff found: dt=$dt\n";
145 if ($diff->{"bind_to"}) {
146 undef $diff->{"bind_to"}->{"diff"};
147 };
148 $diff->{"time_range"}=$dt;
149 $diff->{"bind_to"}=$cl;
151 $cl->{"diff"} = $diff_key;
152 $min_dt = $dt;
153 }
154 }
155 }
158 sub extract_commands_from_cline
159 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
160 # номер первого появление команды в строке:
161 # команда => первая позиция
162 {
163 my $cline = $_[0];
164 my @lists = split /\;/, $cline;
167 my @commands = ();
168 for my $list (@lists) {
169 push @commands, split /\|/, $list;
170 }
172 my %commands;
173 my %files;
174 my $i=0;
175 for my $command (@commands) {
176 $command =~ /\s*(\S+)\s*(.*)/;
177 if ($1 && $1 eq "sudo" ) {
178 $commands{"$1"}=$i++;
179 $command =~ s/\s*sudo\s+//;
180 }
181 $command =~ /\s*(\S+)\s*(.*)/;
182 if ($1 && !defined $commands{"$1"}) {
183 $commands{"$1"}=$i++;
184 };
185 }
186 return %commands;
187 }
189 sub load_command_lines
190 {
191 my $lab_scripts_path = $_[0];
192 my $lab_scripts_mask = $_[1];
194 my $cline_re_base = qq'
195 (
196 (?:\\^?([0-9]*C?)) # exitcode
197 (?:_([0-9]+)_)? # uid
198 (?:_([0-9]+)_) # pid
199 (...?) # day
200 (.?.?) # lab
201 \\s # space separator
202 ([0-9][0-9]):([0-9][0-9]):([0-9][0-9]) # time
203 .\\[50D.\\[K # killing symbols
204 (.*?([\$\#]\\s?)) # prompt
205 (.*) # command line
206 )
207 ';
208 my $cline_re = qr/$cline_re_base/sx;
209 my $cline_re2 = qr/$cline_re_base$/sx;
211 my $cline_re_v2_base = qq'
212 (
213 v2[\#] # version
214 ([0-9]+)[\#] # history line number
215 ([0-9]+)[\#] # exitcode
216 ([0-9]+)[\#] # uid
217 ([0-9]+)[\#] # pid
218 ([0-9]+)[\#] # time
219 (.*?)[\#] # pwd
220 .\\[1024D.\\[K # killing symbols
221 (.*?([\$\#]\\s?)) # prompt
222 (.*) # command line
223 )
224 ';
226 my $cline_re_v2 = qr/$cline_re_v2_base/sx;
227 my $cline_re2_v2 = qr/$cline_re_v2_base$/sx;
229 my $vt = Term::VT102->new ( 'cols' => $Config{"terminal_width"},
230 'rows' => $Config{"terminal_height"});
231 my $cline_vt = Term::VT102->new (
232 'cols' => $Config{"terminal_width"},
233 'rows' => $Config{"terminal_height"});
235 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8")
236 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i);
238 print "Parsing lab scripts...\n" if $Config{"verbose"} =~ /y/;
240 my $file;
241 my $skip_info;
243 my $commandlines_loaded =0;
244 my $commandlines_processed =0;
246 my @lab_scripts = <$lab_scripts_path/$lab_scripts_mask>;
247 for $file (@lab_scripts){
249 # Пропускаем файл, если он не изменялся со времени нашего предудущего прохода
250 my $size = (stat($file))[7];
251 next if ($Script_Files{$file} && $Script_Files{$file}->{size} && $Script_Files{$file}->{size} >= $size);
254 my $local_session_id;
255 # Начальное значение идентификатора текущего сеанса определяем из имени скрипта
256 # Впоследствии оно может быть уточнено
257 $file =~ m@.*/([^/]*)\.script$@;
258 $local_session_id = $1;
260 #Если файл только что появился,
261 #пытаемся найти и загрузить информацию о соответствующей ему сессии
262 if (!$Script_Files{$file}) {
263 my $session_file = $file;
264 $session_file =~ s/\.script/.info/;
265 if (open(SESSION, $session_file)) {
266 local $/;
267 my $data = <SESSION>;
268 close(SESSION);
270 for my $session_data ($data =~ m@<session>(.*?)</session>@sg) {
271 my %session;
272 while ($session_data =~ m@<([^>]*?)>(.*?)</\1>@sg) {
273 $session{$1} = $2;
274 }
275 $local_session_id = $session{"local_session_id"} if $session{"local_session_id"};
276 $Sessions{$local_session_id}=\%session;
277 }
279 #Загруженную информацию сразу же отправляем в поток
280 print_session($Config{cache}, $local_session_id);
281 }
282 else {
283 die "can't open session file";
284 }
285 }
287 open (FILE, "$file");
288 binmode FILE;
290 # Переходим к тому месту, где мы окончили разбор
291 seek (FILE, $Script_Files{$file}->{tell}, 0) if $Script_Files{$file}->{tell};
292 $Script_Files{$file}->{size} = $size;
293 $Script_Files{$file}->{tell} = 0 unless $Script_Files{$file}->{tell};
295 $file =~ m@.*/(.*?)-.*@;
297 print "\n+- processing file $file\n| "
298 if $Config{"verbose"} =~/y/;
300 my $tty = $1;
301 my $first_pass = 1;
302 my %cl;
303 my $last_output_length=0;
304 while (<FILE>) {
305 $commandlines_processed++;
307 next if s/^Script started on.*?\n//s;
309 if (/[0-9][0-9]:[0-9][0-9]:[0-9][0-9].\[[0-9][0-9]D.\[K/ && m/$cline_re/) {
310 s/.*\x0d(?!\x0a)//;
311 m/$cline_re2/gs;
313 $commandlines_loaded++;
314 $last_output_length=0;
316 # Previous command
317 my %last_cl = %cl;
318 my $err = $2 || "";
320 $cl{"local_session_id"} = $local_session_id;
321 # Parse new command
322 $cl{"uid"} = $3;
323 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
324 $cl{"pid"} = $4;
325 $cl{"day"} = $5;
326 $cl{"lab"} = $6;
327 $cl{"hour"} = $7;
328 $cl{"min"} = $8;
329 $cl{"sec"} = $9;
330 #$cl{"fullprompt"} = $10;
331 $cl{"prompt"} = $11;
332 $cl{"raw_cline"} = $12;
334 {
335 use bytes;
336 $cl{"raw_start"} = tell (FILE) - length($1);
337 $cl{"raw_output_start"} = tell FILE;
338 }
339 $cl{"raw_file"} = $file;
341 $cl{"err"} = 0;
342 $cl{"output"} = "";
343 $cl{"tty"} = $tty;
345 $cline_vt->process($cl{"raw_cline"}."\n");
346 $cl{"cline"} = $cline_vt->row_plaintext (1);
347 $cl{"cline"} =~ s/\s*$//;
348 $cline_vt->reset();
350 my %commands = extract_commands_from_cline($cl{"cline"});
351 #$cl{"euid"}=0 if defined $commands{"sudo"};
352 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
353 $cl{"last_command"} = $comms[$#comms] || "";
355 if (
356 $Config{"suppress_editors"} =~ /^y/i
357 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
358 || $Config{"suppress_pagers"} =~ /^y/i
359 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
360 || $Config{"suppress_terminal"}=~ /^y/i
361 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
362 ) {
363 $cl{"suppress_output"} = "1";
364 }
365 else {
366 $cl{"suppress_output"} = "0";
367 }
368 $skip_info = 0;
371 print " ",$cl{"last_command"};
373 # Processing previous command line
374 if ($first_pass) {
375 $first_pass = 0;
376 next;
377 }
379 # Error code
380 $last_cl{"raw_end"} = $cl{"raw_start"};
381 $last_cl{"err"}=$err;
382 $last_cl{"err"}=130 if $err eq "^C";
384 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
385 bind_diff(\%last_cl);
386 }
388 # Output
389 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
390 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
391 my $line= $vt->row_plaintext($i);
392 next if !defined ($line) ; #|| $line =~ /^\s*$/;
393 $line =~ s/\s*$//;
394 $line .= "\n" unless $line =~ /^\s*$/;
395 $last_cl{"output"} .= $line;
396 }
397 }
398 else {
399 $last_cl{"output"}= "";
400 }
402 $vt->reset();
405 # Save
406 if (!$Config{"lab"} || $cl{"lab"} eq $Config{"lab"}) {
407 # Changing encoding
408 for (keys %last_cl) {
409 next if /raw/;
410 $last_cl{$_} = $converter->convert($last_cl{$_})
411 if ($Config{"encoding"} &&
412 $Config{"encoding"} !~ /^utf-8$/i);
413 }
414 push @Command_Lines, \%last_cl;
416 # Сохранение позиции в файле, до которой выполнен
417 # успешный разбор
418 $Script_Files{$file}->{tell} = $last_cl{raw_end};
419 }
420 next;
421 }
424 elsif (m/$cline_re_v2/) {
427 # Разбираем командную строку версии 2
430 s/.*\x0d(?!\x0a)//;
431 m/$cline_re2_v2/gs;
433 $commandlines_loaded++;
434 $last_output_length=0;
436 # Previous command
437 my %last_cl = %cl;
439 $cl{"local_session_id"} = $local_session_id;
440 # Parse new command
441 $cl{"history"} = $2;
442 my $err = $3;
443 $cl{"uid"} = $4;
444 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
445 $cl{"pid"} = $5;
446 $cl{"time"} = $6;
447 $cl{"pwd"} = $7;
448 #$cl{"fullprompt"} = $8;
449 $cl{"prompt"} = $9;
450 $cl{"raw_cline"}= $10;
452 {
453 use bytes;
454 $cl{"raw_start"} = tell (FILE) - length($1);
455 $cl{"raw_output_start"} = tell FILE;
456 }
457 $cl{"raw_file"} = $file;
459 $cl{"err"} = 0;
460 $cl{"output"} = "";
461 #$cl{"tty"} = $tty;
463 $cline_vt->process($cl{"raw_cline"}."\n");
464 $cl{"cline"} = $cline_vt->row_plaintext (1);
465 $cl{"cline"} =~ s/\s*$//;
466 $cline_vt->reset();
468 my %commands = extract_commands_from_cline($cl{"cline"});
469 #$cl{"euid"} = 0 if defined $commands{"sudo"};
470 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
471 $cl{"last_command"}
472 = $comms[$#comms] || "";
474 if (
475 $Config{"suppress_editors"} =~ /^y/i
476 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
477 || $Config{"suppress_pagers"} =~ /^y/i
478 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
479 || $Config{"suppress_terminal"}=~ /^y/i
480 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
481 ) {
482 $cl{"suppress_output"} = "1";
483 }
484 else {
485 $cl{"suppress_output"} = "0";
486 }
487 $skip_info = 0;
490 if ($Config{verbose} =~ /y/i) {
491 print "\n| " if $commandlines_loaded % 5 == 1;
492 print " ",$cl{"last_command"};
493 }
495 # Processing previous command line
496 if ($first_pass) {
497 $first_pass = 0;
498 next;
499 }
501 # Error code
502 $last_cl{"err"}=$err;
503 $last_cl{"raw_end"} = $cl{"raw_start"};
505 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
506 bind_diff(\%last_cl);
507 }
509 # Output
510 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
511 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
512 my $line= $vt->row_plaintext($i);
513 next if !defined ($line) ; #|| $line =~ /^\s*$/;
514 $line =~ s/\s*$//;
515 $line .= "\n" unless $line =~ /^\s*$/;
516 $last_cl{"output"} .= $line;
517 }
518 }
519 else {
520 $last_cl{"output"}= "";
521 }
523 $vt->reset();
526 # Changing encoding
527 for (keys %last_cl) {
528 next if /raw/;
529 if ($Config{"encoding"} &&
530 $Config{"encoding"} !~ /^utf-8$/i) {
531 $last_cl{$_} = $converter->convert($last_cl{$_})
532 }
533 }
534 push @Command_Lines, \%last_cl;
536 # Сохранение позиции в файле, до которой выполнен
537 # успешный разбор
538 $Script_Files{$file}->{tell} = $last_cl{raw_end};
540 next;
542 }
544 # Иначе, это строка вывода
546 $last_output_length+=length($_);
547 #if (!$cl{"suppress_output"} || $last_output_length < 5000) {
548 if ($last_output_length < 50000) {
549 $vt->process("$_"."\n")
550 }
551 else
552 {
553 if (!$skip_info) {
554 print "($cl{last_command})";
555 $skip_info = 1;
556 }
557 }
558 }
559 close(FILE);
561 }
562 if ($Config{"verbose"} =~ /y/) {
563 print "\n`- finished.\n" ;
564 print "Lines loaded: $commandlines_processed\n";
565 print "Command lines: $commandlines_loaded\n";
566 }
567 }
572 sub sort_command_lines
573 {
574 print "Sorting command lines..." if $Config{"verbose"} =~ /y/;
576 # Sort Command_Lines
577 # Write Command_Lines to Command_Lines_Index
579 my @index;
580 for (my $i=0;$i<=$#Command_Lines;$i++) {
581 $index[$i]=$i;
582 }
584 @Command_Lines_Index = sort {
585 defined($Command_Lines[$index[$a]]->{"time"})
586 ? $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
587 : defined($Command_Lines[$index[$a]]->{"day"})
588 ? $Command_Lines[$index[$a]]->{"day"} cmp $Command_Lines[$index[$b]]->{"day"}
589 || $Command_Lines[$index[$a]]->{"hour"} <=> $Command_Lines[$index[$b]]->{"hour"}
590 || $Command_Lines[$index[$a]]->{"min"} <=> $Command_Lines[$index[$b]]->{"min"}
591 || $Command_Lines[$index[$a]]->{"sec"} <=> $Command_Lines[$index[$b]]->{"sec"}
592 : 0
593 } @index;
595 print "finished\n" if $Config{"verbose"} =~ /y/;
597 }
599 sub printq
600 {
601 my $TO = shift;
602 my $text = join "", @_;
603 $text =~ s/&/&amp;/g;
604 $text =~ s/</&lt;/g;
605 $text =~ s/>/&gt;/g;
606 print $TO $text;
607 }
610 =cut
611 Вывести результат обработки журнала.
612 =cut
614 sub print_command_lines
615 {
616 my $output_filename=$_[0];
617 open(OUT, ">>", $output_filename)
618 or die "Can't open $output_filename for writing\n";
621 my $cl;
622 my $in_range=0;
623 for my $i (@Command_Lines_Index) {
624 $cl = $Command_Lines[$i];
626 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
627 $in_range=1;
628 next;
629 }
630 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
631 $in_range=0;
632 next;
633 }
634 next if ($Config{"from"} && $Config{"to"} && !$in_range)
635 ||
636 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
637 ||
638 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
639 ||
640 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
642 # Вырезаем из вывода только нужное количество строк
644 my $output="";
646 if (!grep ($_ eq $cl->{"last_command"}, @{$Config{"full_output_commands"}})
647 && ($Config{"head_lines"}
648 || $Config{"tail_lines"})) {
649 # Partialy output
650 my @lines = split '\n', $cl->{"output"};
651 # head
652 my $mark=1;
653 for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
654 $output .= $lines[$i]."\n";
655 }
656 # tail
657 my $start=$#lines-$Config{"cache_tail_lines"}+1;
658 if ($start < 0) {
659 $start=0;
660 $mark=0;
661 }
662 if ($start < $Config{"cache_head_lines"}) {
663 $start=$Config{"cache_head_lines"};
664 $mark=0;
665 }
666 $output .= $Config{"skip_text"}."\n" if $mark;
667 for ($i=$start; $i<= $#lines; $i++) {
668 $output .= $lines[$i]."\n";
669 }
670 }
671 else {
672 # Full output
673 $output .= $cl->{"output"};
674 }
676 # Совместимость с labmaker
678 # Переводим в секунды Эпохи
679 # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
680 # Информация о годе отсутствовала
681 # Её можно внести:
682 # Декабрь 2004 год; остальные -- 2005 год.
684 my $year = 2005;
685 #$year = 2004 if ( $cl->{day} > 330 );
686 $year = $Config{year} if $Config{year};
687 # timelocal( $sec, $min, $hour, $mday,$mon,$year);
688 $cl->{time} ||= timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
691 # Начинаем вывод команды
692 print OUT "<command>\n";
693 for my $element (qw(
694 local_session_id
695 history
696 uid
697 pid
698 time
699 pwd
700 raw_start
701 raw_output_start
702 raw_end
703 raw_file
704 tty
705 err
706 last_command
707 history
708 )) {
709 next unless defined($cl->{"$element"});
710 print OUT "<$element>".$cl->{$element}."</$element>\n";
711 }
712 for my $element (qw(
713 prompt
714 cline
715 )) {
716 next unless defined($cl->{"$element"});
717 print OUT "<$element>";
718 printq(\*OUT,$cl->{"$element"});
719 print OUT "</$element>\n";
720 }
721 #note
722 #note_title
723 print OUT "<output>";
724 printq(\*OUT,$output);
725 print OUT "</output>\n";
726 if ($cl->{"diff"}) {
727 print OUT "<diff>";
728 printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
729 print OUT "</diff>\n";
730 }
731 print OUT "</command>\n";
733 }
735 close(OUT);
736 }
738 sub print_session
739 {
740 my $output_filename = $_[0];
741 my $local_session_id = $_[1];
742 return if not defined($Sessions{$local_session_id});
744 print "printing session info. session id = ".$local_session_id."\n"
745 if $Config{verbose} =~ /y/;
747 open(OUT, ">>", $output_filename)
748 or die "Can't open $output_filename for writing\n";
749 print OUT "<session>\n";
750 my %session = %{$Sessions{$local_session_id}};
751 for my $key (keys %session) {
752 print OUT "<$key>".$session{$key}."</$key>\n";
753 print " ".$key,"\n";
754 }
755 print OUT "</session>\n";
756 close(OUT);
757 }
759 sub send_cache
760 {
761 # Если в кэше что-то накопилось,
762 # попытаемся отправить это на сервер
763 #
764 my $cache_was_sent=0;
766 if (open(CACHE, $Config{cache})) {
767 local $/;
768 my $cache = <CACHE>;
769 close(CACHE);
771 my $socket = IO::Socket::INET->new(
772 PeerAddr => $Config{backend_address},
773 PeerPort => $Config{backend_port},
774 proto => "tcp",
775 Type => SOCK_STREAM
776 );
778 if ($socket) {
779 print $socket $cache;
780 close($socket);
781 $cache_was_sent = 1;
782 }
783 }
784 return $cache_was_sent;
785 }
787 sub save_cache_stat
788 {
789 open (CACHE, ">$Config{cache_stat}");
790 for my $f (keys %Script_Files) {
791 print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
792 }
793 close(CACHE);
794 }
796 sub load_cache_stat
797 {
798 if (open (CACHE, "$Config{cache_stat}")) {
799 while(<CACHE>) {
800 chomp;
801 my ($f, $size, $tell) = split /\t/;
802 $Script_Files{$f}->{size} = $size;
803 $Script_Files{$f}->{tell} = $tell;
804 }
805 close(CACHE);
806 };
807 }
810 main();
812 sub process_was_killed
813 {
814 $Killed = 1;
815 }
817 sub main
818 {
820 $| = 1;
822 init_variables();
823 init_config();
826 if ($Config{"mode"} ne "daemon") {
828 # В нормальном режиме работы нужно
829 # считать скрипты, обработать их и записать
830 # результат выполнения в результирующий файл.
831 # После этого завершить работу.
833 # Очистим кэш-файл, если он существовал
834 if (open (CACHE, ">", $Config{"cache"})) {
835 close(CACHE);
836 };
837 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
838 load_diff_files($lab_log);
839 }
840 load_command_lines($Config{"input"}, $Config{"input_mask"});
841 sort_command_lines;
842 #process_command_lines;
843 print_command_lines($Config{"cache"});
844 }
845 else {
846 if (open(PIDFILE, $Config{agent_pidfile})) {
847 my $pid = <PIDFILE>;
848 close(PIDFILE);
849 if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
850 print "Removing stale pidfile\n";
851 unlink $Config{agent_pidfile}
852 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
853 }
854 elsif ($^O eq 'freebsd' && $pid && `ps axo uid,pid,command | grep '$<\\s*$pid\\s*$Config{"l3-agent"}' 2> /dev/null`) {
855 print "Removing stale pidfile\n";
856 unlink $Config{agent_pidfile}
857 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
858 }
859 elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
860 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
861 exit(0);
862 }
863 else {
864 print "Unknown operating system";
865 exit(0);
866 }
867 }
868 if ($Config{detach} =~ /^y/i) {
869 #$Config{verbose} = "no";
870 my $pid = fork;
871 exit if $pid;
872 die "Couldn't fork: $!" unless defined ($pid);
874 open(PIDFILE, ">", $Config{agent_pidfile})
875 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
876 print PIDFILE $$;
877 close(PIDFILE);
879 for my $handle (*STDIN, *STDOUT, *STDERR) {
880 open ($handle, "+<", "/dev/null")
881 or die "can't reopen $handle to /dev/null: $!"
882 }
884 POSIX::setsid()
885 or die "Can't start a new session: $!";
887 $0 = $Config{"l3-agent"};
889 $SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&process_was_killed;
890 }
891 while (not $Killed) {
892 @Command_Lines = ();
893 @Command_Lines_Index = ();
894 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
895 load_diff_files($lab_log);
896 }
897 load_cache_stat();
898 load_command_lines($Config{"input"}, $Config{"input_mask"});
899 if (@Command_Lines) {
900 sort_command_lines;
901 #process_command_lines;
902 print_command_lines($Config{"cache"});
903 }
904 save_cache_stat();
905 if (-e $Config{cache} && (stat($Config{cache}))[7]) {
906 send_cache() && unlink($Config{cache});
907 }
908 sleep($Config{"daemon_sleep_interval"} || 1);
909 }
911 unlink $Config{agent_pidfile};
912 }
914 }
916 sub init_variables
917 {
918 }