Skip to content

Commit bb1ef41

Browse files
committed
fix(agent): prevent goroutine pile up in reportMetadataLoop
In the prior implementation, calls to DoChan would stack up because we weren't updating lastCollectedAts until collectMetadata finished. This wasn't a true leak, instead, it meant that there would be up to ~ (collectionRuntime / baseInterval) outstanding goroutines. So, for example, if `sleep 60s` was the metadata script there would be up to 60 goroutines waiting at peak.
1 parent ccadd0f commit bb1ef41

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

agent/agent.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,11 @@ import (
3535
"go.uber.org/atomic"
3636
gossh "golang.org/x/crypto/ssh"
3737
"golang.org/x/exp/slices"
38-
"golang.org/x/sync/singleflight"
3938
"golang.org/x/xerrors"
4039
"tailscale.com/net/speedtest"
4140
"tailscale.com/tailcfg"
4241
"tailscale.com/types/netlogtype"
42+
"tailscale.com/util/singleflight"
4343

4444
"cdr.dev/slog"
4545
"github.com/coder/coder/agent/usershell"
@@ -276,7 +276,7 @@ func (a *agent) reportMetadataLoop(ctx context.Context) {
276276
)
277277
defer baseTicker.Stop()
278278

279-
var flight singleflight.Group
279+
var flight singleflight.Group[string, struct{}]
280280

281281
for {
282282
select {
@@ -345,10 +345,11 @@ func (a *agent) reportMetadataLoop(ctx context.Context) {
345345
}
346346

347347
md := md
348+
lastCollectedAts[md.Key] = time.Now()
348349
// We send the result to the channel in the goroutine to avoid
349350
// sending the same result multiple times. So, we don't care about
350351
// the return values.
351-
flight.DoChan(md.Key, func() (interface{}, error) {
352+
flight.DoChan(md.Key, func() (struct{}, error) {
352353
timeout := md.Timeout
353354
if timeout == 0 {
354355
timeout = md.Interval
@@ -360,13 +361,12 @@ func (a *agent) reportMetadataLoop(ctx context.Context) {
360361

361362
select {
362363
case <-ctx.Done():
363-
return 0, nil
364364
case metadataResults <- metadataResultAndKey{
365365
key: md.Key,
366366
result: a.collectMetadata(ctx, md),
367367
}:
368368
}
369-
return 0, nil
369+
return struct{}{}, nil
370370
})
371371
}
372372
}

0 commit comments

Comments
 (0)