Skip to content

Commit

Permalink
Add http errors handling for all search requests to .apm-agent-config…
Browse files Browse the repository at this point in the history
…uration

Signed-off-by: Up Neck <[email protected]>
  • Loading branch information
up2neck committed Aug 30, 2024
1 parent 36a7f02 commit c33e7d0
Showing 1 changed file with 26 additions and 24 deletions.
50 changes: 26 additions & 24 deletions internal/agentcfg/elasticsearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,10 @@ func (f *ElasticsearchFetcher) refreshCache(ctx context.Context) (err error) {
return err
}

if result.ScrollID == "" {
return errors.New("search scroll_id must not be empty")
}

for _, hit := range result.Hits.Hits {
buffer = append(buffer, AgentConfig{
ServiceName: hit.Source.Service.Name,
Expand All @@ -251,40 +255,38 @@ func (f *ElasticsearchFetcher) refreshCache(ctx context.Context) (err error) {

func (f *ElasticsearchFetcher) singlePageRefresh(ctx context.Context, scrollID string) (cacheResult, error) {
var result cacheResult
var err error
var resp *esapi.Response

if scrollID == "" {
resp, err := esapi.SearchRequest{
switch scrollID {
case "":
resp, err = esapi.SearchRequest{
Index: []string{ElasticsearchIndexName},
Size: &f.searchSize,
Scroll: f.cacheDuration,
}.Do(ctx, f.client)
if err != nil {
return result, err
}
defer resp.Body.Close()

if resp.StatusCode >= http.StatusBadRequest {
// Elasticsearch returns 401 on unauthorized requests and 403 on insufficient permission
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
f.invalidESCfg.Store(true)
}
bodyBytes, err := io.ReadAll(resp.Body)
if err == nil {
f.logger.Debugf("refresh cache elasticsearch returned status %d: %s", resp.StatusCode, string(bodyBytes))
}
return result, fmt.Errorf("refresh cache elasticsearch returned status %d", resp.StatusCode)
}
return result, json.NewDecoder(resp.Body).Decode(&result)
default:
resp, err = esapi.ScrollRequest{
ScrollID: scrollID,
Scroll: f.cacheDuration,
}.Do(ctx, f.client)
}

resp, err := esapi.ScrollRequest{
ScrollID: scrollID,
Scroll: f.cacheDuration,
}.Do(ctx, f.client)
if err != nil {
return result, err
}
defer resp.Body.Close()

if resp.StatusCode >= http.StatusBadRequest {
// Elasticsearch returns 401 on unauthorized requests and 403 on insufficient permission
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
f.invalidESCfg.Store(true)
}
bodyBytes, err := io.ReadAll(resp.Body)
if err == nil {
f.logger.Debugf("refresh cache elasticsearch returned status %d: %s", resp.StatusCode, string(bodyBytes))
}
return result, fmt.Errorf("refresh cache elasticsearch returned status %d", resp.StatusCode)
}
return result, json.NewDecoder(resp.Body).Decode(&result)
}

Expand Down

0 comments on commit c33e7d0

Please sign in to comment.