Skip to content

Commit

Permalink
Refactor the error handling further
Browse files Browse the repository at this point in the history
Use defer, a nested function, and early returns.

Besides being a bit more directly related to what
we want to achieve, this now does not call decompressed.Close()
on a nil value if DecompressStream fails.

Signed-off-by: Miloslav Trmač <mitr@redhat.com>
  • Loading branch information
mtrmac committed May 9, 2024
1 parent a802d65 commit 4a3785d
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions pkg/blobcache/dest.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ func (d *blobCacheDestination) IgnoresEmbeddedDockerReference() bool {
// and this new file.
func (d *blobCacheDestination) saveStream(wg *sync.WaitGroup, decompressReader io.ReadCloser, tempFile *os.File, compressedFilename string, compressedDigest digest.Digest, isConfig bool, alternateDigest *digest.Digest) {
defer wg.Done()
defer decompressReader.Close()

succeeded := false
defer func() {
Expand All @@ -90,28 +91,30 @@ func (d *blobCacheDestination) saveStream(wg *sync.WaitGroup, decompressReader i
}
}()

// Decompress from and digest the reading end of that pipe.
decompressed, err3 := archive.DecompressStream(decompressReader)
digester := digest.Canonical.Digester()
if err3 == nil {
if err := func() error { // A scope for defer
defer tempFile.Close()

// Decompress from and digest the reading end of that pipe.
decompressed, err := archive.DecompressStream(decompressReader)
if err != nil {
// Drain the pipe to keep from stalling the PutBlob() thread.
if _, err2 := io.Copy(io.Discard, decompressReader); err2 != nil {
logrus.Debugf("error draining the pipe: %v", err2)
}
return err
}
defer decompressed.Close()
// Read the decompressed data through the filter over the pipe, blocking until the
// writing end is closed.
_, err3 = io.Copy(io.MultiWriter(tempFile, digester.Hash()), decompressed)
} else {
// Drain the pipe to keep from stalling the PutBlob() thread.
if _, err := io.Copy(io.Discard, decompressReader); err != nil {
logrus.Debugf("error draining the pipe: %v", err)
}
_, err = io.Copy(io.MultiWriter(tempFile, digester.Hash()), decompressed)
return err
}(); err != nil {
return
}
decompressReader.Close()
decompressed.Close()
tempFile.Close()

// Determine the name that we should give to the uncompressed copy of the blob.
decompressedFilename := d.reference.blobPath(digester.Digest(), isConfig)
if err3 != nil {
return
}
// Rename the temporary file.
if err := os.Rename(tempFile.Name(), decompressedFilename); err != nil {
logrus.Debugf("error renaming new decompressed copy of blob %q into place at %q: %v", digester.Digest().String(), decompressedFilename, err)
Expand Down

0 comments on commit 4a3785d

Please sign in to comment.