Skip to content

Commit

Permalink
Merge pull request #144 from lbryio/db_retry
Browse files Browse the repository at this point in the history
DB Retry Behavior
  • Loading branch information
tiger5226 committed Jan 24, 2020
2 parents ab4aeb8 + 4af0cf5 commit c1880cb
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion internal/storage/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package storage

import (
"fmt"
"time"

"github.com/lbryio/lbrytv/internal/monitor"

Expand All @@ -10,6 +11,8 @@ import (
"github.com/volatiletech/sqlboiler/boil"
)

const maxDBConnectAttempts = 7

// Handler implements the app database handler.
type Handler interface {
MigrateUp()
Expand Down Expand Up @@ -59,7 +62,18 @@ func InitConn(params ConnParams) *Connection {
func (c *Connection) Connect() error {
dsn := MakeDSN(c.params)
c.logger.LogF(monitor.F{"dsn": dsn}).Info("connecting to the DB")
db, err := sqlx.Connect(c.dialect, dsn)
var err error
var db *sqlx.DB
for i := 0; i < maxDBConnectAttempts; i++ {
db, err = sqlx.Connect(c.dialect, dsn)
if err == nil {
break
}
secondsToWait := i + 1
c.logger.Log().Warningf("Attempt %d - could not connect to database...retry in %d seconds: %s", i, secondsToWait, err)
time.Sleep(time.Duration(secondsToWait) * time.Second)
}

if err != nil {
c.logger.LogF(monitor.F{"dsn": dsn}).Info("DB connection failed")
return err
Expand Down

0 comments on commit c1880cb

Please sign in to comment.