From 510257fd8b8f3480bd28fb889fc86aade923b997 Mon Sep 17 00:00:00 2001 From: Adhityaa Date: Wed, 20 Jun 2018 09:19:39 +0530 Subject: [PATCH] api: retry database connection if it fails Closes https://gitlab.com/commento/commento-ce/issues/52 --- api/database_connect.go | 15 ++++++++++++++- api/main.go | 2 +- api/testing.go | 2 +- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/api/database_connect.go b/api/database_connect.go index 110763e..202b9bf 100644 --- a/api/database_connect.go +++ b/api/database_connect.go @@ -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 diff --git a/api/main.go b/api/main.go index 703d621..08d5008 100644 --- a/api/main.go +++ b/api/main.go @@ -3,7 +3,7 @@ package main func main() { exitIfError(createLogger()) exitIfError(parseConfig()) - exitIfError(connectDB()) + exitIfError(connectDB(5)) exitIfError(performMigrations()) exitIfError(smtpConfigure()) exitIfError(smtpTemplatesLoad()) diff --git a/api/testing.go b/api/testing.go index 881d2a2..7f7c13d 100644 --- a/api/testing.go +++ b/api/testing.go @@ -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 }