Skip to content

Commit

Permalink
feat: database connection multiple retries (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
vishal-chdhry authored Feb 1, 2024
1 parent 9fc2ccc commit 61f0a02
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion pkg/storage/db/new.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
package db

import (
"context"
"database/sql"
"fmt"
"time"

"github.com/kyverno/reports-server/pkg/storage/api"
_ "github.com/lib/pq"
"k8s.io/klog/v2"
)

const (
maxRetries = 10
backoffDuration = 15 * time.Second
)

func New(config *PostgresConfig) (api.Storage, error) {
klog.Infof("starting postgres db, config: %s", config.String())
db, err := sql.Open("postgres", config.String())
Expand All @@ -17,7 +24,18 @@ func New(config *PostgresConfig) (api.Storage, error) {
return nil, err
}

klog.Info("pinging postgres db")
sleepDuration := 0 * time.Second
for attempt := 1; attempt <= maxRetries; attempt++ {
time.Sleep(sleepDuration)
klog.Infof("pinging postgres db, attempt: %d", attempt)
err := db.PingContext(context.TODO())
if err == nil {
break
}
klog.Error("failed to ping db", err.Error())
sleepDuration = sleepDuration + backoffDuration
}

err = db.Ping()
if err != nil {
klog.Error("failed to ping db", err.Error())
Expand Down

0 comments on commit 61f0a02

Please sign in to comment.