-
-
Notifications
You must be signed in to change notification settings - Fork 432
/
Copy pathlima.go
400 lines (321 loc) · 9.21 KB
/
lima.go
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package lima
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/abiosoft/colima/cli"
"github.com/abiosoft/colima/config"
"github.com/abiosoft/colima/config/configmanager"
"github.com/abiosoft/colima/core"
"github.com/abiosoft/colima/daemon"
"github.com/abiosoft/colima/environment"
"github.com/abiosoft/colima/environment/vm/lima/limaconfig"
"github.com/abiosoft/colima/environment/vm/lima/limautil"
"github.com/abiosoft/colima/util"
"github.com/abiosoft/colima/util/osutil"
"github.com/abiosoft/colima/util/yamlutil"
"github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v3"
)
// New creates a new virtual machine.
func New(host environment.HostActions) environment.VM {
// lima config directory
limaHome := config.LimaDir()
// environment variables for the subprocesses
var envs []string
envHome := limautil.EnvLimaHome + "=" + limaHome
envLimaInstance := envLimaInstance + "=" + config.CurrentProfile().ID
envSSHForward := "LIMA_SSH_PORT_FORWARDER=true"
envBinary := osutil.EnvColimaBinary + "=" + osutil.Executable()
envs = append(envs, envHome, envLimaInstance, envSSHForward, envBinary)
// consider making this truly flexible to support other VMs
return &limaVM{
host: host.WithEnv(envs...),
limaHome: limaHome,
CommandChain: cli.New("vm"),
daemon: daemon.NewManager(host),
}
}
const (
envLimaInstance = "LIMA_INSTANCE"
lima = "lima"
limactl = limautil.LimactlCommand
)
var _ environment.VM = (*limaVM)(nil)
type limaVM struct {
host environment.HostActions
cli.CommandChain
// keep config in case of restart
conf config.Config
// lima config
limaConf limaconfig.Config
// lima config directory
limaHome string
// network between host and the vm
daemon daemon.Manager
}
func (l limaVM) Dependencies() []string {
return []string{
"lima",
}
}
func (l *limaVM) Start(ctx context.Context, conf config.Config) error {
a := l.Init(ctx)
if l.Created() {
return l.resume(ctx, conf)
}
a.Add(func() (err error) {
ctx, err = l.startDaemon(ctx, conf)
return err
})
a.Stage("creating and starting")
confFile := filepath.Join(os.TempDir(), config.CurrentProfile().ID+".yaml")
a.Add(func() (err error) {
l.limaConf, err = newConf(ctx, conf)
return err
})
a.Add(func() error {
return l.downloadDiskImage(ctx, conf)
})
a.Add(func() error {
return yamlutil.WriteYAML(l.limaConf, confFile)
})
a.Add(l.writeNetworkFile)
a.Add(func() error {
return l.host.Run(limactl, "start", "--tty=false", confFile)
})
a.Add(func() error {
return os.Remove(confFile)
})
// adding it to command chain to execute only after successful startup.
a.Add(func() error {
l.conf = conf
return nil
})
l.addPostStartActions(a, conf)
return a.Exec()
}
func (l *limaVM) resume(ctx context.Context, conf config.Config) error {
log := l.Logger(ctx)
a := l.Init(ctx)
if l.Running(ctx) {
log.Println("already running")
return nil
}
a.Add(func() (err error) {
ctx, err = l.startDaemon(ctx, conf)
return err
})
a.Add(func() (err error) {
// disk must be resized before starting
conf = l.syncDiskSize(ctx, conf)
l.limaConf, err = newConf(ctx, conf)
return err
})
a.Add(l.setDiskImage)
a.Add(func() error {
err := yamlutil.WriteYAML(l.limaConf, config.CurrentProfile().LimaFile())
return err
})
a.Add(l.writeNetworkFile)
a.Stage("starting")
a.Add(func() error {
return l.host.Run(limactl, "start", config.CurrentProfile().ID)
})
l.addPostStartActions(a, conf)
return a.Exec()
}
func (l limaVM) Running(_ context.Context) bool {
i, err := limautil.Instance()
if err != nil {
logrus.Trace(fmt.Errorf("error retrieving running instance: %w", err))
return false
}
return i.Running()
}
func (l limaVM) Stop(ctx context.Context, force bool) error {
log := l.Logger(ctx)
a := l.Init(ctx)
if !l.Running(ctx) && !force {
log.Println("not running")
return nil
}
a.Stage("stopping")
if util.MacOS() {
conf, _ := configmanager.LoadInstance()
a.Retry("", time.Second*1, 10, func(retryCount int) error {
err := l.daemon.Stop(ctx, conf)
if err != nil {
err = cli.ErrNonFatal(err)
}
return err
})
}
a.Add(func() error { l.removeHostAddresses(); return nil })
a.Add(func() error {
if force {
return l.host.Run(limactl, "stop", "--force", config.CurrentProfile().ID)
}
return l.host.Run(limactl, "stop", config.CurrentProfile().ID)
})
return a.Exec()
}
func (l limaVM) Teardown(ctx context.Context) error {
a := l.Init(ctx)
if util.MacOS() {
conf, _ := configmanager.LoadInstance()
a.Retry("", time.Second*1, 10, func(retryCount int) error {
return l.daemon.Stop(ctx, conf)
})
}
a.Add(func() error {
return l.host.Run(limactl, "delete", "--force", config.CurrentProfile().ID)
})
return a.Exec()
}
func (l limaVM) Restart(ctx context.Context) error {
if l.conf.Empty() {
return fmt.Errorf("cannot restart, VM not previously started")
}
if err := l.Stop(ctx, false); err != nil {
return err
}
// minor delay to prevent possible race condition.
time.Sleep(time.Second * 2)
if err := l.Start(ctx, l.conf); err != nil {
return err
}
return nil
}
func (l limaVM) Host() environment.HostActions {
return l.host
}
func (l limaVM) Env(s string) (string, error) {
ctx := context.Background()
if !l.Running(ctx) {
return "", fmt.Errorf("not running")
}
return l.RunOutput("echo", "$"+s)
}
func (l limaVM) Created() bool {
stat, err := os.Stat(config.CurrentProfile().LimaFile())
return err == nil && !stat.IsDir()
}
func (l limaVM) User() (string, error) {
return l.RunOutput("whoami")
}
func (l limaVM) Arch() environment.Arch {
a, _ := l.RunOutput("uname", "-m")
return environment.Arch(a)
}
func (l *limaVM) downloadDiskImage(ctx context.Context, conf config.Config) error {
log := l.Logger(ctx)
if image, ok := limautil.ImageCached(l.limaConf.Arch, conf.Runtime); ok {
l.limaConf.Images = []limaconfig.File{image}
return nil
}
log.Infoln("downloading disk image ...")
image, err := limautil.DownloadImage(l.limaConf.Arch, conf.Runtime)
if err != nil {
return fmt.Errorf("error getting qcow image: %w", err)
}
l.limaConf.Images = []limaconfig.File{image}
return nil
}
func (l *limaVM) setDiskImage() error {
var c limaconfig.Config
b, err := os.ReadFile(config.CurrentProfile().LimaFile())
if err != nil {
return err
}
if err := yaml.Unmarshal(b, &c); err != nil {
return err
}
l.limaConf.Images = c.Images
return nil
}
func (l *limaVM) syncDiskSize(ctx context.Context, conf config.Config) config.Config {
log := l.Logger(ctx)
instance, err := configmanager.LoadInstance()
if err != nil {
// instance config missing, ignore
return conf
}
resized := func() bool {
if instance.Disk == conf.Disk {
// nothing to do
return false
}
size := conf.Disk - instance.Disk
if size < 0 {
log.Warnln("disk size cannot be reduced, ignoring...")
return false
}
if err := util.AssertQemuImg(); err != nil {
log.Warnln(fmt.Errorf("unable to resize disk: %w", err))
return false
}
sizeStr := fmt.Sprintf("%dG", conf.Disk)
args := []string{"qemu-img", "resize"}
disk := limautil.ColimaDiffDisk(config.CurrentProfile().ID)
args = append(args, disk, sizeStr)
// qemu-img resize /path/to/diffdisk +10G
if err := l.host.RunQuiet(args...); err != nil {
log.Warnln(fmt.Errorf("unable to resize disk: %w", err))
return false
}
log.Printf("resizing disk to %dGiB...", conf.Disk)
return true
}()
if !resized {
conf.Disk = instance.Disk
}
return conf
}
func (l *limaVM) addPostStartActions(a *cli.ActiveCommandChain, conf config.Config) {
// registry certs
a.Add(l.copyCerts)
// cross-platform emulation
a.Add(func() error {
if !l.limaConf.Rosetta.Enabled {
// use binfmt when rosetta is disabled and emulation is disabled i.e. host arch
if arch := environment.HostArch(); arch == environment.Arch(conf.Arch).Value() {
if err := core.SetupBinfmt(l.host, l, environment.Arch(conf.Arch)); err != nil {
logrus.Warn(fmt.Errorf("unable to enable qemu %s emulation: %w", arch, err))
}
}
// rosetta is disabled
return nil
}
// enable rosetta
err := l.Run("sudo", "sh", "-c", `stat /proc/sys/fs/binfmt_misc/rosetta || echo ':rosetta:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x3e\x00:\xff\xff\xff\xff\xff\xfe\xfe\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/mnt/lima-rosetta/rosetta:OCF' > /proc/sys/fs/binfmt_misc/register`)
if err != nil {
logrus.Warn(fmt.Errorf("unable to enable rosetta: %w", err))
return nil
}
// disable qemu
if err := l.RunQuiet("stat", "/proc/sys/fs/binfmt_misc/qemu-x86_64"); err == nil {
err = l.Run("sudo", "sh", "-c", `echo 0 > /proc/sys/fs/binfmt_misc/qemu-x86_64`)
if err != nil {
logrus.Warn(fmt.Errorf("unable to disable qemu x86_84 emulation: %w", err))
}
}
return nil
})
// replicate addresses when network address is disabled
a.Add(func() error {
if err := l.replicateHostAddresses(conf); err != nil {
logrus.Warnln(fmt.Errorf("unable to assign host IP addresses to the VM: %w", err))
}
return nil
})
// preserve state
a.Add(func() error {
if err := configmanager.SaveToFile(conf, config.CurrentProfile().StateFile()); err != nil {
logrus.Warnln(fmt.Errorf("error persisting Colima state: %w", err))
}
return nil
})
}