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 package main
import ( import (
"time"
"database/sql" "database/sql"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"os" "os"
) )
func connectDB() error { func connectDB(retriesLeft int) error {
con := os.Getenv("POSTGRES") con := os.Getenv("POSTGRES")
logger.Infof("opening connection to postgres: %s", con) logger.Infof("opening connection to postgres: %s", con)
@ -17,6 +18,18 @@ func connectDB() error {
return err 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 := ` statement := `
CREATE TABLE IF NOT EXISTS migrations ( CREATE TABLE IF NOT EXISTS migrations (
filename TEXT NOT NULL UNIQUE filename TEXT NOT NULL UNIQUE

View File

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

View File

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