lilalo
view l3-agent @ 82:7fb205f2c514
Увеличено количество строк вывода при распознавании агентом
author | devi |
---|---|
date | Fri Feb 24 08:49:31 2006 +0200 (2006-02-24) |
parents | d28dda8ea18f |
children | bdc1f02d3f87 |
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"}));
130 print "diff of my session found\n";
132 next if ($diff->{"day"} && $cl->{"day"} && ($cl->{"day"} ne $diff->{"day"}));
134 my $dt;
135 if ($diff->{"time"} && $cl->{"time"}) {
136 $dt = $diff->{"time"} - $cl->{"time"}
137 }
138 else {
139 $dt=($diff->{"hour"}-$hour)*3600 +($diff->{"min"}-$min)*60 + ($diff->{"sec"}-$sec);
140 }
141 if ($dt >0
142 && $dt < $min_dt
143 && ($diff->{"time_range"} <0
144 || $dt < $diff->{"time_range"})) {
145 print "Approppriate diff found: dt=$dt\n";
146 if ($diff->{"bind_to"}) {
147 undef $diff->{"bind_to"}->{"diff"};
148 };
149 $diff->{"time_range"}=$dt;
150 $diff->{"bind_to"}=$cl;
152 $cl->{"diff"} = $diff_key;
153 $min_dt = $dt;
154 }
155 }
156 }
159 sub extract_commands_from_cline
160 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
161 # номер первого появление команды в строке:
162 # команда => первая позиция
163 {
164 my $cline = $_[0];
165 my @lists = split /\;/, $cline;
168 my @commands = ();
169 for my $list (@lists) {
170 push @commands, split /\|/, $list;
171 }
173 my %commands;
174 my %files;
175 my $i=0;
176 for my $command (@commands) {
177 $command =~ /\s*(\S+)\s*(.*)/;
178 if ($1 && $1 eq "sudo" ) {
179 $commands{"$1"}=$i++;
180 $command =~ s/\s*sudo\s+//;
181 }
182 $command =~ /\s*(\S+)\s*(.*)/;
183 if ($1 && !defined $commands{"$1"}) {
184 $commands{"$1"}=$i++;
185 };
186 }
187 return %commands;
188 }
190 sub load_command_lines
191 {
192 my $lab_scripts_path = $_[0];
193 my $lab_scripts_mask = $_[1];
195 my $cline_re_base = qq'
196 (
197 (?:\\^?([0-9]*C?)) # exitcode
198 (?:_([0-9]+)_)? # uid
199 (?:_([0-9]+)_) # pid
200 (...?) # day
201 (.?.?) # lab
202 \\s # space separator
203 ([0-9][0-9]):([0-9][0-9]):([0-9][0-9]) # time
204 .\\[50D.\\[K # killing symbols
205 (.*?([\$\#]\\s?)) # prompt
206 (.*) # command line
207 )
208 ';
209 my $cline_re = qr/$cline_re_base/sx;
210 my $cline_re2 = qr/$cline_re_base$/sx;
212 my $cline_re_v2_base = qq'
213 (
214 v2[\#] # version
215 ([0-9]+)[\#] # history line number
216 ([0-9]+)[\#] # exitcode
217 ([0-9]+)[\#] # uid
218 ([0-9]+)[\#] # pid
219 ([0-9]+)[\#] # time
220 (.*?)[\#] # pwd
221 .\\[1024D.\\[K # killing symbols
222 (.*?([\$\#]\\s?)) # prompt
223 (.*) # command line
224 )
225 ';
227 my $cline_re_v2 = qr/$cline_re_v2_base/sx;
228 my $cline_re2_v2 = qr/$cline_re_v2_base$/sx;
230 my $vt = Term::VT102->new ( 'cols' => $Config{"terminal_width"},
231 'rows' => $Config{"terminal_height"});
232 my $cline_vt = Term::VT102->new (
233 'cols' => $Config{"terminal_width"},
234 'rows' => $Config{"terminal_height"});
236 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8")
237 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i);
239 print "Parsing lab scripts...\n" if $Config{"verbose"} =~ /y/;
241 my $file;
242 my $skip_info;
244 my $commandlines_loaded =0;
245 my $commandlines_processed =0;
247 my @lab_scripts = <$lab_scripts_path/$lab_scripts_mask>;
248 for $file (@lab_scripts){
250 # Пропускаем файл, если он не изменялся со времени нашего предудущего прохода
251 my $size = (stat($file))[7];
252 next if ($Script_Files{$file} && $Script_Files{$file}->{size} && $Script_Files{$file}->{size} >= $size);
255 my $local_session_id;
256 # Начальное значение идентификатора текущего сеанса определяем из имени скрипта
257 # Впоследствии оно может быть уточнено
258 $file =~ m@.*/([^/]*)\.script$@;
259 $local_session_id = $1;
261 #Если файл только что появился,
262 #пытаемся найти и загрузить информацию о соответствующей ему сессии
263 if (!$Script_Files{$file}) {
264 my $session_file = $file;
265 $session_file =~ s/\.script/.info/;
266 if (open(SESSION, $session_file)) {
267 local $/;
268 my $data = <SESSION>;
269 close(SESSION);
271 for my $session_data ($data =~ m@<session>(.*?)</session>@sg) {
272 my %session;
273 while ($session_data =~ m@<([^>]*?)>(.*?)</\1>@sg) {
274 $session{$1} = $2;
275 }
276 $local_session_id = $session{"local_session_id"} if $session{"local_session_id"};
277 $Sessions{$local_session_id}=\%session;
278 }
280 #Загруженную информацию сразу же отправляем в поток
281 print_session($Config{cache}, $local_session_id);
282 }
283 }
285 open (FILE, "$file");
286 binmode FILE;
288 # Переходим к тому месту, где мы окончили разбор
289 seek (FILE, $Script_Files{$file}->{tell}, 0) if $Script_Files{$file}->{tell};
290 $Script_Files{$file}->{size} = $size;
291 $Script_Files{$file}->{tell} = 0 unless $Script_Files{$file}->{tell};
293 $file =~ m@.*/(.*?)-.*@;
295 print "\n+- processing file $file\n" if $Config{"verbose"} =~/y/;
297 my $tty = $1;
298 my $first_pass = 1;
299 my %cl;
300 my $last_output_length=0;
301 while (<FILE>) {
302 $commandlines_processed++;
304 next if s/^Script started on.*?\n//s;
306 if (/[0-9][0-9]:[0-9][0-9]:[0-9][0-9].\[[0-9][0-9]D.\[K/ && m/$cline_re/) {
307 s/.*\x0d(?!\x0a)//;
308 m/$cline_re2/gs;
310 $commandlines_loaded++;
311 $last_output_length=0;
313 # Previous command
314 my %last_cl = %cl;
315 my $err = $2 || "";
317 $cl{"local_session_id"} = $local_session_id;
318 # Parse new command
319 $cl{"uid"} = $3;
320 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
321 $cl{"pid"} = $4;
322 $cl{"day"} = $5;
323 $cl{"lab"} = $6;
324 $cl{"hour"} = $7;
325 $cl{"min"} = $8;
326 $cl{"sec"} = $9;
327 #$cl{"fullprompt"} = $10;
328 $cl{"prompt"} = $11;
329 $cl{"raw_cline"} = $12;
331 {
332 use bytes;
333 $cl{"raw_start"} = tell (FILE) - length($1);
334 $cl{"raw_output_start"} = tell FILE;
335 }
336 $cl{"raw_file"} = $file;
338 $cl{"err"} = 0;
339 $cl{"output"} = "";
340 $cl{"tty"} = $tty;
342 $cline_vt->process($cl{"raw_cline"}."\n");
343 $cl{"cline"} = $cline_vt->row_plaintext (1);
344 $cl{"cline"} =~ s/\s*$//;
345 $cline_vt->reset();
347 my %commands = extract_commands_from_cline($cl{"cline"});
348 #$cl{"euid"}=0 if defined $commands{"sudo"};
349 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
350 $cl{"last_command"} = $comms[$#comms] || "";
352 if (
353 $Config{"suppress_editors"} =~ /^y/i
354 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
355 || $Config{"suppress_pagers"} =~ /^y/i
356 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
357 || $Config{"suppress_terminal"}=~ /^y/i
358 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
359 ) {
360 $cl{"suppress_output"} = "1";
361 }
362 else {
363 $cl{"suppress_output"} = "0";
364 }
365 $skip_info = 0;
368 print " ",$cl{"last_command"};
370 # Processing previous command line
371 if ($first_pass) {
372 $first_pass = 0;
373 next;
374 }
376 # Error code
377 $last_cl{"raw_end"} = $cl{"raw_start"};
378 $last_cl{"err"}=$err;
379 $last_cl{"err"}=130 if $err eq "^C";
381 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
382 bind_diff(\%last_cl);
383 }
385 # Output
386 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
387 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
388 my $line= $vt->row_plaintext($i);
389 next if !defined ($line) ; #|| $line =~ /^\s*$/;
390 $line =~ s/\s*$//;
391 $line .= "\n" unless $line =~ /^\s*$/;
392 $last_cl{"output"} .= $line;
393 }
394 }
395 else {
396 $last_cl{"output"}= "";
397 }
399 $vt->reset();
402 # Save
403 if (!$Config{"lab"} || $cl{"lab"} eq $Config{"lab"}) {
404 # Changing encoding
405 for (keys %last_cl) {
406 next if /raw/;
407 $last_cl{$_} = $converter->convert($last_cl{$_})
408 if ($Config{"encoding"} &&
409 $Config{"encoding"} !~ /^utf-8$/i);
410 }
411 push @Command_Lines, \%last_cl;
413 # Сохранение позиции в файле, до которой выполнен
414 # успешный разбор
415 $Script_Files{$file}->{tell} = $last_cl{raw_end};
416 }
417 next;
418 }
421 elsif (m/$cline_re_v2/) {
424 # Разбираем командную строку версии 2
427 s/.*\x0d(?!\x0a)//;
428 m/$cline_re2_v2/gs;
430 $commandlines_loaded++;
431 $last_output_length=0;
433 # Previous command
434 my %last_cl = %cl;
436 $cl{"local_session_id"} = $local_session_id;
437 # Parse new command
438 $cl{"history"} = $2;
439 my $err = $3;
440 $cl{"uid"} = $4;
441 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
442 $cl{"pid"} = $5;
443 $cl{"time"} = $6;
444 $cl{"pwd"} = $7;
445 #$cl{"fullprompt"} = $8;
446 $cl{"prompt"} = $9;
447 $cl{"raw_cline"}= $10;
449 {
450 use bytes;
451 $cl{"raw_start"} = tell (FILE) - length($1);
452 $cl{"raw_output_start"} = tell FILE;
453 }
454 $cl{"raw_file"} = $file;
456 $cl{"err"} = 0;
457 $cl{"output"} = "";
458 #$cl{"tty"} = $tty;
460 $cline_vt->process($cl{"raw_cline"}."\n");
461 $cl{"cline"} = $cline_vt->row_plaintext (1);
462 $cl{"cline"} =~ s/\s*$//;
463 $cline_vt->reset();
465 my %commands = extract_commands_from_cline($cl{"cline"});
466 #$cl{"euid"} = 0 if defined $commands{"sudo"};
467 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
468 $cl{"last_command"}
469 = $comms[$#comms] || "";
471 if (
472 $Config{"suppress_editors"} =~ /^y/i
473 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
474 || $Config{"suppress_pagers"} =~ /^y/i
475 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
476 || $Config{"suppress_terminal"}=~ /^y/i
477 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
478 ) {
479 $cl{"suppress_output"} = "1";
480 }
481 else {
482 $cl{"suppress_output"} = "0";
483 }
484 $skip_info = 0;
487 if ($Config{verbose} =~ /y/i) {
488 print "\n| " if $commandlines_loaded % 15 == 1;
489 print " ",$cl{"last_command"};
490 }
492 # Processing previous command line
493 if ($first_pass) {
494 $first_pass = 0;
495 next;
496 }
498 # Error code
499 $last_cl{"err"}=$err;
500 $last_cl{"raw_end"} = $cl{"raw_start"};
502 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
503 bind_diff(\%last_cl);
504 }
506 # Output
507 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
508 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
509 my $line= $vt->row_plaintext($i);
510 next if !defined ($line) ; #|| $line =~ /^\s*$/;
511 $line =~ s/\s*$//;
512 $line .= "\n" unless $line =~ /^\s*$/;
513 $last_cl{"output"} .= $line;
514 }
515 }
516 else {
517 $last_cl{"output"}= "";
518 }
520 $vt->reset();
523 # Changing encoding
524 for (keys %last_cl) {
525 next if /raw/;
526 if ($Config{"encoding"} &&
527 $Config{"encoding"} !~ /^utf-8$/i) {
528 $last_cl{$_} = $converter->convert($last_cl{$_})
529 }
530 }
531 push @Command_Lines, \%last_cl;
533 # Сохранение позиции в файле, до которой выполнен
534 # успешный разбор
535 $Script_Files{$file}->{tell} = $last_cl{raw_end};
537 next;
539 }
541 # Иначе, это строка вывода
543 $last_output_length+=length($_);
544 #if (!$cl{"suppress_output"} || $last_output_length < 5000) {
545 if ($last_output_length < 50000) {
546 $vt->process("$_"."\n")
547 }
548 else
549 {
550 if (!$skip_info) {
551 print "($cl{last_command})";
552 $skip_info = 1;
553 }
554 }
555 }
556 close(FILE);
558 }
559 if ($Config{"verbose"} =~ /y/) {
560 print "\n`- finished.\n" ;
561 print "Lines loaded: $commandlines_processed\n";
562 print "Command lines: $commandlines_loaded\n";
563 }
564 }
569 sub sort_command_lines
570 {
571 print "Sorting command lines..." if $Config{"verbose"} =~ /y/;
573 # Sort Command_Lines
574 # Write Command_Lines to Command_Lines_Index
576 my @index;
577 for (my $i=0;$i<=$#Command_Lines;$i++) {
578 $index[$i]=$i;
579 }
581 @Command_Lines_Index = sort {
582 defined($Command_Lines[$index[$a]]->{"time"})
583 ? $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
584 : $Command_Lines[$index[$a]]->{"day"} cmp $Command_Lines[$index[$b]]->{"day"}
585 || $Command_Lines[$index[$a]]->{"hour"} <=> $Command_Lines[$index[$b]]->{"hour"}
586 || $Command_Lines[$index[$a]]->{"min"} <=> $Command_Lines[$index[$b]]->{"min"}
587 || $Command_Lines[$index[$a]]->{"sec"} <=> $Command_Lines[$index[$b]]->{"sec"}
588 } @index;
590 print "finished\n" if $Config{"verbose"} =~ /y/;
592 }
594 sub printq
595 {
596 my $TO = shift;
597 my $text = join "", @_;
598 $text =~ s/&/&/g;
599 $text =~ s/</</g;
600 $text =~ s/>/>/g;
601 print $TO $text;
602 }
605 =cut
606 Вывести результат обработки журнала.
607 =cut
609 sub print_command_lines
610 {
611 my $output_filename=$_[0];
612 my $mode = ">";
613 $mode =">>" if $Config{mode} eq "daemon";
614 open(OUT, $mode, $output_filename)
615 or die "Can't open $output_filename for writing\n";
618 my $cl;
619 my $in_range=0;
620 for my $i (@Command_Lines_Index) {
621 $cl = $Command_Lines[$i];
623 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
624 $in_range=1;
625 next;
626 }
627 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
628 $in_range=0;
629 next;
630 }
631 next if ($Config{"from"} && $Config{"to"} && !$in_range)
632 ||
633 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
634 ||
635 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
636 ||
637 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
639 # Вырезаем из вывода только нужное количество строк
641 my $output="";
643 if (!grep ($_ eq $cl->{"last_command"}, @{$Config{"full_output_commands"}})
644 && ($Config{"head_lines"}
645 || $Config{"tail_lines"})) {
646 # Partialy output
647 my @lines = split '\n', $cl->{"output"};
648 # head
649 my $mark=1;
650 for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
651 $output .= $lines[$i]."\n";
652 }
653 # tail
654 my $start=$#lines-$Config{"cache_tail_lines"}+1;
655 if ($start < 0) {
656 $start=0;
657 $mark=0;
658 }
659 if ($start < $Config{"cache_head_lines"}) {
660 $start=$Config{"cache_head_lines"};
661 $mark=0;
662 }
663 $output .= $Config{"skip_text"}."\n" if $mark;
664 for ($i=$start; $i<= $#lines; $i++) {
665 $output .= $lines[$i]."\n";
666 }
667 }
668 else {
669 # Full output
670 $output .= $cl->{"output"};
671 }
673 # Совместимость с labmaker
675 # Переводим в секунды Эпохи
676 # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
677 # Информация о годе отсутствовала
678 # Её можно внести:
679 # Декабрь 2004 год; остальные -- 2005 год.
681 my $year = 2005;
682 #$year = 2004 if ( $cl->{day} > 330 );
683 $year = $Config{year} if $Config{year};
684 # timelocal( $sec, $min, $hour, $mday,$mon,$year);
685 $cl->{time} ||= timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
688 # Начинаем вывод команды
689 print OUT "<command>\n";
690 for my $element (qw(
691 local_session_id
692 history
693 uid
694 pid
695 time
696 pwd
697 raw_start
698 raw_output_start
699 raw_end
700 raw_file
701 tty
702 err
703 last_command
704 history
705 )) {
706 next unless defined($cl->{"$element"});
707 print OUT "<$element>".$cl->{$element}."</$element>\n";
708 }
709 for my $element (qw(
710 prompt
711 cline
712 )) {
713 next unless defined($cl->{"$element"});
714 print OUT "<$element>";
715 printq(\*OUT,$cl->{"$element"});
716 print OUT "</$element>\n";
717 }
718 #note
719 #note_title
720 print OUT "<output>";
721 printq(\*OUT,$output);
722 print OUT "</output>\n";
723 if ($cl->{"diff"}) {
724 print OUT "<diff>";
725 printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
726 print OUT "</diff>\n";
727 }
728 print OUT "</command>\n";
730 }
732 close(OUT);
733 }
735 sub print_session
736 {
737 my $output_filename = $_[0];
738 my $local_session_id = $_[1];
739 return if not defined($Sessions{$local_session_id});
741 open(OUT, ">>", $output_filename)
742 or die "Can't open $output_filename for writing\n";
743 print OUT "<session>\n";
744 my %session = %{$Sessions{$local_session_id}};
745 for my $key (keys %session) {
746 print OUT "<$key>".$session{$key}."</$key>\n"
747 }
748 print OUT "</session>\n";
749 close(OUT);
750 }
752 sub send_cache
753 {
754 # Если в кэше что-то накопилось,
755 # попытаемся отправить это на сервер
756 #
757 my $cache_was_sent=0;
759 if (open(CACHE, $Config{cache})) {
760 local $/;
761 my $cache = <CACHE>;
762 close(CACHE);
764 my $socket = IO::Socket::INET->new(
765 PeerAddr => $Config{backend_address},
766 PeerPort => $Config{backend_port},
767 proto => "tcp",
768 Type => SOCK_STREAM
769 );
771 if ($socket) {
772 print $socket $cache;
773 close($socket);
774 $cache_was_sent = 1;
775 }
776 }
777 return $cache_was_sent;
778 }
780 sub save_cache_stat
781 {
782 open (CACHE, ">$Config{cache_stat}");
783 for my $f (keys %Script_Files) {
784 print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
785 }
786 close(CACHE);
787 }
789 sub load_cache_stat
790 {
791 if (open (CACHE, "$Config{cache_stat}")) {
792 while(<CACHE>) {
793 chomp;
794 my ($f, $size, $tell) = split /\t/;
795 $Script_Files{$f}->{size} = $size;
796 $Script_Files{$f}->{tell} = $tell;
797 }
798 close(CACHE);
799 };
800 }
803 main();
805 sub process_was_killed
806 {
807 $Killed = 1;
808 }
810 sub main
811 {
813 $| = 1;
815 init_variables();
816 init_config();
819 if ($Config{"mode"} ne "daemon") {
821 # В нормальном режиме работы нужно
822 # считать скрипты, обработать их и записать
823 # результат выполнения в результирующий файл.
824 # После этого завершить работу.
826 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
827 load_diff_files($lab_log);
828 }
829 load_command_lines($Config{"input"}, $Config{"input_mask"});
830 sort_command_lines;
831 #process_command_lines;
832 print_command_lines($Config{"cache"});
833 }
834 else {
835 if (open(PIDFILE, $Config{agent_pidfile})) {
836 my $pid = <PIDFILE>;
837 close(PIDFILE);
838 if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
839 print "Removing stale pidfile\n";
840 unlink $Config{agent_pidfile}
841 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
842 }
843 elsif ($^O eq 'freebsd' && $pid && `ps axo uid,pid,command | grep '$<\\s*$pid\\s*$Config{"l3-agent"}' 2> /dev/null`) {
844 print "Removing stale pidfile\n";
845 unlink $Config{agent_pidfile}
846 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
847 }
848 elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
849 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
850 exit(0);
851 }
852 else {
853 print "Unknown operating system";
854 exit(0);
855 }
856 }
857 if ($Config{detach} =~ /^y/i) {
858 #$Config{verbose} = "no";
859 my $pid = fork;
860 exit if $pid;
861 die "Couldn't fork: $!" unless defined ($pid);
863 open(PIDFILE, ">", $Config{agent_pidfile})
864 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
865 print PIDFILE $$;
866 close(PIDFILE);
868 for my $handle (*STDIN, *STDOUT, *STDERR) {
869 open ($handle, "+<", "/dev/null")
870 or die "can't reopen $handle to /dev/null: $!"
871 }
873 POSIX::setsid()
874 or die "Can't start a new session: $!";
876 $0 = $Config{"l3-agent"};
878 $SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&process_was_killed;
879 }
880 while (not $Killed) {
881 @Command_Lines = ();
882 @Command_Lines_Index = ();
883 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
884 load_diff_files($lab_log);
885 }
886 load_cache_stat();
887 load_command_lines($Config{"input"}, $Config{"input_mask"});
888 if (@Command_Lines) {
889 sort_command_lines;
890 #process_command_lines;
891 print_command_lines($Config{"cache"});
892 }
893 save_cache_stat();
894 if (-e $Config{cache} && (stat($Config{cache}))[7]) {
895 send_cache() && unlink($Config{cache});
896 }
897 sleep($Config{"daemon_sleep_interval"} || 1);
898 }
900 unlink $Config{agent_pidfile};
901 }
903 }
905 sub init_variables
906 {
907 }