Skip to content

Commit e963497

Browse files
authored
internal/gzip: fix goroutine leak in ReadCloserLevel (#2347)
Move defer r.Close() and defer pw.Close() to the top of the goroutine so they execute regardless of which error path exits the function. Previously, r.Close() was only called inside the io.Copy error path and the happy-path end, leaving it unclosed when gw.Close() or bw.Flush() failed. When r wraps a limitedReadCloser (used by the pullLimiter introduced in #2271), failing to close r permanently leaks the limiter token slot. Under layout.WriteImage (used by kaniko for build-stage caching), this eventually deadlocks because all slots are occupied. Also add defer gw.Close() after gw creation so the gzip writer is always properly finalized. Fixes #2342 Signed-off-by: Aaron <[email protected]>
1 parent 02649ea commit e963497

1 file changed

Lines changed: 8 additions & 10 deletions

File tree

‎internal/gzip/zip.go‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,33 +51,31 @@ func ReadCloserLevel(r io.ReadCloser, level int) io.ReadCloser {
5151

5252
// Returns err so we can pw.CloseWithError(err)
5353
go func() error {
54-
// TODO(go1.14): Just defer {pw,gw,r}.Close like you'd expect.
55-
// Context: https://golang.org/issue/24283
54+
// Always close the source reader when the goroutine exits,
55+
// regardless of which error path is taken. This prevents
56+
// resource leaks (e.g. pullLimiter token slots held by
57+
// limitedReadCloser wrappers around r).
58+
defer r.Close()
59+
5660
gw, err := gzip.NewWriterLevel(bw, level)
5761
if err != nil {
5862
return pw.CloseWithError(err)
5963
}
64+
defer gw.Close()
65+
defer pw.Close()
6066

6167
if _, err := io.Copy(gw, r); err != nil {
62-
defer r.Close()
63-
defer gw.Close()
6468
return pw.CloseWithError(err)
6569
}
6670

67-
// Close gzip writer to Flush it and write gzip trailers.
6871
if err := gw.Close(); err != nil {
6972
return pw.CloseWithError(err)
7073
}
7174

72-
// Flush bufio writer to ensure we write out everything.
7375
if err := bw.Flush(); err != nil {
7476
return pw.CloseWithError(err)
7577
}
7678

77-
// We don't really care if these fail.
78-
defer pw.Close()
79-
defer r.Close()
80-
8179
return nil
8280
}()
8381

0 commit comments

Comments
 (0)