Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix unsafe data race in ExecuteCommand #3310

Merged
merged 1 commit into from
Jun 12, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion pkg/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,29 @@ import (
"fmt"
"io"
"os"
"sync"

"k8s.io/klog"

"github.com/openshift/odo/pkg/devfile/adapters/common"
"github.com/openshift/odo/pkg/log"
)

// ExecClient is a wrapper around ExecCMDInContainer which executes a command in a specific container of a pod.
type ExecClient interface {
ExecCMDInContainer(common.ComponentInfo, []string, io.Writer, io.Writer, io.Reader, bool) error
}

// ExecuteCommand executes the given command in the pod's container
func ExecuteCommand(client ExecClient, compInfo common.ComponentInfo, command []string, show bool) (err error) {

// Create a mutex so we don't run into the issue of go routines trying to write to stdout
var mu sync.Mutex

reader, writer := io.Pipe()
var cmdOutput string
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The conventions for mutexes are that they are kept above the things they are guarding. Now you can create a struct called SafeString which holds the mutex and the string or as the mutex is not accessed externally just keep it above cmdOutput.


klog.V(3).Infof("Executing command %v for pod: %v in container: %v", command, compInfo.PodName, compInfo.ContainerName)
klog.V(4).Infof("Executing command %v for pod: %v in container: %v", command, compInfo.PodName, compInfo.ContainerName)

// This Go routine will automatically pipe the output from ExecCMDInContainer to
// our logger.
Expand All @@ -37,13 +43,17 @@ func ExecuteCommand(client ExecClient, compInfo common.ComponentInfo, command []
}
}

mu.Lock()
cmdOutput += fmt.Sprintln(line)
mu.Unlock()
}
}()

err = client.ExecCMDInContainer(compInfo, command, writer, writer, nil, false)
if err != nil {
mu.Lock()
log.Errorf("\nUnable to exec command %v: \n%v", command, cmdOutput)
mu.Unlock()
return err
}

Expand Down