1
0

main.pm 16 KB

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