lilalo

annotate l3-agent @ 65:b7a217f8e963

Небольшие исправления
author devi
date Fri Jan 27 09:53:10 2006 +0200 (2006-01-27)
parents c4bea959dbb1
children 70db89d4f840
rev   line source
devi@52 1 #!/usr/bin/perl -w
devi@23 2
devi@23 3 #
devi@62 4 # (c) Igor Chubin, igor@chub.in, 2004-2006
devi@23 5 #
devi@23 6
devi@50 7
devi@50 8 ## Эта строчка добавлена из блокнота Windows
devi@50 9 ## Надо отдать должное, он каким-то образом научился понимать кодировку
devi@50 10
devi@23 11 use strict;
devi@25 12 use POSIX;
devi@23 13 use Term::VT102;
devi@23 14 use Text::Iconv;
devi@23 15 use Time::Local 'timelocal_nocheck';
devi@27 16 use IO::Socket;
devi@23 17
devi@32 18 use lib "/usr/local/bin";
devi@23 19 use l3config;
devi@23 20
devi@23 21
devi@23 22 our @Command_Lines;
devi@23 23 our @Command_Lines_Index;
devi@28 24 our %Diffs;
devi@27 25 our %Sessions;
devi@23 26
devi@62 27 our %Script_Files; # Информация о позициях в скрипт-файлах,
devi@62 28 # до которых уже выполнен разбор
devi@62 29 # и информация о времени модификации файла
devi@62 30 # $Script_Files{$file}->{size}
devi@62 31 # $Script_Files{$file}->{tell}
devi@23 32
devi@62 33 our $Killed =0; # В режиме демона -- процесс получил сигнал о завершении
devi@23 34
devi@23 35 sub init_variables;
devi@23 36 sub main;
devi@23 37
devi@23 38 sub load_diff_files;
devi@23 39 sub bind_diff;
devi@62 40 sub extract_commands_from_cline;
devi@23 41 sub load_command_lines;
devi@23 42 sub sort_command_lines;
devi@23 43 sub print_command_lines;
devi@23 44 sub printq;
devi@23 45
devi@25 46 sub save_cache_stat;
devi@25 47 sub load_cache_stat;
devi@27 48 sub print_session;
devi@25 49
devi@23 50 sub load_diff_files
devi@23 51 {
devi@62 52 my @pathes = @_;
devi@62 53
devi@62 54 for my $path (@pathes) {
devi@62 55 my $template = "*.diff";
devi@62 56 my @files = <$path/$template>;
devi@62 57 my $i=0;
devi@62 58 for my $file (@files) {
devi@28 59
devi@62 60 next if defined($Diffs{$file});
devi@62 61
devi@62 62 my %diff;
devi@62 63
devi@62 64 $diff{"path"}=$path;
devi@62 65 $diff{"uid"}="SET THIS";
devi@23 66
devi@23 67 # Сейчас UID определяется из названия каталога
devi@23 68 # откуда берутся diff-файлы
devi@23 69 # Это неправильно
devi@23 70 #
devi@23 71 # ВАРИАНТ:
devi@23 72 # К файлам жураналам должны прилагаться ситемны файлы,
devi@23 73 # мз которых и будет определяться соответствие
devi@23 74 # имён пользователей их uid'ам
devi@23 75 #
devi@62 76 $diff{"uid"} = 0 if $path =~ m@/root/@;
devi@62 77
devi@62 78 $diff{"bind_to"}="";
devi@62 79 $diff{"time_range"}=-1;
devi@62 80
devi@62 81 next if not $file=~m@/(D?[0-9][0-9]?[0-9]?)[^/]*?([0-9]*):([0-9]*):?([0-9]*)@;
devi@62 82 $diff{"day"}=$1 || "";
devi@62 83 $diff{"hour"}=$2;
devi@62 84 $diff{"min"}=$3;
devi@62 85 $diff{"sec"}=$4 || 0;
devi@62 86
devi@62 87 $diff{"index"}=$i;
devi@23 88
devi@62 89 print "diff loaded: $diff{day} $diff{hour}:$diff{min}:$diff{sec}\n";
devi@62 90
devi@62 91 local $/;
devi@62 92 open (F, "$file")
devi@62 93 or return "Can't open file $file ($_[0]) for reading";
devi@62 94 my $text = <F>;
devi@62 95 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i) {
devi@62 96 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8");
devi@62 97 $text = $converter->convert($text);
devi@62 98 }
devi@62 99 close(F);
devi@62 100 $diff{"text"}=$text;
devi@62 101 #print "$file loaded ($diff{day})\n";
devi@23 102
devi@62 103 #push @Diffs, \%diff;
devi@62 104 $Diffs{$file} = \%diff;
devi@62 105 $i++;
devi@62 106 }
devi@62 107 }
devi@23 108 }
devi@23 109
devi@23 110
devi@23 111 sub bind_diff
devi@23 112 {
devi@62 113 # my $path = shift;
devi@62 114 # my $pid = shift;
devi@62 115 # my $day = shift;
devi@62 116 # my $lab = shift;
devi@23 117
devi@62 118 print "Trying to bind diff...\n";
devi@23 119
devi@62 120 my $cl = shift;
devi@62 121 my $hour = $cl->{"hour"};
devi@62 122 my $min = $cl->{"min"};
devi@62 123 my $sec = $cl->{"sec"};
devi@23 124
devi@62 125 my $min_dt = 10000;
devi@23 126
devi@62 127 for my $diff_key (keys %Diffs) {
devi@62 128 my $diff = $Diffs{$diff_key};
devi@62 129 # Check here date, time and user
devi@62 130 next if ($diff->{"day"} && $cl->{"day"} && ($cl->{"day"} ne $diff->{"day"}));
devi@62 131 #next if (!$diff->{"uid"} && $cl->{"euid"} != $diff->{"uid"});
devi@62 132
devi@62 133 my $dt=($diff->{"hour"}-$hour)*3600 +($diff->{"min"}-$min)*60 + ($diff->{"sec"}-$sec);
devi@62 134 if ($dt >0 && $dt < $min_dt && ($diff->{"time_range"} <0 || $dt < $diff->{"time_range"})) {
devi@62 135 print "Approppriate diff found: dt=$dt\n";
devi@62 136 if ($diff->{"bind_to"}) {
devi@62 137 undef $diff->{"bind_to"}->{"diff"};
devi@62 138 };
devi@62 139 $diff->{"time_range"}=$dt;
devi@62 140 $diff->{"bind_to"}=$cl;
devi@23 141
devi@62 142 $cl->{"diff"} = $diff_key;
devi@62 143 $min_dt = $dt;
devi@62 144 }
devi@62 145 }
devi@23 146 }
devi@23 147
devi@23 148
devi@62 149 sub extract_commands_from_cline
devi@23 150 # Разобрать командную строку $_[1] и возвратить хэш, содержащий
devi@23 151 # номер первого появление команды в строке:
devi@62 152 # команда => первая позиция
devi@23 153 {
devi@62 154 my $cline = $_[0];
devi@62 155 my @lists = split /\;/, $cline;
devi@62 156
devi@62 157
devi@62 158 my @commands = ();
devi@62 159 for my $list (@lists) {
devi@62 160 push @commands, split /\|/, $list;
devi@62 161 }
devi@23 162
devi@62 163 my %commands;
devi@62 164 my %files;
devi@62 165 my $i=0;
devi@62 166 for my $command (@commands) {
devi@62 167 $command =~ /\s*(\S+)\s*(.*)/;
devi@62 168 if ($1 && $1 eq "sudo" ) {
devi@62 169 $commands{"$1"}=$i++;
devi@62 170 $command =~ s/\s*sudo\s+//;
devi@62 171 }
devi@62 172 $command =~ /\s*(\S+)\s*(.*)/;
devi@62 173 if ($1 && !defined $commands{"$1"}) {
devi@62 174 $commands{"$1"}=$i++;
devi@62 175 };
devi@62 176 }
devi@62 177 return %commands;
devi@23 178 }
devi@23 179
devi@23 180 sub load_command_lines
devi@23 181 {
devi@62 182 my $lab_scripts_path = $_[0];
devi@62 183 my $lab_scripts_mask = $_[1];
devi@23 184
devi@62 185 my $cline_re_base = qq'
devi@62 186 (
devi@62 187 (?:\\^?([0-9]*C?)) # exitcode
devi@62 188 (?:_([0-9]+)_)? # uid
devi@62 189 (?:_([0-9]+)_) # pid
devi@62 190 (...?) # day
devi@62 191 (.?.?) # lab
devi@62 192 \\s # space separator
devi@62 193 ([0-9][0-9]):([0-9][0-9]):([0-9][0-9]) # time
devi@62 194 .\\[50D.\\[K # killing symbols
devi@62 195 (.*?([\$\#]\\s?)) # prompt
devi@62 196 (.*) # command line
devi@62 197 )
devi@62 198 ';
devi@62 199 #my $cline_re = qr/$cline_re_base(?:$cline_re_base|$)/x;
devi@62 200 #my $cline_re = qr/(?:$cline_re_base)*$cline_re_base$/x;
devi@62 201 my $cline_re = qr/$cline_re_base/sx;
devi@62 202 my $cline_re1 = qr/$cline_re_base\x0D/sx;
devi@62 203 my $cline_re2 = qr/$cline_re_base$/sx;
devi@23 204
devi@62 205 my $vt = Term::VT102->new ( 'cols' => $Config{"terminal_width"},
devi@62 206 'rows' => $Config{"terminal_height"});
devi@62 207 my $cline_vt = Term::VT102->new ('cols' => $Config{"terminal_width"},
devi@62 208 'rows' => $Config{"terminal_height"});
devi@23 209
devi@62 210 my $converter = Text::Iconv->new($Config{"encoding"}, "utf-8")
devi@62 211 if ($Config{"encoding"} && $Config{"encoding"} !~ /^utf-8$/i);
devi@62 212
devi@62 213 print "Loading lm-scripts...\n" if $Config{"verbose"} =~ /y/;
devi@23 214
devi@62 215 my $file;
devi@62 216 my $skip_info;
devi@23 217
devi@62 218 my $commandlines_loaded =0;
devi@62 219 my $commandlines_processed =0;
devi@23 220
devi@62 221 my @lab_scripts = <$lab_scripts_path/$lab_scripts_mask>;
devi@62 222 for $file (@lab_scripts){
devi@23 223
devi@62 224 # Пропускаем файл, если он не изменялся со времени нашего предудущего прохода
devi@62 225 my $size = (stat($file))[7];
devi@62 226 next if ($Script_Files{$file} && $Script_Files{$file}->{size} && $Script_Files{$file}->{size} >= $size);
devi@27 227
devi@27 228
devi@62 229 my $local_session_id;
devi@62 230 # Начальное значение идентификатора текущего сеанса определяем из имени скрипта
devi@62 231 # Впоследствии оно может быть уточнено
devi@62 232 $file =~ m@.*/([^/]*)\.script$@;
devi@62 233 $local_session_id = $1;
devi@27 234
devi@62 235 #Если файл только что появился,
devi@62 236 #пытаемся найти и загрузить информацию о соответствующей ему сессии
devi@62 237 if (!$Script_Files{$file}) {
devi@62 238 my $session_file = $file;
devi@62 239 $session_file =~ s/\.script/.info/;
devi@62 240 if (open(SESSION, $session_file)) {
devi@62 241 local $/;
devi@62 242 my $data = <SESSION>;
devi@62 243 close(SESSION);
devi@27 244
devi@62 245 for my $session_data ($data =~ m@<session>(.*?)</session>@sg) {
devi@62 246 my %session;
devi@62 247 while ($session_data =~ m@<([^>]*?)>(.*?)</\1>@sg) {
devi@62 248 $session{$1} = $2;
devi@62 249 }
devi@62 250 $local_session_id = $session{"local_session_id"} if $session{"local_session_id"};
devi@62 251 $Sessions{$local_session_id}=\%session;
devi@62 252 }
devi@25 253
devi@62 254 #Загруженную информацию сразу же отправляем в поток
devi@62 255 print_session($Config{cache}, $local_session_id);
devi@62 256 }
devi@62 257 }
devi@25 258
devi@62 259 open (FILE, "$file");
devi@62 260 binmode FILE;
devi@23 261
devi@62 262 # Переходим к тому месту, где мы окончили разбор
devi@62 263 seek (FILE, $Script_Files{$file}->{tell}, 0) if $Script_Files{$file}->{tell};
devi@62 264 $Script_Files{$file}->{size} = $size;
devi@62 265 $Script_Files{$file}->{tell} = 0 unless $Script_Files{$file}->{tell};
devi@32 266
devi@62 267 $file =~ m@.*/(.*?)-.*@;
devi@23 268
devi@62 269 my $tty = $1;
devi@62 270 my $first_pass = 1;
devi@62 271 my %cl;
devi@62 272 my $last_output_length=0;
devi@62 273 while (<FILE>) {
devi@62 274 $commandlines_processed++;
devi@23 275
devi@62 276 next if s/^Script started on.*?\n//s;
devi@23 277
devi@62 278 if (/[0-9][0-9]:[0-9][0-9]:[0-9][0-9].\[[0-9][0-9]D.\[K/ && m/$cline_re/) {
devi@62 279 s/.*\x0d(?!\x0a)//;
devi@62 280 m/$cline_re2/gs;
devi@23 281
devi@62 282 $commandlines_loaded++;
devi@62 283 $last_output_length=0;
devi@23 284
devi@62 285 # Previous command
devi@62 286 my %last_cl = %cl;
devi@62 287 my $err = $2 || "";
devi@23 288
devi@62 289 $cl{"local_session_id"} = $local_session_id;
devi@62 290 # Parse new command
devi@62 291 $cl{"uid"} = $3;
devi@62 292 $cl{"euid"} = $cl{"uid"}; # Если в команде обнаружится sudo, euid поменяем на 0
devi@62 293 $cl{"pid"} = $4;
devi@62 294 $cl{"day"} = $5;
devi@62 295 $cl{"lab"} = $6;
devi@62 296 $cl{"hour"} = $7;
devi@62 297 $cl{"min"} = $8;
devi@62 298 $cl{"sec"} = $9;
devi@62 299 $cl{"fullprompt"} = $10;
devi@62 300 $cl{"prompt"} = $11;
devi@62 301 $cl{"raw_cline"} = $12;
devi@23 302
devi@62 303 {
devi@62 304 use bytes;
devi@62 305 $cl{"raw_start"} = tell (FILE) - length($1);
devi@62 306 $cl{"raw_output_start"} = tell FILE;
devi@62 307 }
devi@62 308 $cl{"raw_file"} = $file;
devi@23 309
devi@62 310 $cl{"err"} = 0;
devi@62 311 $cl{"output"} = "";
devi@62 312 $cl{"tty"} = $tty;
devi@23 313
devi@62 314 $cline_vt->process($cl{"raw_cline"}."\n");
devi@62 315 $cl{"cline"} = $cline_vt->row_plaintext (1);
devi@62 316 $cl{"cline"} =~ s/\s*$//;
devi@62 317 $cline_vt->reset();
devi@23 318
devi@62 319 my %commands = extract_commands_from_cline($cl{"cline"});
devi@62 320 $cl{"euid"}=0 if defined $commands{"sudo"};
devi@62 321 my @comms = sort { $commands{$a} cmp $commands{$b} } keys %commands;
devi@62 322 $cl{"last_command"} = $comms[$#comms] || "";
devi@23 323
devi@62 324 if (
devi@62 325 $Config{"suppress_editors"} =~ /^y/i
devi@62 326 && grep ($_ eq $cl{"last_command"}, @{$Config{"editors"}})
devi@62 327 || $Config{"suppress_pagers"} =~ /^y/i
devi@62 328 && grep ($_ eq $cl{"last_command"}, @{$Config{"pagers"}})
devi@62 329 || $Config{"suppress_terminal"}=~ /^y/i
devi@62 330 && grep ($_ eq $cl{"last_command"}, @{$Config{"terminal"}})
devi@62 331 ) {
devi@62 332 $cl{"suppress_output"} = "1";
devi@62 333 }
devi@62 334 else {
devi@62 335 $cl{"suppress_output"} = "0";
devi@62 336 }
devi@62 337 $skip_info = 0;
devi@23 338
devi@23 339
devi@62 340 print " ",$cl{"last_command"};
devi@23 341
devi@62 342 # Processing previous command line
devi@62 343 if ($first_pass) {
devi@62 344 $first_pass = 0;
devi@62 345 next;
devi@62 346 }
devi@23 347
devi@62 348 # Error code
devi@62 349 $last_cl{"raw_end"} = $cl{"raw_start"};
devi@62 350 $last_cl{"err"}=$err;
devi@62 351 $last_cl{"err"}=130 if $err eq "^C";
devi@23 352
devi@62 353 if (grep ($_ eq $last_cl{"last_command"}, @{$Config{"editors"}})) {
devi@62 354 bind_diff(\%last_cl);
devi@62 355 }
devi@23 356
devi@62 357 # Output
devi@62 358 if (!$last_cl{"suppress_output"} || $last_cl{"err"}) {
devi@62 359 for (my $i=0; $i<$Config{"terminal_height"}; $i++) {
devi@62 360 my $line= $vt->row_plaintext($i);
devi@62 361 next if !defined ($line) ; #|| $line =~ /^\s*$/;
devi@62 362 $line =~ s/\s*$//;
devi@62 363 $line .= "\n" unless $line =~ /^\s*$/;
devi@62 364 $last_cl{"output"} .= $line;
devi@62 365 }
devi@62 366 }
devi@62 367 else {
devi@62 368 $last_cl{"output"}= "";
devi@62 369 }
devi@23 370
devi@62 371 $vt->reset();
devi@23 372
devi@23 373
devi@62 374 # Classifying the command line
devi@23 375
devi@23 376
devi@62 377 # Save
devi@62 378 if (!$Config{"lab"} || $cl{"lab"} eq $Config{"lab"}) {
devi@62 379 # Changing encoding
devi@62 380 for (keys %last_cl) {
devi@62 381 next if /raw/;
devi@62 382 $last_cl{$_} = $converter->convert($last_cl{$_})
devi@62 383 if ($Config{"encoding"} &&
devi@62 384 $Config{"encoding"} !~ /^utf-8$/i);
devi@62 385 }
devi@62 386 push @Command_Lines, \%last_cl;
devi@23 387
devi@62 388 # Сохранение позиции в файле, до которой выполнен
devi@62 389 # успешный разбор
devi@62 390 $Script_Files{$file}->{tell} = $last_cl{raw_end};
devi@62 391 }
devi@62 392 next;
devi@62 393 }
devi@62 394 $last_output_length+=length($_);
devi@62 395 #if (!$cl{"suppress_output"} || $last_output_length < 5000) {
devi@62 396 if ($last_output_length < 50000) {
devi@62 397 $vt->process("$_"."\n")
devi@62 398 }
devi@62 399 else
devi@62 400 {
devi@62 401 if (!$skip_info) {
devi@62 402 print "($cl{last_command})";
devi@62 403 $skip_info = 1;
devi@62 404 }
devi@62 405 }
devi@62 406 }
devi@62 407 close(FILE);
devi@23 408
devi@62 409 }
devi@62 410 if ($Config{"verbose"} =~ /y/) {
devi@62 411 print "...finished." ;
devi@62 412 print "Lines loaded: $commandlines_processed\n";
devi@62 413 print "Command lines: $commandlines_loaded\n";
devi@62 414 }
devi@23 415 }
devi@23 416
devi@23 417
devi@23 418
devi@62 419
devi@62 420 sub sort_command_lines
devi@62 421 {
devi@62 422 print "Sorting command lines...\n" if $Config{"verbose"} =~ /y/;
devi@62 423
devi@62 424 # Sort Command_Lines
devi@62 425 # Write Command_Lines to Command_Lines_Index
devi@62 426
devi@62 427 my @index;
devi@62 428 for (my $i=0;$i<=$#Command_Lines;$i++) {
devi@62 429 $index[$i]=$i;
devi@62 430 }
devi@62 431
devi@62 432 @Command_Lines_Index = sort {
devi@62 433 $Command_Lines[$index[$a]]->{"day"} cmp $Command_Lines[$index[$b]]->{"day"} ||
devi@62 434 $Command_Lines[$index[$a]]->{"hour"} <=> $Command_Lines[$index[$b]]->{"hour"} ||
devi@62 435 $Command_Lines[$index[$a]]->{"min"} <=> $Command_Lines[$index[$b]]->{"min"} ||
devi@62 436 $Command_Lines[$index[$a]]->{"sec"} <=> $Command_Lines[$index[$b]]->{"sec"}
devi@62 437 } @index;
devi@62 438
devi@62 439 print "...finished\n" if $Config{"verbose"} =~ /y/;
devi@62 440
devi@62 441 }
devi@62 442
devi@23 443 sub printq
devi@23 444 {
devi@62 445 my $TO = shift;
devi@62 446 my $text = join "", @_;
devi@62 447 $text =~ s/&/&amp;/g;
devi@62 448 $text =~ s/</&lt;/g;
devi@62 449 $text =~ s/>/&gt;/g;
devi@62 450 print $TO $text;
devi@23 451 }
devi@23 452
devi@23 453
devi@23 454 =cut
devi@23 455 Вывести результат обработки журнала.
devi@23 456 =cut
devi@23 457
devi@23 458 sub print_command_lines
devi@23 459 {
devi@62 460 my $output_filename=$_[0];
devi@62 461 my $mode = ">";
devi@62 462 $mode =">>" if $Config{mode} eq "daemon";
devi@62 463 open(OUT, $mode, $output_filename)
devi@62 464 or die "Can't open $output_filename for writing\n";
devi@23 465
devi@23 466
devi@62 467 my $cl;
devi@62 468 my $in_range=0;
devi@62 469 for my $i (@Command_Lines_Index) {
devi@62 470 $cl = $Command_Lines[$i];
devi@23 471
devi@62 472 if ($Config{"from"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"from"}/) {
devi@62 473 $in_range=1;
devi@62 474 next;
devi@62 475 }
devi@62 476 if ($Config{"to"} && $cl->{"cline"} =~ /$Config{"signature"}\s*$Config{"to"}/) {
devi@62 477 $in_range=0;
devi@62 478 next;
devi@62 479 }
devi@62 480 next if ($Config{"from"} && $Config{"to"} && !$in_range)
devi@62 481 ||
devi@62 482 ($Config{"skip_empty"} =~ /^y/i && $cl->{"cline"} =~ /^\s*$/ )
devi@62 483 ||
devi@62 484 ($Config{"skip_wrong"} =~ /^y/i && $cl->{"err"} != 0)
devi@62 485 ||
devi@62 486 ($Config{"skip_interrupted"} =~ /^y/i && $cl->{"err"} == 130);
devi@62 487
devi@62 488 # Вырезаем из вывода только нужное количество строк
devi@23 489
devi@62 490 my $output="";
devi@62 491 if ($Config{"head_lines"} || $Config{"tail_lines"}) {
devi@62 492 # Partialy output
devi@62 493 my @lines = split '\n', $cl->{"output"};
devi@62 494 # head
devi@62 495 my $mark=1;
devi@62 496 for (my $i=0; $i<= $#lines && $i < $Config{"cache_head_lines"}; $i++) {
devi@62 497 $output .= $lines[$i]."\n";
devi@62 498 }
devi@62 499 # tail
devi@62 500 my $start=$#lines-$Config{"cache_tail_lines"}+1;
devi@62 501 if ($start < 0) {
devi@62 502 $start=0;
devi@62 503 $mark=0;
devi@62 504 }
devi@62 505 if ($start < $Config{"cache_head_lines"}) {
devi@62 506 $start=$Config{"cache_head_lines"};
devi@62 507 $mark=0;
devi@62 508 }
devi@62 509 $output .= $Config{"skip_text"}."\n" if $mark;
devi@62 510 for (my $i=$start; $i<= $#lines; $i++) {
devi@62 511 $output .= $lines[$i]."\n";
devi@62 512 }
devi@62 513 }
devi@62 514 else {
devi@62 515 # Full output
devi@62 516 $output .= $cl->{"output"};
devi@62 517 }
devi@23 518
devi@62 519 # Совместимость с labmaker
devi@23 520
devi@62 521 # Переводим в секунды Эпохи
devi@62 522 # В labmaker'е данные хранились в неудобной форме: hour, min, sec, day of year
devi@62 523 # Информация о годе отсутствовала
devi@62 524 # Её можно внести:
devi@62 525 # Декабрь 2004 год; остальные -- 2005 год.
devi@23 526
devi@62 527 my $year = 2005;
devi@62 528 #$year = 2004 if ( $cl->{day} > 330 );
devi@62 529 $year = $Config{year} if $Config{year};
devi@62 530 # timelocal( $sec, $min, $hour, $mday,$mon,$year);
devi@62 531 $cl->{time} = timelocal_nocheck($cl->{sec},$cl->{min},$cl->{hour},$cl->{day},0,$year);
devi@23 532
devi@23 533
devi@62 534 # Начинаем вывод команды
devi@62 535 print OUT "<command>\n";
devi@62 536 for my $element (qw(
devi@62 537 local_session_id
devi@62 538 time
devi@62 539 raw_start
devi@62 540 raw_output_start
devi@62 541 raw_end
devi@62 542 raw_file
devi@62 543 tty
devi@62 544 uid
devi@62 545 err
devi@62 546 last_command
devi@62 547 )) {
devi@65 548 next unless defined($cl->{"$element"});
devi@62 549 print OUT "<$element>".$cl->{$element}."</$element>\n";
devi@62 550 }
devi@62 551 for my $element (qw(
devi@62 552 prompt
devi@62 553 cline
devi@62 554 note
devi@62 555 note_title
devi@62 556 )) {
devi@65 557 next unless defined($cl->{"$element"});
devi@62 558 print OUT "<$element>";
devi@62 559 printq(\*OUT,$cl->{"$element"});
devi@62 560 print OUT "</$element>\n";
devi@62 561 }
devi@62 562 print OUT "<output>";
devi@62 563 printq(\*OUT,$output);
devi@62 564 print OUT "</output>\n";
devi@62 565 if ($cl->{"diff"}) {
devi@62 566 print OUT "<diff>";
devi@62 567 printq(\*OUT,${$Diffs{$cl->{"diff"}}}{"text"});
devi@62 568 print OUT "</diff>\n";
devi@62 569 }
devi@62 570 print OUT "</command>\n";
devi@23 571
devi@62 572 }
devi@23 573
devi@62 574 close(OUT);
devi@27 575 }
devi@27 576
devi@27 577 sub print_session
devi@27 578 {
devi@62 579 my $output_filename = $_[0];
devi@62 580 my $local_session_id = $_[1];
devi@62 581 return if not defined($Sessions{$local_session_id});
devi@27 582
devi@62 583 open(OUT, ">>", $output_filename)
devi@62 584 or die "Can't open $output_filename for writing\n";
devi@62 585 print OUT "<session>\n";
devi@62 586 my %session = %{$Sessions{$local_session_id}};
devi@62 587 for my $key (keys %session) {
devi@62 588 print OUT "<$key>".$session{$key}."</$key>\n"
devi@62 589 }
devi@62 590 print OUT "</session>\n";
devi@62 591 close(OUT);
devi@27 592 }
devi@27 593
devi@27 594 sub send_cache
devi@27 595 {
devi@62 596 # Если в кэше что-то накопилось,
devi@62 597 # попытаемся отправить это на сервер
devi@62 598 #
devi@62 599 my $cache_was_sent=0;
devi@62 600
devi@62 601 if (open(CACHE, $Config{cache})) {
devi@62 602 local $/;
devi@62 603 my $cache = <CACHE>;
devi@62 604 close(CACHE);
devi@27 605
devi@62 606 my $socket = IO::Socket::INET->new(
devi@62 607 PeerAddr => $Config{backend_address},
devi@62 608 PeerPort => $Config{backend_port},
devi@62 609 proto => "tcp",
devi@62 610 Type => SOCK_STREAM
devi@62 611 );
devi@27 612
devi@62 613 if ($socket) {
devi@62 614 print $socket $cache;
devi@62 615 close($socket);
devi@62 616 $cache_was_sent = 1;
devi@62 617 }
devi@62 618 }
devi@62 619 return $cache_was_sent;
devi@23 620 }
devi@23 621
devi@25 622 sub save_cache_stat
devi@25 623 {
devi@62 624 open (CACHE, ">$Config{cache_stat}");
devi@62 625 for my $f (keys %Script_Files) {
devi@62 626 print CACHE "$f\t",$Script_Files{$f}->{size},"\t",$Script_Files{$f}->{tell},"\n";
devi@62 627 }
devi@62 628 close(CACHE);
devi@25 629 }
devi@25 630
devi@25 631 sub load_cache_stat
devi@25 632 {
devi@62 633 if (open (CACHE, "$Config{cache_stat}")) {
devi@62 634 while(<CACHE>) {
devi@62 635 chomp;
devi@62 636 my ($f, $size, $tell) = split /\t/;
devi@62 637 $Script_Files{$f}->{size} = $size;
devi@62 638 $Script_Files{$f}->{tell} = $tell;
devi@62 639 }
devi@62 640 close(CACHE);
devi@62 641 };
devi@25 642 }
devi@23 643
devi@23 644
devi@23 645 main();
devi@23 646
devi@25 647 sub process_was_killed
devi@25 648 {
devi@62 649 $Killed = 1;
devi@25 650 }
devi@25 651
devi@23 652 sub main
devi@23 653 {
devi@23 654
devi@62 655 $| = 1;
devi@23 656
devi@62 657 init_variables();
devi@62 658 init_config();
devi@23 659
devi@27 660
devi@62 661 if ($Config{"mode"} ne "daemon") {
devi@27 662
devi@27 663 =cut
devi@62 664 В нормальном режиме работы нужно
devi@62 665 считать скрипты, обработать их и записать
devi@62 666 результат выполнения в результирующий файл.
devi@62 667 После этого завершить работу.
devi@27 668 =cut
devi@62 669 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
devi@62 670 load_diff_files($lab_log);
devi@62 671 }
devi@62 672 load_command_lines($Config{"input"}, $Config{"input_mask"});
devi@65 673 #sort_command_lines;
devi@62 674 #process_command_lines;
devi@62 675 print_command_lines($Config{"cache"});
devi@62 676 }
devi@62 677 else {
devi@62 678 if (open(PIDFILE, $Config{agent_pidfile})) {
devi@62 679 my $pid = <PIDFILE>;
devi@62 680 close(PIDFILE);
devi@62 681 if ($^O eq 'linux' && $pid &&(! -e "/proc/$pid" || !`grep $Config{"l3-agent"} /proc/$pid/cmdline && grep "uid:.*\b$<\b" /proc/$pid/status`)) {
devi@62 682 print "Removing stale pidfile\n";
devi@62 683 unlink $Config{agent_pidfile}
devi@62 684 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
devi@62 685 }
devi@62 686 elsif ($^O eq 'freebsd' && $pid && `ps axo uid,pid,command | grep '$<\\s*$pid\\s*$Config{"l3-agent"}' 2> /dev/null`) {
devi@62 687 print "Removing stale pidfile\n";
devi@62 688 unlink $Config{agent_pidfile}
devi@62 689 or die "Can't remove stale pidfile ". $Config{agent_pidfile}. " : $!";
devi@62 690 }
devi@62 691 elsif ($^O eq 'linux' || $^O eq 'freebsd' ) {
devi@62 692 print "l3-agent is already running: pid=$pid; pidfile=$Config{agent_pidfile}\n";
devi@62 693 exit(0);
devi@62 694 }
devi@62 695 else {
devi@62 696 print "Unknown operating system";
devi@62 697 exit(0);
devi@62 698 }
devi@62 699 }
devi@62 700 if ($Config{detach} =~ /^y/i) {
devi@62 701 #$Config{verbose} = "no";
devi@62 702 my $pid = fork;
devi@62 703 exit if $pid;
devi@62 704 die "Couldn't fork: $!" unless defined ($pid);
devi@27 705
devi@62 706 open(PIDFILE, ">", $Config{agent_pidfile})
devi@62 707 or die "Can't open pidfile ". $Config{agent_pidfile}. " for wrting: $!";
devi@62 708 print PIDFILE $$;
devi@62 709 close(PIDFILE);
devi@27 710
devi@62 711 for my $handle (*STDIN, *STDOUT, *STDERR) {
devi@62 712 open ($handle, "+<", "/dev/null")
devi@62 713 or die "can't reopen $handle to /dev/null: $!"
devi@62 714 }
devi@27 715
devi@62 716 POSIX::setsid()
devi@62 717 or die "Can't start a new session: $!";
devi@27 718
devi@62 719 $0 = $Config{"l3-agent"};
devi@62 720
devi@62 721 $SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&process_was_killed;
devi@62 722 }
devi@62 723 while (not $Killed) {
devi@62 724 @Command_Lines = ();
devi@62 725 @Command_Lines_Index = ();
devi@62 726 for my $lab_log (split (/\s+/, $Config{"diffs"} || $Config{"input"})) {
devi@62 727 load_diff_files($lab_log);
devi@62 728 }
devi@62 729 load_cache_stat();
devi@62 730 load_command_lines($Config{"input"}, $Config{"input_mask"});
devi@62 731 if (@Command_Lines) {
devi@65 732 #sort_command_lines;
devi@65 733 #process_command_lines;
devi@62 734 print_command_lines($Config{"cache"});
devi@62 735 }
devi@62 736 save_cache_stat();
devi@62 737 if (-e $Config{cache} && (stat($Config{cache}))[7]) {
devi@62 738 send_cache() && unlink($Config{cache});
devi@62 739 }
devi@62 740 sleep($Config{"daemon_sleep_interval"} || 1);
devi@62 741 }
devi@62 742
devi@62 743 unlink $Config{agent_pidfile};
devi@62 744 }
devi@23 745
devi@23 746 }
devi@23 747
devi@23 748 sub init_variables
devi@23 749 {
devi@23 750 }