api: retry database connection if it fails

Closes https://gitlab.com/commento/commento-ce/issues/52
This commit is contained in:
Adhityaa 2018-06-20 09:19:39 +05:30
parent 237a02bee9
commit 510257fd8b
3 changed files with 16 additions and 3 deletions

View File

@ -1,12 +1,13 @@
package main
import (
"time"
"database/sql"
_ "github.com/lib/pq"
"os"
)
func connectDB() error {
func connectDB(retriesLeft int) error {
con := os.Getenv("POSTGRES")
logger.Infof("opening connection to postgres: %s", con)
@ -17,6 +18,18 @@ func connectDB() error {
return err
}
err = db.Ping()
if err != nil {
if retriesLeft > 0 {
logger.Errorf("cannot talk to postgres, retrying in 10 seconds (%d attempts left): %v", retriesLeft-1, err)
time.Sleep(10 * time.Second)
return connectDB(retriesLeft - 1)
} else {
logger.Errorf("cannot talk to postgres, last attempt failed: %v", err)
return err
}
}
statement := `
CREATE TABLE IF NOT EXISTS migrations (
filename TEXT NOT NULL UNIQUE

View File

@ -3,7 +3,7 @@ package main
func main() {
exitIfError(createLogger())
exitIfError(parseConfig())
exitIfError(connectDB())
exitIfError(connectDB(5))
exitIfError(performMigrations())
exitIfError(smtpConfigure())
exitIfError(smtpTemplatesLoad())

View File

@ -68,7 +68,7 @@ func setupTestDatabase() error {
os.Setenv("POSTGRES", "postgres://postgres:postgres@localhost/commento_test?sslmode=disable")
}
if err := connectDB(); err != nil {
if err := connectDB(0); err != nil {
return err
}