From 87b57de9cf6b761c15f0e21c8b1a956738be9c71 Mon Sep 17 00:00:00 2001 From: cezar-r <59450965+cezar-r@users.noreply.github.com> Date: Wed, 11 Sep 2024 14:23:34 -0700 Subject: [PATCH] fix: image load should close stream after copy (#34) Signed-off-by: Cezar Rata --- internal/service/image/load.go | 9 +++++++-- internal/service/image/load_test.go | 6 ++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/internal/service/image/load.go b/internal/service/image/load.go index febd5a4..7c7ea49 100644 --- a/internal/service/image/load.go +++ b/internal/service/image/load.go @@ -42,11 +42,16 @@ func (s *service) Load(ctx context.Context, inStream io.Reader, outStream io.Wri return err } defer func() { - rw.Close() os.Remove(img) }() go func() { - io.Copy(rw, inStream) + written, err := io.Copy(rw, inStream) + if err != nil { + s.logger.Errorf("failed to copy: %s", err) + } else { + s.logger.Debugf("copied %d bytes", written) + } + rw.Close() }() if err = s.nctlImageSvc.LoadImage(ctx, img, outStream, quiet); err != nil { s.logger.Errorf("failed to load image %s: %s", img, err) diff --git a/internal/service/image/load_test.go b/internal/service/image/load_test.go index f6fc394..11d438d 100644 --- a/internal/service/image/load_test.go +++ b/internal/service/image/load_test.go @@ -46,26 +46,28 @@ var _ = Describe("Image Load API", func() { Return(name, nil) ncClient.EXPECT().LoadImage(gomock.Any(), gomock.Any(), nil, gomock.Any()). Return(nil) + logger.EXPECT().Debugf(gomock.Any(), gomock.Any()) // service should return no error err := service.Load(ctx, inStream, nil, false) Expect(err).Should(BeNil()) }) It("should return an error if load image method returns an error", func() { - logger.EXPECT().Errorf(gomock.Any(), gomock.Any()) ncClient.EXPECT().GetDataStore(). Return(name, nil) ncClient.EXPECT().LoadImage(gomock.Any(), gomock.Any(), nil, gomock.Any()). Return(errors.New("error message")) + logger.EXPECT().Errorf(gomock.Any(), gomock.Any()) + logger.EXPECT().Debugf(gomock.Any(), gomock.Any()) // service should return an error err := service.Load(ctx, inStream, nil, false) Expect(err).ShouldNot(BeNil()) }) It("should return an error if get datastore method returns an error", func() { - logger.EXPECT().Errorf(gomock.Any(), gomock.Any()) ncClient.EXPECT().GetDataStore(). Return(name, errors.New("error message")) + logger.EXPECT().Errorf(gomock.Any(), gomock.Any()) // service should return an error err := service.Load(ctx, inStream, nil, false)