Skip to content

Commit

Permalink
refactor: lazy get metadata
Browse files Browse the repository at this point in the history
This changes how metadata handler works - now metadata will be fetched
only once during first request.
  • Loading branch information
VAveryanov8 committed Jan 8, 2025
1 parent 35c416c commit 3fc9989
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions pkg/cmd/agent/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package main
import (
"context"
"net/http"
"sync"

"github.com/go-chi/render"
"github.com/pkg/errors"
Expand All @@ -14,21 +15,25 @@ import (
)

func newMetadataHandler(logger log.Logger) (http.HandlerFunc, error) {
ctx := context.Background()
metaSvc, err := cloudmeta.NewCloudMeta(logger)
if err != nil {
return nil, errors.Wrap(err, "NewCloudMeta")
}

instanceMeta, err := metaSvc.GetInstanceMetadata(ctx)
if err != nil {
// Metadata may not be available for several reasons:
// 1. running on-premise 2. disabled 3. smth went wrong with metadata server.
// As we cannot distinguish between these cases, we can only log err.
logger.Error(ctx, "GetInstanceMetadata", "err", err)
}
lazyGetMetadata := sync.OnceValues(func() (cloudmeta.InstanceMetadata, error) {
return metaSvc.GetInstanceMetadata(context.Background())
})

return func(w http.ResponseWriter, r *http.Request) {
instanceMeta, err := lazyGetMetadata()
if err != nil {
// Metadata may not be available for several reasons:
// 1. running on-premise 2. disabled 3. smth went wrong with metadata server.
// As we cannot distinguish between these cases, we can only log err.
logger.Error(r.Context(), "GetInstanceMetadata", "err", err)
render.Respond(w, r, models.InstanceMetadata{})
return
}
render.Respond(w, r, models.InstanceMetadata{
CloudProvider: string(instanceMeta.CloudProvider),
InstanceType: instanceMeta.InstanceType,
Expand Down

0 comments on commit 3fc9989

Please sign in to comment.