From e52a375a1edfabfeabe3d3a641967e9a70ad3cd8 Mon Sep 17 00:00:00 2001 From: Javier Marcos <1271349+javuto@users.noreply.github.com> Date: Mon, 11 Dec 2023 09:46:17 +0100 Subject: [PATCH] Adding db connection retry --- api/main.go | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/api/main.go b/api/main.go index 0fc5b32c..ff05c981 100644 --- a/api/main.go +++ b/api/main.go @@ -51,6 +51,8 @@ const ( defJWTConfigurationFile = "config/jwt.json" // Default refreshing interval in seconds defaultRefresh int = 300 + // Default timeout to attempt backend reconnect + defaultBackendRetryTimeout int = 7 ) // Paths @@ -86,11 +88,6 @@ const ( apiSettingsPath = "/settings" ) -var ( - // Wait for backend in seconds - backendWait = 7 * time.Second -) - // Global variables var ( err error @@ -344,6 +341,13 @@ func init() { EnvVars: []string{"DB_CONN_MAX_LIFETIME"}, Destination: &dbConfig.ConnMaxLifetime, }, + &cli.IntFlag{ + Name: "db-conn-retry", + Value: defaultBackendRetryTimeout, + Usage: "Time in seconds to retry the connection to the database, if set to 0 the service will stop if the connection fails", + EnvVars: []string{"DB_CONN_RETRY"}, + Destination: &dbConfig.ConnRetry, + }, &cli.BoolFlag{ Name: "tls", Aliases: []string{"t"}, @@ -411,10 +415,13 @@ func osctrlAPIService() { break } if err != nil { - log.Fatalf("Failed to connect to backend - %v", err) + log.Printf("Failed to connect to backend - %v", err) + if dbConfig.ConnRetry == 0 { + log.Fatalf("Connection to backend failed and no retry was set") + } } - log.Println("Backend NOT ready! waiting...") - time.Sleep(backendWait) + log.Printf("Backend NOT ready! Retrying in %d seconds...\n", dbConfig.ConnRetry) + time.Sleep(time.Duration(dbConfig.ConnRetry) * time.Second) } // Redis - cache redis, err = cache.CreateRedisManager(redisConfig)