File: shell.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (373 lines) | stat: -rw-r--r-- 11,078 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
Copyright (C) 2019 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 util

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"os/exec"
	"runtime"
	"strings"
	"time"

	"github.com/cucumber/messages-go/v10"
)

const (
	exitCodeIdentifier = "exitCodeOfLastCommandInShell="

	bashExitCodeCheck = "echo %v$?"
	// fishExitCodeCheck       = "echo %v$status"
	tcshExitCodeCheck       = "echo %v$?"
	zshExitCodeCheck        = "echo %v$?"
	cmdExitCodeCheck        = "echo %v%%errorlevel%%"
	powershellExitCodeCheck = "echo %v$lastexitcode"
)

var (
	shell ShellInstance
)

type ShellInstance struct {
	startArgument    []string
	name             string
	checkExitCodeCmd string

	instance *exec.Cmd
	outbuf   bytes.Buffer
	errbuf   bytes.Buffer
	excbuf   bytes.Buffer

	outPipe io.ReadCloser
	errPipe io.ReadCloser
	inPipe  io.WriteCloser

	outScanner *bufio.Scanner
	errScanner *bufio.Scanner

	exitCodeChannel chan string
}

func (shell *ShellInstance) GetLastCmdOutput(stdType string) string {
	var returnValue string
	switch stdType {
	case "stdout":
		returnValue = shell.outbuf.String()
	case "stderr":
		returnValue = shell.errbuf.String()
	case "exitcode":
		returnValue = shell.excbuf.String()
	default:
		fmt.Printf("Field '%s' of shell's output is not supported. Only 'stdout', 'stderr' and 'exitcode' are supported.", stdType)
	}

	returnValue = strings.TrimSuffix(returnValue, "\n")

	return returnValue
}

func (shell *ShellInstance) ScanPipe(scanner *bufio.Scanner, buffer *bytes.Buffer, stdType string) {
	for scanner.Scan() {
		str := scanner.Text()
		err := LogMessage(stdType, str)
		if err != nil {
			fmt.Println("error logging:", err)
		}

		if strings.Contains(str, exitCodeIdentifier) && !strings.Contains(str, shell.checkExitCodeCmd) {
			exitCode := strings.Split(str, "=")[1]
			shell.exitCodeChannel <- exitCode
		} else {
			buffer.WriteString(str + "\n")
		}
	}
}

func (shell *ShellInstance) ConfigureTypeOfShell(shellName string) {
	switch shellName {
	case "bash":
		shell.name = shellName
		shell.checkExitCodeCmd = fmt.Sprintf(bashExitCodeCheck, exitCodeIdentifier)
	case "tcsh":
		shell.name = shellName
		shell.checkExitCodeCmd = fmt.Sprintf(tcshExitCodeCheck, exitCodeIdentifier)
	case "zsh":
		shell.name = shellName
		shell.checkExitCodeCmd = fmt.Sprintf(zshExitCodeCheck, exitCodeIdentifier)
	case "cmd":
		shell.name = shellName
		shell.checkExitCodeCmd = fmt.Sprintf(cmdExitCodeCheck, exitCodeIdentifier)
	case "powershell":
		shell.name = shellName
		shell.startArgument = []string{"-Command", "-"}
		shell.checkExitCodeCmd = fmt.Sprintf(powershellExitCodeCheck, exitCodeIdentifier)
	case "fish":
		fmt.Println("Fish shell is currently not supported by e2e tests. Default shell for the OS will be used.")
		fallthrough
	default:
		if shell.name != "" {
			fmt.Printf("Shell %v is not supported, will set the default shell for the OS to be used.\n", shell.name)
		}
		switch runtime.GOOS {
		case "darwin", "linux":
			shell.name = "bash"
			shell.checkExitCodeCmd = fmt.Sprintf(bashExitCodeCheck, exitCodeIdentifier)
		case "windows":
			shell.name = "powershell"
			shell.startArgument = []string{"-Command", "-"}
			shell.checkExitCodeCmd = fmt.Sprintf(powershellExitCodeCheck, exitCodeIdentifier)
		}
	}
}

func StartHostShellInstance(shellName string) error {
	return shell.Start(shellName)
}

func (shell *ShellInstance) Start(shellName string) error {
	var err error

	if shell.name == "" {
		shell.ConfigureTypeOfShell(shellName)
	}
	shell.exitCodeChannel = make(chan string)

	shell.instance = exec.Command(shell.name, shell.startArgument...) // #nosec G204

	shell.outPipe, err = shell.instance.StdoutPipe()
	if err != nil {
		return err
	}

	shell.errPipe, err = shell.instance.StderrPipe()
	if err != nil {
		return err
	}

	shell.inPipe, err = shell.instance.StdinPipe()
	if err != nil {
		return err
	}

	shell.outScanner = bufio.NewScanner(shell.outPipe)
	shell.errScanner = bufio.NewScanner(shell.errPipe)

	go shell.ScanPipe(shell.outScanner, &shell.outbuf, "stdout")
	go shell.ScanPipe(shell.errScanner, &shell.errbuf, "stderr")

	err = shell.instance.Start()
	if err != nil {
		return err
	}

	// Too much output, commented out the following line
	// fmt.Printf("The %v instance has been started and will be used for testing.\n", shell.name)
	return err
}

func CloseHostShellInstance() error {
	return shell.Close()
}

func (shell *ShellInstance) Close() error {
	closingCmd := "exit\n"
	_, err := io.WriteString(shell.inPipe, closingCmd)
	if err != nil {
		return err
	}
	err = shell.instance.Wait()
	if err != nil {
		fmt.Println("error closing shell instance:", err)
	}

	shell.instance = nil

	return err
}

