Guest User

Untitled

a guest
Apr 14th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1.  
  2. use strict;
  3. use warnings;
  4. use Socket;
  5. use Getopt::Long;
  6. use DBI ':sql_types';
  7.  
  8. use Time::HiRes 'gettimeofday';
  9. use Try::Tiny;
  10.  
  11. Getopt::Long::Configure(qw/bundling no_ignore_case/);
  12. my %opt;
  13. GetOptions(\%opt, qw/
  14. port|p=s host|h=s count|c=i fork|f=i debug|d=s
  15. /);
  16. $opt{host} ||= '127.0.0.1';
  17.  
  18. my $pid = $$;
  19.  
  20. my $cc = 1;
  21. my @childs;
  22. my $logname = sprintf("db_c%s_f%s_%s.log", $opt{count}, $opt{fork}, 'insert');
  23.  
  24. _log(sprintf "fork [%s], count [%s]", $opt{fork}, $opt{count});
  25.  
  26. for (my $f = 1; $f <= $opt{fork}; $f++) {
  27. my $parent = fork();
  28. if ($parent) {
  29. push(@childs, $parent);
  30. } elsif ($parent == 0) {
  31. my $dbh = db_connect();
  32. commands: for (my $i = 1; $i <= $opt{count}; $i++) {
  33. my $handle = sprintf "T%d%03d%03d%03d", $$, $cc, $i, $f;
  34. my $t0 = [gettimeofday];
  35. try {
  36. my $sql = insert_contact();
  37. my $sth = $dbh->prepare($sql);
  38. $sth->bind_param(':handle', $handle);
  39. $sth->execute;
  40. $sth->finish;
  41. $dbh->commit;
  42. } catch {
  43. $dbh = db_connect();
  44. _log("reconnecting $i, $f, $cc");
  45. redo commands;
  46. };
  47. my $elapsed = Time::HiRes::tv_interval ( $t0 );
  48. _log("handle:[$handle];timed[$elapsed]");
  49. # sleep 1;
  50. }
  51. $dbh->disconnect();
  52. exit(0);
  53. } ## end of fork if
  54. else { die "we have a furcking problem $!\n"; }
  55. }
  56.  
  57. foreach (@childs) {
  58. waitpid($_, 0);
  59. }
  60.  
  61. exit;
  62.  
  63. sub db_connect {
  64. my $host = 'localhost';
  65. my $dbname = 'mh_regbox';
  66. my $port = '5432';
  67. my $username = 'mh';
  68. my $password = 'mh';
  69.  
  70. my $dbh = DBI->connect("dbi:Pg:dbname=$dbname;host=$host;port=$port;", "$username", "$password",
  71. {AutoCommit => 0});
  72. return $dbh;
  73. }
  74.  
  75. sub _log {
  76. my $str = shift;
  77. 1 while chomp($str);
  78. my $message = sprintf "%s [%08d] %s\n", precdate(1), $$, $str;
  79. # print STDERR $message;
  80. open LOG, ">>$logname";
  81. print LOG $message;
  82. close LOG;
  83. }
  84.  
  85.  
  86. sub precdate {
  87. my @hires = gettimeofday();
  88. return sub {
  89. sprintf "%04d%02d%02d.%02d%02d%02d",
  90. $_[5]+1900,$_[4]+1,@_[3,2,1,0]
  91. }->(localtime($hires[0]))
  92. . (@_ ? sprintf(".%06d",$hires[1]) : "");
  93. }
  94.  
  95.  
  96. sub insert_contact {
  97. qq/INSERT INTO bla (
  98. /;
  99. }
Add Comment
Please, Sign In to add comment