From 3b5d037a270d3e9e11587562e83fbaa6628f4526 Mon Sep 17 00:00:00 2001 From: Umair Idris Date: Mon, 24 Feb 2020 17:59:53 +0000 Subject: [PATCH] add health check (#44) * add health check * use new var name * improve healthcheck to detect invalid credentials * simplify error msg * add retry * add sleep * replace dots with colon --- cdap/provider.go | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/cdap/provider.go b/cdap/provider.go index 8ba288b..ab8b415 100644 --- a/cdap/provider.go +++ b/cdap/provider.go @@ -17,6 +17,9 @@ package cdap import ( "context" + "encoding/json" + "fmt" + "log" "net/http" "time" @@ -72,16 +75,45 @@ func configureProvider(d *schema.ResourceData) (interface{}, error) { TokenType: "Bearer", })) } - httpClient.Timeout = 30 * time.Minute + httpClient.Timeout = 5 * time.Minute storageClient, err := storage.NewClient(ctx, option.WithScopes(storage.ScopeReadOnly)) if err != nil { return nil, err } - return &Config{ + c := &Config{ host: d.Get("host").(string), httpClient: httpClient, storageClient: storageClient, - }, nil + } + + if err := healthcheck(c); err != nil { + log.Printf("failed health check, trying again after 5 seconds: %v", err) + time.Sleep(5 * time.Second) + if err := healthcheck(c); err != nil { + return nil, fmt.Errorf("failed health check, possibly due to an invalid host or credentials: %v", err) + } + } + return c, nil +} + +func healthcheck(c *Config) error { + addr := urlJoin(c.host, "/v3/namespaces") + req, err := http.NewRequest(http.MethodGet, addr, nil) + if err != nil { + return err + } + b, err := httpCall(c.httpClient, req) + if err != nil { + return err + } + + // Invalid credentials currently result in a redirect to sign in page instead of an error. + // So check for a valid return value by unmarshalling the JSON. + var v interface{} + if err := json.Unmarshal(b, &v); err != nil { + return fmt.Errorf("failed to unmarshal response: %v\n%v", err, string(b)) + } + return nil }