lilalo

view l3-agent @ 118:73fb48eb8110

typo fixed
author igor
date Mon Mar 10 16:35:37 2008 +0200 (2008-03-10)
parents 658b4ea105c1
children 71bd999bcb04
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 "/etc/lilalo";
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 $cline_re_v3_base = qq'
230 (
231 v3[\#] # version
232 .*
233 )
234 ';
235 my $cline_re_v3 = qr/$cline_re_v3_base/sx;
237 my $cline_re2_v3_base = qq'
238 (
239 v3[\#] # version
240 ([0-9]+)[\#] # history line number
241 ([0-9]+)[\#] # exitcode
242 ([0-9]+)[\#] # uid
243 ([0-9]+)[\#] # pid
244 ([0-9]+)[\#] # time
245 (.*?)[\#] # pwd
246 (.*?([\$\#]\\s?)) # prompt
247 (.*) # command line
248 )
249 ';
250 my $cline_re2_v3 = qr/$cline_re2_v3_base$/sx;
253 my %vt; # Хэш виртуальных терминалов. По одному на каждый сеанс
254 my $cline_vt = Term::VT102->new (
255 'cols' => $Config{"terminal_width"},
256 'rows' => $Config{"terminal_height"});
258 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8")
259 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i);
261 print "Parsing lab scripts...\n" if $Config{"verbose"} =~ /y/;
263 my $file;
264 my $skip_info;
266 my $commandlines_loaded =0;
267 my $commandlines_processed =0;
269 my @lab_scripts = <$lab_scripts_path/$lab_scripts_mask>;
270 for $file (@lab_scripts){
272 # Пропускаем файл, если он не изменялся со времени нашего предудущего прохода
273 my $size = (stat($file))[7];
274 next if ($Script_Files{$file} && $Script_Files{$file}->{size} && $Script_Files{$file}->{size} >= $size);
277 my $local_session_id;
278 # Начальное значение идентификатора текущего сеанса определяем из имени скрипта
279 # Впоследствии оно может быть уточнено
280 $file =~ m@.*/([^/]*)\.script$@;
281 $local_session_id = $1;
283 if (not defined($vt{$local_session_id})) {
284 $vt{$local_session_id} = Term::VT102->new (
285 'cols' => $Config{"terminal_width"},
286 'rows' => $Config{"terminal_height"});
287 }
289 #Если файл только что появился,
290 #пытаемся найти и загрузить информацию о соответствующей ему сессии
291 if (!$Script_Files{$file}) {
292 my $session_file = $file;
293 $session_file =~ s/\.script/.info/;
294 if (open(SESSION, $session_file)) {
295 local $/;
296 my $data = <SESSION>;
297 close(SESSION);
299 for my $session_data ($data =~ m@<session>(.*?)</session>@sg) {
300 my %session;
301 while ($session_data =~ m@<([^>]*?)>(.*?)</\1>@sg) {
302 $session{$1} = $2;
303 }
304 $local_session_id = $session{"local_session_id"} if $session{"local_session_id"};
305 $Sessions{$local_session_id}=\%session;
306 }
308 #Загруженную информацию сразу же отправляем в поток
309 print_session($Config{cache}, $local_session_id);
310 }
311 else {
312 die "can't open session file";
313 }
314 }
316 open (FILE, "$file");
317 binmode FILE;
319 # Переходим к тому месту, где мы окончили разбор
320 seek (FILE, $Script_Files{$file}->{tell}, 0) if $Script_Files{$file}->{tell};
321 $Script_Files{$file}->{size} = $size;
322 $Script_Files{$file}->{tell} = 0 unless $Script_Files{$file}->{tell};
324 $file =~ m@.*/(.*?)-.*@;
326 print "\n+- processing file $file\n| "
327 if $Config{"verbose"} =~/y/;
329 my $tty = $1;
330 my $first_pass = 1;
331 my %cl;
332 my $last_output_length=0;
333 while (<FILE>) {
334 $commandlines_processed++;
336 next if s/^Script started on.*?\n//s;
338 if (/[0-9][0-9]:[0-9][0-9]:[0-9][0-9].\[[0-9][0-9]D.\[K/ && m/$cline_re/) {
339 s/.*\x0d(?!\x0a)//;
340 m/$cline_re2/gs;
342 $commandlines_loaded++;
343 $last_output_length=0;
345 # Previous command
346 my %last_cl = %cl;
347 my $err = $2 || "";
349 $cl{"local_session_id"} = $local_session_id;
350 # Parse new command
351 $cl{"uid"} = $3;
352 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
353 $cl{"pid"} = $4;
354 $cl{"day"} = $5;
355 $cl{"lab"} = $6;
356 $cl{"hour"} = $7;
357 $cl{"min"} = $8;
358 $cl{"sec"} = $9;
359 #$cl{"fullprompt"} = $10;
360 $cl{"prompt"} = $11;
361 $cl{"raw_cline"} = $12;
363 {
364 use bytes;
365 $cl{"raw_start"} = tell (FILE) - length($1);
366 $cl{"raw_output_start"} = tell FILE;
367 }
368 $cl{"raw_file"} = $file;
370 $cl{"err"} = 0;
371 $cl{"output"} = "";
372 $cl{"tty"} = $tty;
374 $cline_vt->process($cl{"raw_cline"}."\n");
375 $cl{"cline"} = $cline_vt->row_plaintext (1);
376 $cl{"cline"} =~ s/\s*$//;
377 $cline_vt->reset();
379 my %commands = extract_commands_from_cline($cl{"cline"});
380 #$cl{"euid"}=0 if defined $commands{"sudo"};
381 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
382 $cl{"last_command"} = $comms[$#comms] || "";
384 if (
385 $Config{"suppress_editors"} =~ /^y/i
386 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
387 || $Config{"suppress_pagers"} =~ /^y/i
388 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
389 || $Config{"suppress_terminal"}=~ /^y/i
390 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
391 ) {
392 $cl{"suppress_output"} = "1";
393 }
394 else {
395 $cl{"suppress_output"} = "0";
396 }
397 $skip_info = 0;
400 print " ",$cl{"last_command"};
402 # Processing previous command line
403 if ($first_pass) {
404 $first_pass = 0;
405 next;
406 }
408 # Error code
409 $last_cl{"raw_end"} = $cl{"raw_start"};
410 $last_cl{"err"}=$err;
411 $last_cl{"err"}=130 if $err eq "^C";
413 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
414 bind_diff(\%last_cl);
415 }
417 # Output
418 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
419 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
420 my $line= $vt{$local_session_id}->row_plaintext($i);
421 next if !defined ($line) ; #|| $line =~ /^\s*$/;
422 $line =~ s/\s*$//;
423 $line .= "\n" unless $line =~ /^\s*$/;
424 $last_cl{"output"} .= $line;
425 }
426 }
427 else {
428 $last_cl{"output"}= "";
429 }
431 $vt{$local_session_id}->reset();
434 # Save
435 if (!$Config{"lab"} || $cl{"lab"} eq $Config{"lab"}) {
436 # Changing encoding
437 for (keys %last_cl) {
438 next if /raw/;
439 $last_cl{$_} = $converter->convert($last_cl{$_})
440 if ($Config{"encoding"} &&
441 $Config{"encoding"} !~ /^utf-8$/i);
442 }
443 push @Command_Lines, \%last_cl;
445 # Сохранение позиции в файле, до которой выполнен
446 # успешный разбор
447 $Script_Files{$file}->{tell} = $last_cl{raw_end};
448 }
449 next;
450 }
452 elsif (m/$cline_re_v2/ || m/$cline_re_v3/) {
453 # Разбираем командную строку версии 2
455 s/.*\x0d(?!\x0a)//;
456 my $re;
457 if (m/$cline_re_v2/) {
458 $re=$cline_re2_v2;
459 }
460 else {
461 s/.\[1K.\[10D//gs;
462 $re=$cline_re2_v3;
463 }
464 m/$re/gs;
466 $commandlines_loaded++;
467 $last_output_length=0;
469 # Previous command
470 my %last_cl = %cl;
472 $cl{"local_session_id"} = $local_session_id;
473 # Parse new command
474 $cl{"history"} = $2;
475 my $err = $3;
476 $cl{"uid"} = $4;
477 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
478 $cl{"pid"} = $5;
479 $cl{"time"} = $6;
480 $cl{"pwd"} = $7;
481 #$cl{"fullprompt"} = $8;
482 $cl{"prompt"} = $9;
483 $cl{"raw_cline"}= $10;
485 {
486 use bytes;
487 $cl{"raw_start"} = tell (FILE) - length($1);
488 $cl{"raw_output_start"} = tell FILE;
489 }
490 $cl{"raw_file"} = $file;
492 $cl{"err"} = 0;
493 $cl{"output"} = "";
494 #$cl{"tty"} = $tty;
496 $cline_vt->process($cl{"raw_cline"}."\n");
497 $cl{"cline"} = $cline_vt->row_plaintext (1);
498 $cl{"cline"} =~ s/\s*$//;
499 $cline_vt->reset();
501 my %commands = extract_commands_from_cline($cl{"cline"});
502 #$cl{"euid"} = 0 if defined $commands{"sudo"};
503 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
504 $cl{"last_command"}
505 = $comms[$#comms] || "";
507 if (
508 $Config{"suppress_editors"} =~ /^y/i
509 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
510 || $Config{"suppress_pagers"} =~ /^y/i
511 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
512 || $Config{"suppress_terminal"}=~ /^y/i
513 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
514 ) {
515 $cl{"suppress_output"} = "1";
516 }
517 else {
518 $cl{"suppress_output"} = "0";
519 }
520 $skip_info = 0;
523 if ($Config{verbose} =~ /y/i) {
524 print "\n| " if $commandlines_loaded % 5 == 1;
525 print " ",$cl{"last_command"};
526 }
528 # Processing previous command line
529 if ($first_pass) {
530 $first_pass = 0;
531 next;
532 }
534 # Error code
535 $last_cl{"err"}=$err;
536 $last_cl{"raw_end"} = $cl{"raw_start"};
538 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
539 bind_diff(\%last_cl);
540 }
542 # Output
543 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
544 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
545 my $line= $vt{$local_session_id}->row_plaintext($i);
546 next if !defined ($line) ; #|| $line =~ /^\s*$/;
547 $line =~ s/\s*$//;
548 $line .= "\n" unless $line =~ /^\s*$/;
549 $last_cl{"output"} .= $line;
550 }
551 }
552 else {
553 $last_cl{"output"}= "";
554 }
556 $vt{$local_session_id}->reset();
559 # Changing encoding
560 for (keys %last_cl) {
561 next if /raw/;
562 if ($Config{"encoding"} &&
563 $Config{"encoding"} !~ /^utf-8$/i) {
564 $last_cl{$_} = $converter->convert($last_cl{$_})
565 }
566 }
567 push @Command_Lines, \%last_cl;
569 # Сохранение позиции в файле, до которой выполнен
570 # успешный разбор
571 $Script_Files{$file}->{tell} = $last_cl{raw_end};
573 next;
575 }
577 # Иначе, это строка вывода
579 $last_output_length+=length($_);
580 #if (!$cl{"suppress_output"} || $last_output_length < 5000) {
581 if ($last_output_length < 50000) {
582 $vt{$local_session_id}->process("$_"."\n")
583 }
584 else
585 {
586 if (!$skip_info) {
587 print "($cl{last_command})";
588 $skip_info = 1;
589 }
590 }
591 }
592 close(FILE);
594 }
595 if ($Config{"verbose"} =~ /y/) {
596 print "\n`- finished.\n" ;
597 print "Lines loaded: $commandlines_processed\n";
598 print "Command lines: $commandlines_loaded\n";
599 }
600 }
605 sub sort_command_lines
606 {
607 print "Sorting command lines..." if $Config{"verbose"} =~ /y/;
609 # Sort Command_Lines
610 # Write Command_Lines to Command_Lines_Index
612 my @index;
613 for (my $i=0;$i<=$#Command_Lines;$i++) {
614 $index[$i]=$i;
615 }
617 @Command_Lines_Index = sort {
618 defined($Command_Lines[$index[$a]]->{"time"})
619 && defined($Command_Lines[$index[$b]]->{"time"})
620 ? $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
621 : defined($Command_Lines[$index[$a]]->{"day"})
622 && defined($Command_Lines[$index[$b]]->{"day"})
623 && defined($Command_Lines[$index[$a]]->{"hour"})
624 && defined($Command_Lines[$index[$b]]->{"hour"})
625 && defined($Command_Lines[$index[$a]]->{"min"})
626 && defined($Command_Lines[$index[$b]]->{"min"})
627 && defined($Command_Lines[$index[$a]]->{"sec"})
628 && defined($Command_Lines[$index[$b]]->{"sec"})
629 ? $Command_Lines[$index[$a]]->{"day"} cmp $Command_Lines[$index[$b]]->{"day"}
630 || $Command_Lines[$index[$a]]->{"hour"} <=> $Command_Lines[$index[$b]]->{"hour"}
631 || $Command_Lines[$index[$a]]->{"min"} <=> $Command_Lines[$index[$b]]->{"min"}
632 || $Command_Lines[$index[$a]]->{"sec"} <=> $Command_Lines[$index[$b]]->{"sec"}
633 : 0
634 } @index;
636 print "finished\n" if $Config{"verbose"} =~ /y/;
638 }
640 sub printq
641 {
642 my $TO = shift;
643 my $text = join "", @_;
644 $text =~ s/&/&amp;/g;
645 $text =~ s/</&lt;/g;
646 $text =~ s/>/&gt;/g;
647 print $TO $text;
648 }
651 =cut
652 Вывести результат обработки журнала.
653 =cut
655 sub print_command_lines
656 {
657 my $output_filename=$_[0];
658 open(OUT, ">>", $output_filename)
659 or die "Can't open $output_filename for writing\n";
662 my $cl;
663 my $in_range=0;
664 for my $i (@Command_Lines_Index) {
665 $cl = $Command_Lines[$i];
667 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
668 $in_range=1;
669 next;
670 }
671 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
672 $in_range=0;
673 next;
674 }
675 next if ($Config{"from"} && $Config{"to"} && !$in_range)
676 ||
677 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
678 ||
679 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
680 ||
681 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
683 # Вырезаем из вывода только нужное количество строк
685 my $output="";
687 if (!grep ($_ eq $cl->{"last_command"}, @{$Config{"full_output_commands"}})
688 && ($Config{"head_lines"}
689 || $Config{"tail_lines"})) {
690 # Partialy output
691 my @lines = split '\n', $cl->{"output"};
692 # head
693 my $mark=1;
694 for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
695 $output .= $lines[$i]."\n";
696 }
697 # tail
698 my $start=$#lines-$Config{"cache_tail_lines"}+1;
699 if ($start < 0) {
700 $start=0;
701 $mark=0;
702 }
703 if ($start < $Config{"cache_head_lines"}) {
704 $start=$Config{"cache_head_lines"};
705 $mark=0;
706 }
707 $output .= $Config{"skip_text"}."\n" if $mark;
708 for ($i=$start; $i<= $#lines; $i++) {
709 $output .= $lines[$i]."\n";
710 }
711 }
712 else {
713 # Full output
714 $output .= $cl->{"output"};
715 }
717 # Совместимость с labmaker
719 # Переводим в секунды Эпохи
720 # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
721 # Информация о годе отсутствовала
722 # Её можно внести:
723 # Декабрь 2004 год; остальные -- 2005 год.
725 my $year = 2005;
726 #$year = 2004 if ( $cl->{day} > 330 );
727 $year = $Config{year} if $Config{year};
728 # timelocal( $sec, $min, $hour, $mday,$mon,$year);
729 $cl->{time} ||= timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
732 # Начинаем вывод команды
733 print OUT "<command>\n";
734 print OUT "<l3cd>$Config{l3cd}</l3cd>\n" if $Config{"l3cd"};
735 for my $element (qw(
736 local_session_id
737 history
738 uid
739 pid
740 time
741 pwd
742 raw_start
743 raw_output_start
744 raw_end
745 raw_file
746 tty
747 err
748 last_command
749 history
750 )) {
751 next unless defined($cl->{"$element"});
752 print OUT "<$element>".$cl->{$element}."</$element>\n";
753 }
754 for my $element (qw(
755 prompt
756 cline
757 )) {
758 next unless defined($cl->{"$element"});
759 print OUT "<$element>";
760 printq(\*OUT,$cl->{"$element"});
761 print OUT "</$element>\n";
762 }
763 #note
764 #note_title
765 print OUT "<output>";
766 printq(\*OUT,$output);
767 print OUT "</output>\n";
768 if ($cl->{"diff"}) {
769 print OUT "<diff>";
770 printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
771 print OUT "</diff>\n";
772 }
773 print OUT "</command>\n";
775 }
777 close(OUT);
778 }
780 sub print_session
781 {
782 my $output_filename = $_[0];
783 my $local_session_id = $_[1];
784 return if not defined($Sessions{$local_session_id});
786 print "printing session info. session id = ".$local_session_id."\n"
787 if $Config{verbose} =~ /y/;
789 open(OUT, ">>", $output_filename)
790 or die "Can't open $output_filename for writing\n";
791 print OUT "<session>\n";
792 print OUT "<l3cd>$Config{l3cd}</l3cd>\n" if $Config{"l3cd"};
793 my %session = %{$Sessions{$local_session_id}};
794 for my $key (keys %session) {
795 print OUT "<$key>".$session{$key}."</$key>\n";
796 print " ".$key,"\n";
797 }
798 print OUT "</session>\n";
799 close(OUT);
800 }
802 sub send_cache
803 {
804 # Если в кэше что-то накопилось,
805 # попытаемся отправить это на сервер
806 #
807 my $cache_was_sent=0;
809 if (open(CACHE, $Config{cache})) {
810 local $/;
811 my $cache = <CACHE>;
812 close(CACHE);
814 my $socket = IO::Socket::INET->new(
815 PeerAddr => $Config{backend_address},
816 PeerPort => $Config{backend_port},
817 proto => "tcp",
818 Type => SOCK_STREAM
819 );
821 if ($socket) {
822 print $socket $cache;
823 close($socket);
824 $cache_was_sent = 1;
825 }
826 }
827 return $cache_was_sent;
828 }
830 sub save_cache_stat
831 {
832 open (CACHE, ">$Config{cache_stat}");
833 for my $f (keys %Script_Files) {
834 print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
835 }
836 close(CACHE);
837 }
839 sub load_cache_stat
840 {
841 if (open (CACHE, "$Config{cache_stat}")) {
842 while(<CACHE>) {
843 chomp;
844 my ($f, $size, $tell) = split /\t/;
845 $Script_Files{$f}->{size} = $size;
846 $Script_Files{$f}->{tell} = $tell;
847 }
848 close(CACHE);
849 };
850 }
853 main();
855 sub process_was_killed
856 {
857 $Killed = 1;
858 }
860 sub reload
861 {
862 init_config;
863 }
865 sub main
866 {
868 $| = 1;
870 init_variables();
871 init_config();
874 if ($Config{"mode"} ne "daemon") {
876 # В нормальном режиме работы нужно
877 # считать скрипты, обработать их и записать
878 # результат выполнения в результирующий файл.
879 # После этого завершить работу.
881 # Очистим кэш-файл, если он существовал
882 if (open (CACHE, ">", $Config{"cache"})) {
883 close(CACHE);
884 };
885 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
886 load_diff_files($lab_log);
887 }
888 load_command_lines($Config{"input"}, $Config{"input_mask"});
889 sort_command_lines;
890 #process_command_lines;
891 print_command_lines($Config{"cache"});
892 }
893 else {
894 if (open(PIDFILE, $Config{agent_pidfile})) {
895 my $pid = <PIDFILE>;
896 close(PIDFILE);
897 if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
898 print "Removing stale pidfile\n";
899 unlink $Config{agent_pidfile}
900 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
901 }
902 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`) {
903 print "Removing stale pidfile\n";
904 unlink $Config{agent_pidfile}
905 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
906 }
907 elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
908 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
909 exit(0);
910 }
911 else {
912 print "Unknown operating system";
913 exit(0);
914 }
915 }
916 if ($Config{detach} =~ /^y/i) {
917 #$Config{verbose} = "no";
918 my $pid = fork;
919 exit if $pid;
920 die "Couldn't fork: $!" unless defined ($pid);
922 open(PIDFILE, ">", $Config{agent_pidfile})
923 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
924 print PIDFILE $$;
925 close(PIDFILE);
927 for my $handle (*STDIN, *STDOUT, *STDERR) {
928 open ($handle, "+<", "/dev/null")
929 or die "can't reopen $handle to /dev/null: $!"
930 }
932 POSIX::setsid()
933 or die "Can't start a new session: $!";
935 $0 = $Config{"l3-agent"};
937 $SIG{INT} = $SIG{TERM} = \&process_was_killed;
938 $SIG{HUP} = \&reload;
940 }
941 while (not $Killed) {
942 @Command_Lines = ();
943 @Command_Lines_Index = ();
944 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
945 load_diff_files($lab_log);
946 }
947 load_cache_stat();
948 load_command_lines($Config{"input"}, $Config{"input_mask"});
949 if (@Command_Lines) {
950 sort_command_lines;
951 #process_command_lines;
952 print_command_lines($Config{"cache"});
953 }
954 save_cache_stat();
955 if (-e $Config{cache} && (stat($Config{cache}))[7]) {
956 send_cache() && unlink($Config{cache});
957 }
958 sleep($Config{"daemon_sleep_interval"} || 1);
959 }
961 unlink $Config{agent_pidfile};
962 }
964 }
966 sub init_variables
967 {
968 }