Skip to content

Commit

Permalink
feat: add timeout to connect
Browse files Browse the repository at this point in the history
  • Loading branch information
anbraten committed Feb 1, 2022
1 parent 612e60c commit a526aaf
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
8 changes: 7 additions & 1 deletion adapters/couchdb_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,13 @@ func (adapter couchdbAdapter) Close(ctx context.Context) error {
func GetCouchdbConnection(ctx context.Context, url string) (*couchdbAdapter, error) {
client, err := kivik.New("couch", url)
if err != nil {
panic(err)
return nil, err
}

// do some call to test if connection is working
_, err = client.ClusterStatus(ctx)
if err != nil {
return nil, err
}

adapter := couchdbAdapter{
Expand Down
1 change: 0 additions & 1 deletion adapters/mongo_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ func (adapter mongoAdapter) Close(ctx context.Context) error {
func GetMongoConnection(ctx context.Context, url string) (*mongoAdapter, error) {
clientOpts := options.Client().ApplyURI(url)
client, err := mongo.Connect(ctx, clientOpts)

if err != nil {
return nil, err
}
Expand Down
7 changes: 6 additions & 1 deletion controllers/database_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package controllers
import (
"context"
"os"
"time"

"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/api/errors"
Expand Down Expand Up @@ -53,7 +54,11 @@ func (r *DatabaseReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
return ctrl.Result{}, err
}

db, err := r.getDatabaseConnection(ctx, database.Spec.Type)
// use maximum of 3 seconds to connect
openCtx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*3))
defer cancel()

db, err := r.getDatabaseConnection(openCtx, database.Spec.Type)
if err != nil {
log.Error(err, "Failed to detect or open database connection")
return ctrl.Result{}, err
Expand Down

0 comments on commit a526aaf

Please sign in to comment.