Skip to content

Commit

Permalink
Improving error messages in windows command execution (#2054)
Browse files Browse the repository at this point in the history
improving error messages from executing commands on windows
  • Loading branch information
ramiro-gamarra committed Jul 18, 2023
1 parent 8a105b9 commit 99843e9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
16 changes: 8 additions & 8 deletions platform/os_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/Azure/azure-container-networking/log"
"github.com/Azure/azure-container-networking/platform/windows/adapter"
"github.com/Azure/azure-container-networking/platform/windows/adapter/mellanox"
"github.com/pkg/errors"
"golang.org/x/sys/windows"
)

Expand Down Expand Up @@ -108,20 +109,19 @@ func GetLastRebootTime() (time.Time, error) {
}

func (p *execClient) ExecuteCommand(command string) (string, error) {
log.Printf("[Azure-Utils] %s", command)
log.Printf("[Azure-Utils] ExecuteCommand: %q", command)

var stderr, stdout bytes.Buffer

var stderr bytes.Buffer
var out bytes.Buffer
cmd := exec.Command("cmd", "/c", command)
cmd.Stderr = &stderr
cmd.Stdout = &out
cmd.Stdout = &stdout

err := cmd.Run()
if err != nil {
return "", fmt.Errorf("%s:%s", err.Error(), stderr.String())
if err := cmd.Run(); err != nil {
return "", errors.Wrapf(err, "ExecuteCommand failed. stdout: %q, stderr: %q", stdout.String(), stderr.String())
}

return out.String(), nil
return stdout.String(), nil
}

func SetOutboundSNAT(subnet string) error {
Expand Down
17 changes: 17 additions & 0 deletions platform/os_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package platform

import (
"errors"
"os/exec"
"testing"

"github.com/Azure/azure-container-networking/platform/windows/adapter/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

var errTestFailure = errors.New("test failure")
Expand Down Expand Up @@ -81,3 +83,18 @@ func TestUpdatePriorityVLANTagIfRequiredIfCurrentValNotEqualDesiredValAndSetRetu
result := updatePriorityVLANTagIfRequired(mockNetworkAdapter, 5)
assert.EqualError(t, result, "error while setting Priority VLAN Tag value: test failure")
}

func TestExecuteCommand(t *testing.T) {
out, err := NewExecClient().ExecuteCommand("dir")
require.NoError(t, err)
require.NotEmpty(t, out)
}

func TestExecuteCommandError(t *testing.T) {
_, err := NewExecClient().ExecuteCommand("dontaddtopath")
require.Error(t, err)

var xErr *exec.ExitError
assert.ErrorAs(t, err, &xErr)
assert.Equal(t, 1, xErr.ExitCode())
}

0 comments on commit 99843e9

Please sign in to comment.