From 8f154c6a8a126cc207103b671de483a0e265158a Mon Sep 17 00:00:00 2001 From: "brian m. carlson" Date: Wed, 26 Jun 2019 21:55:48 +0000 Subject: [PATCH] object_db: prevent FD leaks when writing blobs When writing a blob, there are two places where we use temporary files. First, we use them when we write the blob itself. Second, we use them when we encode the buffer. In both of these cases, however, we failed to close the file after we were done with it, leading to file descriptor leaks until Go garbage-collected the items. Add a helper function to close and remove these files and use it in each of these places. Place the os.Remove statement after the Close statement, since Windows will be happier if we don't try to remove a file we have open. --- object_db.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/object_db.go b/object_db.go index c96b961..659b45b 100644 --- a/object_db.go +++ b/object_db.go @@ -158,7 +158,7 @@ func (o *ObjectDatabase) WriteBlob(b *Blob) ([]byte, error) { if err != nil { return nil, err } - defer os.Remove(buf.Name()) + defer o.cleanup(buf) sha, _, err := o.encodeBuffer(b, buf) if err != nil { @@ -236,7 +236,7 @@ func (d *ObjectDatabase) encodeBuffer(object Object, buf io.ReadWriter) (sha []b if err != nil { return nil, 0, err } - defer os.Remove(tmp.Name()) + defer d.cleanup(tmp) to := NewObjectWriter(tmp) if _, err = to.WriteHeader(object.Type(), int64(cn)); err != nil { @@ -323,3 +323,8 @@ func (o *ObjectDatabase) decode(r *ObjectReader, into Object) error { } return r.Close() } + +func (o *ObjectDatabase) cleanup(f *os.File) { + f.Close() + os.Remove(f.Name()) +}