diff --git a/pkg/archive/archive.go b/pkg/archive/archive.go index afb16c7c66..cbcf865323 100644 --- a/pkg/archive/archive.go +++ b/pkg/archive/archive.go @@ -1218,6 +1218,9 @@ func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) { return nil, err } + // Ensure the command has exited before we clean anything up + done := make(chan struct{}) + // Copy stdout to the returned pipe go func() { if err := cmd.Wait(); err != nil { @@ -1225,9 +1228,16 @@ func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) { } else { pipeW.Close() } + close(done) }() - return pipeR, nil + return ioutils.NewReadCloserWrapper(pipeR, func() error { + // Close pipeR, and then wait for the command to complete before returning. We have to close pipeR first, as + // cmd.Wait waits for any non-file stdout/stderr/stdin to close. + err := pipeR.Close() + <-done + return err + }), nil } // NewTempArchive reads the content of src into a temporary file, and returns the contents diff --git a/pkg/archive/archive_test.go b/pkg/archive/archive_test.go index b49ad6723e..043853c96c 100644 --- a/pkg/archive/archive_test.go +++ b/pkg/archive/archive_test.go @@ -1332,7 +1332,9 @@ func TestPigz(t *testing.T) { _, err := exec.LookPath("unpigz") if err == nil { t.Log("Tested whether Pigz is used, as it installed") - assert.Equal(t, reflect.TypeOf(contextReaderCloserWrapper.Reader), reflect.TypeOf(&io.PipeReader{})) + // For the command wait wrapper + cmdWaitCloserWrapper := contextReaderCloserWrapper.Reader.(*ioutils.ReadCloserWrapper) + assert.Equal(t, reflect.TypeOf(cmdWaitCloserWrapper.Reader), reflect.TypeOf(&io.PipeReader{})) } else { t.Log("Tested whether Pigz is not used, as it not installed") assert.Equal(t, reflect.TypeOf(contextReaderCloserWrapper.Reader), reflect.TypeOf(&gzip.Reader{}))