lilalo

annotate l3-agent @ 77:e56f21c44faf

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