Retry opening DB connections. (#140)

Make sure DB connection retry also reopens a connection after closing it
This commit is contained in:
Oleksii Kliukin 2017-10-18 16:28:00 +02:00 committed by GitHub
parent 99870d8eac
commit 1dbf259c76
1 changed files with 18 additions and 14 deletions

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"net" "net"
"strings" "strings"
"time"
"github.com/lib/pq" "github.com/lib/pq"
@ -35,7 +36,7 @@ func (c *Cluster) pgConnectionString() string {
fmt.Sprintf("%s.%s.svc.cluster.local", c.Name, c.Namespace), fmt.Sprintf("%s.%s.svc.cluster.local", c.Name, c.Namespace),
c.systemUsers[constants.SuperuserKeyName].Name, c.systemUsers[constants.SuperuserKeyName].Name,
strings.Replace(password, "$", "\\$", -1), strings.Replace(password, "$", "\\$", -1),
constants.PostgresConnectTimeout) constants.PostgresConnectTimeout/time.Second)
} }
func (c *Cluster) databaseAccessDisabled() bool { func (c *Cluster) databaseAccessDisabled() bool {
@ -52,33 +53,36 @@ func (c *Cluster) initDbConn() error {
return nil return nil
} }
conn, err := sql.Open("postgres", c.pgConnectionString()) var conn *sql.DB
if err != nil { connstring := c.pgConnectionString()
return err
}
c.logger.Debug("new database connection") finalerr := retryutil.Retry(constants.PostgresConnectTimeout, constants.PostgresConnectRetryTimeout,
err = retryutil.Retry(constants.PostgresConnectTimeout, constants.PostgresConnectRetryTimeout,
func() (bool, error) { func() (bool, error) {
err := conn.Ping() var err error
conn, err = sql.Open("postgres", connstring)
if err == nil { if err == nil {
return true, nil err = conn.Ping()
} }
if err2 := conn.Close(); err2 != nil { if err == nil {
c.logger.Errorf("error when closing PostgreSQL connection after another error: %v", err2) return true, nil
return false, err2
} }
if _, ok := err.(*net.OpError); ok { if _, ok := err.(*net.OpError); ok {
c.logger.Errorf("could not connect to PostgreSQL database: %v", err) c.logger.Errorf("could not connect to PostgreSQL database: %v", err)
return false, nil return false, nil
} }
if err2 := conn.Close(); err2 != nil {
c.logger.Errorf("error when closing PostgreSQL connection after another error: %v", err)
return false, err2
}
return false, err return false, err
}) })
if err != nil { if finalerr != nil {
return fmt.Errorf("could not init db connection: %v", err) return fmt.Errorf("could not init db connection: %v", finalerr)
} }
c.pgDb = conn c.pgDb = conn