/
qemu_driver.go
457 lines (415 loc) · 11.9 KB
/
qemu_driver.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package qemu
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"text/template"
"time"
"github.com/digitalocean/go-qemu/qmp"
"github.com/digitalocean/go-qemu/qmp/raw"
"github.com/lima-vm/lima/pkg/driver"
"github.com/lima-vm/lima/pkg/limayaml"
"github.com/lima-vm/lima/pkg/networks/usernet"
"github.com/lima-vm/lima/pkg/store"
"github.com/lima-vm/lima/pkg/store/filenames"
"github.com/sirupsen/logrus"
)
type LimaQemuDriver struct {
*driver.BaseDriver
qCmd *exec.Cmd
qWaitCh chan error
vhostCmds []*exec.Cmd
}
func New(driver *driver.BaseDriver) *LimaQemuDriver {
return &LimaQemuDriver{
BaseDriver: driver,
}
}
func (l *LimaQemuDriver) Validate() error {
if *l.Yaml.MountType == limayaml.VIRTIOFS && runtime.GOOS != "linux" {
return fmt.Errorf("field `mountType` must be %q or %q for QEMU driver on non-Linux, got %q",
limayaml.REVSSHFS, limayaml.NINEP, *l.Yaml.MountType)
}
return nil
}
func (l *LimaQemuDriver) CreateDisk(ctx context.Context) error {
qCfg := Config{
Name: l.Instance.Name,
InstanceDir: l.Instance.Dir,
LimaYAML: l.Yaml,
}
return EnsureDisk(ctx, qCfg)
}
func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) {
ctx, cancel := context.WithCancel(ctx)
defer func() {
if l.qCmd == nil {
cancel()
}
}()
qCfg := Config{
Name: l.Instance.Name,
InstanceDir: l.Instance.Dir,
LimaYAML: l.Yaml,
SSHLocalPort: l.SSHLocalPort,
}
qExe, qArgs, err := Cmdline(ctx, qCfg)
if err != nil {
return nil, err
}
var vhostCmds []*exec.Cmd
if *l.Yaml.MountType == limayaml.VIRTIOFS {
vhostExe, err := FindVirtiofsd(qExe)
if err != nil {
return nil, err
}
for i := range l.Yaml.Mounts {
args, err := VirtiofsdCmdline(qCfg, i)
if err != nil {
return nil, err
}
vhostCmds = append(vhostCmds, exec.CommandContext(ctx, vhostExe, args...))
}
}
var qArgsFinal []string
applier := &qArgTemplateApplier{}
for _, unapplied := range qArgs {
applied, err := applier.applyTemplate(unapplied)
if err != nil {
return nil, err
}
qArgsFinal = append(qArgsFinal, applied)
}
qCmd := exec.CommandContext(ctx, qExe, qArgsFinal...)
qCmd.ExtraFiles = append(qCmd.ExtraFiles, applier.files...)
qStdout, err := qCmd.StdoutPipe()
if err != nil {
return nil, err
}
go logPipeRoutine(qStdout, "qemu[stdout]")
qStderr, err := qCmd.StderrPipe()
if err != nil {
return nil, err
}
go logPipeRoutine(qStderr, "qemu[stderr]")
for i, vhostCmd := range vhostCmds {
vhostStdout, err := vhostCmd.StdoutPipe()
if err != nil {
return nil, err
}
go logPipeRoutine(vhostStdout, fmt.Sprintf("virtiofsd-%d[stdout]", i))
vhostStderr, err := vhostCmd.StderrPipe()
if err != nil {
return nil, err
}
go logPipeRoutine(vhostStderr, fmt.Sprintf("virtiofsd-%d[stderr]", i))
}
for i, vhostCmd := range vhostCmds {
i := i
vhostCmd := vhostCmd
logrus.Debugf("vhostCmd[%d].Args: %v", i, vhostCmd.Args)
if err := vhostCmd.Start(); err != nil {
return nil, err
}
vhostWaitCh := make(chan error)
go func() {
vhostWaitCh <- vhostCmd.Wait()
}()
vhostSock := filepath.Join(l.Instance.Dir, fmt.Sprintf(filenames.VhostSock, i))
vhostSockExists := false
for attempt := 0; attempt < 5; attempt++ {
logrus.Debugf("Try waiting for %s to appear (attempt %d)", vhostSock, attempt)
if _, err := os.Stat(vhostSock); err != nil {
if !errors.Is(err, fs.ErrNotExist) {
logrus.Warnf("Failed to check for vhost socket: %v", err)
}
} else {
vhostSockExists = true
break
}
retry := time.NewTimer(200 * time.Millisecond)
select {
case err = <-vhostWaitCh:
return nil, fmt.Errorf("virtiofsd never created vhost socket: %w", err)
case <-retry.C:
}
}
if !vhostSockExists {
return nil, fmt.Errorf("vhost socket %s never appeared", vhostSock)
}
go func() {
if err := <-vhostWaitCh; err != nil {
logrus.Errorf("Error from virtiofsd instance #%d: %v", i, err)
}
}()
}
logrus.Infof("Starting QEMU (hint: to watch the boot progress, see %q)", filepath.Join(qCfg.InstanceDir, "serial*.log"))
logrus.Debugf("qCmd.Args: %v", qCmd.Args)
if err := qCmd.Start(); err != nil {
return nil, err
}
l.qCmd = qCmd
l.qWaitCh = make(chan error)
go func() {
l.qWaitCh <- qCmd.Wait()
}()
l.vhostCmds = vhostCmds
go func() {
if usernetIndex := limayaml.FirstUsernetIndex(l.Yaml); usernetIndex != -1 {
client := usernet.NewClientByName(l.Yaml.Networks[usernetIndex].Lima)
err := client.ConfigureDriver(ctx, l.BaseDriver)
if err != nil {
l.qWaitCh <- err
}
}
}()
return l.qWaitCh, nil
}
func (l *LimaQemuDriver) Stop(ctx context.Context) error {
return l.shutdownQEMU(ctx, 3*time.Minute, l.qCmd, l.qWaitCh)
}
func (l *LimaQemuDriver) ChangeDisplayPassword(_ context.Context, password string) error {
return l.changeVNCPassword(password)
}
func (l *LimaQemuDriver) GetDisplayConnection(_ context.Context) (string, error) {
return l.getVNCDisplayPort()
}
func waitFileExists(path string, timeout time.Duration) error {
startWaiting := time.Now()
for {
_, err := os.Stat(path)
if err == nil {
break
}
if !errors.Is(err, os.ErrNotExist) {
return err
}
if time.Since(startWaiting) > timeout {
return fmt.Errorf("timeout waiting for %s", path)
}
time.Sleep(500 * time.Millisecond)
}
return nil
}
func (l *LimaQemuDriver) changeVNCPassword(password string) error {
qmpSockPath := filepath.Join(l.Instance.Dir, filenames.QMPSock)
err := waitFileExists(qmpSockPath, 30*time.Second)
if err != nil {
return err
}
qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
if err != nil {
return err
}
if err := qmpClient.Connect(); err != nil {
return err
}
defer func() { _ = qmpClient.Disconnect() }()
rawClient := raw.NewMonitor(qmpClient)
err = rawClient.ChangeVNCPassword(password)
if err != nil {
return err
}
return nil
}
func (l *LimaQemuDriver) getVNCDisplayPort() (string, error) {
qmpSockPath := filepath.Join(l.Instance.Dir, filenames.QMPSock)
qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
if err != nil {
return "", err
}
if err := qmpClient.Connect(); err != nil {
return "", err
}
defer func() { _ = qmpClient.Disconnect() }()
rawClient := raw.NewMonitor(qmpClient)
info, err := rawClient.QueryVNC()
if err != nil {
return "", err
}
return *info.Service, nil
}
func (l *LimaQemuDriver) removeVNCFiles() error {
vncfile := filepath.Join(l.Instance.Dir, filenames.VNCDisplayFile)
err := os.RemoveAll(vncfile)
if err != nil {
return err
}
vncpwdfile := filepath.Join(l.Instance.Dir, filenames.VNCPasswordFile)
err = os.RemoveAll(vncpwdfile)
if err != nil {
return err
}
return nil
}
func (l *LimaQemuDriver) killVhosts() error {
var errs []error
for i, vhost := range l.vhostCmds {
if err := vhost.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
errs = append(errs, fmt.Errorf("Failed to kill virtiofsd instance #%d: %w", i, err))
}
}
return errors.Join(errs...)
}
func (l *LimaQemuDriver) shutdownQEMU(ctx context.Context, timeout time.Duration, qCmd *exec.Cmd, qWaitCh <-chan error) error {
logrus.Info("Shutting down QEMU with ACPI")
if usernetIndex := limayaml.FirstUsernetIndex(l.Yaml); usernetIndex != -1 {
client := usernet.NewClientByName(l.Yaml.Networks[usernetIndex].Lima)
err := client.UnExposeSSH(l.SSHLocalPort)
if err != nil {
logrus.Warnf("Failed to remove SSH binding for port %d", l.SSHLocalPort)
}
}
qmpSockPath := filepath.Join(l.Instance.Dir, filenames.QMPSock)
qmpClient, err := qmp.NewSocketMonitor("unix", qmpSockPath, 5*time.Second)
if err != nil {
logrus.WithError(err).Warnf("failed to open the QMP socket %q, forcibly killing QEMU", qmpSockPath)
return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
}
if err := qmpClient.Connect(); err != nil {
logrus.WithError(err).Warnf("failed to connect to the QMP socket %q, forcibly killing QEMU", qmpSockPath)
return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
}
defer func() { _ = qmpClient.Disconnect() }()
rawClient := raw.NewMonitor(qmpClient)
logrus.Info("Sending QMP system_powerdown command")
if err := rawClient.SystemPowerdown(); err != nil {
logrus.WithError(err).Warnf("failed to send system_powerdown command via the QMP socket %q, forcibly killing QEMU", qmpSockPath)
return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
}
deadline := time.After(timeout)
select {
case qWaitErr := <-qWaitCh:
entry := logrus.NewEntry(logrus.StandardLogger())
if qWaitErr != nil {
entry = entry.WithError(qWaitErr)
}
entry.Info("QEMU has exited")
_ = l.removeVNCFiles()
return errors.Join(qWaitErr, l.killVhosts())
case <-deadline:
}
logrus.Warnf("QEMU did not exit in %v, forcibly killing QEMU", timeout)
return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
}
func (l *LimaQemuDriver) killQEMU(_ context.Context, _ time.Duration, qCmd *exec.Cmd, qWaitCh <-chan error) error {
var qWaitErr error
if qCmd.ProcessState == nil {
if killErr := qCmd.Process.Kill(); killErr != nil {
logrus.WithError(killErr).Warn("failed to kill QEMU")
}
qWaitErr = <-qWaitCh
logrus.WithError(qWaitErr).Info("QEMU has exited, after killing forcibly")
} else {
logrus.Info("QEMU has already exited")
}
qemuPIDPath := filepath.Join(l.Instance.Dir, filenames.PIDFile(*l.Yaml.VMType))
_ = os.RemoveAll(qemuPIDPath)
_ = l.removeVNCFiles()
return errors.Join(qWaitErr, l.killVhosts())
}
func logPipeRoutine(r io.Reader, header string) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
logrus.Debugf("%s: %s", header, line)
}
}
func (l *LimaQemuDriver) DeleteSnapshot(_ context.Context, tag string) error {
qCfg := Config{
Name: l.Instance.Name,
InstanceDir: l.Instance.Dir,
LimaYAML: l.Yaml,
}
return Del(qCfg, l.Instance.Status == store.StatusRunning, tag)
}
func (l *LimaQemuDriver) CreateSnapshot(_ context.Context, tag string) error {
qCfg := Config{
Name: l.Instance.Name,
InstanceDir: l.Instance.Dir,
LimaYAML: l.Yaml,
}
return Save(qCfg, l.Instance.Status == store.StatusRunning, tag)
}
func (l *LimaQemuDriver) ApplySnapshot(_ context.Context, tag string) error {
qCfg := Config{
Name: l.Instance.Name,
InstanceDir: l.Instance.Dir,
LimaYAML: l.Yaml,
}
return Load(qCfg, l.Instance.Status == store.StatusRunning, tag)
}
func (l *LimaQemuDriver) ListSnapshots(_ context.Context) (string, error) {
qCfg := Config{
Name: l.Instance.Name,
InstanceDir: l.Instance.Dir,
LimaYAML: l.Yaml,
}
return List(qCfg, l.Instance.Status == store.StatusRunning)
}
func (l *LimaQemuDriver) GuestAgentConn(ctx context.Context) (net.Conn, error) {
var d net.Dialer
dialContext, err := d.DialContext(ctx, "unix", filepath.Join(l.Instance.Dir, filenames.GuestAgentSock))
return dialContext, err
}
type qArgTemplateApplier struct {
files []*os.File
}
func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) {
if !strings.Contains(qArg, "{{") {
return qArg, nil
}
funcMap := template.FuncMap{
"fd_connect": func(v interface{}) string {
fn := func(v interface{}) (string, error) {
s, ok := v.(string)
if !ok {
return "", fmt.Errorf("non-string argument %+v", v)
}
addr := &net.UnixAddr{
Net: "unix",
Name: s,
}
conn, err := net.DialUnix("unix", nil, addr)
if err != nil {
return "", err
}
f, err := conn.File()
if err != nil {
return "", err
}
if err := conn.Close(); err != nil {
return "", err
}
a.files = append(a.files, f)
fd := len(a.files) + 2 // the first FD is 3
return strconv.Itoa(fd), nil
}
res, err := fn(v)
if err != nil {
panic(fmt.Errorf("fd_connect: %w", err))
}
return res
},
}
tmpl, err := template.New("").Funcs(funcMap).Parse(qArg)
if err != nil {
return "", err
}
var b bytes.Buffer
if err := tmpl.Execute(&b, nil); err != nil {
return "", err
}
return b.String(), nil
}