From 1828fb212a4cbfdd8b7f21694796a27c279d2658 Mon Sep 17 00:00:00 2001 From: jiuker <2818723467@qq.com> Date: Thu, 9 Feb 2023 01:11:16 +0800 Subject: [PATCH] fix: avoid goroutine leak after timeouts in PeerMetrics (#16569) --- cmd/peer-rest-client.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/cmd/peer-rest-client.go b/cmd/peer-rest-client.go index ec43174d5..a7935bfcd 100644 --- a/cmd/peer-rest-client.go +++ b/cmd/peer-rest-client.go @@ -838,14 +838,20 @@ func (client *peerRESTClient) GetPeerMetrics(ctx context.Context) (<-chan Metric dec := gob.NewDecoder(respBody) ch := make(chan Metric) go func(ch chan<- Metric) { + defer func() { + xhttp.DrainBody(respBody) + close(ch) + }() for { var metric Metric if err := dec.Decode(&metric); err != nil { - xhttp.DrainBody(respBody) - close(ch) return } - ch <- metric + select { + case <-ctx.Done(): + return + case ch <- metric: + } } }(ch) return ch, nil