lilalo

view l3-agent @ 84:2cb912bff2ea

* В журнале выводится имя курса, а не только его код
* Исправлена ошибка с фильтром при чтении журнала из XML-репозитория
Теперь всё ок
author devi
date Sat Feb 25 08:02:25 2006 +0200 (2006-02-25)
parents bdc1f02d3f87
children 3f92cd706473
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 my $mode = ">";
618 $mode =">>" if $Config{mode} eq "daemon";
619 open(OUT, $mode, $output_filename)
620 or die "Can't open $output_filename for writing\n";
623 my $cl;
624 my $in_range=0;
625 for my $i (@Command_Lines_Index) {
626 $cl = $Command_Lines[$i];
628 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
629 $in_range=1;
630 next;
631 }
632 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
633 $in_range=0;
634 next;
635 }
636 next if ($Config{"from"} && $Config{"to"} && !$in_range)
637 ||
638 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
639 ||
640 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
641 ||
642 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
644 # Вырезаем из вывода только нужное количество строк
646 my $output="";
648 if (!grep ($_ eq $cl->{"last_command"}, @{$Config{"full_output_commands"}})
649 && ($Config{"head_lines"}
650 || $Config{"tail_lines"})) {
651 # Partialy output
652 my @lines = split '\n', $cl->{"output"};
653 # head
654 my $mark=1;
655 for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
656 $output .= $lines[$i]."\n";
657 }
658 # tail
659 my $start=$#lines-$Config{"cache_tail_lines"}+1;
660 if ($start < 0) {
661 $start=0;
662 $mark=0;
663 }
664 if ($start < $Config{"cache_head_lines"}) {
665 $start=$Config{"cache_head_lines"};
666 $mark=0;
667 }
668 $output .= $Config{"skip_text"}."\n" if $mark;
669 for ($i=$start; $i<= $#lines; $i++) {
670 $output .= $lines[$i]."\n";
671 }
672 }
673 else {
674 # Full output
675 $output .= $cl->{"output"};
676 }
678 # Совместимость с labmaker
680 # Переводим в секунды Эпохи
681 # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
682 # Информация о годе отсутствовала
683 # Её можно внести:
684 # Декабрь 2004 год; остальные -- 2005 год.
686 my $year = 2005;
687 #$year = 2004 if ( $cl->{day} > 330 );
688 $year = $Config{year} if $Config{year};
689 # timelocal( $sec, $min, $hour, $mday,$mon,$year);
690 $cl->{time} ||= timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
693 # Начинаем вывод команды
694 print OUT "<command>\n";
695 for my $element (qw(
696 local_session_id
697 history
698 uid
699 pid
700 time
701 pwd
702 raw_start
703 raw_output_start
704 raw_end
705 raw_file
706 tty
707 err
708 last_command
709 history
710 )) {
711 next unless defined($cl->{"$element"});
712 print OUT "<$element>".$cl->{$element}."</$element>\n";
713 }
714 for my $element (qw(
715 prompt
716 cline
717 )) {
718 next unless defined($cl->{"$element"});
719 print OUT "<$element>";
720 printq(\*OUT,$cl->{"$element"});
721 print OUT "</$element>\n";
722 }
723 #note
724 #note_title
725 print OUT "<output>";
726 printq(\*OUT,$output);
727 print OUT "</output>\n";
728 if ($cl->{"diff"}) {
729 print OUT "<diff>";
730 printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
731 print OUT "</diff>\n";
732 }
733 print OUT "</command>\n";
735 }
737 close(OUT);
738 }
740 sub print_session
741 {
742 my $output_filename = $_[0];
743 my $local_session_id = $_[1];
744 return if not defined($Sessions{$local_session_id});
746 print "printing session info. session id = ".$local_session_id."\n"
747 if $Config{verbose} =~ /y/;
749 open(OUT, ">>", $output_filename)
750 or die "Can't open $output_filename for writing\n";
751 print OUT "<session>\n";
752 my %session = %{$Sessions{$local_session_id}};
753 for my $key (keys %session) {
754 print OUT "<$key>".$session{$key}."</$key>\n";
755 print " ".$key,"\n";
756 }
757 print OUT "</session>\n";
758 close(OUT);
759 }
761 sub send_cache
762 {
763 # Если в кэше что-то накопилось,
764 # попытаемся отправить это на сервер
765 #
766 my $cache_was_sent=0;
768 if (open(CACHE, $Config{cache})) {
769 local $/;
770 my $cache = <CACHE>;
771 close(CACHE);
773 my $socket = IO::Socket::INET->new(
774 PeerAddr => $Config{backend_address},
775 PeerPort => $Config{backend_port},
776 proto => "tcp",
777 Type => SOCK_STREAM
778 );
780 if ($socket) {
781 print $socket $cache;
782 close($socket);
783 $cache_was_sent = 1;
784 }
785 }
786 return $cache_was_sent;
787 }
789 sub save_cache_stat
790 {
791 open (CACHE, ">$Config{cache_stat}");
792 for my $f (keys %Script_Files) {
793 print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
794 }
795 close(CACHE);
796 }
798 sub load_cache_stat
799 {
800 if (open (CACHE, "$Config{cache_stat}")) {
801 while(<CACHE>) {
802 chomp;
803 my ($f, $size, $tell) = split /\t/;
804 $Script_Files{$f}->{size} = $size;
805 $Script_Files{$f}->{tell} = $tell;
806 }
807 close(CACHE);
808 };
809 }
812 main();
814 sub process_was_killed
815 {
816 $Killed = 1;
817 }
819 sub main
820 {
822 $| = 1;
824 init_variables();
825 init_config();
828 if ($Config{"mode"} ne "daemon") {
830 # В нормальном режиме работы нужно
831 # считать скрипты, обработать их и записать
832 # результат выполнения в результирующий файл.
833 # После этого завершить работу.
835 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
836 load_diff_files($lab_log);
837 }
838 load_command_lines($Config{"input"}, $Config{"input_mask"});
839 sort_command_lines;
840 #process_command_lines;
841 print_command_lines($Config{"cache"});
842 }
843 else {
844 if (open(PIDFILE, $Config{agent_pidfile})) {
845 my $pid = <PIDFILE>;
846 close(PIDFILE);
847 if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
848 print "Removing stale pidfile\n";
849 unlink $Config{agent_pidfile}
850 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
851 }
852 elsif ($^O eq 'freebsd' && $pid && `ps axo uid,pid,command | grep '$<\\s*$pid\\s*$Config{"l3-agent"}' 2> /dev/null`) {
853 print "Removing stale pidfile\n";
854 unlink $Config{agent_pidfile}
855 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
856 }
857 elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
858 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
859 exit(0);
860 }
861 else {
862 print "Unknown operating system";
863 exit(0);
864 }
865 }
866 if ($Config{detach} =~ /^y/i) {
867 #$Config{verbose} = "no";
868 my $pid = fork;
869 exit if $pid;
870 die "Couldn't fork: $!" unless defined ($pid);
872 open(PIDFILE, ">", $Config{agent_pidfile})
873 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
874 print PIDFILE $$;
875 close(PIDFILE);
877 for my $handle (*STDIN, *STDOUT, *STDERR) {
878 open ($handle, "+<", "/dev/null")
879 or die "can't reopen $handle to /dev/null: $!"
880 }
882 POSIX::setsid()
883 or die "Can't start a new session: $!";
885 $0 = $Config{"l3-agent"};
887 $SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&process_was_killed;
888 }
889 while (not $Killed) {
890 @Command_Lines = ();
891 @Command_Lines_Index = ();
892 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
893 load_diff_files($lab_log);
894 }
895 load_cache_stat();
896 load_command_lines($Config{"input"}, $Config{"input_mask"});
897 if (@Command_Lines) {
898 sort_command_lines;
899 #process_command_lines;
900 print_command_lines($Config{"cache"});
901 }
902 save_cache_stat();
903 if (-e $Config{cache} && (stat($Config{cache}))[7]) {
904 send_cache() && unlink($Config{cache});
905 }
906 sleep($Config{"daemon_sleep_interval"} || 1);
907 }
909 unlink $Config{agent_pidfile};
910 }
912 }
914 sub init_variables
915 {
916 }