api: retry database connection if it fails
Closes https://gitlab.com/commento/commento-ce/issues/52
This commit is contained in:
parent
237a02bee9
commit
510257fd8b
@ -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
|
||||
|
@ -3,7 +3,7 @@ package main
|
||||
func main() {
|
||||
exitIfError(createLogger())
|
||||
exitIfError(parseConfig())
|
||||
exitIfError(connectDB())
|
||||
exitIfError(connectDB(5))
|
||||
exitIfError(performMigrations())
|
||||
exitIfError(smtpConfigure())
|
||||
exitIfError(smtpTemplatesLoad())
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user