From dbfa2d8b913378a66db37ed58ead0aa2c3e3c3c2 Mon Sep 17 00:00:00 2001 From: lfz941 Date: Thu, 9 Jan 2025 20:27:56 +0800 Subject: [PATCH] fix(store/v2): chunkBody.Close and chunkFile.Close both are called twice --- store/v2/snapshots/store.go | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/store/v2/snapshots/store.go b/store/v2/snapshots/store.go index 2928b6c026dc..2f9e4dc5a13e 100644 --- a/store/v2/snapshots/store.go +++ b/store/v2/snapshots/store.go @@ -298,29 +298,30 @@ func (s *Store) Save( // saveChunk saves the given chunkBody with the given index to its appropriate path on disk. // The hash of the chunk is appended to the snapshot's metadata, // and the overall snapshot hash is updated with the chunk content too. -func (s *Store) saveChunk(chunkBody io.ReadCloser, index uint32, snapshot *types.Snapshot, chunkHasher, snapshotHasher hash.Hash) error { - defer chunkBody.Close() +func (s *Store) saveChunk(chunkBody io.ReadCloser, index uint32, snapshot *types.Snapshot, chunkHasher, snapshotHasher hash.Hash) (err error) { + defer func() { + if cErr := chunkBody.Close(); cErr != nil { + err = errors.Wrapf(cErr, "failed to close snapshot chunk body %d", index) + } + }() path := s.PathChunk(snapshot.Height, snapshot.Format, index) chunkFile, err := os.Create(path) if err != nil { return errors.Wrapf(err, "failed to create snapshot chunk file %q", path) } - defer chunkFile.Close() + + defer func() { + if cErr := chunkFile.Close(); cErr != nil { + err = errors.Wrapf(cErr, "failed to close snapshot chunk file %d", index) + } + }() chunkHasher.Reset() if _, err := io.Copy(io.MultiWriter(chunkFile, chunkHasher, snapshotHasher), chunkBody); err != nil { return errors.Wrapf(err, "failed to generate snapshot chunk %d", index) } - if err := chunkFile.Close(); err != nil { - return errors.Wrapf(err, "failed to close snapshot chunk file %d", index) - } - - if err := chunkBody.Close(); err != nil { - return errors.Wrapf(err, "failed to close snapshot chunk body %d", index) - } - snapshot.Metadata.ChunkHashes = append(snapshot.Metadata.ChunkHashes, chunkHasher.Sum(nil)) return nil }