File: host.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 (94 lines) | stat: -rw-r--r-- 2,243 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
package host

import (
	"context"
	"errors"
	"fmt"
	"net/rpc"
	"strings"
	"time"

	crcerrors "github.com/crc-org/crc/v2/pkg/crc/errors"
	log "github.com/crc-org/crc/v2/pkg/crc/logging"
	"github.com/crc-org/machine/libmachine/drivers"
	"github.com/crc-org/machine/libmachine/state"
)

// ConfigVersion dictates which version of the config.json format is
// used. It needs to be bumped if there is a breaking change, and
// therefore migration, introduced to the config file format.
const Version = 3

type Host struct {
	ConfigVersion int
	Driver        drivers.Driver
	DriverName    string
	DriverPath    string
	Name          string
	RawDriver     []byte `json:"-"`
}

type Metadata struct {
	ConfigVersion int
}

func (h *Host) runActionForState(action func() error, desiredState state.State) error {
	if err := MachineInState(h.Driver, desiredState)(); err == nil {
		return fmt.Errorf("machine is already %s", strings.ToLower(desiredState.String()))
	}

	if err := action(); err != nil {
		return err
	}

	return crcerrors.Retry(context.Background(), 3*time.Minute, MachineInState(h.Driver, desiredState), 3*time.Second)
}

func (h *Host) Stop() error {
	log.Debugf("Stopping %q...", h.Name)
	if err := h.runActionForState(h.Driver.Stop, state.Stopped); err != nil {
		return err
	}

	log.Debugf("Machine %q was stopped.", h.Name)
	return nil
}

func (h *Host) Kill() error {
	log.Debugf("Killing %q...", h.Name)
	if err := h.runActionForState(h.Driver.Kill, state.Stopped); err != nil {
		return err
	}

	log.Debugf("Machine %q was killed.", h.Name)
	return nil
}

func (h *Host) UpdateConfig(rawConfig []byte) error {
	err := h.Driver.UpdateConfigRaw(rawConfig)
	if err != nil {
		var e rpc.ServerError
		if errors.As(err, &e) && err.Error() == "Not Implemented" {
			err = drivers.ErrNotImplemented
		}
		return err
	}
	h.RawDriver = rawConfig

	return nil
}

func MachineInState(d drivers.Driver, desiredState state.State) func() error {
	return func() error {
		currentState, err := d.GetState()
		if err != nil {
			return err
		}
		if currentState == desiredState {
			return nil
		}
		return &crcerrors.RetriableError{
			Err: fmt.Errorf("expected machine state %s, got %s", desiredState.String(), currentState.String()),
		}
	}
}