Skip to content

Commit 76c6e40

Browse files
authored
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
1 parent 49c9ac1 commit 76c6e40

1 file changed

Lines changed: 15 additions & 10 deletions

File tree

compute/metadata/metadata.go

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,18 @@ var (
6161
instID = &cachedValue{k: "instance/id", trim: true}
6262
)
6363

64-
var defaultClient = &Client{hc: &http.Client{
65-
Transport: &http.Transport{
66-
Dial: (&net.Dialer{
67-
Timeout: 2 * time.Second,
68-
KeepAlive: 30 * time.Second,
69-
}).Dial,
70-
},
71-
}}
64+
var defaultClient = &Client{hc: newDefaultHTTPClient()}
65+
66+
func newDefaultHTTPClient() *http.Client {
67+
return &http.Client{
68+
Transport: &http.Transport{
69+
Dial: (&net.Dialer{
70+
Timeout: 2 * time.Second,
71+
KeepAlive: 30 * time.Second,
72+
}).Dial,
73+
},
74+
}
75+
}
7276

7377
// NotDefinedError is returned when requested metadata is not defined.
7478
//
@@ -130,7 +134,7 @@ func testOnGCE() bool {
130134
go func() {
131135
req, _ := http.NewRequest("GET", "http://"+metadataIP, nil)
132136
req.Header.Set("User-Agent", userAgent)
133-
res, err := defaultClient.hc.Do(req.WithContext(ctx))
137+
res, err := newDefaultHTTPClient().Do(req.WithContext(ctx))
134138
if err != nil {
135139
resc <- false
136140
return
@@ -140,7 +144,8 @@ func testOnGCE() bool {
140144
}()
141145

142146
go func() {
143-
addrs, err := net.DefaultResolver.LookupHost(ctx, "metadata.google.internal")
147+
resolver := &net.Resolver{}
148+
addrs, err := resolver.LookupHost(ctx, "metadata.google.internal")
144149
if err != nil || len(addrs) == 0 {
145150
resc <- false
146151
return

0 commit comments

Comments
 (0)