lilalo

view l3-agent @ 114:658b4ea105c1

PS1 bug fixed
author igor
date Sun Mar 09 02:38:56 2008 +0200 (2008-03-09)
parents 0d49f33696b3
children 9e6359b7ad55
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 $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;
254 my $vt = Term::VT102->new ( 'cols' => $Config{"terminal_width"},
255 'rows' => $Config{"terminal_height"});
256 my $cline_vt = Term::VT102->new (
257 'cols' => $Config{"terminal_width"},
258 'rows' => $Config{"terminal_height"});
260 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8")
261 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i);
263 print "Parsing lab scripts...\n" if $Config{"verbose"} =~ /y/;
265 my $file;
266 my $skip_info;
268 my $commandlines_loaded =0;
269 my $commandlines_processed =0;
271 my @lab_scripts = <$lab_scripts_path/$lab_scripts_mask>;
272 for $file (@lab_scripts){
274 # Пропускаем файл, если он не изменялся со времени нашего предудущего прохода
275 my $size = (stat($file))[7];
276 next if ($Script_Files{$file} && $Script_Files{$file}->{size} && $Script_Files{$file}->{size} >= $size);
279 my $local_session_id;
280 # Начальное значение идентификатора текущего сеанса определяем из имени скрипта
281 # Впоследствии оно может быть уточнено
282 $file =~ m@.*/([^/]*)\.script$@;
283 $local_session_id = $1;
285 #Если файл только что появился,
286 #пытаемся найти и загрузить информацию о соответствующей ему сессии
287 if (!$Script_Files{$file}) {
288 my $session_file = $file;
289 $session_file =~ s/\.script/.info/;
290 if (open(SESSION, $session_file)) {
291 local $/;
292 my $data = <SESSION>;
293 close(SESSION);
295 for my $session_data ($data =~ m@<session>(.*?)</session>@sg) {
296 my %session;
297 while ($session_data =~ m@<([^>]*?)>(.*?)</\1>@sg) {
298 $session{$1} = $2;
299 }
300 $local_session_id = $session{"local_session_id"} if $session{"local_session_id"};
301 $Sessions{$local_session_id}=\%session;
302 }
304 #Загруженную информацию сразу же отправляем в поток
305 print_session($Config{cache}, $local_session_id);
306 }
307 else {
308 die "can't open session file";
309 }
310 }
312 open (FILE, "$file");
313 binmode FILE;
315 # Переходим к тому месту, где мы окончили разбор
316 seek (FILE, $Script_Files{$file}->{tell}, 0) if $Script_Files{$file}->{tell};
317 $Script_Files{$file}->{size} = $size;
318 $Script_Files{$file}->{tell} = 0 unless $Script_Files{$file}->{tell};
320 $file =~ m@.*/(.*?)-.*@;
322 print "\n+- processing file $file\n| "
323 if $Config{"verbose"} =~/y/;
325 my $tty = $1;
326 my $first_pass = 1;
327 my %cl;
328 my $last_output_length=0;
329 while (<FILE>) {
330 $commandlines_processed++;
332 next if s/^Script started on.*?\n//s;
334 if (/[0-9][0-9]:[0-9][0-9]:[0-9][0-9].\[[0-9][0-9]D.\[K/ && m/$cline_re/) {
335 s/.*\x0d(?!\x0a)//;
336 m/$cline_re2/gs;
338 $commandlines_loaded++;
339 $last_output_length=0;
341 # Previous command
342 my %last_cl = %cl;
343 my $err = $2 || "";
345 $cl{"local_session_id"} = $local_session_id;
346 # Parse new command
347 $cl{"uid"} = $3;
348 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
349 $cl{"pid"} = $4;
350 $cl{"day"} = $5;
351 $cl{"lab"} = $6;
352 $cl{"hour"} = $7;
353 $cl{"min"} = $8;
354 $cl{"sec"} = $9;
355 #$cl{"fullprompt"} = $10;
356 $cl{"prompt"} = $11;
357 $cl{"raw_cline"} = $12;
359 {
360 use bytes;
361 $cl{"raw_start"} = tell (FILE) - length($1);
362 $cl{"raw_output_start"} = tell FILE;
363 }
364 $cl{"raw_file"} = $file;
366 $cl{"err"} = 0;
367 $cl{"output"} = "";
368 $cl{"tty"} = $tty;
370 $cline_vt->process($cl{"raw_cline"}."\n");
371 $cl{"cline"} = $cline_vt->row_plaintext (1);
372 $cl{"cline"} =~ s/\s*$//;
373 $cline_vt->reset();
375 my %commands = extract_commands_from_cline($cl{"cline"});
376 #$cl{"euid"}=0 if defined $commands{"sudo"};
377 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
378 $cl{"last_command"} = $comms[$#comms] || "";
380 if (
381 $Config{"suppress_editors"} =~ /^y/i
382 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
383 || $Config{"suppress_pagers"} =~ /^y/i
384 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
385 || $Config{"suppress_terminal"}=~ /^y/i
386 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
387 ) {
388 $cl{"suppress_output"} = "1";
389 }
390 else {
391 $cl{"suppress_output"} = "0";
392 }
393 $skip_info = 0;
396 print " ",$cl{"last_command"};
398 # Processing previous command line
399 if ($first_pass) {
400 $first_pass = 0;
401 next;
402 }
404 # Error code
405 $last_cl{"raw_end"} = $cl{"raw_start"};
406 $last_cl{"err"}=$err;
407 $last_cl{"err"}=130 if $err eq "^C";
409 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
410 bind_diff(\%last_cl);
411 }
413 # Output
414 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
415 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
416 my $line= $vt->row_plaintext($i);
417 next if !defined ($line) ; #|| $line =~ /^\s*$/;
418 $line =~ s/\s*$//;
419 $line .= "\n" unless $line =~ /^\s*$/;
420 $last_cl{"output"} .= $line;
421 }
422 }
423 else {
424 $last_cl{"output"}= "";
425 }
427 $vt->reset();
430 # Save
431 if (!$Config{"lab"} || $cl{"lab"} eq $Config{"lab"}) {
432 # Changing encoding
433 for (keys %last_cl) {
434 next if /raw/;
435 $last_cl{$_} = $converter->convert($last_cl{$_})
436 if ($Config{"encoding"} &&
437 $Config{"encoding"} !~ /^utf-8$/i);
438 }
439 push @Command_Lines, \%last_cl;
441 # Сохранение позиции в файле, до которой выполнен
442 # успешный разбор
443 $Script_Files{$file}->{tell} = $last_cl{raw_end};
444 }
445 next;
446 }
448 elsif (m/$cline_re_v2/ || m/$cline_re_v3/) {
449 # Разбираем командную строку версии 2
451 s/.*\x0d(?!\x0a)//;
452 my $re;
453 if (m/$cline_re_v2/) {
454 $re=$cline_re2_v2;
455 }
456 else {
457 s/.\[1K.\[10D//gs;
458 $re=$cline_re2_v3;
459 }
460 m/$re/gs;
462 $commandlines_loaded++;
463 $last_output_length=0;
465 # Previous command
466 my %last_cl = %cl;
468 $cl{"local_session_id"} = $local_session_id;
469 # Parse new command
470 $cl{"history"} = $2;
471 my $err = $3;
472 $cl{"uid"} = $4;
473 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
474 $cl{"pid"} = $5;
475 $cl{"time"} = $6;
476 $cl{"pwd"} = $7;
477 #$cl{"fullprompt"} = $8;
478 $cl{"prompt"} = $9;
479 $cl{"raw_cline"}= $10;
481 {
482 use bytes;
483 $cl{"raw_start"} = tell (FILE) - length($1);
484 $cl{"raw_output_start"} = tell FILE;
485 }
486 $cl{"raw_file"} = $file;
488 $cl{"err"} = 0;
489 $cl{"output"} = "";
490 #$cl{"tty"} = $tty;
492 $cline_vt->process($cl{"raw_cline"}."\n");
493 $cl{"cline"} = $cline_vt->row_plaintext (1);
494 $cl{"cline"} =~ s/\s*$//;
495 $cline_vt->reset();
497 my %commands = extract_commands_from_cline($cl{"cline"});
498 #$cl{"euid"} = 0 if defined $commands{"sudo"};
499 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
500 $cl{"last_command"}
501 = $comms[$#comms] || "";
503 if (
504 $Config{"suppress_editors"} =~ /^y/i
505 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
506 || $Config{"suppress_pagers"} =~ /^y/i
507 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
508 || $Config{"suppress_terminal"}=~ /^y/i
509 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
510 ) {
511 $cl{"suppress_output"} = "1";
512 }
513 else {
514 $cl{"suppress_output"} = "0";
515 }
516 $skip_info = 0;
519 if ($Config{verbose} =~ /y/i) {
520 print "\n| " if $commandlines_loaded % 5 == 1;
521 print " ",$cl{"last_command"};
522 }
524 # Processing previous command line
525 if ($first_pass) {
526 $first_pass = 0;
527 next;
528 }
530 # Error code
531 $last_cl{"err"}=$err;
532 $last_cl{"raw_end"} = $cl{"raw_start"};
534 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
535 bind_diff(\%last_cl);
536 }
538 # Output
539 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
540 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
541 my $line= $vt->row_plaintext($i);
542 next if !defined ($line) ; #|| $line =~ /^\s*$/;
543 $line =~ s/\s*$//;
544 $line .= "\n" unless $line =~ /^\s*$/;
545 $last_cl{"output"} .= $line;
546 }
547 }
548 else {
549 $last_cl{"output"}= "";
550 }
552 $vt->reset();
555 # Changing encoding
556 for (keys %last_cl) {
557 next if /raw/;
558 if ($Config{"encoding"} &&
559 $Config{"encoding"} !~ /^utf-8$/i) {
560 $last_cl{$_} = $converter->convert($last_cl{$_})
561 }
562 }
563 push @Command_Lines, \%last_cl;
565 # Сохранение позиции в файле, до которой выполнен
566 # успешный разбор
567 $Script_Files{$file}->{tell} = $last_cl{raw_end};
569 next;
571 }
573 # Иначе, это строка вывода
575 $last_output_length+=length($_);
576 #if (!$cl{"suppress_output"} || $last_output_length < 5000) {
577 if ($last_output_length < 50000) {
578 $vt->process("$_"."\n")
579 }
580 else
581 {
582 if (!$skip_info) {
583 print "($cl{last_command})";
584 $skip_info = 1;
585 }
586 }
587 }
588 close(FILE);
590 }
591 if ($Config{"verbose"} =~ /y/) {
592 print "\n`- finished.\n" ;
593 print "Lines loaded: $commandlines_processed\n";
594 print "Command lines: $commandlines_loaded\n";
595 }
596 }
601 sub sort_command_lines
602 {
603 print "Sorting command lines..." if $Config{"verbose"} =~ /y/;
605 # Sort Command_Lines
606 # Write Command_Lines to Command_Lines_Index
608 my @index;
609 for (my $i=0;$i<=$#Command_Lines;$i++) {
610 $index[$i]=$i;
611 }
613 @Command_Lines_Index = sort {
614 defined($Command_Lines[$index[$a]]->{"time"})
615 && defined($Command_Lines[$index[$b]]->{"time"})
616 ? $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
617 : defined($Command_Lines[$index[$a]]->{"day"})
618 && defined($Command_Lines[$index[$b]]->{"day"})
619 && defined($Command_Lines[$index[$a]]->{"hour"})
620 && defined($Command_Lines[$index[$b]]->{"hour"})
621 && defined($Command_Lines[$index[$a]]->{"min"})
622 && defined($Command_Lines[$index[$b]]->{"min"})
623 && defined($Command_Lines[$index[$a]]->{"sec"})
624 && defined($Command_Lines[$index[$b]]->{"sec"})
625 ? $Command_Lines[$index[$a]]->{"day"} cmp $Command_Lines[$index[$b]]->{"day"}
626 || $Command_Lines[$index[$a]]->{"hour"} <=> $Command_Lines[$index[$b]]->{"hour"}
627 || $Command_Lines[$index[$a]]->{"min"} <=> $Command_Lines[$index[$b]]->{"min"}
628 || $Command_Lines[$index[$a]]->{"sec"} <=> $Command_Lines[$index[$b]]->{"sec"}
629 : 0
630 } @index;
632 print "finished\n" if $Config{"verbose"} =~ /y/;
634 }
636 sub printq
637 {
638 my $TO = shift;
639 my $text = join "", @_;
640 $text =~ s/&/&amp;/g;
641 $text =~ s/</&lt;/g;
642 $text =~ s/>/&gt;/g;
643 print $TO $text;
644 }
647 =cut
648 Вывести результат обработки журнала.
649 =cut
651 sub print_command_lines
652 {
653 my $output_filename=$_[0];
654 open(OUT, ">>", $output_filename)
655 or die "Can't open $output_filename for writing\n";
658 my $cl;
659 my $in_range=0;
660 for my $i (@Command_Lines_Index) {
661 $cl = $Command_Lines[$i];
663 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
664 $in_range=1;
665 next;
666 }
667 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
668 $in_range=0;
669 next;
670 }
671 next if ($Config{"from"} && $Config{"to"} && !$in_range)
672 ||
673 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
674 ||
675 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
676 ||
677 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
679 # Вырезаем из вывода только нужное количество строк
681 my $output="";
683 if (!grep ($_ eq $cl->{"last_command"}, @{$Config{"full_output_commands"}})
684 && ($Config{"head_lines"}
685 || $Config{"tail_lines"})) {
686 # Partialy output
687 my @lines = split '\n', $cl->{"output"};
688 # head
689 my $mark=1;
690 for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
691 $output .= $lines[$i]."\n";
692 }
693 # tail
694 my $start=$#lines-$Config{"cache_tail_lines"}+1;
695 if ($start < 0) {
696 $start=0;
697 $mark=0;
698 }
699 if ($start < $Config{"cache_head_lines"}) {
700 $start=$Config{"cache_head_lines"};
701 $mark=0;
702 }
703 $output .= $Config{"skip_text"}."\n" if $mark;
704 for ($i=$start; $i<= $#lines; $i++) {
705 $output .= $lines[$i]."\n";
706 }
707 }
708 else {
709 # Full output
710 $output .= $cl->{"output"};
711 }
713 # Совместимость с labmaker
715 # Переводим в секунды Эпохи
716 # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
717 # Информация о годе отсутствовала
718 # Её можно внести:
719 # Декабрь 2004 год; остальные -- 2005 год.
721 my $year = 2005;
722 #$year = 2004 if ( $cl->{day} > 330 );
723 $year = $Config{year} if $Config{year};
724 # timelocal( $sec, $min, $hour, $mday,$mon,$year);
725 $cl->{time} ||= timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
728 # Начинаем вывод команды
729 print OUT "<command>\n";
730 print OUT "<l3cd>$Config{l3cd}</l3cd>\n" if $Config{"l3cd"};
731 for my $element (qw(
732 local_session_id
733 history
734 uid
735 pid
736 time
737 pwd
738 raw_start
739 raw_output_start
740 raw_end
741 raw_file
742 tty
743 err
744 last_command
745 history
746 )) {
747 next unless defined($cl->{"$element"});
748 print OUT "<$element>".$cl->{$element}."</$element>\n";
749 }
750 for my $element (qw(
751 prompt
752 cline
753 )) {
754 next unless defined($cl->{"$element"});
755 print OUT "<$element>";
756 printq(\*OUT,$cl->{"$element"});
757 print OUT "</$element>\n";
758 }
759 #note
760 #note_title
761 print OUT "<output>";
762 printq(\*OUT,$output);
763 print OUT "</output>\n";
764 if ($cl->{"diff"}) {
765 print OUT "<diff>";
766 printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
767 print OUT "</diff>\n";
768 }
769 print OUT "</command>\n";
771 }
773 close(OUT);
774 }
776 sub print_session
777 {
778 my $output_filename = $_[0];
779 my $local_session_id = $_[1];
780 return if not defined($Sessions{$local_session_id});
782 print "printing session info. session id = ".$local_session_id."\n"
783 if $Config{verbose} =~ /y/;
785 open(OUT, ">>", $output_filename)
786 or die "Can't open $output_filename for writing\n";
787 print OUT "<session>\n";
788 print OUT "<l3cd>$Config{l3cd}</l3cd>\n" if $Config{"l3cd"};
789 my %session = %{$Sessions{$local_session_id}};
790 for my $key (keys %session) {
791 print OUT "<$key>".$session{$key}."</$key>\n";
792 print " ".$key,"\n";
793 }
794 print OUT "</session>\n";
795 close(OUT);
796 }
798 sub send_cache
799 {
800 # Если в кэше что-то накопилось,
801 # попытаемся отправить это на сервер
802 #
803 my $cache_was_sent=0;
805 if (open(CACHE, $Config{cache})) {
806 local $/;
807 my $cache = <CACHE>;
808 close(CACHE);
810 my $socket = IO::Socket::INET->new(
811 PeerAddr => $Config{backend_address},
812 PeerPort => $Config{backend_port},
813 proto => "tcp",
814 Type => SOCK_STREAM
815 );
817 if ($socket) {
818 print $socket $cache;
819 close($socket);
820 $cache_was_sent = 1;
821 }
822 }
823 return $cache_was_sent;
824 }
826 sub save_cache_stat
827 {
828 open (CACHE, ">$Config{cache_stat}");
829 for my $f (keys %Script_Files) {
830 print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
831 }
832 close(CACHE);
833 }
835 sub load_cache_stat
836 {
837 if (open (CACHE, "$Config{cache_stat}")) {
838 while(<CACHE>) {
839 chomp;
840 my ($f, $size, $tell) = split /\t/;
841 $Script_Files{$f}->{size} = $size;
842 $Script_Files{$f}->{tell} = $tell;
843 }
844 close(CACHE);
845 };
846 }
849 main();
851 sub process_was_killed
852 {
853 $Killed = 1;
854 }
856 sub reload
857 {
858 init_config;
859 }
861 sub main
862 {
864 $| = 1;
866 init_variables();
867 init_config();
870 if ($Config{"mode"} ne "daemon") {
872 # В нормальном режиме работы нужно
873 # считать скрипты, обработать их и записать
874 # результат выполнения в результирующий файл.
875 # После этого завершить работу.
877 # Очистим кэш-файл, если он существовал
878 if (open (CACHE, ">", $Config{"cache"})) {
879 close(CACHE);
880 };
881 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
882 load_diff_files($lab_log);
883 }
884 load_command_lines($Config{"input"}, $Config{"input_mask"});
885 sort_command_lines;
886 #process_command_lines;
887 print_command_lines($Config{"cache"});
888 }
889 else {
890 if (open(PIDFILE, $Config{agent_pidfile})) {
891 my $pid = <PIDFILE>;
892 close(PIDFILE);
893 if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
894 print "Removing stale pidfile\n";
895 unlink $Config{agent_pidfile}
896 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
897 }
898 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`) {
899 print "Removing stale pidfile\n";
900 unlink $Config{agent_pidfile}
901 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
902 }
903 elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
904 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
905 exit(0);
906 }
907 else {
908 print "Unknown operating system";
909 exit(0);
910 }
911 }
912 if ($Config{detach} =~ /^y/i) {
913 #$Config{verbose} = "no";
914 my $pid = fork;
915 exit if $pid;
916 die "Couldn't fork: $!" unless defined ($pid);
918 open(PIDFILE, ">", $Config{agent_pidfile})
919 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
920 print PIDFILE $$;
921 close(PIDFILE);
923 for my $handle (*STDIN, *STDOUT, *STDERR) {
924 open ($handle, "+<", "/dev/null")
925 or die "can't reopen $handle to /dev/null: $!"
926 }
928 POSIX::setsid()
929 or die "Can't start a new session: $!";
931 $0 = $Config{"l3-agent"};
933 $SIG{INT} = $SIG{TERM} = \&process_was_killed;
934 $SIG{HUP} = \&reload;
936 }
937 while (not $Killed) {
938 @Command_Lines = ();
939 @Command_Lines_Index = ();
940 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
941 load_diff_files($lab_log);
942 }
943 load_cache_stat();
944 load_command_lines($Config{"input"}, $Config{"input_mask"});
945 if (@Command_Lines) {
946 sort_command_lines;
947 #process_command_lines;
948 print_command_lines($Config{"cache"});
949 }
950 save_cache_stat();
951 if (-e $Config{cache} && (stat($Config{cache}))[7]) {
952 send_cache() && unlink($Config{cache});
953 }
954 sleep($Config{"daemon_sleep_interval"} || 1);
955 }
957 unlink $Config{agent_pidfile};
958 }
960 }
962 sub init_variables
963 {
964 }