From ceb61bed3b2fc9e5ea6fa3c9fec16196c1fd8613 Mon Sep 17 00:00:00 2001 From: dougbtv Date: Thu, 4 Jan 2024 15:45:50 -0500 Subject: [PATCH] Adds a wait to account for the possiblity of a not ready unix socket --- pkg/server/api/api.go | 47 ++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/pkg/server/api/api.go b/pkg/server/api/api.go index 9f348545e..eb52708cd 100644 --- a/pkg/server/api/api.go +++ b/pkg/server/api/api.go @@ -22,6 +22,7 @@ import ( "net" "net/http" "strings" + "time" ) const ( @@ -43,30 +44,40 @@ func DoCNI(url string, req interface{}, socketPath string) ([]byte, error) { return nil, fmt.Errorf("failed to marshal CNI request %v: %v", req, err) } - client := &http.Client{ - Transport: &http.Transport{ - Dial: func(proto, addr string) (net.Conn, error) { - return net.Dial("unix", socketPath) + // Retry parameters + maxRetries := 60 + delay := 2 * time.Second + + for i := 0; i < maxRetries; i++ { + client := &http.Client{ + Transport: &http.Transport{ + Dial: func(proto, addr string) (net.Conn, error) { + return net.Dial("unix", socketPath) + }, }, - }, - } + } - resp, err := client.Post(url, "application/json", bytes.NewReader(data)) - if err != nil { - return nil, fmt.Errorf("failed to send CNI request: %v", err) - } - defer resp.Body.Close() + resp, err := client.Post(url, "application/json", bytes.NewReader(data)) + if err == nil { + defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("failed to read CNI result: %v", err) - } + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read CNI result: %v", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("CNI request failed with status %v: '%s'", resp.StatusCode, string(body)) + } + + return body, nil + } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("CNI request failed with status %v: '%s'", resp.StatusCode, string(body)) + // Wait for the next retry + time.Sleep(delay) } - return body, nil + return nil, fmt.Errorf("failed to send CNI request after %d retries: %v", maxRetries, err) } // GetAPIEndpoint returns endpoint URL for multus-daemon