Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding multiple retries for agent metadata query #1

Merged
merged 1 commit into from
Dec 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion nex-agent/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package nexagent

import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"

agentapi "github.com/ConnectEverything/nex/agent-api"
)
Expand Down Expand Up @@ -34,12 +36,31 @@ func GetMachineMetadata() (*agentapi.MachineMetadata, error) {
req.Header.Set("Accept", "application/json")
req.Header.Set("X-metadata-token", token)

remainingAttempts := 3
client := &http.Client{}
for remainingAttempts > 0 {
metadata, err := performMatadataQuery(url, req, client)
if err != nil {
remainingAttempts -= 1
time.Sleep(1 * time.Second)
continue
} else {
return metadata, nil
}
}

return nil, errors.New("failed to obtain metadata after multiple attempts")
}

func performMatadataQuery(url string, req *http.Request, client *http.Client) (*agentapi.MachineMetadata, error) {
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, errors.New("metadata not found")
}
bodyBytes, err := io.ReadAll(resp.Body)

if err != nil {
Expand All @@ -51,7 +72,6 @@ func GetMachineMetadata() (*agentapi.MachineMetadata, error) {
if err != nil {
return nil, fmt.Errorf("deserialization failure: %s: body: '%s'", err, string(bodyBytes))
}

return &metadata, nil
}

Expand Down