main.pm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. package Rstat::main;
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use strict;
  7. use English;
  8. use FindBin '$Bin';
  9. use lib "$Bin";
  10. use base 'Exporter';
  11. use vars qw(@EXPORT @ISA);
  12. use Rstat::config;
  13. use Socket;
  14. use IO::Select;
  15. use IO::Handle;
  16. our @ISA = qw(Exporter);
  17. our @EXPORT = qw(
  18. log_file
  19. write_to_file
  20. wrlog
  21. log_session
  22. log_warning
  23. log_info
  24. log_debug
  25. log_error
  26. log_verbose
  27. log_die
  28. timestamp
  29. do_exec
  30. do_exec_ref
  31. do_exit
  32. sendEmail
  33. IsNotRun
  34. IsMyPID
  35. Add_PID
  36. Remove_PID
  37. IsNotLocked
  38. IsMyLock
  39. Add_Lock
  40. Remove_Lock
  41. DefHash
  42. read_file
  43. uniq
  44. strim
  45. trim
  46. is_integer
  47. is_float
  48. run_in_parallel
  49. translit
  50. );
  51. BEGIN
  52. {
  53. #---------------------------------------------------------------------------------------------------------
  54. sub log_file {
  55. return if (!$_[0]);
  56. return if (!$_[1]);
  57. return if (!$_[2]);
  58. open (LG,">>$_[0]") || die("Error open log file $_[0]!!! die...");
  59. my ($sec,$min,$hour,$mday,$mon,$year) = (localtime())[0,1,2,3,4,5];
  60. $mon += 1; $year += 1900;
  61. my @msg = split("\n",$_[2]);
  62. foreach my $row (@msg) {
  63. next if (!$row);
  64. printf LG "%04d%02d%02d-%02d%02d%02d %s [%d] %s\n",$year,$mon,$mday,$hour,$min,$sec,$_[1],$$,$row;
  65. }
  66. close (LG);
  67. if ($< ==0) {
  68. my $uid = getpwnam $log_owner_user;
  69. my $gid = getgrnam $log_owner_user;
  70. if (!$gid) { $gid=getgrnam "root"; }
  71. if (!$uid) { $uid=getpwnam "root"; }
  72. chown $uid, $gid, $_[0];
  73. chmod oct("0660"), $_[0];
  74. }
  75. }
  76. #---------------------------------------------------------------------------------------------------------
  77. sub write_to_file {
  78. return if (!$_[0]);
  79. return if (!$_[1]);
  80. my $f_name = shift;
  81. my $cmd = shift;
  82. my $append = shift;
  83. if ($append) {
  84. open (LG,">>$f_name") || die("Error open file $f_name!!! die...");
  85. } else {
  86. open (LG,">$f_name") || die("Error open file $f_name!!! die...");
  87. }
  88. if (ref($cmd) eq 'ARRAY') {
  89. foreach my $row (@$cmd) {
  90. next if (!$row);
  91. print LG $row."\n";
  92. }
  93. } else {
  94. my @msg = split("\n",$cmd);
  95. foreach my $row (@msg) {
  96. next if (!$row);
  97. print LG $row."\n";
  98. }
  99. }
  100. close (LG);
  101. }
  102. #---------------------------------------------------------------------------------------------------------
  103. sub wrlog {
  104. my $level = shift;
  105. my $string = shift;
  106. my $PRN_LEVEL = 'INFO:';
  107. if ($level == $W_INFO) { log_info($string); }
  108. if ($level == $W_ERROR) { $PRN_LEVEL = 'ERROR:'; log_error($string); }
  109. if ($level == $W_DEBUG) { $PRN_LEVEL = 'DEBUG'; log_debug($string); }
  110. my @msg = split("\n",$string);
  111. foreach my $row (@msg) {
  112. next if (!$row);
  113. print $PRN_LEVEL.' '.$row."\n";
  114. }
  115. }
  116. #---------------------------------------------------------------------------------------------------------
  117. sub log_session { log_file($LOG_COMMON,"SESSION:",$_[0]) if ($log_enable); }
  118. #---------------------------------------------------------------------------------------------------------
  119. sub log_info { log_file($LOG_COMMON,"INFO:",$_[0]) if ($log_enable); }
  120. #---------------------------------------------------------------------------------------------------------
  121. sub log_verbose { log_file($LOG_COMMON,"VERBOSE:",$_[0]) if ($log_enable); }
  122. #---------------------------------------------------------------------------------------------------------
  123. sub log_warning { log_file($LOG_COMMON,"WARN:",$_[0]) if ($log_enable); }
  124. #---------------------------------------------------------------------------------------------------------
  125. sub log_debug { log_file($LOG_DEBUG,"DEBUG:",$_[0]) if $debug; }
  126. #---------------------------------------------------------------------------------------------------------
  127. sub log_error { log_file($LOG_ERR,"ERROR:",$_[0]) if ($log_enable); }
  128. #---------------------------------------------------------------------------------------------------------
  129. sub log_die {
  130. wrlog($W_ERROR,$_[0]);
  131. my $worktime = time()-$BASETIME;
  132. log_info("Script work $worktime sec.");
  133. sendEmail("$HOSTNAME - $MY_NAME die! ","Process: $MY_NAME aborted with error:\n$_[0]");
  134. die ($_[0]);
  135. }
  136. #---------------------------------------------------------------------------------------------------------
  137. sub timestamp {
  138. my $worktime = time()-$BASETIME;
  139. log_info("TimeStamp: $worktime sec.");
  140. }
  141. #---------------------------------------------------------------------------------------------------------.
  142. sub do_exec_ref {
  143. my $ret = `$_[0]`;
  144. my $res = $?;
  145. my %result;
  146. chomp($ret);
  147. $result{output}=$ret;
  148. $result{status}=$res;
  149. log_debug("Run: $_[0] Output:\n$ret\nResult code: $res");
  150. if ($res eq "0") { log_info("Run: $_[0] - $ret"); } else { log_error("Run: $_[0] - $ret"); }
  151. return %result;
  152. }
  153. #---------------------------------------------------------------------------------------------------------
  154. sub do_exec {
  155. my $ret = `$_[0]`;
  156. my $res = $?;
  157. log_debug("Run: $_[0] Output:\n$ret\nResult code: $res");
  158. if ($res eq "0") {
  159. log_info("Run: $_[0] - $ret");
  160. } else {
  161. $ret = "Error";
  162. log_error("Run: $_[0] - $ret");
  163. }
  164. return $ret;
  165. }
  166. #---------------------------------------------------------------------------------------------------------
  167. sub do_exit {
  168. my $worktime = time()-$BASETIME;
  169. my $code;
  170. if ($_[0]) { $code = $_[0]; } else { $code = 0; }
  171. log_info("Script work $worktime sec. Exit code: $code");
  172. exit $code;
  173. }
  174. #---------------------------------------------------------------------------------------------------------
  175. sub sendEmail {
  176. my ($subject, $message, $crf) = @_;
  177. return if (!$send_email);
  178. my $sendmail = '/sbin/sendmail';
  179. open(MAIL, "|$sendmail -oi -t");
  180. print MAIL "From: $sender_email\n";
  181. print MAIL "To: $admin_email\n";
  182. print MAIL "Subject: $subject\nMIME-Version: 1.0\nContent-Language: ru\nContent-Type: text/html; charset=utf-8\nContent-Transfer-Encoding: 8bit\n\n";
  183. print MAIL '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n";
  184. print MAIL '<html xmlns="http://www.w3.org/1999/xhtml">'."\n";
  185. print MAIL "<head><title>$subject </title></head><body>\n";
  186. my @msg = split("\n",$message);
  187. foreach my $row (@msg) {
  188. if ($crf) { print MAIL "$row<br>"; } else { print MAIL "$row\n"; };
  189. }
  190. print MAIL "</body></html>\n";
  191. close(MAIL);
  192. log_info("Send email from $sender_email to $admin_email with subject: $subject");
  193. log_debug("Body:\n$message");
  194. }
  195. #---------------------------------------------------------------------------------------------------------
  196. ### Check few run script
  197. sub IsNotRun {
  198. my $pname = shift;
  199. my $lockfile = $pname.".pid";
  200. # if pid file not exists - OK
  201. log_debug("Check what pid file $lockfile exists.");
  202. if (! -e $lockfile) { log_debug("pid file not found. Continue."); return 1; }
  203. open (FF,"<$lockfile") or log_die("can't open file $lockfile: $!");
  204. my $lockid = <FF>;
  205. close(FF);
  206. chomp($lockid);
  207. # If the process ID belongs to the current program - OK
  208. if ($lockid eq $$) { log_debug("pid file found, but owner is this process. Continue. "); return 1; }
  209. # if owner of this process ID not exists - OK
  210. my $process_count = `ps -p $lockid | grep \'$lockid\' | wc -l`;
  211. chomp($process_count);
  212. log_debug("Process count with id $lockid is $process_count");
  213. if ($process_count==0) { log_debug("pid file found, but owner process not found. Remove lock file and continue. "); unlink $lockfile; return 1; }
  214. log_debug("Another proceess with name $MY_NAME pid: $lockid already worked. ");
  215. return 0;
  216. }
  217. #---------------------------------------------------------------------------------------------------------
  218. sub IsMyPID {
  219. my $pname = shift;
  220. my $lockfile = $pname.".pid";
  221. log_debug("Check what pid file $lockfile exists.");
  222. if (! -e $lockfile) { log_debug("pid file not found. Continue."); return 1; }
  223. open (FF,"<$lockfile") or log_die "can't open file $lockfile: $!";
  224. my $lockid = <FF>;
  225. close(FF);
  226. chomp($lockid);
  227. if ($lockid eq $$) { log_debug("pid file is my. continue."); return 1; }
  228. log_debug("Another proceess with name $MY_NAME pid: $lockid already worked. ");
  229. return 0;
  230. }
  231. #---------------------------------------------------------------------------------------------------------
  232. sub Add_PID {
  233. my $pname = shift;
  234. my $lockfile = $pname.".pid";
  235. log_debug("Try create lock file $lockfile");
  236. open (FF,">$lockfile") or log_die "can't open file $lockfile: $!";
  237. flock(FF,2) or log_die "can't flock $lockfile: $!";
  238. print FF $$;
  239. close(FF);
  240. log_debug("Ok.");
  241. return 1;
  242. }
  243. #---------------------------------------------------------------------------------------------------------
  244. sub Remove_PID {
  245. my $pname = shift;
  246. my $lockfile = $pname.".pid";
  247. log_debug("Check what pid file $lockfile exists.");
  248. if (! -e $lockfile) { log_debug("pid file not exists. Continue."); return 1; }
  249. unlink $lockfile or return 0;
  250. log_debug("pid file $lockfile removed.");
  251. return 1;
  252. }
  253. #---------------------------------------------------------------------------------------------------------
  254. sub IsNotLocked {
  255. my $lockfile = $_[0] . ".lock";
  256. log_debug("Check what lock file $lockfile exists.");
  257. if (! -e $lockfile) { log_debug("lock file not found. Continue."); return 1; }
  258. open (FF,"<$lockfile") or log_die "can't open file $lockfile: $!";
  259. my $lockid = <FF>;
  260. close(FF);
  261. chomp($lockid);
  262. if ($lockid eq $$) { log_debug("lock file found, but it is owner is this process. Continue. "); return 1; }
  263. my $process_count = `ps -p $lockid | grep \'$lockid\' | wc -l`;
  264. if ($process_count lt 1) { log_debug("lock file found, but owner process not found. Remove lock file and continue. "); unlink $lockfile; return 1; }
  265. log_debug("Another proceess with pid: $lockid already use $_[0]");
  266. return 0;
  267. }
  268. #---------------------------------------------------------------------------------------------------------
  269. sub IsMyLock {
  270. my $lockfile = $_[0] . ".lock";
  271. log_debug("Check what lock file $lockfile exists.");
  272. if (! -e $lockfile) { log_debug("lock file not found. Continue."); return 0; }
  273. open (FF,"<$lockfile") or log_die "can't open file $lockfile: $!";
  274. my $lockid = <FF>;
  275. close(FF);
  276. chomp($lockid);
  277. if ($lockid eq $$) { log_debug("lock file found, but it is owner is this process. Continue. "); return 1; }
  278. log_debug("file $_[0] used by process with pid: $lockid");
  279. return 0;
  280. }
  281. #---------------------------------------------------------------------------------------------------------
  282. sub Add_Lock {
  283. if (!IsNotLocked($_[0])) { return 0; }
  284. my $lockfile = $_[0] . ".lock";
  285. open (FF,">$lockfile") or log_die "can't open file $lockfile: $!";
  286. flock(FF,2) or log_die "can't flock $lockfile: $!";
  287. print FF $$;
  288. close(FF);
  289. log_debug("Create lock file for $_[0]");
  290. return 1;
  291. }
  292. #---------------------------------------------------------------------------------------------------------
  293. sub Remove_Lock {
  294. if (!IsNotLocked($_[0])) { return 0; }
  295. my $lockfile = $_[0] . ".lock";
  296. if (! -e $lockfile) { return 1; }
  297. unlink $lockfile or return 0;
  298. log_debug("Lock file for $_[0] removed");
  299. return 1;
  300. }
  301. #---------------------------------------------------------------------------------------------------------
  302. sub DefHash {
  303. my $hash=$_[0];
  304. my $num_list = $_[1];
  305. my %num_keys;
  306. if ($num_list) {
  307. my @ret_num = split(' ',$num_list);
  308. %num_keys = map { $_, 1 } @ret_num;
  309. }
  310. foreach my $key (keys %$hash) {
  311. my $null_value = "";
  312. $null_value = 0 if (defined $num_keys{$key});
  313. $hash->{$key}=$null_value if (!defined($hash->{$key}));
  314. }
  315. return $hash;
  316. }
  317. #---------------------------------------------------------------------------------------------------------
  318. sub read_file {
  319. my $filename = shift;
  320. return if (!$filename);
  321. return if (!-e $filename);
  322. open (FF,"<$filename") or die "unable to open file $filename!" ;
  323. my @tmp=<FF>;
  324. close(FF);
  325. chomp(@tmp);
  326. return @tmp;
  327. }
  328. #---------------------------------------------------------------------------------------------------------
  329. sub uniq (\@) {
  330. my @tmp = @{(shift)};
  331. if (scalar(@tmp) eq 0) { return @tmp; }
  332. chomp(@tmp);
  333. my %newlist = map { $_, 1 } @tmp;
  334. return keys %newlist;
  335. }
  336. #---------------------------------------------------------------------------------------------------------
  337. sub strim {
  338. my $str=shift;
  339. return if (!$str);
  340. #$str =~ s/.*[^[:print:]]+//g;
  341. #$str =~ s/[^[:print:]]+//g;
  342. #$str =~ s/[^(a-z|A-Z|0-9|\:|\-|\s|\.)]//g;
  343. #$str =~ s/[:^print:]//g;
  344. $str =~ s/[^[:ascii:]]//g;
  345. $str =~ s/^\s+//g;
  346. $str =~ s/\s+$//g;
  347. return $str;
  348. }
  349. #---------------------------------------------------------------------------------------------------------
  350. sub trim {
  351. my $str=shift;
  352. return if (!$str);
  353. $str =~ s/\n/ /g;
  354. $str =~ s/^\s+//g;
  355. $str =~ s/\s+$//g;
  356. return $str;
  357. }
  358. #---------------------------------------------------------------------------------------------------------
  359. sub is_integer {
  360. defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
  361. }
  362. #---------------------------------------------------------------------------------------------------------
  363. sub is_float {
  364. defined $_[0] && $_[0] =~ /^[+-]?\d+(\.\d+)?$/;
  365. }
  366. #---------------------------------------------------------------------------------------------------------
  367. sub run_in_parallel(\@) {
  368. my @commands = @{(shift)};
  369. my @result = ();
  370. return @result if (!@commands or !scalar(@commands));
  371. my $count = scalar(@commands);
  372. my $start = 0;
  373. while ($start<=$count-1) {
  374. my @run_list=();
  375. my $select = IO::Select->new();
  376. my $stop = $start + $parallel_process_count;
  377. $stop=$count-1 if ($stop >=$count);
  378. for (my $index = $start; $index <=$stop; $index++) {
  379. next if (!$commands[$index]);
  380. my $cmd=$commands[$index];
  381. log_info("Starting ".$cmd);
  382. my ($hchild, $hparent, $childid);
  383. socketpair($hchild, $hparent, AF_UNIX, SOCK_STREAM, PF_UNSPEC) or die "socketpair: $!";
  384. $childid = fork;
  385. die "cannot fork" if($childid == -1);
  386. # redirect child Input|Output
  387. unless($childid) {
  388. open STDIN, "<&", $hparent;
  389. open STDOUT, ">&", $hparent;
  390. open STDERR, ">&", $hparent;
  391. close $hparent;
  392. close $hchild;
  393. $select->remove($_) and close $_ for($select->handles);
  394. exec "/bin/nice -n 15 ".$cmd;
  395. }
  396. close $hparent;
  397. $select->add($hchild);
  398. }
  399. while (my @ready = $select->can_read) {
  400. next if (!@ready or !scalar(@ready));
  401. for my $read(@ready) {
  402. if($read->eof || $read->error) {
  403. # child exit
  404. $select->remove($read);
  405. close $read;
  406. next;
  407. }
  408. if(defined(my $str = <$read>)) {
  409. log_info("Read:".$str);
  410. push(@result,$str);
  411. }
  412. }
  413. }
  414. $start = $stop+1;
  415. }
  416. return (@result);
  417. }
  418. sub translit {
  419. my $textline=shift;
  420. return if (!$textline);
  421. $textline =~ s/А/A/g; $textline =~ s/а/a/g;
  422. $textline =~ s/Б/B/g; $textline =~ s/б/b/g;
  423. $textline =~ s/В/V/g; $textline =~ s/в/v/g;
  424. $textline =~ s/Г/G/g; $textline =~ s/г/g/g;
  425. $textline =~ s/Д/D/g; $textline =~ s/д/d/g;
  426. $textline =~ s/Е/E/g; $textline =~ s/е/e/g;
  427. $textline =~ s/Ё/E/g; $textline =~ s/ё/e/g;
  428. $textline =~ s/Ж/Zh/g; $textline =~ s/ж/zh/g;
  429. $textline =~ s/З/Z/g; $textline =~ s/з/z/g;
  430. $textline =~ s/И/I/g; $textline =~ s/и/i/g;
  431. $textline =~ s/Й/I/g; $textline =~ s/й/i/g;
  432. $textline =~ s/К/K/g; $textline =~ s/к/k/g;
  433. $textline =~ s/Л/L/g; $textline =~ s/л/l/g;
  434. $textline =~ s/М/M/g; $textline =~ s/м/m/g;
  435. $textline =~ s/Н/N/g; $textline =~ s/н/n/g;
  436. $textline =~ s/О/O/g; $textline =~ s/о/o/g;
  437. $textline =~ s/П/P/g; $textline =~ s/п/p/g;
  438. $textline =~ s/Р/R/g; $textline =~ s/р/r/g;
  439. $textline =~ s/ТС/T-S/g; $textline =~ s/Тс/T-s/g; $textline =~ s/тс/t-s/g;
  440. $textline =~ s/С/S/g; $textline =~ s/с/s/g;
  441. $textline =~ s/Т/T/g; $textline =~ s/т/t/g;
  442. $textline =~ s/У/U/g; $textline =~ s/у/u/g;
  443. $textline =~ s/Ф/F/g; $textline =~ s/ф/f/g;
  444. $textline =~ s/Х/Kh/g; $textline =~ s/х/kh/g;
  445. $textline =~ s/Ц/Ts/g; $textline =~ s/ц/ts/g;
  446. $textline =~ s/Ч/Ch/g; $textline =~ s/ч/ch/g;
  447. $textline =~ s/Ш/Sh/g; $textline =~ s/ш/sh/g;
  448. $textline =~ s/Щ/Shch/g; $textline =~ s/щ/shch/g;
  449. $textline =~ s/Ь/'/g; $textline =~ s/ь/'/g;
  450. $textline =~ s/Ы/Y/g; $textline =~ s/ы/y/g;
  451. $textline =~ s/Ъ/''/g; $textline =~ s/ъ/''/g;
  452. $textline =~ s/Э/E/g; $textline =~ s/э/e/g;
  453. $textline =~ s/Ю/Yu/g; $textline =~ s/ю/yu/g;
  454. $textline =~ s/Я/Ya/g; $textline =~ s/я/ya/g;
  455. return $textline;
  456. }
  457. #log_file($LOG_COMMON,"INFO:","----------------------------------------------------------------------------------------");
  458. #log_file($LOG_COMMON,"INFO:","Run script $0. Pid: $$ Pid file: $SPID.pid");
  459. #log_file($LOG_COMMON,"INFO:","User uid: $< Effective uid: $>");
  460. #log_file($LOG_COMMON,"INFO:","Status:");
  461. #log_file($LOG_COMMON,"INFO:","Logging enabled: $log_enable");
  462. #log_file($LOG_COMMON,"INFO:","Logging debug: $debug");
  463. 1;
  464. }