Skip to content

Commit

Permalink
Icinga2Client#Do(): call parent method, re-try on HTTP 503 300 times
Browse files Browse the repository at this point in the history
  • Loading branch information
Al2Klimov committed Mar 12, 2024
1 parent 18da892 commit df59d44
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions utils/icinga2_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"net/http"
"testing"
"time"
)

type Icinga2Client struct {
Expand All @@ -35,6 +36,39 @@ func NewIcinga2Client(address string, username string, password string) *Icinga2
}
}

// getNoBody successfully returns http.NoBody.
func getNoBody() (io.ReadCloser, error) {
return http.NoBody, nil
}

func (c *Icinga2Client) Do(req *http.Request) (*http.Response, error) {
if req.Body == nil && req.GetBody == nil {
req.Body = http.NoBody
req.GetBody = getNoBody
}

for attempt := 1; ; attempt++ {
response, err := c.Client.Do(req)
if err == nil && response.StatusCode == http.StatusServiceUnavailable && req.GetBody != nil && attempt < 300 {
if body, err := req.GetBody(); err == nil {
_ = response.Body.Close()
req.Body = body
ctx := req.Context()

select {
case <-time.After(time.Second):
case <-ctx.Done():
return nil, ctx.Err()
}

continue
}
}

return response, err
}
}

func (c *Icinga2Client) addJsonHeaders(req *http.Request) {
req.Header.Add("Accept", "application/json")
if req.Body != nil {
Expand Down

0 comments on commit df59d44

Please sign in to comment.