http://www.perlmonks.org?node_id=548304

Readonly my $MAX_ATTEMPTS => 5; my ( $i, $dbh ); for ( $i = 1 ; $i < $MAX_ATTEMPTS ; ++$i ) { $dbh = DBI->connect( "dbi:SQLite:dbname=$DB", "", "" ); if ( !$dbh ) { warn "problem from $host: " . $DBI::errstr; next; } my $ss = "insert into stats values(?,?,?,?,?,?,?,?,?)"; my $ts = strftime( "%F@%T", localtime ); my $rv = $dbh->do( $ss, undef, $host, $load, $sf, $tmeming, $mempct, @stats{ 'runproc', 'users' }, $ts, $msg ); ( $dbh->errstr ) && warn "problem from $host: " . $dbh->errstr; if ($rv) { last; } else { warn "problem from $host: " . $dbh->errstr; } sleep(1); } ## end for ( $i = 1 ; $i < 5 ; ++$i ) if ( $i == $MAX_ATTEMPTS ) { warn "$DB failed write test five times from $host"; } elsif ( $i > 1 ) { my $msg = "$ts $host had to try $i time(s) to write to $DB"; warn $msg; }

More current code:

my ( $num_tries, $curr_dbh ); UPD_CURR_DB: for my $i ( 1 .. $MAX_ATTEMPTS ) { $num_tries = $i; $curr_dbh = DBI->connect( "dbi:SQLite:dbname=$CURR_DB", "", "" ); if ( !$curr_dbh ) { warn "problem from $stats{host}: " . $DBI::errstr; #If it didn't work, take a nap and maybe things will get bette +r... sleep(1); next UPD_CURR_DB; } #Aha! Now you see why we used this construct to store our stats! #format: do(sql statement,attrs hash,bind values) my $sql_stmt = "replace into $DB_TABLE $COL_LIST values(?,?,?,?,?, +?)"; my $rv = $curr_dbh->do( $sql_stmt, undef, @stats{ 'host', 'load', 'free_scratch', 'free_mem', 'swapped_m +em', 'timestamp', } ); ( $curr_dbh->errstr ) && warn "problem from $stats{host}: " . $cur +r_dbh->errstr; if ($rv) { #if this is our first try, get out of the DB ($i == 1) && $curr_dbh->disconnect or warn "problem from $stats{host} on try # $i: " . $curr_dbh->er +rstr; # and move on, ASAP! last UPD_CURR_DB; } else { warn "problem from $stats{host} on try # $i: " . $curr_dbh->er +rstr; } #If it didn't work, take a nap and maybe things will get better... sleep(1); } ## end for my $i ( 1 .. 5 ) #print "It took us $num_tries tries to write to $CURR_DB."; if ( $num_tries == $MAX_ATTEMPTS ) { warn "$CURR_DB failed write test $MAX_ATTEMPTS times from $stats{h +ost}"; } elsif ( $num_tries > 1 ) { my $sql_stmt = "update $DB_TABLE set Message=? where Host=?"; my $msg = "Took $num_tries tries to update DB"; my $rv = $dbh->do( $sql_stmt, undef, $stats{host},$msg); if ( !$rv ) { warn "problem from $stats{host}: " . $dbh->errstr; my $rv2 = open( F, ">>/fst/prod1/lib/peak/peakstats.log" ); my $ofh; if ($rv2) { $ofh = select F; } else { warn "can't open log file from $stats{host} to append: $!" +; } print "$msg; this fact could not be recorded in 'retries' tabl +e: " . $dbh->errstr; if ($rv2) { select $ofh; close(F); } } ## end if ( !$rv ) } ## end elsif ( $i > 1 ) [ if ( $i == 5 ) ($dbh) && $dbh->disconnect;