Skip to content

Commit 1032c25

Browse files
authored
Merge pull request #47 from AkihiroSuda/dev
refactoring
2 parents 06dd452 + fdbae4c commit 1032c25

File tree

12 files changed

+134
-107
lines changed

12 files changed

+134
-107
lines changed

cmd/lima

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,18 @@
22
set -eu
33
: "${LIMA_INSTANCE:=default}"
44
: "${LIMACTL:=limactl}"
5+
6+
if [ "$#" -eq 1 ]; then
7+
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
8+
base="$(basename "$0")"
9+
echo "Usage: ${base} [COMMAND...]"
10+
echo
11+
echo "${base} is an alias for \"${LIMACTL} shell ${LIMA_INSTANCE}\"."
12+
echo "The instance name (\"${LIMA_INSTANCE}\") can be changed by specifying \$LIMA_INSTANCE."
13+
echo
14+
echo "See \`${LIMACTL} shell --help\` for further information."
15+
exit 0
16+
fi
17+
fi
18+
519
exec "$LIMACTL" shell "$LIMA_INSTANCE" "$@"

cmd/limactl/hostagent.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313
var hostagentCommand = &cli.Command{
1414
Name: "hostagent",
1515
Usage: "DO NOT EXECUTE MANUALLY",
16-
ArgsUsage: "NAME",
16+
ArgsUsage: "INSTANCE",
1717
Hidden: true,
1818
Flags: []cli.Flag{
1919
&cli.StringFlag{

cmd/limactl/shell.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ import (
1919
var shellCommand = &cli.Command{
2020
Name: "shell",
2121
Usage: "Execute shell in Lima",
22-
ArgsUsage: "[flags] INSTANCE [COMMAND...]",
23-
Description: "`lima` command is provided as an alias for `limactl shell $LIMA_INSTANCE`. $LIMA_INSTANCE defaults to " + DefaultInstanceName + ".\n" +
22+
ArgsUsage: "INSTANCE [COMMAND...]",
23+
Description: "`lima` command is provided as an alias for `limactl shell $LIMA_INSTANCE`. $LIMA_INSTANCE defaults to \"" + DefaultInstanceName + "\".\n" +
2424
"Hint: try --debug to show the detailed logs, if it seems hanging (mostly due to some SSH issue).",
2525
Flags: []cli.Flag{
2626
&cli.StringFlag{
@@ -57,7 +57,7 @@ func shellAction(clicontext *cli.Context) error {
5757
if inst.Status == store.StatusStopped {
5858
return errors.Errorf("instance %q is stopped, run `limactl start %s` to start the instance", instName, instName)
5959
}
60-
y, _, err := store.LoadYAMLByInstanceName(instName)
60+
y, err := inst.LoadYAML()
6161
if err != nil {
6262
return err
6363
}

cmd/limactl/start.go

Lines changed: 31 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/AkihiroSuda/lima/pkg/limayaml"
1212
"github.com/AkihiroSuda/lima/pkg/start"
1313
"github.com/AkihiroSuda/lima/pkg/store"
14+
"github.com/AkihiroSuda/lima/pkg/store/filenames"
1415
"github.com/containerd/containerd/identifiers"
1516
"github.com/mattn/go-isatty"
1617
"github.com/norouter/norouter/cmd/norouter/editorcmd"
@@ -22,7 +23,7 @@ import (
2223
var startCommand = &cli.Command{
2324
Name: "start",
2425
Usage: fmt.Sprintf("Start an instance of Lima. If the instance does not exist, open an editor for creating new one, with name %q", DefaultInstanceName),
25-
ArgsUsage: "[flags] NAME|FILE.yaml",
26+
ArgsUsage: "NAME|FILE.yaml",
2627
Flags: []cli.Flag{
2728
&cli.BoolFlag{
2829
Name: "tty",
@@ -34,86 +35,88 @@ var startCommand = &cli.Command{
3435
BashComplete: startBashComplete,
3536
}
3637

37-
func loadOrCreateYAML(clicontext *cli.Context) (y *limayaml.LimaYAML, instDir string, err error) {
38+
func loadOrCreateInstance(clicontext *cli.Context) (*store.Instance, error) {
3839
if clicontext.NArg() > 1 {
39-
return nil, "", errors.Errorf("too many arguments")
40+
return nil, errors.Errorf("too many arguments")
4041
}
4142

4243
arg := clicontext.Args().First()
4344
if arg == "" {
4445
arg = DefaultInstanceName
4546
}
4647

47-
yBytes := limayaml.DefaultTemplate
48-
var instName string
48+
var (
49+
instName string
50+
yBytes = limayaml.DefaultTemplate
51+
err error
52+
)
4953

5054
if argSeemsYAMLPath(arg) {
5155
instName = instNameFromYAMLPath(arg)
5256
logrus.Debugf("interpreting argument %q as a file path for instance %q", arg, instName)
5357
yBytes, err = os.ReadFile(arg)
5458
if err != nil {
55-
return nil, "", err
59+
return nil, err
5660
}
5761
} else {
5862
instName = arg
5963
logrus.Debugf("interpreting argument %q as an instance name %q", arg, instName)
60-
if err = identifiers.Validate(instName); err != nil {
61-
return nil, "", errors.Wrapf(err, "argument must be either an instance name or a YAML file path, got %q", instName)
64+
if err := identifiers.Validate(instName); err != nil {
65+
return nil, errors.Wrapf(err, "argument must be either an instance name or a YAML file path, got %q", instName)
6266
}
63-
y, instDir, err = store.LoadYAMLByInstanceName(instName)
64-
if err == nil {
67+
if inst, err := store.Inspect(instName); err == nil {
6568
logrus.Infof("Using the existing instance %q", instName)
66-
return y, instDir, nil
69+
return inst, nil
6770
} else {
6871
if !errors.Is(err, os.ErrNotExist) {
69-
return nil, "", err
72+
return nil, err
7073
}
7174
}
7275
}
7376
// create a new instance from the template
74-
instDir, err = store.InstanceDir(instName)
77+
instDir, err := store.InstanceDir(instName)
7578
if err != nil {
76-
return nil, "", err
79+
return nil, err
7780
}
7881

7982
if _, err := os.Stat(instDir); !errors.Is(err, os.ErrNotExist) {
80-
return nil, "", errors.Errorf("instance %q already exists (%q)", instName, instDir)
83+
return nil, errors.Errorf("instance %q already exists (%q)", instName, instDir)
8184
}
8285

8386
if clicontext.Bool("tty") {
8487
yBytes, err = openEditor(clicontext, instName, yBytes)
8588
if err != nil {
86-
return nil, "", err
89+
return nil, err
8790
}
8891
if len(yBytes) == 0 {
8992
logrus.Info("Aborting, as requested by saving the file with empty content")
9093
os.Exit(0)
91-
return nil, "", errors.New("should not reach here")
94+
return nil, errors.New("should not reach here")
9295
}
9396
} else {
9497
logrus.Info("Terminal is not available, proceeding without opening an editor")
9598
}
96-
y, err = limayaml.Load(yBytes)
99+
y, err := limayaml.Load(yBytes)
97100
if err != nil {
98-
return nil, "", err
101+
return nil, err
99102
}
100103
if err := limayaml.Validate(*y); err != nil {
101104
if !clicontext.Bool("tty") {
102-
return nil, "", err
105+
return nil, err
103106
}
104107
rejectedYAML := "lima.REJECTED.yaml"
105108
if writeErr := os.WriteFile(rejectedYAML, yBytes, 0644); writeErr != nil {
106-
return nil, "", errors.Wrapf(err, "the YAML is invalid, attempted to save the buffer as %q but failed: %v", rejectedYAML, writeErr)
109+
return nil, errors.Wrapf(err, "the YAML is invalid, attempted to save the buffer as %q but failed: %v", rejectedYAML, writeErr)
107110
}
108-
return nil, "", errors.Wrapf(err, "the YAML is invalid, saved the buffer as %q", rejectedYAML)
111+
return nil, errors.Wrapf(err, "the YAML is invalid, saved the buffer as %q", rejectedYAML)
109112
}
110113
if err := os.MkdirAll(instDir, 0700); err != nil {
111-
return nil, "", err
114+
return nil, err
112115
}
113-
if err := os.WriteFile(filepath.Join(instDir, store.YAMLFileName), yBytes, 0644); err != nil {
114-
return nil, "", err
116+
if err := os.WriteFile(filepath.Join(instDir, filenames.LimaYAML), yBytes, 0644); err != nil {
117+
return nil, err
115118
}
116-
return y, instDir, nil
119+
return store.Inspect(instName)
117120
}
118121

119122
// openEditor opens an editor, and returns the content (not path) of the modified yaml.
@@ -164,16 +167,12 @@ func openEditor(clicontext *cli.Context, name string, initialContent []byte) ([]
164167
}
165168

166169
func startAction(clicontext *cli.Context) error {
167-
y, instDir, err := loadOrCreateYAML(clicontext)
168-
if err != nil {
169-
return err
170-
}
171-
instName, err := store.InstanceNameFromInstanceDir(instDir)
170+
inst, err := loadOrCreateInstance(clicontext)
172171
if err != nil {
173172
return err
174173
}
175174
ctx := clicontext.Context
176-
return start.Start(ctx, instName, instDir, y)
175+
return start.Start(ctx, inst)
177176
}
178177

179178
func argSeemsYAMLPath(arg string) bool {

cmd/limactl/stop.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010

1111
hostagentapi "github.com/AkihiroSuda/lima/pkg/hostagent/api"
1212
"github.com/AkihiroSuda/lima/pkg/store"
13+
"github.com/AkihiroSuda/lima/pkg/store/filenames"
1314
"github.com/pkg/errors"
1415
"github.com/sirupsen/logrus"
1516
"github.com/urfave/cli/v2"
@@ -83,8 +84,8 @@ func waitForHostAgentTermination(ctx context.Context, inst *store.Instance) erro
8384
return false
8485
}
8586

86-
haStdoutPath := filepath.Join(inst.Dir, "ha.stdout.log")
87-
haStderrPath := filepath.Join(inst.Dir, "ha.stderr.log")
87+
haStdoutPath := filepath.Join(inst.Dir, filenames.HostAgentStdoutLog)
88+
haStderrPath := filepath.Join(inst.Dir, filenames.HostAgentStderrLog)
8889

8990
if err := hostagentapi.WatchEvents(ctx2, haStdoutPath, haStderrPath, onEvent); err != nil {
9091
return err

pkg/hostagent/hostagent.go

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"github.com/AkihiroSuda/lima/pkg/qemu"
2121
"github.com/AkihiroSuda/lima/pkg/sshutil"
2222
"github.com/AkihiroSuda/lima/pkg/store"
23+
"github.com/AkihiroSuda/lima/pkg/store/filenames"
2324
"github.com/AkihiroSuda/sshocker/pkg/ssh"
2425
"github.com/digitalocean/go-qemu/qmp"
2526
"github.com/digitalocean/go-qemu/qmp/raw"
@@ -56,22 +57,27 @@ func New(instName string, stdout, stderr io.Writer, sigintCh chan os.Signal) (*H
5657
Level: logrus.DebugLevel,
5758
}
5859

59-
y, instDir, err := store.LoadYAMLByInstanceName(instName)
60+
inst, err := store.Inspect(instName)
61+
if err != nil {
62+
return nil, err
63+
}
64+
65+
y, err := inst.LoadYAML()
6066
if err != nil {
6167
return nil, err
6268
}
6369

6470
qCfg := qemu.Config{
6571
Name: instName,
66-
InstanceDir: instDir,
72+
InstanceDir: inst.Dir,
6773
LimaYAML: y,
6874
}
6975
qExe, qArgs, err := qemu.Cmdline(qCfg)
7076
if err != nil {
7177
return nil, err
7278
}
7379

74-
sshArgs, err := sshutil.SSHArgs(instDir)
80+
sshArgs, err := sshutil.SSHArgs(inst.Dir)
7581
if err != nil {
7682
return nil, err
7783
}
@@ -82,7 +88,7 @@ func New(instName string, stdout, stderr io.Writer, sigintCh chan os.Signal) (*H
8288
a := &HostAgent{
8389
l: l,
8490
y: y,
85-
instDir: instDir,
91+
instDir: inst.Dir,
8692
sshConfig: sshConfig,
8793
portForwarder: newPortForwarder(l, sshConfig, y.SSH.LocalPort),
8894
qExe: qExe,
@@ -134,7 +140,7 @@ func (a *HostAgent) Run(ctx context.Context) error {
134140
}
135141
defer logPipeRoutine(a.l, qStderr, "qemu[stderr]")
136142

137-
a.l.Infof("Starting QEMU (hint: to watch the boot progress, see %q)", filepath.Join(a.instDir, "serial.log"))
143+
a.l.Infof("Starting QEMU (hint: to watch the boot progress, see %q)", filepath.Join(a.instDir, filenames.SerialLog))
138144
a.l.Debugf("qCmd.Args: %v", qCmd.Args)
139145
if err := qCmd.Start(); err != nil {
140146
return err
@@ -188,7 +194,7 @@ func (a *HostAgent) Run(ctx context.Context) error {
188194

189195
func (a *HostAgent) shutdownQEMU(ctx context.Context, timeout time.Duration, qCmd *exec.Cmd, qWaitCh <-chan error) error {
190196
a.l.Info("Shutting down QEMU with ACPI")
191-
qmpSockPath := filepath.Join(a.instDir, "qmp.sock")
197+
qmpSockPath := filepath.Join(a.instDir, filenames.QMPSock)
192198
qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
193199
if err != nil {
194200
a.l.WithError(err).Warnf("failed to open the QMP socket %q, forcibly killing QEMU", qmpSockPath)
@@ -222,7 +228,7 @@ func (a *HostAgent) killQEMU(ctx context.Context, timeout time.Duration, qCmd *e
222228
}
223229
qWaitErr := <-qWaitCh
224230
a.l.WithError(qWaitErr).Info("QEMU has exited, after killing forcibly")
225-
qemuPIDPath := filepath.Join(a.instDir, "qemu.pid")
231+
qemuPIDPath := filepath.Join(a.instDir, filenames.QemuPID)
226232
_ = os.RemoveAll(qemuPIDPath)
227233
return qWaitErr
228234
}
@@ -274,7 +280,7 @@ func (a *HostAgent) close() error {
274280
func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) {
275281
// TODO: use vSock (when QEMU for macOS gets support for vSock)
276282

277-
localUnix := filepath.Join(a.instDir, "ga.sock")
283+
localUnix := filepath.Join(a.instDir, filenames.GuestAgentSock)
278284
// guest should have same UID as the host (specified in cidata)
279285
remoteUnix := fmt.Sprintf("/run/user/%d/lima-guestagent.sock", os.Getuid())
280286

pkg/qemu/qemu.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010

1111
"github.com/AkihiroSuda/lima/pkg/downloader"
1212
"github.com/AkihiroSuda/lima/pkg/limayaml"
13+
"github.com/AkihiroSuda/lima/pkg/store/filenames"
1314
"github.com/docker/go-units"
1415
"github.com/pkg/errors"
1516
"github.com/sirupsen/logrus"
@@ -22,13 +23,13 @@ type Config struct {
2223
}
2324

2425
func EnsureDisk(cfg Config) error {
25-
diffDisk := filepath.Join(cfg.InstanceDir, "diffdisk")
26+
diffDisk := filepath.Join(cfg.InstanceDir, filenames.DiffDisk)
2627
if _, err := os.Stat(diffDisk); err == nil || !errors.Is(err, os.ErrNotExist) {
2728
// disk is already ensured
2829
return err
2930
}
3031

31-
baseDisk := filepath.Join(cfg.InstanceDir, "basedisk")
32+
baseDisk := filepath.Join(cfg.InstanceDir, filenames.BaseDisk)
3233
if _, err := os.Stat(baseDisk); errors.Is(err, os.ErrNotExist) {
3334
var ensuredBaseDisk bool
3435
errs := make([]error, len(cfg.LimaYAML.Images))
@@ -120,10 +121,10 @@ func Cmdline(cfg Config) (string, []string, error) {
120121
args = append(args, "-boot", "order=c,splash-time=0,menu=on")
121122

122123
// Root disk
123-
args = append(args, "-drive", fmt.Sprintf("file=%s,if=virtio", filepath.Join(cfg.InstanceDir, "diffdisk")))
124+
args = append(args, "-drive", fmt.Sprintf("file=%s,if=virtio", filepath.Join(cfg.InstanceDir, filenames.DiffDisk)))
124125

125126
// cloud-init
126-
args = append(args, "-cdrom", filepath.Join(cfg.InstanceDir, "cidata.iso"))
127+
args = append(args, "-cdrom", filepath.Join(cfg.InstanceDir, filenames.CIDataISO))
127128

128129
// Network
129130
// CIDR is intentionally hardcoded to 192.168.5.0/24, as each of QEMU has its own independent slirp network.
@@ -155,11 +156,11 @@ func Cmdline(cfg Config) (string, []string, error) {
155156
args = append(args, "-parallel", "none")
156157

157158
// Serial
158-
serialSock := filepath.Join(cfg.InstanceDir, "serial.sock")
159+
serialSock := filepath.Join(cfg.InstanceDir, filenames.SerialSock)
159160
if err := os.RemoveAll(serialSock); err != nil {
160161
return "", nil, err
161162
}
162-
serialLog := filepath.Join(cfg.InstanceDir, "serial.log")
163+
serialLog := filepath.Join(cfg.InstanceDir, filenames.SerialLog)
163164
if err := os.RemoveAll(serialLog); err != nil {
164165
return "", nil, err
165166
}
@@ -170,7 +171,7 @@ func Cmdline(cfg Config) (string, []string, error) {
170171
// We also want to enable vsock and virtfs here, but QEMU does not support vsock and virtfs for macOS hosts
171172

172173
// QMP
173-
qmpSock := filepath.Join(cfg.InstanceDir, "qmp.sock")
174+
qmpSock := filepath.Join(cfg.InstanceDir, filenames.QMPSock)
174175
if err := os.RemoveAll(qmpSock); err != nil {
175176
return "", nil, err
176177
}
@@ -180,7 +181,7 @@ func Cmdline(cfg Config) (string, []string, error) {
180181

181182
// QEMU process
182183
args = append(args, "-name", "lima-"+cfg.Name)
183-
args = append(args, "-pidfile", filepath.Join(cfg.InstanceDir, "qemu.pid"))
184+
args = append(args, "-pidfile", filepath.Join(cfg.InstanceDir, filenames.QemuPID))
184185

185186
return exe, args, nil
186187
}

pkg/sshutil/sshutil.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"runtime"
77
"strings"
88

9+
"github.com/AkihiroSuda/lima/pkg/store/filenames"
910
"github.com/pkg/errors"
1011
"github.com/sirupsen/logrus"
1112
)
@@ -46,7 +47,7 @@ func DefaultPubKeys() []PubKey {
4647
}
4748

4849
func SSHArgs(instDir string) ([]string, error) {
49-
controlSock := filepath.Join(instDir, "ssh.sock")
50+
controlSock := filepath.Join(instDir, filenames.SSHSock)
5051
maxSockLen := 104
5152
if runtime.GOOS == "linux" {
5253
maxSockLen = 108

0 commit comments

Comments
 (0)