From a526aafd558e0daa7f33ae2db29157391fe8f7e7 Mon Sep 17 00:00:00 2001 From: Anton Bracke Date: Tue, 1 Feb 2022 17:46:04 +0100 Subject: [PATCH] feat: add timeout to connect --- adapters/couchdb_adapter.go | 8 +++++++- adapters/mongo_adapter.go | 1 - controllers/database_controller.go | 7 ++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/adapters/couchdb_adapter.go b/adapters/couchdb_adapter.go index 10d8880..2efa993 100644 --- a/adapters/couchdb_adapter.go +++ b/adapters/couchdb_adapter.go @@ -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{ diff --git a/adapters/mongo_adapter.go b/adapters/mongo_adapter.go index 1b85357..87b97a0 100644 --- a/adapters/mongo_adapter.go +++ b/adapters/mongo_adapter.go @@ -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 } diff --git a/controllers/database_controller.go b/controllers/database_controller.go index 753b832..da4ce98 100644 --- a/controllers/database_controller.go +++ b/controllers/database_controller.go @@ -3,6 +3,7 @@ package controllers import ( "context" "os" + "time" "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/api/errors" @@ -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