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

feat(compute/metadata): add debug logging #11078

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
5 changes: 4 additions & 1 deletion compute/metadata/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ module cloud.google.com/go/compute/metadata

go 1.21

require golang.org/x/sys v0.25.0
require (
github.com/googleapis/gax-go/v2 v2.0.0-00010101000000-000000000000
golang.org/x/sys v0.25.0
)
2 changes: 2 additions & 0 deletions compute/metadata/go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
53 changes: 42 additions & 11 deletions compute/metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,16 @@ import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"

"github.com/googleapis/gax-go/v2/internallog"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there any way to avoid this? compute/metadata is impossible to avoid as a dependency (google.golang.org/grpc pulls it in, etc)

we really should not be forcing transitive deps on cloud modules like this

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At this layer specifically we cloud likely just take slog as a dep and pass in a logger. But this means the default case can never work with the semantics we are adding here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compute/metadata specifically is required by almost everything in the go ecosystem, keeping its dependency graph small and avoiding transitive deps to other cloud libraries is much more important for this module than anything else in this repo.

using stdlib slog or a locally-defined interface and pushing callers to wire any specific cloud instrumentation they want is much more in line with what I would expect here.

I'd also like to see a presubmit that will catch / guard against unconsidered introduction of new dependencies to this module in particular

)

const (
Expand Down Expand Up @@ -60,7 +63,10 @@ var (
instID = &cachedValue{k: "instance/id", trim: true}
)

var defaultClient = &Client{hc: newDefaultHTTPClient()}
var defaultClient = &Client{
hc: newDefaultHTTPClient(),
logger: internallog.New(nil),
}

func newDefaultHTTPClient() *http.Client {
return &http.Client{
Expand Down Expand Up @@ -408,17 +414,38 @@ func strsContains(ss []string, s string) bool {

// A Client provides metadata.
type Client struct {
hc *http.Client
hc *http.Client
logger *slog.Logger
}

type Options struct {
Client *http.Client
Logger *slog.Logger
}

// NewClient returns a Client that can be used to fetch metadata.
// Returns the client that uses the specified http.Client for HTTP requests.
// If nil is specified, returns the default client.
func NewClient(c *http.Client) *Client {
if c == nil {
client := c
if client == nil {
client = newDefaultHTTPClient()
}
return NewWithOptions(&Options{
Client: client,
})
}

func NewWithOptions(opts *Options) *Client {
if opts == nil {
return defaultClient
}
return &Client{hc: c}
client := opts.Client
if client == nil {
client = newDefaultHTTPClient()
}
logger := internallog.New(opts.Logger)
return &Client{hc: client, logger: logger}
}

// getETag returns a value from the metadata service as well as the associated ETag.
Expand Down Expand Up @@ -448,12 +475,21 @@ func (c *Client) getETag(ctx context.Context, suffix string) (value, etag string
req.Header.Set("User-Agent", userAgent)
var res *http.Response
var reqErr error
var body []byte
retryer := newRetryer()
for {
c.logger.DebugContext(ctx, "metadata request", "request", internallog.HTTPRequest(req, nil))
res, reqErr = c.hc.Do(req)
var code int
if res != nil {
code = res.StatusCode
body, err = io.ReadAll(res.Body)
if err != nil {
res.Body.Close()
return "", "", err
}
c.logger.DebugContext(ctx, "metadata response", "response", internallog.HTTPResponse(res, body))
res.Body.Close()
}
if delay, shouldRetry := retryer.Retry(code, reqErr); shouldRetry {
if res != nil && res.Body != nil {
Expand All @@ -469,18 +505,13 @@ func (c *Client) getETag(ctx context.Context, suffix string) (value, etag string
if reqErr != nil {
return "", "", reqErr
}
defer res.Body.Close()
if res.StatusCode == http.StatusNotFound {
return "", "", NotDefinedError(suffix)
}
all, err := io.ReadAll(res.Body)
if err != nil {
return "", "", err
}
if res.StatusCode != 200 {
return "", "", &Error{Code: res.StatusCode, Message: string(all)}
return "", "", &Error{Code: res.StatusCode, Message: string(body)}
}
return string(all), res.Header.Get("Etag"), nil
return string(body), res.Header.Get("Etag"), nil
}

// Get returns a value from the metadata service.
Expand Down
2 changes: 0 additions & 2 deletions compute/metadata/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"bytes"
"context"
"io"
"log"
"net/http"
"os"
"strings"
Expand Down Expand Up @@ -70,7 +69,6 @@ func TestGetFailsOnBadURL(t *testing.T) {
c := NewClient(http.DefaultClient)
t.Setenv(metadataHostEnv, "host:-1")
_, err := c.GetWithContext(ctx, "suffix")
log.Printf("%v", err)
if err == nil {
t.Errorf("got %v, want non-nil error", err)
}
Expand Down
Loading