Debian Codegraph @

qemu/qmp.go

raw symbols SCIP
1 /*
2 // Copyright contributors to the Virtual Machine Manager for Go project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16
17 package qemu
18
19 import (
20 "bufio"
21 "container/list"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "net"
27 "os"
28 "strconv"
29 "syscall"
30 "time"
31
32 "context"
33 "strings"
34 )
35
36 // QMPLog is a logging interface used by the qemu package to log various
37 // interesting pieces of information. Rather than introduce a dependency
38 // on a given logging package, qemu presents this interface that allows
39 // clients to provide their own logging type which they can use to
40 // seamlessly integrate qemu's logs into their own logs. A QMPLog
41 // implementation can be specified in the QMPConfig structure.
42 type QMPLog interface {
43 // V returns true if the given argument is less than or equal
44 // to the implementation's defined verbosity level.
45 V(int32) bool
46
47 // Infof writes informational output to the log. A newline will be
48 // added to the output if one is not provided.
49 Infof(string, ...interface{})
50
51 // Warningf writes warning output to the log. A newline will be
52 // added to the output if one is not provided.
53 Warningf(string, ...interface{})
54
55 // Errorf writes error output to the log. A newline will be
56 // added to the output if one is not provided.
57 Errorf(string, ...interface{})
58 }
59
60 type qmpNullLogger struct{}
61
62 func (l qmpNullLogger) V(level int32) bool {
63 return false
64 }
65
66 func (l qmpNullLogger) Infof(format string, v ...interface{}) {
67 }
68
69 func (l qmpNullLogger) Warningf(format string, v ...interface{}) {
70 }
71
72 func (l qmpNullLogger) Errorf(format string, v ...interface{}) {
73 }
74
75 // QMPConfig is a configuration structure that can be used to specify a
76 // logger and a channel to which logs and QMP events are to be sent. If
77 // neither of these fields are specified, or are set to nil, no logs will be
78 // written and no QMP events will be reported to the client.
79 type QMPConfig struct {
80 // eventCh can be specified by clients who wish to receive QMP
81 // events.
82 EventCh chan<- QMPEvent
83
84 // logger is used by the qmpStart function and all the go routines
85 // it spawns to log information.
86 Logger QMPLog
87
88 // specify the capacity of buffer used by receive QMP response.
89 MaxCapacity int
90 }
91
92 type qmpEventFilter struct {
93 eventName string
94 dataKey string
95 dataValue string
96 }
97
98 // QMPEvent contains a single QMP event, sent on the QMPConfig.EventCh channel.
99 type QMPEvent struct {
100 // The name of the event, e.g., DEVICE_DELETED
101 Name string
102
103 // The data associated with the event. The contents of this map are
104 // unprocessed by the qemu package. It is simply the result of
105 // unmarshalling the QMP json event. Here's an example map
106 // map[string]interface{}{
107 // "driver": "virtio-blk-pci",
108 // "drive": "drive_3437843748734873483",
109 // }
110 Data map[string]interface{}
111
112 // The event's timestamp converted to a time.Time object.
113 Timestamp time.Time
114 }
115
116 type qmpResult struct {
117 response interface{}
118 err error
119 }
120
121 type qmpCommand struct {
122 ctx context.Context
123 res chan qmpResult
124 name string
125 args map[string]interface{}
126 filter *qmpEventFilter
127 resultReceived bool
128 oob []byte
129 }
130
131 // QMP is a structure that contains the internal state used by startQMPLoop and
132 // the go routines it spwans. All the contents of this structure are private.
133 type QMP struct {
134 cmdCh chan qmpCommand
135 conn io.ReadWriteCloser
136 cfg QMPConfig
137 connectedCh chan<- *QMPVersion
138 disconnectedCh chan struct{}
139 version *QMPVersion
140 }
141
142 // QMPVersion contains the version number and the capabailities of a QEMU
143 // instance, as reported in the QMP greeting message.
144 type QMPVersion struct {
145 Major int
146 Minor int
147 Micro int
148 Capabilities []string
149 }
150
151 // CPUProperties contains the properties of a CPU instance
152 type CPUProperties struct {
153 Node int `json:"node-id"`
154 Socket int `json:"socket-id"`
155 Die int `json:"die-id"`
156 Core int `json:"core-id"`
157 Thread int `json:"thread-id"`
158 }
159
160 // HotpluggableCPU represents a hotpluggable CPU
161 type HotpluggableCPU struct {
162 Type string `json:"type"`
163 VcpusCount int `json:"vcpus-count"`
164 Properties CPUProperties `json:"props"`
165 QOMPath string `json:"qom-path"`
166 }
167
168 // MemoryDevicesData cotains the data describes a memory device
169 type MemoryDevicesData struct {
170 Slot int `json:"slot"`
171 Node int `json:"node"`
172 Addr uint64 `json:"addr"`
173 Memdev string `json:"memdev"`
174 ID string `json:"id"`
175 Hotpluggable bool `json:"hotpluggable"`
176 Hotplugged bool `json:"hotplugged"`
177 Size uint64 `json:"size"`
178 }
179
180 // MemoryDevices represents memory devices of vm
181 type MemoryDevices struct {
182 Data MemoryDevicesData `json:"data"`
183 Type string `json:"type"`
184 }
185
186 // CPUInfo represents information about each virtual CPU
187 type CPUInfo struct {
188 CPU int `json:"CPU"`
189 Current bool `json:"current"`
190 Halted bool `json:"halted"`
191 QomPath string `json:"qom_path"`
192 Arch string `json:"arch"`
193 Pc int `json:"pc"`
194 ThreadID int `json:"thread_id"`
195 Props CPUProperties `json:"props"`
196 }
197
198 // CPUInfoFast represents information about each virtual CPU
199 type CPUInfoFast struct {
200 CPUIndex int `json:"cpu-index"`
201 QomPath string `json:"qom-path"`
202 Arch string `json:"arch"`
203 ThreadID int `json:"thread-id"`
204 Target string `json:"target"`
205 Props CPUProperties `json:"props"`
206 }
207
208 // MigrationRAM represents migration ram status
209 type MigrationRAM struct {
210 Total int64 `json:"total"`
211 Remaining int64 `json:"remaining"`
212 Transferred int64 `json:"transferred"`
213 TotalTime int64 `json:"total-time"`
214 SetupTime int64 `json:"setup-time"`
215 ExpectedDowntime int64 `json:"expected-downtime"`
216 Duplicate int64 `json:"duplicate"`
217 Normal int64 `json:"normal"`
218 NormalBytes int64 `json:"normal-bytes"`
219 DirtySyncCount int64 `json:"dirty-sync-count"`
220 }
221
222 // MigrationDisk represents migration disk status
223 type MigrationDisk struct {
224 Total int64 `json:"total"`
225 Remaining int64 `json:"remaining"`
226 Transferred int64 `json:"transferred"`
227 }
228
229 // MigrationXbzrleCache represents migration XbzrleCache status
230 type MigrationXbzrleCache struct {
231 CacheSize int64 `json:"cache-size"`
232 Bytes int64 `json:"bytes"`
233 Pages int64 `json:"pages"`
234 CacheMiss int64 `json:"cache-miss"`
235 CacheMissRate int64 `json:"cache-miss-rate"`
236 Overflow int64 `json:"overflow"`
237 }
238
239 // MigrationStatus represents migration status of a vm
240 type MigrationStatus struct {
241 Status string `json:"status"`
242 Capabilities []map[string]interface{} `json:"capabilities,omitempty"`
243 RAM MigrationRAM `json:"ram,omitempty"`
244 Disk MigrationDisk `json:"disk,omitempty"`
245 XbzrleCache MigrationXbzrleCache `json:"xbzrle-cache,omitempty"`
246 }
247
248 // SchemaInfo represents all QMP wire ABI
249 type SchemaInfo struct {
250 MetaType string `json:"meta-type"`
251 Name string `json:"name"`
252 }
253
254 // StatusInfo represents guest running status
255 type StatusInfo struct {
256 Running bool `json:"running"`
257 SingleStep bool `json:"singlestep"`
258 Status string `json:"status"`
259 }
260
261 func (q *QMP) readLoop(fromVMCh chan<- []byte) {
262 scanner := bufio.NewScanner(q.conn)
263 if q.cfg.MaxCapacity > 0 {
264 buffer := make([]byte, q.cfg.MaxCapacity)
265 scanner.Buffer(buffer, q.cfg.MaxCapacity)
266 }
267
268 for scanner.Scan() {
269 line := scanner.Bytes()
270 // Since []byte channel type transfer slice info(include slice underlying array pointer, len, cap)
271 // between channel sender and receiver. scanner.Bytes() returned slice's underlying array
272 // may point to data that will be overwritten by a subsequent call to Scan(reference from:
273 // https://golang.org/pkg/bufio/#Scanner.Bytes), which may make receiver read mixed data,
274 // so we need to copy line to new allocated space and then send to channel receiver
275 sendLine := make([]byte, len(line))
276 copy(sendLine, line)
277
278 fromVMCh <- sendLine
279 }
280 q.cfg.Logger.Infof("scanner return error: %v", scanner.Err())
281 close(fromVMCh)
282 }
283
284 func (q *QMP) processQMPEvent(cmdQueue *list.List, name interface{}, data interface{},
285 timestamp interface{}) {
286
287 strname, ok := name.(string)
288 if !ok {
289 return
290 }
291
292 var eventData map[string]interface{}
293 if data != nil {
294 eventData, _ = data.(map[string]interface{})
295 }
296
297 cmdEl := cmdQueue.Front()
298 if cmdEl != nil {
299 cmd := cmdEl.Value.(*qmpCommand)
300 filter := cmd.filter
301 if filter != nil {
302 if filter.eventName == strname {
303 match := filter.dataKey == ""
304 if !match && eventData != nil {
305 match = eventData[filter.dataKey] == filter.dataValue
306 }
307 if match {
308 if cmd.resultReceived {
309 q.finaliseCommand(cmdEl, cmdQueue, true)
310 } else {
311 cmd.filter = nil
312 }
313 }
314 }
315 }
316 }
317
318 if q.cfg.EventCh != nil {
319 ev := QMPEvent{
320 Name: strname,
321 Data: eventData,
322 }
323 if timestamp != nil {
324 timestamp, ok := timestamp.(map[string]interface{})
325 if ok {
326 seconds, _ := timestamp["seconds"].(float64)
327 microseconds, _ := timestamp["microseconds"].(float64)
328 ev.Timestamp = time.Unix(int64(seconds), int64(microseconds))
329 }
330 }
331
332 q.cfg.EventCh <- ev
333 }
334 }
335
336 func (q *QMP) finaliseCommandWithResponse(cmdEl *list.Element, cmdQueue *list.List, succeeded bool, response interface{}) {
337 cmd := cmdEl.Value.(*qmpCommand)
338 cmdQueue.Remove(cmdEl)
339 select {
340 case <-cmd.ctx.Done():
341 default:
342 if succeeded {
343 cmd.res <- qmpResult{response: response}
344 } else {
345 cmd.res <- qmpResult{err: fmt.Errorf("QMP command failed: %v", response)}
346 }
347 }
348 if cmdQueue.Len() > 0 {
349 q.writeNextQMPCommand(cmdQueue)
350 }
351 }
352
353 func (q *QMP) finaliseCommand(cmdEl *list.Element, cmdQueue *list.List, succeeded bool) {
354 q.finaliseCommandWithResponse(cmdEl, cmdQueue, succeeded, nil)
355 }
356
357 func (q *QMP) errorDesc(errorData interface{}) (string, error) {
358 // convert error to json
359 data, err := json.Marshal(errorData)
360 if err != nil {
361 return "", fmt.Errorf("unable to extract error information: %v", err)
362 }
363
364 // see: https://github.com/qemu/qemu/blob/stable-2.12/qapi/qmp-dispatch.c#L125
365 var qmpErr map[string]string
366 // convert json to qmpError
367 if err = json.Unmarshal(data, &qmpErr); err != nil {
368 return "", fmt.Errorf("unable to convert json to qmpError: %v", err)
369 }
370
371 return qmpErr["desc"], nil
372 }
373
374 func (q *QMP) processQMPInput(line []byte, cmdQueue *list.List) {
375 var vmData map[string]interface{}
376 err := json.Unmarshal(line, &vmData)
377 if err != nil {
378 q.cfg.Logger.Warningf("Unable to decode response [%s] from VM: %v",
379 string(line), err)
380 return
381 }
382 if evname, found := vmData["event"]; found {
383 q.processQMPEvent(cmdQueue, evname, vmData["data"], vmData["timestamp"])
384 return
385 }
386
387 response, succeeded := vmData["return"]
388 errData, failed := vmData["error"]
389
390 if !succeeded && !failed {
391 return
392 }
393
394 cmdEl := cmdQueue.Front()
395 if cmdEl == nil {
396 q.cfg.Logger.Warningf("Unexpected command response received [%s] from VM",
397 string(line))
398 return
399 }
400 cmd := cmdEl.Value.(*qmpCommand)
401 if failed || cmd.filter == nil {
402 if errData != nil {
403 desc, err := q.errorDesc(errData)
404 if err != nil {
405 q.cfg.Logger.Infof("Get error description failed: %v", err)
406 } else {
407 response = desc
408 }
409 }
410 q.finaliseCommandWithResponse(cmdEl, cmdQueue, succeeded, response)
411 } else {
412 cmd.resultReceived = true
413 }
414 }
415
416 func currentCommandDoneCh(cmdQueue *list.List) <-chan struct{} {
417 cmdEl := cmdQueue.Front()
418 if cmdEl == nil {
419 return nil
420 }
421 cmd := cmdEl.Value.(*qmpCommand)
422 return cmd.ctx.Done()
423 }
424
425 func (q *QMP) writeNextQMPCommand(cmdQueue *list.List) {
426 cmdEl := cmdQueue.Front()
427 cmd := cmdEl.Value.(*qmpCommand)
428 cmdData := make(map[string]interface{})
429 cmdData["execute"] = cmd.name
430 if cmd.args != nil {
431 cmdData["arguments"] = cmd.args
432 }
433 encodedCmd, err := json.Marshal(&cmdData)
434 if err != nil {
435 cmd.res <- qmpResult{
436 err: fmt.Errorf("unable to marhsall command %s: %v",
437 cmd.name, err),
438 }
439 cmdQueue.Remove(cmdEl)
440 }
441 encodedCmd = append(encodedCmd, '\n')
442 if unixConn, ok := q.conn.(*net.UnixConn); ok && len(cmd.oob) > 0 {
443 _, _, err = unixConn.WriteMsgUnix(encodedCmd, cmd.oob, nil)
444 } else {
445 _, err = q.conn.Write(encodedCmd)
446 }
447
448 if err != nil {
449 cmd.res <- qmpResult{
450 err: fmt.Errorf("unable to write command to qmp socket %v", err),
451 }
452 cmdQueue.Remove(cmdEl)
453 }
454 }
455
456 func failOutstandingCommands(cmdQueue *list.List) {
457 for e := cmdQueue.Front(); e != nil; e = e.Next() {
458 cmd := e.Value.(*qmpCommand)
459 select {
460 case cmd.res <- qmpResult{
461 err: errors.New("exitting QMP loop, command cancelled"),
462 }:
463 case <-cmd.ctx.Done():
464 }
465 }
466 }
467
468 func (q *QMP) cancelCurrentCommand(cmdQueue *list.List) {
469 cmdEl := cmdQueue.Front()
470 cmd := cmdEl.Value.(*qmpCommand)
471 if cmd.resultReceived {
472 q.finaliseCommand(cmdEl, cmdQueue, false)
473 } else {
474 cmd.filter = nil
475 }
476 }
477
478 func (q *QMP) parseVersion(version []byte) *QMPVersion {
479 var qmp map[string]interface{}
480 err := json.Unmarshal(version, &qmp)
481 if err != nil {
482 q.cfg.Logger.Errorf("Invalid QMP greeting: %s", string(version))
483 return nil
484 }
485
486 versionMap := qmp
487 for _, k := range []string{"QMP", "version", "qemu"} {
488 versionMap, _ = versionMap[k].(map[string]interface{})
489 if versionMap == nil {
490 return nil
491 }
492 }
493
494 micro, _ := versionMap["micro"].(float64)
495 minor, _ := versionMap["minor"].(float64)
496 major, _ := versionMap["major"].(float64)
497 capabilities, _ := qmp["QMP"].(map[string]interface{})["capabilities"].([]interface{})
498 stringcaps := make([]string, 0, len(capabilities))
499 for _, c := range capabilities {
500 if cap, ok := c.(string); ok {
501 stringcaps = append(stringcaps, cap)
502 }
503 }
504 return &QMPVersion{Major: int(major),
505 Minor: int(minor),
506 Micro: int(micro),
507 Capabilities: stringcaps,
508 }
509 }
510
511 // The qemu package allows multiple QMP commands to be submitted concurrently
512 // from different Go routines. Unfortunately, QMP doesn't really support parallel
513 // commands as there is no way reliable way to associate a command response
514 // with a request. For this reason we need to submit our commands to
515 // QMP serially. The qemu package performs this serialisation using a
516 // queue (cmdQueue owned by mainLoop). We use a queue rather than a simple
517 // mutex so we can support cancelling of commands (see below) and ordered
518 // execution of commands, i.e., if command B is issued before command C,
519 // it should be executed before command C even if both commands are initially
520 // blocked waiting for command A to finish. This would be hard to achieve with
521 // a simple mutex.
522 //
523 // Cancelling is a little tricky. Commands such as ExecuteQMPCapabilities
524 // can be cancelled by cancelling or timing out their contexts. When a
525 // command is cancelled the calling function, e.g., ExecuteQMPCapabilities,
526 // will return but we may not be able to remove the command's entry from
527 // the command queue or issue the next command. There are two scenarios
528 // here.
529 //
530 // 1. The command has been processed by QMP, i.e., we have received a
531 // return or an error, but is still blocking as it is waiting for
532 // an event. For example, the ExecuteDeviceDel blocks until a DEVICE_DELETED
533 // event is received. When such a command is cancelled we can remove it
534 // from the queue and start issuing the next command. When the DEVICE_DELETED
535 // event eventually arrives it will just be ignored.
536 //
537 // 2. The command has not been processed by QMP. In this case the command
538 // needs to remain on the cmdQueue until the response to this command is
539 // received from QMP. During this time no new commands can be issued. When the
540 // response is received, it is discarded (as no one is interested in the result
541 // any more), the entry is removed from the cmdQueue and we can proceed to
542 // execute the next command.
543
544 func (q *QMP) mainLoop() {
545 cmdQueue := list.New().Init()
546 fromVMCh := make(chan []byte)
547 go q.readLoop(fromVMCh)
548
549 defer func() {
550 if q.cfg.EventCh != nil {
551 close(q.cfg.EventCh)
552 }
553 /* #nosec */
554 _ = q.conn.Close()
555 <-fromVMCh
556 failOutstandingCommands(cmdQueue)
557 close(q.disconnectedCh)
558 }()
559
560 var cmdDoneCh <-chan struct{}
561 var version *QMPVersion
562 ready := false
563
564 for {
565 select {
566 case cmd, ok := <-q.cmdCh:
567 if !ok {
568 return
569 }
570 _ = cmdQueue.PushBack(&cmd)
571
572 // We only want to execute the new cmd if QMP is
573 // ready and there are no other commands pending.
574 // If there are commands pending our new command
575 // will get run when the pending commands complete.
576 if ready && cmdQueue.Len() == 1 {
577 q.writeNextQMPCommand(cmdQueue)
578 cmdDoneCh = currentCommandDoneCh(cmdQueue)
579 }
580
581 case line, ok := <-fromVMCh:
582 if !ok {
583 return
584 }
585
586 if !ready {
587 // Not ready yet. Check if line is the QMP version.
588 // Sometimes QMP events are thrown before the QMP version,
589 // hence it's not a guarantee that the first data read from
590 // the channel is the QMP version.
591 version = q.parseVersion(line)
592 if version != nil {
593 q.connectedCh <- version
594 ready = true
595 }
596 // Do not process QMP input to avoid deadlocks.
597 break
598 }
599
600 q.processQMPInput(line, cmdQueue)
601 cmdDoneCh = currentCommandDoneCh(cmdQueue)
602
603 case <-cmdDoneCh:
604 q.cancelCurrentCommand(cmdQueue)
605 cmdDoneCh = currentCommandDoneCh(cmdQueue)
606 }
607 }
608 }
609
610 func startQMPLoop(conn io.ReadWriteCloser, cfg QMPConfig,
611 connectedCh chan<- *QMPVersion, disconnectedCh chan struct{}) *QMP {
612 q := &QMP{
613 cmdCh: make(chan qmpCommand),
614 conn: conn,
615 cfg: cfg,
616 connectedCh: connectedCh,
617 disconnectedCh: disconnectedCh,
618 }
619 go q.mainLoop()
620 return q
621 }
622
623 func (q *QMP) executeCommandWithResponse(ctx context.Context, name string, args map[string]interface{},
624 oob []byte, filter *qmpEventFilter) (interface{}, error) {
625 var err error
626 var response interface{}
627 resCh := make(chan qmpResult)
628 select {
629 case <-q.disconnectedCh:
630 err = errors.New("exitting QMP loop, command cancelled")
631 case q.cmdCh <- qmpCommand{
632 ctx: ctx,
633 res: resCh,
634 name: name,
635 args: args,
636 filter: filter,
637 oob: oob,
638 }:
639 }
640
641 if err != nil {
642 return response, err
643 }
644
645 select {
646 case res := <-resCh:
647 err = res.err
648 response = res.response
649 case <-ctx.Done():
650 err = ctx.Err()
651 }
652
653 return response, err
654 }
655
656 func (q *QMP) executeCommand(ctx context.Context, name string, args map[string]interface{},
657 filter *qmpEventFilter) error {
658
659 _, err := q.executeCommandWithResponse(ctx, name, args, nil, filter)
660 return err
661 }
662
663 // QMPStart connects to a unix domain socket maintained by a QMP instance. It
664 // waits to receive the QMP welcome message via the socket and spawns some go
665 // routines to manage the socket. The function returns a *QMP which can be
666 // used by callers to send commands to the QEMU instance or to close the
667 // socket and all the go routines that have been spawned to monitor it. A
668 // *QMPVersion is also returned. This structure contains the version and
669 // capabilities information returned by the QEMU instance in its welcome
670 // message.
671 //
672 // socket contains the path to the domain socket. cfg contains some options
673 // that can be specified by the caller, namely where the qemu package should
674 // send logs and QMP events. disconnectedCh is a channel that must be supplied
675 // by the caller. It is closed when an error occurs openning or writing to
676 // or reading from the unix domain socket. This implies that the QEMU instance
677 // that opened the socket has closed.
678 //
679 // If this function returns without error, callers should call QMP.Shutdown
680 // when they wish to stop monitoring the QMP instance. This is not strictly
681 // necessary if the QEMU instance exits and the disconnectedCh is closed, but
682 // doing so will not cause any problems.
683 //
684 // Commands can be sent to the QEMU instance via the QMP.Execute methods.
685 // These commands are executed serially, even if the QMP.Execute methods
686 // are called from different go routines. The QMP.Execute methods will
687 // block until they have received a success or failure message from QMP,
688 // i.e., {"return": {}} or {"error":{}}, and in some cases certain events
689 // are received.
690 //
691 // QEMU currently requires that the "qmp_capabilties" command is sent before any
692 // other command. Therefore you must call qmp.ExecuteQMPCapabilities() before
693 // you execute any other command.
694 func QMPStart(ctx context.Context, socket string, cfg QMPConfig, disconnectedCh chan struct{}) (*QMP, *QMPVersion, error) {
695 if cfg.Logger == nil {
696 cfg.Logger = qmpNullLogger{}
697 }
698 dialer := net.Dialer{Cancel: ctx.Done()}
699 conn, err := dialer.Dial("unix", socket)
700 if err != nil {
701 cfg.Logger.Warningf("Unable to connect to unix socket (%s): %v", socket, err)
702 close(disconnectedCh)
703 return nil, nil, err
704 }
705
706 connectedCh := make(chan *QMPVersion)
707
708 q := startQMPLoop(conn, cfg, connectedCh, disconnectedCh)
709 select {
710 case <-ctx.Done():
711 q.Shutdown()
712 <-disconnectedCh
713 return nil, nil, fmt.Errorf("canceled by caller")
714 case <-disconnectedCh:
715 return nil, nil, fmt.Errorf("lost connection to VM")
716 case q.version = <-connectedCh:
717 if q.version == nil {
718 return nil, nil, fmt.Errorf("failed to find QMP version information")
719 }
720 }
721
722 if q.version.Major < 5 {
723 return nil, nil, fmt.Errorf("govmm requires qemu version 5.0 or later, this is qemu (%d.%d)", q.version.Major, q.version.Minor)
724 }
725
726 return q, q.version, nil
727 }
728
729 // Shutdown closes the domain socket used to monitor a QEMU instance and
730 // terminates all the go routines spawned by QMPStart to manage that instance.
731 // QMP.Shutdown does not shut down the running instance. Calling QMP.Shutdown
732 // will result in the disconnectedCh channel being closed, indicating that we
733 // have lost connection to the QMP instance. In this case it does not indicate
734 // that the instance has quit.
735 //
736 // QMP.Shutdown should not be called concurrently with other QMP methods. It
737 // should not be called twice on the same QMP instance.
738 //
739 // Calling QMP.Shutdown after the disconnectedCh channel is closed is permitted but
740 // will not have any effect.
741 func (q *QMP) Shutdown() {
742 close(q.cmdCh)
743 }
744
745 // ExecuteQMPCapabilities executes the qmp_capabilities command on the instance.
746 func (q *QMP) ExecuteQMPCapabilities(ctx context.Context) error {
747 return q.executeCommand(ctx, "qmp_capabilities", nil, nil)
748 }
749
750 // ExecuteStop sends the stop command to the instance.
751 func (q *QMP) ExecuteStop(ctx context.Context) error {
752 return q.executeCommand(ctx, "stop", nil, nil)
753 }
754
755 // ExecuteCont sends the cont command to the instance.
756 func (q *QMP) ExecuteCont(ctx context.Context) error {
757 return q.executeCommand(ctx, "cont", nil, nil)
758 }
759
760 // ExecuteSystemPowerdown sends the system_powerdown command to the instance.
761 // This function will block until the SHUTDOWN event is received.
762 func (q *QMP) ExecuteSystemPowerdown(ctx context.Context) error {
763 filter := &qmpEventFilter{
764 eventName: "POWERDOWN",
765 }
766 return q.executeCommand(ctx, "system_powerdown", nil, filter)
767 }
768
769 // ExecuteQuit sends the quit command to the instance, terminating
770 // the QMP instance immediately.
771 func (q *QMP) ExecuteQuit(ctx context.Context) error {
772 return q.executeCommand(ctx, "quit", nil, nil)
773 }
774
775 func (q *QMP) blockdevAddBaseArgs(driver, device, blockdevID string, ro bool) (map[string]interface{}, map[string]interface{}) {
776 var args map[string]interface{}
777
778 blockdevArgs := map[string]interface{}{
779 "driver": "raw",
780 "read-only": ro,
781 "file": map[string]interface{}{
782 "driver": driver,
783 "filename": device,
784 },
785 }
786
787 blockdevArgs["node-name"] = blockdevID
788 args = blockdevArgs
789
790 return args, blockdevArgs
791 }
792
793 // ExecuteBlockdevAdd sends a blockdev-add to the QEMU instance. device is the
794 // path of the device to add, e.g., /dev/rdb0, and blockdevID is an identifier
795 // used to name the device. As this identifier will be passed directly to QMP,
796 // it must obey QMP's naming rules, e,g., it must start with a letter.
797 func (q *QMP) ExecuteBlockdevAdd(ctx context.Context, device, blockdevID string, ro bool) error {
798 args, _ := q.blockdevAddBaseArgs("host_device", device, blockdevID, ro)
799
800 return q.executeCommand(ctx, "blockdev-add", args, nil)
801 }
802
803 // ExecuteBlockdevAddWithCache has two more parameters direct and noFlush
804 // than ExecuteBlockdevAdd.
805 // They are cache-related options for block devices that are described in
806 // https://github.com/qemu/qemu/blob/master/qapi/block-core.json.
807 // direct denotes whether use of O_DIRECT (bypass the host page cache)
808 // is enabled. noFlush denotes whether flush requests for the device are
809 // ignored.
810 func (q *QMP) ExecuteBlockdevAddWithCache(ctx context.Context, device, blockdevID string, direct, noFlush, ro bool) error {
811 args, blockdevArgs := q.blockdevAddBaseArgs("host_device", device, blockdevID, ro)
812
813 blockdevArgs["cache"] = map[string]interface{}{
814 "direct": direct,
815 "no-flush": noFlush,
816 }
817
818 return q.executeCommand(ctx, "blockdev-add", args, nil)
819 }
820
821 // ExecuteBlockdevAddWithDriverCache has three one parameter driver
822 // than ExecuteBlockdevAddWithCache.
823 // Parameter driver can set the driver of block device.
824 func (q *QMP) ExecuteBlockdevAddWithDriverCache(ctx context.Context, driver, device, blockdevID string, direct, noFlush, ro bool) error {
825 args, blockdevArgs := q.blockdevAddBaseArgs(driver, device, blockdevID, ro)
826
827 blockdevArgs["cache"] = map[string]interface{}{
828 "direct": direct,
829 "no-flush": noFlush,
830 }
831
832 return q.executeCommand(ctx, "blockdev-add", args, nil)
833 }
834
835 // ExecuteDeviceAdd adds the guest portion of a device to a QEMU instance
836 // using the device_add command. blockdevID should match the blockdevID passed
837 // to a previous call to ExecuteBlockdevAdd. devID is the id of the device to
838 // add. Both strings must be valid QMP identifiers. driver is the name of the
839 // driver,e.g., virtio-blk-pci, and bus is the name of the bus. bus is optional.
840 // shared denotes if the drive can be shared allowing it to be passed more than once.
841 // disableModern indicates if virtio version 1.0 should be replaced by the
842 // former version 0.9, as there is a KVM bug that occurs when using virtio
843 // 1.0 in nested environments.
844 func (q *QMP) ExecuteDeviceAdd(ctx context.Context, blockdevID, devID, driver, bus, romfile string, shared, disableModern bool) error {
845 args := map[string]interface{}{
846 "id": devID,
847 "driver": driver,
848 "drive": blockdevID,
849 }
850
851 var transport VirtioTransport
852
853 if transport.isVirtioCCW(nil) {
854 args["devno"] = bus
855 } else if bus != "" {
856 args["bus"] = bus
857 }
858
859 if shared {
860 args["share-rw"] = "on"
861 }
862 if transport.isVirtioPCI(nil) {
863 args["romfile"] = romfile
864
865 if disableModern {
866 args["disable-modern"] = disableModern
867 }
868 }
869
870 return q.executeCommand(ctx, "device_add", args, nil)
871 }
872
873 // ExecuteSCSIDeviceAdd adds the guest portion of a block device to a QEMU instance
874 // using a SCSI driver with the device_add command. blockdevID should match the
875 // blockdevID passed to a previous call to ExecuteBlockdevAdd. devID is the id of
876 // the device to add. Both strings must be valid QMP identifiers. driver is the name of the
877 // scsi driver,e.g., scsi-hd, and bus is the name of a SCSI controller bus.
878 // scsiID is the SCSI id, lun is logical unit number. scsiID and lun are optional, a negative value
879 // for scsiID and lun is ignored. shared denotes if the drive can be shared allowing it
880 // to be passed more than once.
881 // disableModern indicates if virtio version 1.0 should be replaced by the
882 // former version 0.9, as there is a KVM bug that occurs when using virtio
883 // 1.0 in nested environments.
884 func (q *QMP) ExecuteSCSIDeviceAdd(ctx context.Context, blockdevID, devID, driver, bus, romfile string, scsiID, lun int, shared, disableModern bool) error {
885 // TBD: Add drivers for scsi passthrough like scsi-generic and scsi-block
886 drivers := []string{"scsi-hd", "scsi-cd", "scsi-disk"}
887
888 isSCSIDriver := false
889 for _, d := range drivers {
890 if driver == d {
891 isSCSIDriver = true
892 break
893 }
894 }
895
896 if !isSCSIDriver {
897 return fmt.Errorf("invalid SCSI driver provided %s", driver)
898 }
899
900 args := map[string]interface{}{
901 "id": devID,
902 "driver": driver,
903 "drive": blockdevID,
904 "bus": bus,
905 }
906
907 if scsiID >= 0 {
908 args["scsi-id"] = scsiID
909 }
910 if lun >= 0 {
911 args["lun"] = lun
912 }
913 if shared {
914 args["share-rw"] = "on"
915 }
916
917 return q.executeCommand(ctx, "device_add", args, nil)
918 }
919
920 // ExecuteBlockdevDel deletes a block device by sending blockdev-del
921 // command. blockdevID is the id of the block device to be deleted.
922 // Typically, this will match the id passed to ExecuteBlockdevAdd. It
923 // must be a valid QMP id.
924 func (q *QMP) ExecuteBlockdevDel(ctx context.Context, blockdevID string) error {
925 args := map[string]interface{}{}
926
927 args["node-name"] = blockdevID
928 return q.executeCommand(ctx, "blockdev-del", args, nil)
929 }
930
931 // ExecuteChardevDel deletes a char device by sending a chardev-remove command.
932 // chardevID is the id of the char device to be deleted. Typically, this will
933 // match the id passed to ExecuteCharDevUnixSocketAdd. It must be a valid QMP id.
934 func (q *QMP) ExecuteChardevDel(ctx context.Context, chardevID string) error {
935 args := map[string]interface{}{
936 "id": chardevID,
937 }
938
939 return q.executeCommand(ctx, "chardev-remove", args, nil)
940 }
941
942 // ExecuteNetdevAdd adds a Net device to a QEMU instance
943 // using the netdev_add command. netdevID is the id of the device to add.
944 // Must be valid QMP identifier.
945 func (q *QMP) ExecuteNetdevAdd(ctx context.Context, netdevType, netdevID, ifname, downscript, script string, queues int) error {
946 args := map[string]interface{}{
947 "type": netdevType,
948 "id": netdevID,
949 "ifname": ifname,
950 "downscript": downscript,
951 "script": script,
952 }
953 if queues > 1 {
954 args["queues"] = queues
955 }
956
957 return q.executeCommand(ctx, "netdev_add", args, nil)
958 }
959
960 // ExecuteNetdevChardevAdd adds a Net device to a QEMU instance
961 // using the netdev_add command. netdevID is the id of the device to add.
962 // Must be valid QMP identifier.
963 func (q *QMP) ExecuteNetdevChardevAdd(ctx context.Context, netdevType, netdevID, chardev string, queues int) error {
964 args := map[string]interface{}{
965 "type": netdevType,
966 "id": netdevID,
967 "chardev": chardev,
968 }
969 if queues > 1 {
970 args["queues"] = queues
971 }
972
973 return q.executeCommand(ctx, "netdev_add", args, nil)
974 }
975
976 // ExecuteNetdevAddByFds adds a Net device to a QEMU instance
977 // using the netdev_add command by fds and vhostfds. netdevID is the id of the device to add.
978 // Must be valid QMP identifier.
979 func (q *QMP) ExecuteNetdevAddByFds(ctx context.Context, netdevType, netdevID string, fdNames, vhostFdNames []string) error {
980 fdNameStr := strings.Join(fdNames, ":")
981 args := map[string]interface{}{
982 "type": netdevType,
983 "id": netdevID,
984 "fds": fdNameStr,
985 }
986 if len(vhostFdNames) > 0 {
987 vhostFdNameStr := strings.Join(vhostFdNames, ":")
988 args["vhost"] = true
989 args["vhostfds"] = vhostFdNameStr
990 }
991
992 return q.executeCommand(ctx, "netdev_add", args, nil)
993 }
994
995 // ExecuteNetdevDel deletes a Net device from a QEMU instance
996 // using the netdev_del command. netdevID is the id of the device to delete.
997 func (q *QMP) ExecuteNetdevDel(ctx context.Context, netdevID string) error {
998 args := map[string]interface{}{
999 "id": netdevID,
1000 }
1001 return q.executeCommand(ctx, "netdev_del", args, nil)
1002 }
1003
1004 // ExecuteNetPCIDeviceAdd adds a Net PCI device to a QEMU instance
1005 // using the device_add command. devID is the id of the device to add.
1006 // Must be valid QMP identifier. netdevID is the id of nic added by previous netdev_add.
1007 // queues is the number of queues of a nic.
1008 // disableModern indicates if virtio version 1.0 should be replaced by the
1009 // former version 0.9, as there is a KVM bug that occurs when using virtio
1010 // 1.0 in nested environments.
1011 func (q *QMP) ExecuteNetPCIDeviceAdd(ctx context.Context, netdevID, devID, macAddr, addr, bus, romfile string, queues int, disableModern bool) error {
1012 args := map[string]interface{}{
1013 "id": devID,
1014 "driver": VirtioNetPCI,
1015 "romfile": romfile,
1016 }
1017
1018 if bus != "" {
1019 args["bus"] = bus
1020 }
1021 if addr != "" {
1022 args["addr"] = addr
1023 }
1024 if macAddr != "" {
1025 args["mac"] = macAddr
1026 }
1027 if netdevID != "" {
1028 args["netdev"] = netdevID
1029 }
1030 if disableModern {
1031 args["disable-modern"] = disableModern
1032 }
1033
1034 if queues > 0 {
1035 // (2N+2 vectors, N for tx queues, N for rx queues, 1 for config, and one for possible control vq)
1036 // -device virtio-net-pci,mq=on,vectors=2N+2...
1037 // enable mq in guest by 'ethtool -L eth0 combined $queue_num'
1038 // Clearlinux automatically sets up the queues properly
1039 // The agent implementation should do this to ensure that it is
1040 // always set
1041 args["mq"] = "on"
1042 args["vectors"] = 2*queues + 2
1043 }
1044
1045 return q.executeCommand(ctx, "device_add", args, nil)
1046 }
1047
1048 // ExecuteNetCCWDeviceAdd adds a Net CCW device to a QEMU instance
1049 // using the device_add command. devID is the id of the device to add.
1050 // Must be valid QMP identifier. netdevID is the id of nic added by previous netdev_add.
1051 // queues is the number of queues of a nic.
1052 func (q *QMP) ExecuteNetCCWDeviceAdd(ctx context.Context, netdevID, devID, macAddr, bus string, queues int) error {
1053 args := map[string]interface{}{
1054 "id": devID,
1055 "driver": VirtioNetCCW,
1056 "netdev": netdevID,
1057 "mac": macAddr,
1058 "devno": bus,
1059 }
1060
1061 if queues > 0 {
1062 args["mq"] = "on"
1063 }
1064
1065 return q.executeCommand(ctx, "device_add", args, nil)
1066 }
1067
1068 // ExecuteDeviceDel deletes guest portion of a QEMU device by sending a
1069 // device_del command. devId is the identifier of the device to delete.
1070 // Typically it would match the devID parameter passed to an earlier call
1071 // to ExecuteDeviceAdd. It must be a valid QMP identidier.
1072 //
1073 // This method blocks until a DEVICE_DELETED event is received for devID.
1074 func (q *QMP) ExecuteDeviceDel(ctx context.Context, devID string) error {
1075 args := map[string]interface{}{
1076 "id": devID,
1077 }
1078 filter := &qmpEventFilter{
1079 eventName: "DEVICE_DELETED",
1080 dataKey: "device",
1081 dataValue: devID,
1082 }
1083 return q.executeCommand(ctx, "device_del", args, filter)
1084 }
1085
1086 // ExecutePCIDeviceAdd is the PCI version of ExecuteDeviceAdd. This function can be used
1087 // to hot plug PCI devices on PCI(E) bridges, unlike ExecuteDeviceAdd this function receive the
1088 // device address on its parent bus. bus is optional. queues specifies the number of queues of
1089 // a block device. shared denotes if the drive can be shared allowing it to be passed more than once.
1090 // disableModern indicates if virtio version 1.0 should be replaced by the
1091 // former version 0.9, as there is a KVM bug that occurs when using virtio
1092 // 1.0 in nested environments.
1093 func (q *QMP) ExecutePCIDeviceAdd(ctx context.Context, blockdevID, devID, driver, addr, bus, romfile string, queues int, shared, disableModern bool) error {
1094 args := map[string]interface{}{
1095 "id": devID,
1096 "driver": driver,
1097 "drive": blockdevID,
1098 "addr": addr,
1099 }
1100 if bus != "" {
1101 args["bus"] = bus
1102 }
1103 if shared {
1104 args["share-rw"] = "on"
1105 }
1106 if queues > 0 {
1107 args["num-queues"] = strconv.Itoa(queues)
1108 }
1109
1110 var transport VirtioTransport
1111
1112 if transport.isVirtioPCI(nil) {
1113 args["romfile"] = romfile
1114
1115 if disableModern {
1116 args["disable-modern"] = disableModern
1117 }
1118 }
1119
1120 return q.executeCommand(ctx, "device_add", args, nil)
1121 }
1122
1123 // ExecutePCIVhostUserDevAdd adds a vhost-user device to a QEMU instance using the device_add command.
1124 // This function can be used to hot plug vhost-user devices on PCI(E) bridges.
1125 // It receives the bus and the device address on its parent bus. bus is optional.
1126 // devID is the id of the device to add.Must be valid QMP identifier. chardevID
1127 // is the QMP identifier of character device using a unix socket as backend.
1128 // driver is the name of vhost-user driver, like vhost-user-blk-pci.
1129 func (q *QMP) ExecutePCIVhostUserDevAdd(ctx context.Context, driver, devID, chardevID, addr, bus string) error {
1130 args := map[string]interface{}{
1131 "driver": driver,
1132 "id": devID,
1133 "chardev": chardevID,
1134 "addr": addr,
1135 }
1136
1137 if bus != "" {
1138 args["bus"] = bus
1139 }
1140
1141 return q.executeCommand(ctx, "device_add", args, nil)
1142 }
1143
1144 // ExecuteVFIODeviceAdd adds a VFIO device to a QEMU instance using the device_add command.
1145 // devID is the id of the device to add. Must be valid QMP identifier.
1146 // bdf is the PCI bus-device-function of the pci device.
1147 // bus is optional. When hot plugging a PCIe device, the bus can be the ID of the pcie-root-port.
1148 func (q *QMP) ExecuteVFIODeviceAdd(ctx context.Context, devID, bdf, bus, romfile string) error {
1149 var driver string
1150 var transport VirtioTransport
1151
1152 if transport.isVirtioCCW(nil) {
1153 driver = string(VfioCCW)
1154 } else {
1155 driver = string(VfioPCI)
1156 }
1157
1158 args := map[string]interface{}{
1159 "id": devID,
1160 "driver": driver,
1161 "host": bdf,
1162 "romfile": romfile,
1163 }
1164 if bus != "" {
1165 args["bus"] = bus
1166 }
1167 return q.executeCommand(ctx, "device_add", args, nil)
1168 }
1169
1170 // ExecutePCIVFIODeviceAdd adds a VFIO device to a QEMU instance using the device_add command.
1171 // This function can be used to hot plug VFIO devices on PCI(E) bridges, unlike
1172 // ExecuteVFIODeviceAdd this function receives the bus and the device address on its parent bus.
1173 // bus is optional. devID is the id of the device to add.Must be valid QMP identifier. bdf is the
1174 // PCI bus-device-function of the pci device.
1175 func (q *QMP) ExecutePCIVFIODeviceAdd(ctx context.Context, devID, bdf, addr, bus, romfile string) error {
1176 args := map[string]interface{}{
1177 "id": devID,
1178 "driver": VfioPCI,
1179 "host": bdf,
1180 "addr": addr,
1181 "romfile": romfile,
1182 }
1183
1184 if bus != "" {
1185 args["bus"] = bus
1186 }
1187 return q.executeCommand(ctx, "device_add", args, nil)
1188 }
1189
1190 // ExecutePCIVFIOMediatedDeviceAdd adds a VFIO mediated device to a QEMU instance using the device_add command.
1191 // This function can be used to hot plug VFIO mediated devices on PCI(E) bridges or root bus, unlike
1192 // ExecuteVFIODeviceAdd this function receives the bus and the device address on its parent bus.
1193 // devID is the id of the device to add. Must be valid QMP identifier. sysfsdev is the VFIO mediated device.
1194 // Both bus and addr are optional. If they are both set to be empty, the system will pick up an empty slot on root bus.
1195 func (q *QMP) ExecutePCIVFIOMediatedDeviceAdd(ctx context.Context, devID, sysfsdev, addr, bus, romfile string) error {
1196 args := map[string]interface{}{
1197 "id": devID,
1198 "driver": VfioPCI,
1199 "sysfsdev": sysfsdev,
1200 "romfile": romfile,
1201 }
1202
1203 if bus != "" {
1204 args["bus"] = bus
1205 }
1206 if addr != "" {
1207 args["addr"] = addr
1208 }
1209 return q.executeCommand(ctx, "device_add", args, nil)
1210 }
1211
1212 // ExecuteAPVFIOMediatedDeviceAdd adds a VFIO mediated AP device to a QEMU instance using the device_add command.
1213 func (q *QMP) ExecuteAPVFIOMediatedDeviceAdd(ctx context.Context, sysfsdev string) error {
1214 args := map[string]interface{}{
1215 "driver": VfioAP,
1216 "sysfsdev": sysfsdev,
1217 }
1218 return q.executeCommand(ctx, "device_add", args, nil)
1219 }
1220
1221 // isSocketIDSupported returns if the cpu driver supports the socket id option
1222 func isSocketIDSupported(driver string) bool {
1223 if driver == "host-s390x-cpu" || driver == "host-powerpc64-cpu" {
1224 return false
1225 }
1226 return true
1227 }
1228
1229 // isThreadIDSupported returns if the cpu driver supports the thread id option
1230 func isThreadIDSupported(driver string) bool {
1231 if driver == "host-s390x-cpu" || driver == "host-powerpc64-cpu" {
1232 return false
1233 }
1234 return true
1235 }
1236
1237 // isDieIDSupported returns if the cpu driver and the qemu version support the die id option
1238 func (q *QMP) isDieIDSupported(driver string) bool {
1239 return driver == "host-x86_64-cpu"
1240 }
1241
1242 // ExecuteCPUDeviceAdd adds a CPU to a QEMU instance using the device_add command.
1243 // driver is the CPU model, cpuID must be a unique ID to identify the CPU, socketID is the socket number within
1244 // node/board the CPU belongs to, coreID is the core number within socket the CPU belongs to, threadID is the
1245 // thread number within core the CPU belongs to. Note that socketID and threadID are not a requirement for
1246 // architecures like ppc64le.
1247 func (q *QMP) ExecuteCPUDeviceAdd(ctx context.Context, driver, cpuID, socketID, dieID, coreID, threadID, romfile string) error {
1248 args := map[string]interface{}{
1249 "driver": driver,
1250 "id": cpuID,
1251 "core-id": coreID,
1252 }
1253
1254 if socketID != "" && isSocketIDSupported(driver) {
1255 args["socket-id"] = socketID
1256 }
1257
1258 if threadID != "" && isThreadIDSupported(driver) {
1259 args["thread-id"] = threadID
1260 }
1261
1262 if q.isDieIDSupported(driver) {
1263 if dieID != "" {
1264 args["die-id"] = dieID
1265 }
1266 }
1267
1268 return q.executeCommand(ctx, "device_add", args, nil)
1269 }
1270
1271 // ExecuteQueryHotpluggableCPUs returns a slice with the list of hotpluggable CPUs
1272 func (q *QMP) ExecuteQueryHotpluggableCPUs(ctx context.Context) ([]HotpluggableCPU, error) {
1273 response, err := q.executeCommandWithResponse(ctx, "query-hotpluggable-cpus", nil, nil, nil)
1274 if err != nil {
1275 return nil, err
1276 }
1277
1278 // convert response to json
1279 data, err := json.Marshal(response)
1280 if err != nil {
1281 return nil, fmt.Errorf("unable to extract CPU information: %v", err)
1282 }
1283
1284 var cpus []HotpluggableCPU
1285 // convert json to []HotpluggableCPU
1286 if err = json.Unmarshal(data, &cpus); err != nil {
1287 return nil, fmt.Errorf("unable to convert json to hotpluggable CPU: %v", err)
1288 }
1289
1290 return cpus, nil
1291 }
1292
1293 // ExecSetMigrationCaps sets migration capabilities
1294 func (q *QMP) ExecSetMigrationCaps(ctx context.Context, caps []map[string]interface{}) error {
1295 args := map[string]interface{}{
1296 "capabilities": caps,
1297 }
1298
1299 return q.executeCommand(ctx, "migrate-set-capabilities", args, nil)
1300 }
1301
1302 // ExecSetMigrateArguments sets the command line used for migration
1303 func (q *QMP) ExecSetMigrateArguments(ctx context.Context, url string) error {
1304 args := map[string]interface{}{
1305 "uri": url,
1306 }
1307
1308 return q.executeCommand(ctx, "migrate", args, nil)
1309 }
1310
1311 // ExecQueryMemoryDevices returns a slice with the list of memory devices
1312 func (q *QMP) ExecQueryMemoryDevices(ctx context.Context) ([]MemoryDevices, error) {
1313 response, err := q.executeCommandWithResponse(ctx, "query-memory-devices", nil, nil, nil)
1314 if err != nil {
1315 return nil, err
1316 }
1317
1318 // convert response to json
1319 data, err := json.Marshal(response)
1320 if err != nil {
1321 return nil, fmt.Errorf("unable to extract memory devices information: %v", err)
1322 }
1323
1324 var memoryDevices []MemoryDevices
1325 // convert json to []MemoryDevices
1326 if err = json.Unmarshal(data, &memoryDevices); err != nil {
1327 return nil, fmt.Errorf("unable to convert json to memory devices: %v", err)
1328 }
1329
1330 return memoryDevices, nil
1331 }
1332
1333 // ExecQueryCpus returns a slice with the list of `CpuInfo`
1334 // Since qemu 2.12, we have `query-cpus-fast` as a better choice in production
1335 // we can still choose `ExecQueryCpus` for compatibility though not recommended.
1336 func (q *QMP) ExecQueryCpus(ctx context.Context) ([]CPUInfo, error) {
1337 response, err := q.executeCommandWithResponse(ctx, "query-cpus", nil, nil, nil)
1338 if err != nil {
1339 return nil, err
1340 }
1341
1342 // convert response to json
1343 data, err := json.Marshal(response)
1344 if err != nil {
1345 return nil, fmt.Errorf("unable to extract memory devices information: %v", err)
1346 }
1347
1348 var cpuInfo []CPUInfo
1349 // convert json to []CPUInfo
1350 if err = json.Unmarshal(data, &cpuInfo); err != nil {
1351 return nil, fmt.Errorf("unable to convert json to CPUInfo: %v", err)
1352 }
1353
1354 return cpuInfo, nil
1355 }
1356
1357 // ExecQueryCpusFast returns a slice with the list of `CpuInfoFast`
1358 // This is introduced since 2.12, it does not incur a performance penalty and
1359 // should be used in production instead of query-cpus.
1360 func (q *QMP) ExecQueryCpusFast(ctx context.Context) ([]CPUInfoFast, error) {
1361 response, err := q.executeCommandWithResponse(ctx, "query-cpus-fast", nil, nil, nil)
1362 if err != nil {
1363 return nil, err
1364 }
1365
1366 // convert response to json
1367 data, err := json.Marshal(response)
1368 if err != nil {
1369 return nil, fmt.Errorf("unable to extract memory devices information: %v", err)
1370 }
1371
1372 var cpuInfoFast []CPUInfoFast
1373 // convert json to []CPUInfoFast
1374 if err = json.Unmarshal(data, &cpuInfoFast); err != nil {
1375 return nil, fmt.Errorf("unable to convert json to CPUInfoFast: %v", err)
1376 }
1377
1378 return cpuInfoFast, nil
1379 }
1380
1381 // ExecMemdevAdd adds size of MiB memory device to the guest
1382 func (q *QMP) ExecMemdevAdd(ctx context.Context, qomtype, id, mempath string, size int, share bool, driver, driverID, addr, bus string) error {
1383 args := map[string]interface{}{
1384 "qom-type": qomtype,
1385 "id": id,
1386 "size": uint64(size) << 20,
1387 }
1388 if mempath != "" {
1389 args["mem-path"] = mempath
1390 }
1391 if share {
1392 args["share"] = true
1393 }
1394 err := q.executeCommand(ctx, "object-add", args, nil)
1395 if err != nil {
1396 return err
1397 }
1398
1399 defer func() {
1400 if err != nil {
1401 q.cfg.Logger.Errorf("Unable to add memory device %s: %v", id, err)
1402 err = q.executeCommand(ctx, "object-del", map[string]interface{}{"id": id}, nil)
1403 if err != nil {
1404 q.cfg.Logger.Warningf("Unable to clean up memory object %s: %v", id, err)
1405 }
1406 }
1407 }()
1408
1409 args = map[string]interface{}{
1410 "driver": driver,
1411 "id": driverID,
1412 "memdev": id,
1413 }
1414
1415 if bus != "" {
1416 args["bus"] = bus
1417 }
1418 if addr != "" {
1419 args["addr"] = addr
1420 }
1421
1422 err = q.executeCommand(ctx, "device_add", args, nil)
1423
1424 return err
1425 }
1426
1427 // ExecHotplugMemory adds size of MiB memory to the guest
1428 func (q *QMP) ExecHotplugMemory(ctx context.Context, qomtype, id, mempath string, size int, share bool) error {
1429 return q.ExecMemdevAdd(ctx, qomtype, id, mempath, size, share, "pc-dimm", "dimm"+id, "", "")
1430 }
1431
1432 // ExecuteNVDIMMDeviceAdd adds a block device to a QEMU instance using
1433 // a NVDIMM driver with the device_add command.
1434 // id is the id of the device to add. It must be a valid QMP identifier.
1435 // mempath is the path of the device to add, e.g., /dev/rdb0. size is
1436 // the data size of the device. pmem is to guarantee the persistence of QEMU writes
1437 // to the vNVDIMM backend.
1438 func (q *QMP) ExecuteNVDIMMDeviceAdd(ctx context.Context, id, mempath string, size int64, pmem *bool) error {
1439 args := map[string]interface{}{
1440 "qom-type": "memory-backend-file",
1441 "id": "nvdimmbackmem" + id,
1442 "mem-path": mempath,
1443 "size": size,
1444 "share": true,
1445 }
1446
1447 if pmem != nil {
1448 args["pmem"] = *pmem
1449 }
1450
1451 err := q.executeCommand(ctx, "object-add", args, nil)
1452 if err != nil {
1453 return err
1454 }
1455
1456 args = map[string]interface{}{
1457 "driver": "nvdimm",
1458 "id": "nvdimm" + id,
1459 "memdev": "nvdimmbackmem" + id,
1460 }
1461 if err = q.executeCommand(ctx, "device_add", args, nil); err != nil {
1462 q.cfg.Logger.Errorf("Unable to hotplug NVDIMM device: %v", err)
1463 err2 := q.executeCommand(ctx, "object-del", map[string]interface{}{"id": "nvdimmbackmem" + id}, nil)
1464 if err2 != nil {
1465 q.cfg.Logger.Warningf("Unable to clean up memory object: %v", err2)
1466 }
1467 }
1468
1469 return err
1470 }
1471
1472 // ExecuteBalloon sets the size of the balloon, hence updates the memory
1473 // allocated for the VM.
1474 func (q *QMP) ExecuteBalloon(ctx context.Context, bytes uint64) error {
1475 args := map[string]interface{}{
1476 "value": bytes,
1477 }
1478 return q.executeCommand(ctx, "balloon", args, nil)
1479 }
1480
1481 // ExecutePCIVSockAdd adds a vhost-vsock-pci bus
1482 // disableModern indicates if virtio version 1.0 should be replaced by the
1483 // former version 0.9, as there is a KVM bug that occurs when using virtio
1484 // 1.0 in nested environments.
1485 func (q *QMP) ExecutePCIVSockAdd(ctx context.Context, id, guestCID, vhostfd, addr, bus, romfile string, disableModern bool) error {
1486 args := map[string]interface{}{
1487 "driver": VHostVSockPCI,
1488 "id": id,
1489 "guest-cid": guestCID,
1490 "vhostfd": vhostfd,
1491 "addr": addr,
1492 "romfile": romfile,
1493 }
1494
1495 if bus != "" {
1496 args["bus"] = bus
1497 }
1498
1499 if disableModern {
1500 args["disable-modern"] = disableModern
1501 }
1502
1503 return q.executeCommand(ctx, "device_add", args, nil)
1504 }
1505
1506 // ExecuteGetFD sends a file descriptor via SCM rights and assigns it a name
1507 func (q *QMP) ExecuteGetFD(ctx context.Context, fdname string, fd *os.File) error {
1508 oob := syscall.UnixRights(int(fd.Fd()))
1509 args := map[string]interface{}{
1510 "fdname": fdname,
1511 }
1512
1513 _, err := q.executeCommandWithResponse(ctx, "getfd", args, oob, nil)
1514 return err
1515 }
1516
1517 // ExecuteCharDevUnixSocketAdd adds a character device using as backend a unix socket,
1518 // id is an identifier for the device, path specifies the local path of the unix socket,
1519 // wait is to block waiting for a client to connect, server specifies that the socket is a listening socket.
1520 func (q *QMP) ExecuteCharDevUnixSocketAdd(ctx context.Context, id, path string, wait, server bool) error {
1521 args := map[string]interface{}{
1522 "id": id,
1523 "backend": map[string]interface{}{
1524 "type": "socket",
1525 "data": map[string]interface{}{
1526 "wait": wait,
1527 "server": server,
1528 "addr": map[string]interface{}{
1529 "type": "unix",
1530 "data": map[string]interface{}{
1531 "path": path,
1532 },
1533 },
1534 },
1535 },
1536 }
1537 return q.executeCommand(ctx, "chardev-add", args, nil)
1538 }
1539
1540 // ExecuteVirtSerialPortAdd adds a virtserialport.
1541 // id is an identifier for the virtserialport, name is a name for the virtserialport and
1542 // it will be visible in the VM, chardev is the character device id previously added.
1543 func (q *QMP) ExecuteVirtSerialPortAdd(ctx context.Context, id, name, chardev string) error {
1544 args := map[string]interface{}{
1545 "driver": VirtioSerialPort,
1546 "id": id,
1547 "name": name,
1548 "chardev": chardev,
1549 }
1550
1551 return q.executeCommand(ctx, "device_add", args, nil)
1552 }
1553
1554 // ExecuteQueryMigration queries migration progress.
1555 func (q *QMP) ExecuteQueryMigration(ctx context.Context) (MigrationStatus, error) {
1556 response, err := q.executeCommandWithResponse(ctx, "query-migrate", nil, nil, nil)
1557 if err != nil {
1558 return MigrationStatus{}, err
1559 }
1560
1561 data, err := json.Marshal(response)
1562 if err != nil {
1563 return MigrationStatus{}, fmt.Errorf("unable to extract migrate status information: %v", err)
1564 }
1565
1566 var status MigrationStatus
1567 if err = json.Unmarshal(data, &status); err != nil {
1568 return MigrationStatus{}, fmt.Errorf("unable to convert migrate status information: %v", err)
1569 }
1570
1571 return status, nil
1572 }
1573
1574 // ExecuteMigrationIncoming start migration from incoming uri.
1575 func (q *QMP) ExecuteMigrationIncoming(ctx context.Context, uri string) error {
1576 args := map[string]interface{}{
1577 "uri": uri,
1578 }
1579 return q.executeCommand(ctx, "migrate-incoming", args, nil)
1580 }
1581
1582 // ExecQueryQmpSchema query all QMP wire ABI and returns a slice
1583 func (q *QMP) ExecQueryQmpSchema(ctx context.Context) ([]SchemaInfo, error) {
1584 response, err := q.executeCommandWithResponse(ctx, "query-qmp-schema", nil, nil, nil)
1585 if err != nil {
1586 return nil, err
1587 }
1588
1589 // convert response to json
1590 data, err := json.Marshal(response)
1591 if err != nil {
1592 return nil, fmt.Errorf("unable to extract memory devices information: %v", err)
1593 }
1594
1595 var schemaInfo []SchemaInfo
1596 if err = json.Unmarshal(data, &schemaInfo); err != nil {
1597 return nil, fmt.Errorf("unable to convert json to schemaInfo: %v", err)
1598 }
1599
1600 return schemaInfo, nil
1601 }
1602
1603 // ExecuteQueryStatus queries guest status
1604 func (q *QMP) ExecuteQueryStatus(ctx context.Context) (StatusInfo, error) {
1605 response, err := q.executeCommandWithResponse(ctx, "query-status", nil, nil, nil)
1606 if err != nil {
1607 return StatusInfo{}, err
1608 }
1609
1610 data, err := json.Marshal(response)
1611 if err != nil {
1612 return StatusInfo{}, fmt.Errorf("unable to extract migrate status information: %v", err)
1613 }
1614
1615 var status StatusInfo
1616 if err = json.Unmarshal(data, &status); err != nil {
1617 return StatusInfo{}, fmt.Errorf("unable to convert migrate status information: %v", err)
1618 }
1619
1620 return status, nil
1621 }
1622
1623 // ExecQomSet qom-set path property value
1624 func (q *QMP) ExecQomSet(ctx context.Context, path, property string, value uint64) error {
1625 args := map[string]interface{}{
1626 "path": path,
1627 "property": property,
1628 "value": value,
1629 }
1630
1631 return q.executeCommand(ctx, "qom-set", args, nil)
1632 }
1633
1634 // ExecQomGet qom-get path property
1635 func (q *QMP) ExecQomGet(ctx context.Context, path, property string) (interface{}, error) {
1636 args := map[string]interface{}{
1637 "path": path,
1638 "property": property,
1639 }
1640
1641 response, err := q.executeCommandWithResponse(ctx, "qom-get", args, nil, nil)
1642 if err != nil {
1643 return "", err
1644 }
1645
1646 return response, nil
1647 }
1648
1649 // ExecuteDumpGuestMemory dump guest memory to host
1650 func (q *QMP) ExecuteDumpGuestMemory(ctx context.Context, protocol string, paging bool, format string) error {
1651 args := map[string]interface{}{
1652 "protocol": protocol,
1653 "paging": paging,
1654 "format": format,
1655 }
1656
1657 return q.executeCommand(ctx, "dump-guest-memory", args, nil)
1658 }