Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(compute/metadata): init a HTTP client in OnGCE check (#5439)
Initalize a resolver and http.Client locally in function to force
GC to cleanup background resources such as cached connections. This
can falsely report as leaked goroutines otherwise. This kind of issue
will still persist for calling methods like ProjectID, but we are
intentionally caching a client and its connections for these occations
today. If this ends up causing users issues in the fututure we can
reevaluate at that time.

Fixes: #5430
  • Loading branch information
codyoss committed Feb 3, 2022
1 parent 49c9ac1 commit 76c6e40
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions compute/metadata/metadata.go
Expand Up @@ -61,14 +61,18 @@ var (
instID = &cachedValue{k: "instance/id", trim: true}
)

var defaultClient = &Client{hc: &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 2 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
},
}}
var defaultClient = &Client{hc: newDefaultHTTPClient()}

func newDefaultHTTPClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 2 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
},
}
}

// NotDefinedError is returned when requested metadata is not defined.
//
Expand Down Expand Up @@ -130,7 +134,7 @@ func testOnGCE() bool {
go func() {
req, _ := http.NewRequest("GET", "http://"+metadataIP, nil)
req.Header.Set("User-Agent", userAgent)
res, err := defaultClient.hc.Do(req.WithContext(ctx))
res, err := newDefaultHTTPClient().Do(req.WithContext(ctx))
if err != nil {
resc <- false
return
Expand All @@ -140,7 +144,8 @@ func testOnGCE() bool {
}()

go func() {
addrs, err := net.DefaultResolver.LookupHost(ctx, "metadata.google.internal")
resolver := &net.Resolver{}
addrs, err := resolver.LookupHost(ctx, "metadata.google.internal")
if err != nil || len(addrs) == 0 {
resc <- false
return
Expand Down

0 comments on commit 76c6e40

Please sign in to comment.