From d6a9ddc08b8de84aabb756a411d166fa8110b726 Mon Sep 17 00:00:00 2001 From: Lorna Song Date: Thu, 19 May 2022 21:30:50 -0400 Subject: [PATCH] Refactor runTerraformCmd - Use waitgroups for more readability - Improve handling errors from writeOutput Resolves a test error: `read |0: file already closed` --- tfexec/cmd_default.go | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/tfexec/cmd_default.go b/tfexec/cmd_default.go index ea79afef..760d504f 100644 --- a/tfexec/cmd_default.go +++ b/tfexec/cmd_default.go @@ -7,6 +7,7 @@ import ( "context" "os/exec" "strings" + "sync" ) func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { @@ -46,13 +47,17 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { return tf.wrapExitError(ctx, err, "") } - exitChLen := 2 - exitCh := make(chan error, exitChLen) + var errStdout, errStderr error + var wg sync.WaitGroup + wg.Add(2) go func() { - exitCh <- writeOutput(stdoutPipe, stdoutWriter) + errStdout = writeOutput(stdoutPipe, stdoutWriter) + wg.Done() }() + go func() { - exitCh <- writeOutput(stderrPipe, stderrWriter) + errStderr = writeOutput(stderrPipe, stderrWriter) + wg.Done() }() err = cmd.Wait() @@ -63,16 +68,16 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { return tf.wrapExitError(ctx, err, errBuf.String()) } - // Wait for the logs to finish writing - counter := 0 - for { - counter++ - err := <-exitCh - if err != nil && err != context.Canceled { - return tf.wrapExitError(ctx, err, errBuf.String()) - } - if counter >= exitChLen { - return ctx.Err() - } + // Ensure that outputs are done writing after Wait to be safe + wg.Wait() + + // Return error if there was an issue reading the std out/err + if errStdout != nil && ctx.Err() != nil { + return tf.wrapExitError(ctx, errStdout, errBuf.String()) } + if errStderr != nil && ctx.Err() != nil { + return tf.wrapExitError(ctx, errStderr, errBuf.String()) + } + + return nil }