func ExecuteCommand(command string) error {
	if shell.instance == nil {
		return errors.New("shell instance is not started")
	}

	shell.outbuf.Reset()
	shell.errbuf.Reset()
	shell.excbuf.Reset()

	err := LogMessage(shell.name, command)
	if err != nil {
		fmt.Println("error logging:", err)
	}

	_, err = io.WriteString(shell.inPipe, command+"\n")
	if err != nil {
		return err
	}

	_, err = shell.inPipe.Write([]byte(shell.checkExitCodeCmd + "\n"))
	if err != nil {
		return err
	}

	exitCode := <-shell.exitCodeChannel
	shell.excbuf.WriteString(exitCode)

	return err
}

func ExecuteCommandSucceedsOrFails(command string, expectedResult string) error {
	err := ExecuteCommand(command)
	if err != nil {
		return err
	}

	exitCode := shell.excbuf.String()

	if expectedResult == "succeeds" && exitCode != "0" {
		err = fmt.Errorf("command '%s', expected to succeed, exited with exit code: %s\nCommand stdout: %s\nCommand stderr: %s", command, exitCode, shell.outbuf.String(), shell.errbuf.String())
	}
	if expectedResult == "fails" && exitCode == "0" {
		err = fmt.Errorf("command '%s', expected to fail, exited with exit code: %s\nCommand stdout: %s\nCommand stderr: %s", command, exitCode, shell.outbuf.String(), shell.errbuf.String())
	}

	return err
}

func ExecuteCommandWithRetry(retryCount int, retryTime string, command string, containsOrNot string, expected string) error {
	var exitCode, stdout string
	retryDuration, err := time.ParseDuration(retryTime)
	if err != nil {
		return err
	}

	for i := 0; i < retryCount; i++ {
		err := ExecuteCommand(command)
		exitCode, stdout := shell.excbuf.String(), shell.outbuf.String()
		if strings.Contains(containsOrNot, " not ") {
			if err == nil && exitCode == "0" && !strings.Contains(stdout, expected) {
				return nil
			}
		} else {
			if err == nil && exitCode == "0" && strings.Contains(stdout, expected) {
				return nil
			}
		}
		time.Sleep(retryDuration)
	}

	return fmt.Errorf("command '%s', Expected: exitCode 0, stdout %s, Actual: exitCode %s, stdout %s", command, expected, exitCode, stdout)
}

func ExecuteStdoutLineByLine() error {
	var err error
	stdout := shell.GetLastCmdOutput("stdout")
	commandArray := strings.Split(stdout, "\n")
	for index := range commandArray {
		if !strings.Contains(commandArray[index], exitCodeIdentifier) {
			err = ExecuteCommand(commandArray[index])
		}
	}

	return err
}

func CommandReturnShouldContain(commandField string, expected string) error {
	return CompareExpectedWithActualContains(expected, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldContainContent(commandField string, expected *messages.PickleStepArgument_PickleDocString) error {
	return CompareExpectedWithActualContains(expected.Content, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldNotContain(commandField string, notexpected string) error {
	return CompareExpectedWithActualNotContains(notexpected, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldNotContainContent(commandField string, notexpected *messages.PickleStepArgument_PickleDocString) error {
	return CompareExpectedWithActualNotContains(notexpected.Content, shell.GetLastCmdOutput(commandField))
}

func GetLastCommandOutput(commandField string) string {
	return shell.GetLastCmdOutput(commandField)
}

func CommandReturnShouldBeEmpty(commandField string) error {
	return CompareExpectedWithActualEquals("", shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldNotBeEmpty(commandField string) error {
	return CompareExpectedWithActualNotEquals("", shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldEqual(commandField string, expected string) error {
	return CompareExpectedWithActualEquals(expected, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldEqualContent(commandField string, expected *messages.PickleStepArgument_PickleDocString) error {
	return CompareExpectedWithActualEquals(expected.Content, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldNotEqual(commandField string, expected string) error {
	return CompareExpectedWithActualNotEquals(expected, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldNotEqualContent(commandField string, expected *messages.PickleStepArgument_PickleDocString) error {
	return CompareExpectedWithActualNotEquals(expected.Content, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldMatch(commandField string, expected string) error {
	return CompareExpectedWithActualMatchesRegex(expected, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldMatchContent(commandField string, expected *messages.PickleStepArgument_PickleDocString) error {
	return CompareExpectedWithActualMatchesRegex(expected.Content, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldNotMatch(commandField string, expected string) error {
	return CompareExpectedWithActualNotMatchesRegex(expected, shell.GetLastCmdOutput(commandField))
}

func CommandReturnShouldNotMatchContent(commandField string, expected *messages.PickleStepArgument_PickleDocString) error {
	return CompareExpectedWithActualNotMatchesRegex(expected.Content, shell.GetLastCmdOutput(commandField))
}

func ShouldBeInValidFormat(commandField string, format string) error {
	return CheckFormat(format, shell.GetLastCmdOutput(commandField))
}

func SetScenarioVariableExecutingCommand(variableName string, command string) error {
	err := ExecuteCommand(command)
	if err != nil {
		return err
	}

	commandFailed := (shell.GetLastCmdOutput("exitcode") != "0" || len(shell.GetLastCmdOutput("stderr")) != 0)
	if commandFailed {
		return fmt.Errorf("command '%v' did not execute successfully. cmdExit: %v, cmdErr: %v",
			command,
			shell.GetLastCmdOutput("exitcode"),
			shell.GetLastCmdOutput("stderr"))
	}

	stdout := shell.GetLastCmdOutput("stdout")
	SetScenarioVariable(variableName, strings.TrimSpace(stdout))

	return nil
}