File: cmd.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (347 lines) | stat: -rw-r--r-- 9,334 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
package cmd

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

	"github.com/crc-org/crc/v2/pkg/crc/logging"
	"github.com/crc-org/crc/v2/test/extended/util"
	"github.com/sirupsen/logrus"
)

const (
	// timeout to wait for cluster to change its state
	clusterStateRetryCount = 25
	clusterStateTimeout    = 600
	// defines the number of times the state should be matches in a row
	clusterStateRepetition    = 3
	CRCExecutableInstalled    = "installed"
	CRCExecutableNotInstalled = "notInstalled"
)

var (
	commands = map[string]struct{}{
		"bundle":     {},
		"cleanup":    {},
		"config":     {},
		"console":    {},
		"delete":     {},
		"help":       {},
		"ip":         {},
		"oc-env":     {},
		"podman-env": {},
		"setup":      {},
		"start":      {},
		"status":     {},
		"stop":       {},
		"version":    {},
	}
)

type Command struct {
	command     string
	updateCheck bool
	disableNTP  bool
}

func CRC(command string) Command {
	return Command{command: command}
}

func (c Command) WithUpdateCheck() Command {
	c.updateCheck = true
	return c
}

func (c Command) WithDisableNTP() Command {
	c.disableNTP = true
	return c
}

func (c Command) ToString() string {
	cmd := append(c.env(), "crc", c.command)
	return strings.Join(cmd, " ")
}

func (c Command) ExecuteWithExpectedExit(expectedExit string) error {
	if err := c.validate(); err != nil {
		return err
	}
	if expectedExit == "succeeds" || expectedExit == "fails" {
		return util.ExecuteCommandSucceedsOrFails(c.ToString(), expectedExit)
	}
	return fmt.Errorf("%s is a valid expected exit status", expectedExit)
}

func (c Command) Execute() error {
	if err := c.validate(); err != nil {
		return err
	}
	return util.ExecuteCommand(c.ToString())
}

func (c Command) env() []string {
	var env []string
	if !c.updateCheck {
		env = append(env, envVariable("CRC_DISABLE_UPDATE_CHECK", "true"))
	}
	if c.disableNTP {
		env = append(env, envVariable("CRC_DEBUG_ENABLE_STOP_NTP", "true"))
	}
	return env
}

func envVariable(key, value string) string {
	if runtime.GOOS == "windows" {
		return fmt.Sprintf("$env:%s=%s;", key, value)
	}
	return fmt.Sprintf("%s=%s", key, value)
}

func (c Command) validate() error {
	cmdline := strings.Fields(c.command)
	if len(cmdline) < 1 {
		return fmt.Errorf("empty command? %s", c.command)
	}
	if _, ok := commands[cmdline[0]]; !ok {
		return fmt.Errorf("%s is not a supported command", cmdline[0])
	}
	return nil
}

func SetConfigPropertyToValueSucceedsOrFails(property string, value string, expected string) error {
	cmd := "crc config set " + property + " " + value
	return util.ExecuteCommandSucceedsOrFails(cmd, expected)
}

func UnsetConfigPropertySucceedsOrFails(property string, expected string) error {
	cmd := "crc config unset " + property
	return util.ExecuteCommandSucceedsOrFails(cmd, expected)
}

func WaitForClusterInState(state string) error {
	return util.MatchRepetitionsWithRetry(state, CheckCRCStatus, clusterStateRepetition,
		clusterStateRetryCount, clusterStateTimeout)
}

func CheckCRCStatus(state string) error {

	// Podman status does not show Running, so need to OR it separately
	expression := `.*CRC VM: *Running\s.*: *Running|.*CRC VM: *Running\s.*Podman: *\d+\.\d+\.\d+`

	// Does not apply to Podman preset
	if state == "stopped" {
		expression = `.*CRC VM:.*\s.*: .*Stopped.*`
	}

	err := util.ExecuteCommand("crc status")
	if err != nil {
		return err
	}
	out := util.GetLastCommandOutput("stdout")
	err = util.CompareExpectedWithActualMatchesRegex(expression, string(out))
	return err
}

func CheckCRCExecutableState(state string) error {
	command := "which crc"
	if runtime.GOOS == "windows" {
		if err := util.ExecuteCommand("$env:Path = [System.Environment]::GetEnvironmentVariable(\"Path\",\"Machine\")"); err != nil {
			return err
		}
	}
	switch state {
	case CRCExecutableInstalled:
		return util.ExecuteCommandSucceedsOrFails(command, "succeeds")
	case CRCExecutableNotInstalled:
		return util.ExecuteCommandSucceedsOrFails(command, "fails")
	default:
		return fmt.Errorf("%s state is not defined as valid crc executable state", state)
	}
}

func DeleteCRC() error {

	_ = util.ExecuteCommand(CRC("delete").ToString())

	fmt.Printf("Deleted CRC instance (if one existed).\n")
	return nil
}

func (c Command) ExecuteSingleWithExpectedExit(expectedExit string) error {
	if err := c.validate(); err != nil {
		return err
	}
	if expectedExit == "succeeds" || expectedExit == "fails" {
		// Disable G204 lint check as it will force us to use fixed args for the command
		cmd := exec.Command("crc", strings.Split(c.command, " ")...) // #nosec G204
		err := cmd.Run()
		logging.Debugf("Running single command crc %s", c.command)
		if err != nil && expectedExit == "fails" ||
			err == nil && expectedExit == "succeeds" {
			return nil
		}
		return fmt.Errorf("%s expected %s but it did not", c.ToString(), expectedExit)
	}
	return fmt.Errorf("%s is a valid expected exit status", expectedExit)
}

