lilalo

view l3-agent @ 120:42d9af3c851c

minifix
author igor
date Thu Mar 13 12:22:31 2008 +0200 (2008-03-13)
parents 71bd999bcb04
children 58c869722fd0
line source
1 #!/usr/bin/perl -w
3 #
4 # (c) Igor Chubin, igor@chub.in, 2004-2008
5 #
7 use strict;
8 use POSIX;
9 use Term::VT102;
10 use Text::Iconv;
11 use Time::Local 'timelocal_nocheck';
12 use IO::Socket;
14 use lib "/etc/lilalo";
15 use l3config;
17 our @Command_Lines;
18 our @Command_Lines_Index;
19 our %Diffs;
20 our %Sessions;
22 our %Script_Files; # Информация о позициях в скрипт-файлах,
23 # до которых уже выполнен разбор
24 # и информация о времени модификации файла
25 # $Script_Files{$file}->{size}
26 # $Script_Files{$file}->{tell}
28 our $Killed =0; # В режиме демона -- процесс получил сигнал о завершении
30 sub init_variables;
31 sub main;
33 sub load_diff_files;
34 sub bind_diff;
35 sub extract_commands_from_cline;
36 sub load_command_lines;
37 sub sort_command_lines;
38 sub print_command_lines;
39 sub printq;
41 sub save_cache_stat;
42 sub load_cache_stat;
43 sub print_session;
45 sub load_diff_files
46 {
47 my @pathes = @_;
49 for my $path (@pathes) {
50 my $template = "*.diff";
51 my @files = <$path/$template>;
52 my $i=0;
53 for my $file (@files) {
55 next if defined($Diffs{$file});
56 my %diff;
58 # Старый формат имени diff-файла
59 # DEPRECATED
60 if ($file=~m@/(D?[0-9][0-9]?[0-9]?)[^/]*?([0-9]*):([0-9]*):?([0-9]*)@) {
61 $diff{"day"}=$1 || "";
62 $diff{"hour"}=$2;
63 $diff{"min"}=$3;
64 $diff{"sec"}=$4 || 0;
66 $diff{"uid"} = 0 if $path =~ m@/root/@;
68 print "diff loaded: $diff{day} $diff{hour}:$diff{min}:$diff{sec}\n";
70 }
71 # Новый формат имени diff-файла
72 elsif ($file =~ m@.*/([^_]*)_([0-9]+)(.*)@) {
73 $diff{"local_session_id"} = $1;
74 $diff{"time"} = $2;
75 $diff{"filename"} = $3;
76 $diff{"filename"} =~ s@_@/@g;
77 $diff{"filename"} =~ s@//@_@g;
79 print "diff loaded: $diff{filename} (time=$diff{time},session=$diff{local_session_id})\n";
80 }
81 else {
82 next;
83 }
85 # Чтение и изменение кодировки содержимого diff-файла
86 local $/;
87 open (F, "$file")
88 or return "Can't open file $file ($_[0]) for reading";
89 my $text = <F>;
90 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i) {
91 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8");
92 $text = $converter->convert($text);
93 }
94 close(F);
95 $diff{"text"}=$text;
97 $diff{"path"}=$path;
98 $diff{"bind_to"}="";
99 $diff{"time_range"}=-1;
100 $diff{"index"}=$i;
102 $Diffs{$file} = \%diff;
103 $i++;
104 }
105 }
106 }
109 sub bind_diff
110 {
111 print "Trying to bind diff...\n";
113 my $cl = shift;
114 my $hour = $cl->{"hour"};
115 my $min = $cl->{"min"};
116 my $sec = $cl->{"sec"};
118 my $min_dt = 10000;
120 if (defined($cl->{"diff"})) {
121 print STDERR "Command ".$cl->{time}." is already bound";
122 return;
123 }
125 # Загружаем новые diff-файлы
126 # Это нужно делать непосредственно перед привязкой, поскольку diff'ы могли образоваться только что
127 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
128 load_diff_files($lab_log);
129 }
131 my $diff_to_bind;
132 for my $diff_key (keys %Diffs) {
133 my $diff = $Diffs{$diff_key};
134 next if ($diff->{"local_session_id"}
135 && $cl->{"local_session_id"}
136 && ($cl->{"local_session_id"} ne $diff->{"local_session_id"}));
138 next if ($diff->{"day"} && $cl->{"day"} && ($cl->{"day"} ne $diff->{"day"}));
140 my $dt;
141 if (not $diff->{"time"}) {
142 print STDERR "diff time is 0";
143 print STDERR join(" ", keys(%$diff));
144 print STDERR $diff->{text};
145 }
146 if (not $cl->{"time"}) {
147 print STDERR "cl time is 0";
148 }
149 if ($diff->{"time"} && $cl->{"time"}) {
150 $dt = $diff->{"time"} - $cl->{"time"}
151 }
152 else {
153 $dt=($diff->{"hour"}-$hour)*3600 +($diff->{"min"}-$min)*60 + ($diff->{"sec"}-$sec);
154 }
155 if ($dt >=0 && $dt < $min_dt && !$diff->{"bind_to"}) {
156 $min_dt = $dt;
157 $diff_to_bind = $diff_key;
158 }
159 }
160 if ($diff_to_bind) {
161 print "Approppriate diff found: dt=$min_dt\n";
162 $Diffs{$diff_to_bind}->{"bind_to"}=$cl;
163 $cl->{"diff"} = $diff_to_bind;
164 }
165 else {
166 print STDERR "Diff not found\n";
167 print STDERR "cl{time}",$cl->{time},"\n";
168 }
169 }
172 sub extract_commands_from_cline
173 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
174 # номер первого появление команды в строке:
175 # команда => первая позиция
176 {
177 my $cline = $_[0];
178 my @lists = split /\;/, $cline;
181 my @commands = ();
182 for my $list (@lists) {
183 push @commands, split /\|/, $list;
184 }
186 my %commands;
187 my %files;
188 my $i=0;
189 for my $command (@commands) {
190 $command =~ /\s*(\S+)\s*(.*)/;
191 if ($1 && $1 eq "sudo" ) {
192 $commands{"$1"}=$i++;
193 $command =~ s/\s*sudo\s+//;
194 }
195 $command =~ /\s*(\S+)\s*(.*)/;
196 if ($1 && !defined $commands{"$1"}) {
197 $commands{"$1"}=$i++;
198 };
199 }
200 return %commands;
201 }
203 sub load_command_lines
204 {
205 my $lab_scripts_path = $_[0];
206 my $lab_scripts_mask = $_[1];
208 my $cline_re_base = qq'
209 (
210 (?:\\^?([0-9]*C?)) # exitcode
211 (?:_([0-9]+)_)? # uid
212 (?:_([0-9]+)_) # pid
213 (...?) # day
214 (.?.?) # lab
215 \\s # space separator
216 ([0-9][0-9]):([0-9][0-9]):([0-9][0-9]) # time
217 .\\[50D.\\[K # killing symbols
218 (.*?([\$\#]\\s?)) # prompt
219 (.*) # command line
220 )
221 ';
222 my $cline_re = qr/$cline_re_base/sx;
223 my $cline_re2 = qr/$cline_re_base$/sx;
225 my $cline_re_v2_base = qq'
226 (
227 v2[\#] # version
228 ([0-9]+)[\#] # history line number
229 ([0-9]+)[\#] # exitcode
230 ([0-9]+)[\#] # uid
231 ([0-9]+)[\#] # pid
232 ([0-9]+)[\#] # time
233 (.*?)[\#] # pwd
234 .\\[1024D.\\[K # killing symbols
235 (.*?([\$\#]\\s?)) # prompt
236 (.*) # command line
237 )
238 ';
240 my $cline_re_v2 = qr/$cline_re_v2_base/sx;
241 my $cline_re2_v2 = qr/$cline_re_v2_base$/sx;
243 my $cline_re_v3_base = qq'
244 (
245 v3[\#] # version
246 .*
247 )
248 ';
249 my $cline_re_v3 = qr/$cline_re_v3_base/sx;
251 my $cline_re2_v3_base = qq'
252 (
253 v3[\#] # version
254 ([0-9]+)[\#] # history line number
255 ([0-9]+)[\#] # exitcode
256 ([0-9]+)[\#] # uid
257 ([0-9]+)[\#] # pid
258 ([0-9]+)[\#] # time
259 (.*?)[\#] # pwd
260 (.*?)[\#] # nonce
261 (.*?([\$\#]\\s?)) # prompt
262 (.*) # command line
263 )
264 ';
265 my $cline_re2_v3 = qr/$cline_re2_v3_base$/sx;
268 my %vt; # Хэш виртуальных терминалов. По одному на каждый сеанс
269 my $cline_vt = Term::VT102->new (
270 'cols' => $Config{"terminal_width"},
271 'rows' => $Config{"terminal_height"});
273 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8")
274 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i);
276 print "Parsing lab scripts...\n" if $Config{"verbose"} =~ /y/;
278 my $file;
279 my $skip_info;
281 my $commandlines_loaded =0;
282 my $commandlines_processed =0;
284 my @lab_scripts = <$lab_scripts_path/$lab_scripts_mask>;
285 for $file (@lab_scripts){
287 # Пропускаем файл, если он не изменялся со времени нашего предудущего прохода
288 my $size = (stat($file))[7];
289 next if ($Script_Files{$file} && $Script_Files{$file}->{size} && $Script_Files{$file}->{size} >= $size);
292 my $local_session_id;
293 # Начальное значение идентификатора текущего сеанса определяем из имени скрипта
294 # Впоследствии оно может быть уточнено
295 $file =~ m@.*/([^/]*)\.script$@;
296 $local_session_id = $1;
298 if (not defined($vt{$local_session_id})) {
299 $vt{$local_session_id} = Term::VT102->new (
300 'cols' => $Config{"terminal_width"},
301 'rows' => $Config{"terminal_height"});
302 }
304 #Если файл только что появился,
305 #пытаемся найти и загрузить информацию о соответствующей ему сессии
306 if (!$Script_Files{$file}) {
307 my $session_file = $file;
308 $session_file =~ s/\.script/.info/;
309 if (open(SESSION, $session_file)) {
310 local $/;
311 my $data = <SESSION>;
312 close(SESSION);
314 for my $session_data ($data =~ m@<session>(.*?)</session>@sg) {
315 my %session;
316 while ($session_data =~ m@<([^>]*?)>(.*?)</\1>@sg) {
317 $session{$1} = $2;
318 }
319 $local_session_id = $session{"local_session_id"} if $session{"local_session_id"};
320 $Sessions{$local_session_id}=\%session;
321 }
323 #Загруженную информацию сразу же отправляем в поток
324 print_session($Config{cache}, $local_session_id);
325 }
326 else {
327 die "can't open session file";
328 }
329 }
331 open (FILE, "$file");
332 binmode FILE;
334 # Переходим к тому месту, где мы окончили разбор
335 seek (FILE, $Script_Files{$file}->{tell}, 0) if $Script_Files{$file}->{tell};
336 $Script_Files{$file}->{size} = $size;
337 $Script_Files{$file}->{tell} = 0 unless $Script_Files{$file}->{tell};
339 $file =~ m@.*/(.*?)-.*@;
341 print "\n+- processing file $file\n| "
342 if $Config{"verbose"} =~/y/;
344 my $tty = $1;
345 my %cl;
346 my $last_output_length=0;
347 while (<FILE>) {
348 $commandlines_processed++;
350 next if s/^Script started on.*?\n//s;
352 if (/[0-9][0-9]:[0-9][0-9]:[0-9][0-9].\[[0-9][0-9]D.\[K/ && m/$cline_re/) {
353 s/.*\x0d(?!\x0a)//;
354 m/$cline_re2/gs;
356 $commandlines_loaded++;
357 $last_output_length=0;
359 # Previous command
360 my %last_cl = %cl;
361 my $this_line = $1;
362 my $err = $2 || "";
364 $cl{"local_session_id"} = $local_session_id;
365 # Parse new command
366 $cl{"uid"} = $3;
367 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
368 $cl{"pid"} = $4;
369 $cl{"day"} = $5;
370 $cl{"lab"} = $6;
371 $cl{"hour"} = $7;
372 $cl{"min"} = $8;
373 $cl{"sec"} = $9;
374 #$cl{"fullprompt"} = $10;
375 $cl{"prompt"} = $11;
376 $cl{"raw_cline"} = $12;
378 {
379 use bytes;
380 $cl{"raw_start"} = tell (FILE) - length($this_line);
381 $cl{"raw_output_start"} = tell FILE;
382 }
383 $cl{"raw_file"} = $file;
385 $cl{"err"} = 0;
386 $cl{"output"} = "";
387 $cl{"tty"} = $tty;
389 $cline_vt->process($cl{"raw_cline"}."\n");
390 $cl{"cline"} = $cline_vt->row_plaintext (1);
391 $cl{"cline"} =~ s/\s*$//;
392 $cl{"cline"} =~ s/.*?[\#\$]\s*//;
393 $cline_vt->reset();
395 my %commands = extract_commands_from_cline($cl{"cline"});
396 #$cl{"euid"}=0 if defined $commands{"sudo"};
397 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
398 $cl{"last_command"} = $comms[$#comms] || "";
400 if (
401 $Config{"suppress_editors"} =~ /^y/i
402 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
403 || $Config{"suppress_pagers"} =~ /^y/i
404 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
405 || $Config{"suppress_terminal"}=~ /^y/i
406 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
407 ) {
408 $cl{"suppress_output"} = "1";
409 }
410 else {
411 $cl{"suppress_output"} = "0";
412 }
413 $skip_info = 0;
416 print " ",$cl{"last_command"};
418 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
419 bind_diff(\%last_cl);
420 }
422 # Error code
423 $last_cl{"raw_end"} = $cl{"raw_start"};
424 $last_cl{"err"}=$err;
425 $last_cl{"err"}=130 if $err eq "^C";
428 # Output
429 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
430 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
431 my $line= $vt{$local_session_id}->row_plaintext($i);
432 next if !defined ($line) ; #|| $line =~ /^\s*$/;
433 $line =~ s/\s*$//;
434 $line .= "\n" unless $line =~ /^\s*$/;
435 $last_cl{"output"} .= $line;
436 }
437 }
438 else {
439 $last_cl{"output"}= "";
440 }
442 $vt{$local_session_id}->reset();
445 # Save
446 if (!$Config{"lab"} || $cl{"lab"} eq $Config{"lab"}) {
447 # Changing encoding
448 for (keys %last_cl) {
449 next if /raw/;
450 $last_cl{$_} = $converter->convert($last_cl{$_})
451 if ($Config{"encoding"} &&
452 $Config{"encoding"} !~ /^utf-8$/i);
453 }
454 push @Command_Lines, \%last_cl;
456 # Сохранение позиции в файле, до которой выполнен
457 # успешный разбор
458 $Script_Files{$file}->{tell} = $last_cl{raw_end};
459 }
460 next;
461 }
463 elsif (m/$cline_re_v2/ || m/$cline_re_v3/) {
464 # Разбираем командную строку версии 2
465 my $before=$_;
466 s/.*\x0d(?!\x0a)//;
468 my $re;
469 if (m/$cline_re_v2/) {
470 $re=$cline_re2_v2;
471 }
472 else {
473 s/.\[1K.\[10D//gs;
474 $re=$cline_re2_v3;
475 print STDERR "... $_ ...\n";
476 }
478 $commandlines_loaded++;
479 $last_output_length=0;
481 # Previous command
482 my %last_cl = %cl;
484 $cl{"local_session_id"} = $local_session_id;
485 # Parse new command
486 my $this_line = $1;
487 $cl{"history"} = $2;
488 my $err = $3;
489 $cl{"uid"} = $4;
490 #$cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
491 $cl{"pid"} = $5;
492 $cl{"time"} = $6;
493 $cl{"pwd"} = $7;
494 $cl{"nonce"} = $8;
495 #$cl{"fullprompt"} = $8;
496 $cl{"prompt"} = $10;
497 #$cl{"raw_cline"}= $10;
498 $cl{"raw_cline"}= $before;
500 {
501 use bytes;
502 $cl{"raw_start"} = tell (FILE) - length($before);
503 $cl{"raw_output_start"} = tell FILE;
504 }
505 $cl{"raw_file"} = $file;
507 $cl{"err"} = 0;
508 $cl{"output"} = "";
509 #$cl{"tty"} = $tty;
511 $cline_vt->process($cl{"raw_cline"}."\n");
512 $cl{"cline"} = $cline_vt->row_plaintext (1);
513 $cl{"cline"} =~ s/\s*$//;
514 $cl{"cline"} =~ s/.*?[\#\$]\s*//;
515 $cline_vt->reset();
516 print STDERR "cline=".$cl{"cline"}."<<\n";
518 my %commands = extract_commands_from_cline($cl{"cline"});
519 #$cl{"euid"} = 0 if defined $commands{"sudo"};
520 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
521 $cl{"last_command"}
522 = $comms[$#comms] || "";
524 print STDERR "last_command=".$cl{"last_command"}."<<\n";
526 if (
527 $Config{"suppress_editors"} =~ /^y/i
528 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
529 || $Config{"suppress_pagers"} =~ /^y/i
530 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
531 || $Config{"suppress_terminal"}=~ /^y/i
532 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
533 ) {
534 $cl{"suppress_output"} = "1";
535 }
536 else {
537 $cl{"suppress_output"} = "0";
538 }
539 $skip_info = 0;
541 if ($Config{verbose} =~ /y/i) {
542 print "\n| " if $commandlines_loaded % 5 == 1;
543 print " ",$cl{"last_command"};
544 }
546 if (defined($last_cl{time})
547 && grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
548 bind_diff(\%last_cl);
549 }
551 # Error code
552 $last_cl{"err"}=$err;
553 $last_cl{"raw_end"} = $cl{"raw_start"};
555 # Output
556 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
557 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
558 my $line= $vt{$local_session_id}->row_plaintext($i);
559 next if !defined ($line) ; #|| $line =~ /^\s*$/;
560 $line =~ s/\s*$//;
561 $line .= "\n" unless $line =~ /^\s*$/;
562 $last_cl{"output"} .= $line;
563 }
564 }
565 else {
566 $last_cl{"output"}= "";
567 }
569 $vt{$local_session_id}->reset();
572 # Changing encoding
573 for (keys %last_cl) {
574 next if /raw/;
575 if ($Config{"encoding"} &&
576 $Config{"encoding"} !~ /^utf-8$/i) {
577 $last_cl{$_} = $converter->convert($last_cl{$_})
578 }
579 }
580 if (defined($last_cl{time})) {
581 print STDERR "push id=".$last_cl{time}."\n";
582 push @Command_Lines, \%last_cl;
583 # Сохранение позиции в файле, до которой выполнен
584 # успешный разбор
585 $Script_Files{$file}->{tell} = $last_cl{raw_end};
586 }
587 next;
588 }
590 # Иначе, это строка вывода
592 $last_output_length+=length($_);
593 #if (!$cl{"suppress_output"} || $last_output_length < 5000) {
594 if ($last_output_length < 50000) {
595 $vt{$local_session_id}->process("$_"."\n")
596 }
597 else
598 {
599 if (!$skip_info && defined($cl{last_command})) {
600 print "($cl{last_command})";
601 $skip_info = 1;
602 }
603 }
604 }
605 close(FILE);
607 }
608 if ($Config{"verbose"} =~ /y/) {
609 print "\n`- finished.\n" ;
610 print "Lines loaded: $commandlines_processed\n";
611 print "Command lines: $commandlines_loaded\n";
612 }
613 }
618 sub sort_command_lines
619 {
620 print "Sorting command lines..." if $Config{"verbose"} =~ /y/;
622 # Sort Command_Lines
623 # Write Command_Lines to Command_Lines_Index
625 my @index;
626 for (my $i=0;$i<=$#Command_Lines;$i++) {
627 $index[$i]=$i;
628 }
630 @Command_Lines_Index = sort {
631 defined($Command_Lines[$index[$a]]->{"time"})
632 && defined($Command_Lines[$index[$b]]->{"time"})
633 ? $Command_Lines[$index[$a]]->{"time"} <=> $Command_Lines[$index[$b]]->{"time"}
634 : defined($Command_Lines[$index[$a]]->{"day"})
635 && defined($Command_Lines[$index[$b]]->{"day"})
636 && defined($Command_Lines[$index[$a]]->{"hour"})
637 && defined($Command_Lines[$index[$b]]->{"hour"})
638 && defined($Command_Lines[$index[$a]]->{"min"})
639 && defined($Command_Lines[$index[$b]]->{"min"})
640 && defined($Command_Lines[$index[$a]]->{"sec"})
641 && defined($Command_Lines[$index[$b]]->{"sec"})
642 ? $Command_Lines[$index[$a]]->{"day"} cmp $Command_Lines[$index[$b]]->{"day"}
643 || $Command_Lines[$index[$a]]->{"hour"} <=> $Command_Lines[$index[$b]]->{"hour"}
644 || $Command_Lines[$index[$a]]->{"min"} <=> $Command_Lines[$index[$b]]->{"min"}
645 || $Command_Lines[$index[$a]]->{"sec"} <=> $Command_Lines[$index[$b]]->{"sec"}
646 : 0
647 } @index;
649 print "finished\n" if $Config{"verbose"} =~ /y/;
651 }
653 sub printq
654 {
655 my $TO = shift;
656 my $text = join "", @_;
657 $text =~ s/&/&amp;/g;
658 $text =~ s/</&lt;/g;
659 $text =~ s/>/&gt;/g;
660 print $TO $text;
661 }
664 =cut
665 Вывести результат обработки журнала.
666 =cut
668 sub print_command_lines
669 {
670 my $output_filename=$_[0];
671 open(OUT, ">>", $output_filename)
672 or die "Can't open $output_filename for writing\n";
675 my $cl;
676 my $in_range=0;
677 for my $i (@Command_Lines_Index) {
678 $cl = $Command_Lines[$i];
680 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
681 $in_range=1;
682 next;
683 }
684 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
685 $in_range=0;
686 next;
687 }
688 next if ($Config{"from"} && $Config{"to"} && !$in_range)
689 ||
690 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
691 ||
692 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
693 ||
694 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
696 # Вырезаем из вывода только нужное количество строк
698 my $output="";
700 if (!grep ($_ eq $cl->{"last_command"}, @{$Config{"full_output_commands"}})
701 && ($Config{"head_lines"}
702 || $Config{"tail_lines"})) {
703 # Partialy output
704 my @lines = split '\n', $cl->{"output"};
705 # head
706 my $mark=1;
707 for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
708 $output .= $lines[$i]."\n";
709 }
710 # tail
711 my $start=$#lines-$Config{"cache_tail_lines"}+1;
712 if ($start < 0) {
713 $start=0;
714 $mark=0;
715 }
716 if ($start < $Config{"cache_head_lines"}) {
717 $start=$Config{"cache_head_lines"};
718 $mark=0;
719 }
720 $output .= $Config{"skip_text"}."\n" if $mark;
721 for ($i=$start; $i<= $#lines; $i++) {
722 $output .= $lines[$i]."\n";
723 }
724 }
725 else {
726 # Full output
727 $output .= $cl->{"output"};
728 }
730 # Совместимость с labmaker
732 # Переводим в секунды Эпохи
733 # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
734 # Информация о годе отсутствовала
735 # Её можно внести:
736 # Декабрь 2004 год; остальные -- 2005 год.
738 my $year = 2005;
739 #$year = 2004 if ( $cl->{day} > 330 );
740 $year = $Config{year} if $Config{year};
741 # timelocal( $sec, $min, $hour, $mday,$mon,$year);
742 $cl->{time} ||= timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
745 # Начинаем вывод команды
746 print OUT "<command>\n";
747 print OUT "<l3cd>$Config{l3cd}</l3cd>\n" if $Config{"l3cd"};
748 for my $element (qw(
749 local_session_id
750 history
751 uid
752 pid
753 time
754 pwd
755 raw_start
756 raw_output_start
757 raw_end
758 raw_file
759 tty
760 err
761 last_command
762 history
763 nonce
764 )) {
765 next unless defined($cl->{"$element"});
766 print OUT "<$element>".$cl->{$element}."</$element>\n";
767 }
768 for my $element (qw(
769 prompt
770 cline
771 )) {
772 next unless defined($cl->{"$element"});
773 print OUT "<$element>";
774 printq(\*OUT,$cl->{"$element"});
775 print OUT "</$element>\n";
776 }
777 #note
778 #note_title
779 print OUT "<output>";
780 printq(\*OUT,$output);
781 print OUT "</output>\n";
782 if ($cl->{"diff"}) {
783 print OUT "<diff>";
784 printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
785 print OUT "</diff>\n";
786 }
787 print OUT "</command>\n";
789 }
791 close(OUT);
792 }
794 sub print_session
795 {
796 my $output_filename = $_[0];
797 my $local_session_id = $_[1];
798 return if not defined($Sessions{$local_session_id});
800 print "printing session info. session id = ".$local_session_id."\n"
801 if $Config{verbose} =~ /y/;
803 open(OUT, ">>", $output_filename)
804 or die "Can't open $output_filename for writing\n";
805 print OUT "<session>\n";
806 print OUT "<l3cd>$Config{l3cd}</l3cd>\n" if $Config{"l3cd"};
807 my %session = %{$Sessions{$local_session_id}};
808 for my $key (keys %session) {
809 print OUT "<$key>".$session{$key}."</$key>\n";
810 print " ".$key,"\n";
811 }
812 print OUT "</session>\n";
813 close(OUT);
814 }
816 sub send_cache
817 {
818 # Если в кэше что-то накопилось,
819 # попытаемся отправить это на сервер
820 #
821 my $cache_was_sent=0;
823 if (open(CACHE, $Config{cache})) {
824 local $/;
825 my $cache = <CACHE>;
826 close(CACHE);
828 my $socket = IO::Socket::INET->new(
829 PeerAddr => $Config{backend_address},
830 PeerPort => $Config{backend_port},
831 proto => "tcp",
832 Type => SOCK_STREAM
833 );
835 if ($socket) {
836 print $socket $cache;
837 close($socket);
838 $cache_was_sent = 1;
839 }
840 }
841 return $cache_was_sent;
842 }
844 sub save_cache_stat
845 {
846 open (CACHE, ">$Config{cache_stat}");
847 for my $f (keys %Script_Files) {
848 print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
849 }
850 close(CACHE);
851 }
853 sub load_cache_stat
854 {
855 if (open (CACHE, "$Config{cache_stat}")) {
856 while(<CACHE>) {
857 chomp;
858 my ($f, $size, $tell) = split /\t/;
859 $Script_Files{$f}->{size} = $size;
860 $Script_Files{$f}->{tell} = $tell;
861 }
862 close(CACHE);
863 };
864 }
867 main();
869 sub process_was_killed
870 {
871 $Killed = 1;
872 }
874 sub reload
875 {
876 init_config;
877 }
879 sub main
880 {
882 $| = 1;
884 init_variables();
885 init_config();
888 if ($Config{"mode"} ne "daemon") {
890 # В нормальном режиме работы нужно
891 # считать скрипты, обработать их и записать
892 # результат выполнения в результирующий файл.
893 # После этого завершить работу.
895 # Очистим кэш-файл, если он существовал
896 if (open (CACHE, ">", $Config{"cache"})) {
897 close(CACHE);
898 };
899 load_command_lines($Config{"input"}, $Config{"input_mask"});
900 sort_command_lines;
901 #process_command_lines;
902 print_command_lines($Config{"cache"});
903 }
904 else {
905 if (open(PIDFILE, $Config{agent_pidfile})) {
906 my $pid = <PIDFILE>;
907 close(PIDFILE);
908 if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
909 print "Removing stale pidfile\n";
910 unlink $Config{agent_pidfile}
911 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
912 }
913 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`) {
914 print "Removing stale pidfile\n";
915 unlink $Config{agent_pidfile}
916 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
917 }
918 elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
919 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
920 exit(0);
921 }
922 else {
923 print "Unknown operating system";
924 exit(0);
925 }
926 }
927 if ($Config{detach} =~ /^y/i) {
928 #$Config{verbose} = "no";
929 my $pid = fork;
930 exit if $pid;
931 die "Couldn't fork: $!" unless defined ($pid);
933 open(PIDFILE, ">", $Config{agent_pidfile})
934 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
935 print PIDFILE $$;
936 close(PIDFILE);
938 for my $handle (*STDIN, *STDOUT, *STDERR) {
939 open ($handle, "+<", "/dev/null")
940 or die "can't reopen $handle to /dev/null: $!"
941 }
943 POSIX::setsid()
944 or die "Can't start a new session: $!";
946 $0 = $Config{"l3-agent"};
948 $SIG{INT} = $SIG{TERM} = \&process_was_killed;
949 $SIG{HUP} = \&reload;
951 }
952 while (not $Killed) {
953 @Command_Lines = ();
954 @Command_Lines_Index = ();
955 load_cache_stat();
956 load_command_lines($Config{"input"}, $Config{"input_mask"});
957 if (@Command_Lines) {
958 sort_command_lines;
959 #process_command_lines;
960 print_command_lines($Config{"cache"});
961 }
962 save_cache_stat();
963 if (-e $Config{cache} && (stat($Config{cache}))[7]) {
964 send_cache() && unlink($Config{cache});
965 }
966 sleep($Config{"daemon_sleep_interval"} || 1);
967 }
969 unlink $Config{agent_pidfile};
970 }
972 }
974 sub init_variables
975 {
976 }