From 3555580412eca9528efdb3e93d03b4b01620fc6f Mon Sep 17 00:00:00 2001 From: Debarshi Ray Date: Wed, 6 Dec 2023 12:45:19 +0100 Subject: [PATCH] pkg/shell: Add cancellable versions of Run and RunWithExitCode A subsequent commit will use this to ensure that the user can still interact with the image download prompt while 'skopeo inspect' fetches the image size from the remote registry. Initially, the prompt will be shown without the image size. If the user responds before the size is fetched, then the pending 'skopeo inspect' will be cancelled. https://github.com/containers/toolbox/issues/752 https://github.com/containers/toolbox/issues/1263 --- src/pkg/shell/shell.go | 30 ++++++-- src/pkg/shell/shell_test.go | 139 ++++++++++++++++++++++++++++++++++++ 2 files changed, 165 insertions(+), 4 deletions(-) diff --git a/src/pkg/shell/shell.go b/src/pkg/shell/shell.go index ee5fe0e7b..71ba1b119 100644 --- a/src/pkg/shell/shell.go +++ b/src/pkg/shell/shell.go @@ -1,5 +1,5 @@ /* - * Copyright © 2019 – 2022 Red Hat Inc. + * Copyright © 2019 – 2023 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package shell import ( + "context" "errors" "fmt" "io" @@ -27,7 +28,13 @@ import ( ) func Run(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) error { - exitCode, err := RunWithExitCode(name, stdin, stdout, stderr, arg...) + ctx := context.Background() + err := RunContext(ctx, name, stdin, stdout, stderr, arg...) + return err +} + +func RunContext(ctx context.Context, name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) error { + exitCode, err := RunContextWithExitCode(ctx, name, stdin, stdout, stderr, arg...) if err != nil { return err } @@ -37,13 +44,18 @@ func Run(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) return nil } -func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) (int, error) { +func RunContextWithExitCode(ctx context.Context, + name string, + stdin io.Reader, + stdout, stderr io.Writer, + arg ...string) (int, error) { + logLevel := logrus.GetLevel() if stderr == nil && logLevel >= logrus.DebugLevel { stderr = os.Stderr } - cmd := exec.Command(name, arg...) + cmd := exec.CommandContext(ctx, name, arg...) cmd.Stdin = stdin cmd.Stdout = stdout cmd.Stderr = stderr @@ -53,6 +65,10 @@ func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg return 1, fmt.Errorf("%s(1) not found", name) } + if ctxErr := ctx.Err(); ctxErr != nil { + return 1, ctxErr + } + var exitErr *exec.ExitError if errors.As(err, &exitErr) { exitCode := exitErr.ExitCode() @@ -64,3 +80,9 @@ func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg return 0, nil } + +func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) (int, error) { + ctx := context.Background() + exitCode, err := RunContextWithExitCode(ctx, name, stdin, stdout, stderr, arg...) + return exitCode, err +} diff --git a/src/pkg/shell/shell_test.go b/src/pkg/shell/shell_test.go index 081387881..e8b83554d 100644 --- a/src/pkg/shell/shell_test.go +++ b/src/pkg/shell/shell_test.go @@ -1,10 +1,29 @@ +/* + * Copyright © 2023 Red Hat Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package shell_test import ( + "context" "errors" "io" "os" + "strings" "testing" + "time" "github.com/containers/toolbox/pkg/shell" "github.com/sirupsen/logrus" @@ -100,6 +119,126 @@ func TestShellRun(t *testing.T) { } } +func TestRunContextWithExitCode(t *testing.T) { + testCases := []struct { + cancel bool + command []string + err error + errMsg string + exitCode int + stdout []byte + stderr []byte + timeout time.Duration + }{ + { + command: []string{"true"}, + }, + { + command: []string{"false"}, + exitCode: 1, + }, + { + command: []string{"echo"}, + stdout: []byte("\n"), + }, + { + command: []string{"echo", "hello, world"}, + err: nil, + exitCode: 0, + stdout: []byte("hello, world\n"), + }, + { + command: []string{"command-does-not-exist"}, + errMsg: "command-does-not-exist(1) not found", + exitCode: 1, + }, + { + command: []string{"cat", "/file/does/not/exist"}, + exitCode: 1, + stderr: []byte("cat: /file/does/not/exist: No such file or directory\n"), + }, + { + cancel: true, + command: []string{"sleep", "+Inf"}, + err: context.Canceled, + exitCode: 1, + }, + { + command: []string{"sleep", "+Inf"}, + err: context.DeadlineExceeded, + exitCode: 1, + timeout: 1 * time.Second, + }, + } + + for _, tc := range testCases { + name := strings.Join(tc.command, " ") + if tc.cancel { + name += " (cancel)" + } + if tc.timeout != 0 { + name += " (timeout)" + } + + t.Run(name, func(t *testing.T) { + var cancel context.CancelFunc + ctx := context.Background() + if tc.cancel { + ctx, cancel = context.WithCancel(ctx) + defer cancel() + } + if tc.timeout != 0 { + ctx, cancel = context.WithTimeout(ctx, tc.timeout) + defer cancel() + } + + if tc.cancel { + cancel() + } + + var stdout outputMock + var stderr outputMock + + exitCode, err := shell.RunContextWithExitCode(ctx, + tc.command[0], + os.Stdin, + &stdout, + &stderr, + tc.command[1:]...) + + if tc.err == nil && tc.errMsg == "" { + assert.NoError(t, err) + } + + if tc.err != nil { + assert.Error(t, err) + assert.ErrorIs(t, err, tc.err) + } + + if tc.errMsg != "" { + assert.Error(t, err) + assert.EqualError(t, err, tc.errMsg) + } + + assert.Equal(t, tc.exitCode, exitCode) + + if tc.stdout == nil { + assert.Empty(t, stdout.written) + } else { + assert.NotEmpty(t, stdout.written) + assert.Equal(t, tc.stdout, stdout.written) + } + + if tc.stderr == nil { + assert.Empty(t, stderr.written) + } else { + assert.NotEmpty(t, stderr.written) + assert.Equal(t, tc.stderr, stderr.written) + } + }) + } +} + func TestShellRunWithExitCode(t *testing.T) { type input struct { commandName string