// PODMAN

// PodmanBuilder is used to build, customize, and execute a podman-remote command.
type PodmanBuilder struct {
	cmd     *exec.Cmd
	timeout <-chan time.Time
}

// NewPodmanCommand returns a PodmanBuilder for running CRC.
func NewPodmanCommand(args ...string) *PodmanBuilder {

	cmd := exec.Command("podman", args...)

	switch runtime.GOOS {
	case "linux":
		cmd = exec.Command("podman-remote", args...)
	case "windows":
		cmd = exec.Command("podman.exe", args...)
	}

	return &PodmanBuilder{
		cmd: cmd,
	}
}

// WithTimeout sets the given timeout and returns itself.
func (b *PodmanBuilder) WithTimeout(t <-chan time.Time) *PodmanBuilder {
	b.timeout = t
	return b
}

// WithStdinData sets the given data to stdin and returns itself.
func (b PodmanBuilder) WithStdinData(data string) *PodmanBuilder {
	b.cmd.Stdin = strings.NewReader(data)
	return &b
}

// WithStdinReader sets the given reader and returns itself.
func (b PodmanBuilder) WithStdinReader(reader io.Reader) *PodmanBuilder {
	b.cmd.Stdin = reader
	return &b
}

// ExecOrDie runs the executable or dies if error occurs.
func (b PodmanBuilder) ExecOrDie() (string, error) {
	stdout, err := b.Exec()
	return stdout, err
}

// ExecOrDieWithLogs runs the executable or dies if error occurs.
func (b PodmanBuilder) ExecOrDieWithLogs() (string, string, error) {
	stdout, stderr, err := b.ExecWithFullOutput()
	return stdout, stderr, err
}

// Exec runs the executable.
func (b PodmanBuilder) Exec() (string, error) {
	stdout, _, err := b.ExecWithFullOutput()
	return stdout, err
}

// ExecWithFullOutput runs the executable and returns the stdout and stderr.
func (b PodmanBuilder) ExecWithFullOutput() (string, string, error) {
	return Exec(b.cmd, b.timeout)
}

func Exec(cmd *exec.Cmd, timeout <-chan time.Time) (string, string, error) {
	var stdout, stderr bytes.Buffer
	cmd.Stdout, cmd.Stderr = &stdout, &stderr

	logrus.Infof("Running '%s %s'", cmd.Path, strings.Join(cmd.Args[1:], " ")) // skip arg[0] as it is printed separately
	if err := cmd.Start(); err != nil {
		return "", "", fmt.Errorf("error starting %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, cmd.Stdout, cmd.Stderr, err)
	}
	errCh := make(chan error, 1)
	go func() {
		errCh <- cmd.Wait()
	}()
	select {
	case err := <-errCh:
		if err != nil {
			var rc = 127
			if ee, ok := err.(*exec.ExitError); ok {
				rc = int(ee.Sys().(syscall.WaitStatus).ExitStatus())
				logrus.Infof("rc: %d", rc)
			}
			return stdout.String(), stderr.String(), CodeExitError{
				Err:  fmt.Errorf("error running %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, cmd.Stdout, cmd.Stderr, err),
				Code: rc,
			}
		}
	case <-timeout:
		_ = cmd.Process.Kill()
		return "", "", fmt.Errorf("timed out waiting for command %v:\nCommand stdout:\n%v\nstderr:\n%v", cmd, cmd.Stdout, cmd.Stderr)
	}
	logrus.Infof("stderr: %q", stderr.String())
	logrus.Infof("stdout: %q", stdout.String())
	return stdout.String(), stderr.String(), nil
}

// RunPodmanExpectSuccess is a convenience wrapper over podman-remote
func RunPodmanExpectSuccess(args ...string) (string, error) {
	return NewPodmanCommand(args...).ExecOrDie()
}

// RunPodmanExpectFail is a convenience wrapper over PodmanBuilder
// if err != nil: return stderr, nil
// if err == nil: return stdout, err
func RunPodmanExpectFail(args ...string) (string, error) {
	stdout, stderr, err := NewPodmanCommand(args...).ExecWithFullOutput()

	if err == nil {
		err = fmt.Errorf("Expected error but exited without error")
		return stdout, err
	}

	return stderr, nil
}

// ExitError is an interface that presents an API similar to os.ProcessState, which is
// what ExitError from os/exec is.  This is designed to make testing a bit easier and
// probably loses some of the cross-platform properties of the underlying library.
type ExitError interface {
	String() string
	Error() string
	Exited() bool
	ExitStatus() int
}

// CodeExitError is an implementation of ExitError consisting of an error object
// and an exit code (the upper bits of os.exec.ExitStatus).
type CodeExitError struct {
	Err  error
	Code int
}

var _ ExitError = CodeExitError{}

func (e CodeExitError) Error() string {
	return e.Err.Error()
}

func (e CodeExitError) String() string {
	return e.Err.Error()
}

func (e CodeExitError) Exited() bool {
	return true
}

func (e CodeExitError) ExitStatus() int {
	return e.Code
}