@@ -99,6 +99,28 @@ func retryHTTPRequest(requestFunc func() (*http.Response, error), retries int, b
9999 return resp , nil
100100}
101101
102+ // "Check the response status; if it is one of 500, 501, 502, 503, or 504 the request will be resending (only 4 retries)."
103+ func retryHTTPForIAMRequest (requestFunc func () (* http.Response , error ), retries int , baseDelayInMilliSec time.Duration ) (* http.Response , error ) {
104+
105+ var resp * http.Response
106+ var err error
107+
108+ for attempt := 0 ; attempt < retries ; attempt ++ {
109+ resp , err = requestFunc ()
110+ if err != nil {
111+ return nil , err
112+ }
113+ if resp .StatusCode >= 500 && resp .StatusCode <= 504 {
114+ logger .PrintIfVerbose (fmt .Sprintf ("Encountered HTTP %s response — will retry " , resp .Status ))
115+ } else {
116+ return resp , nil
117+ }
118+ _ = resp .Body .Close ()
119+ time .Sleep (baseDelayInMilliSec * (3 << attempt ))
120+ }
121+ return nil , err
122+ }
123+
102124func setAgentNameAndOrigin (req * http.Request ) {
103125 agentStr := viper .GetString (commonParams .AgentNameKey ) + "/" + commonParams .Version
104126 req .Header .Set ("User-Agent" , agentStr )
@@ -513,7 +535,26 @@ func getNewToken(credentialsPayload, authServerURI string) (string, error) {
513535 clientTimeout := viper .GetUint (commonParams .ClientTimeoutKey )
514536 client := GetClient (clientTimeout )
515537
516- res , err := doPrivateRequest (client , req )
538+ //Save body for retry logic
539+ var body []byte
540+ if req .Body != nil {
541+ body , err = io .ReadAll (req .Body )
542+ if err != nil {
543+ fmt .Errorf ("failed to read request body: %w" , err )
544+ }
545+ if req .Body != nil {
546+ req .Body .Close ()
547+ }
548+ }
549+ fn := func () (* http.Response , error ) {
550+ if body != nil {
551+ _ = req .Body .Close ()
552+ req .Body = io .NopCloser (bytes .NewBuffer (body ))
553+ }
554+ return doPrivateRequest (client , req )
555+ }
556+ res , err := retryHTTPForIAMRequest (fn , retryAttempts , retryDelay * time .Millisecond )
557+
517558 if err != nil {
518559 authURL , _ := GetAuthURI ()
519560 return "" , errors .Errorf ("%s %s" , checkmarxURLError , authURL )
@@ -528,7 +569,7 @@ func getNewToken(credentialsPayload, authServerURI string) (string, error) {
528569 return "" , errors .Errorf ("%d %s \n " , res .StatusCode , invalidCredentialsError )
529570 }
530571
531- body , _ : = ioutil .ReadAll (res .Body )
572+ body , _ = ioutil .ReadAll (res .Body )
532573 if res .StatusCode != http .StatusOK {
533574 credentialsErr := ClientCredentialsError {}
534575 err = json .Unmarshal (body , & credentialsErr )
0 commit comments