kuberay icon indicating copy to clipboard operation
kuberay copied to clipboard

fix(kubectl-plugin): close file immediately after write loop to prevent FD leak (fixes #4695)

Open CatfishGG opened this issue 6 months ago • 0 comments

Summary

Two bugs fixed in kubectl-plugin/pkg/cmd/log/log.go:

Bug 1: File descriptor leak from defer inside loop

defer outFile.Close() was placed inside the tar extraction loop. Each iteration opens a file but only schedules its close for when the parent function returns. For large tarballs, this keeps thousands of FDs open simultaneously, causing "too many open files" errors.

Fix: Replaced defer outFile.Close() with an explicit, immediately-called outFile.Close() after the io.CopyN loop completes.

Bug 2: G115 bounds check fall-through

When header.Mode was out of uint32 range, the code printed a warning but then fell through to create the file anyway (with mode 0). No continue meant it would attempt to read the next tar header from a corrupted state.

Fix: Added continue after the bounds warning to skip the invalid file cleanly.

Changes

  • Remove defer outFile.Close() inside the tar loop → use explicit close after write loop
  • Add continue after G115 bounds check to prevent fall-through
  • Improve //nolint:gosec comment clarity
  • Fix grammar: out side of acceptable value → out of acceptable range

Testing

go test ./pkg/cmd/log/... passes, build succeeds.

Fixes #4695

CatfishGG avatar May 14 '26 08:05 CatfishGG