From af4c8f61da6c94e9ac2f1d1438bd7c7ac134d304 Mon Sep 17 00:00:00 2001 From: gfrancqu Date: Thu, 28 Mar 2019 04:48:31 +0100 Subject: [PATCH] Wait for db (#1402) Added a loop that attempts to connect to the configured database. --- models/models.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/models/models.go b/models/models.go index 3b1c82f9..1ef38a47 100644 --- a/models/models.go +++ b/models/models.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "fmt" "io" + "time" "bitbucket.org/liamstask/goose/lib/goose" @@ -17,6 +18,8 @@ import ( var db *gorm.DB var conf *config.Config +const MaxDatabaseConnectionAttempts int = 10 + const ( CampaignInProgress string = "In progress" CampaignQueued string = "Queued" @@ -94,7 +97,20 @@ func Setup(c *config.Config) error { return err } // Open our database connection - db, err = gorm.Open(conf.DBName, conf.DBPath) + i := 0 + for { + db, err = gorm.Open(conf.DBName, conf.DBPath) + if err == nil { + break + } + if err != nil && i >= MaxDatabaseConnectionAttempts { + log.Error(err) + return err + } + i += 1 + log.Warn("waiting for database to be up...") + time.Sleep(5 * time.Second) + } db.LogMode(false) db.SetLogger(log.Logger) db.DB().SetMaxOpenConns(1)