-
Notifications
You must be signed in to change notification settings - Fork 2
/
qmp.go
1665 lines (1445 loc) · 51.6 KB
/
qmp.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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
// Copyright contributors to the Virtual Machine Manager for Go project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
package qcli
import (
"bufio"
"container/list"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"strconv"
"syscall"
"time"
"context"
"strings"
)
// QMPLog is a logging interface used by the qemu package to log various
// interesting pieces of information. Rather than introduce a dependency
// on a given logging package, qemu presents this interface that allows
// clients to provide their own logging type which they can use to
// seamlessly integrate qemu's logs into their own logs. A QMPLog
// implementation can be specified in the QMPConfig structure.
type QMPLog interface {
// V returns true if the given argument is less than or equal
// to the implementation's defined verbosity level.
V(int32) bool
// Infof writes informational output to the log. A newline will be
// added to the output if one is not provided.
Infof(string, ...interface{})
// Warningf writes warning output to the log. A newline will be
// added to the output if one is not provided.
Warningf(string, ...interface{})
// Errorf writes error output to the log. A newline will be
// added to the output if one is not provided.
Errorf(string, ...interface{})
}
type qmpNullLogger struct{}
func (l qmpNullLogger) V(level int32) bool {
return false
}
func (l qmpNullLogger) Infof(format string, v ...interface{}) {
}
func (l qmpNullLogger) Warningf(format string, v ...interface{}) {
}
func (l qmpNullLogger) Errorf(format string, v ...interface{}) {
}
// QMPConfig is a configuration structure that can be used to specify a
// logger and a channel to which logs and QMP events are to be sent. If
// neither of these fields are specified, or are set to nil, no logs will be
// written and no QMP events will be reported to the client.
type QMPConfig struct {
// eventCh can be specified by clients who wish to receive QMP
// events.
EventCh chan<- QMPEvent
// logger is used by the qmpStart function and all the go routines
// it spawns to log information.
Logger QMPLog
// specify the capacity of buffer used by receive QMP response.
MaxCapacity int
}
type qmpEventFilter struct {
eventName string
dataKey string
dataValue string
}
// QMPEvent contains a single QMP event, sent on the QMPConfig.EventCh channel.
type QMPEvent struct {
// The name of the event, e.g., DEVICE_DELETED
Name string
// The data associated with the event. The contents of this map are
// unprocessed by the qemu package. It is simply the result of
// unmarshalling the QMP json event. Here's an example map
// map[string]interface{}{
// "driver": "virtio-blk-pci",
// "drive": "drive_3437843748734873483",
// }
Data map[string]interface{}
// The event's timestamp converted to a time.Time object.
Timestamp time.Time
}
type qmpResult struct {
response interface{}
err error
}
type qmpCommand struct {
ctx context.Context
res chan qmpResult
name string
args map[string]interface{}
filter *qmpEventFilter
resultReceived bool
oob []byte
}
// QMP is a structure that contains the internal state used by startQMPLoop and
// the go routines it spwans. All the contents of this structure are private.
type QMP struct {
cmdCh chan qmpCommand
conn io.ReadWriteCloser
cfg QMPConfig
connectedCh chan<- *QMPVersion
disconnectedCh chan struct{}
version *QMPVersion
}
// QMPVersion contains the version number and the capabailities of a QEMU
// instance, as reported in the QMP greeting message.
type QMPVersion struct {
Major int
Minor int
Micro int
Capabilities []string
}
// CPUProperties contains the properties of a CPU instance
type CPUProperties struct {
Node int `json:"node-id"`
Socket int `json:"socket-id"`
Die int `json:"die-id"`
Core int `json:"core-id"`
Thread int `json:"thread-id"`
}
// HotpluggableCPU represents a hotpluggable CPU
type HotpluggableCPU struct {
Type string `json:"type"`
VcpusCount int `json:"vcpus-count"`
Properties CPUProperties `json:"props"`
QOMPath string `json:"qom-path"`
}
// MemoryDevicesData cotains the data describes a memory device
type MemoryDevicesData struct {
Slot int `json:"slot"`
Node int `json:"node"`
Addr uint64 `json:"addr"`
Memdev string `json:"memdev"`
ID string `json:"id"`
Hotpluggable bool `json:"hotpluggable"`
Hotplugged bool `json:"hotplugged"`
Size uint64 `json:"size"`
}
// MemoryDevices represents memory devices of vm
type MemoryDevices struct {
Data MemoryDevicesData `json:"data"`
Type string `json:"type"`
}
// CPUInfo represents information about each virtual CPU
type CPUInfo struct {
CPU int `json:"CPU"`
Current bool `json:"current"`
Halted bool `json:"halted"`
QomPath string `json:"qom_path"`
Arch string `json:"arch"`
Pc int `json:"pc"`
ThreadID int `json:"thread_id"`
Props CPUProperties `json:"props"`
}
// CPUInfoFast represents information about each virtual CPU
type CPUInfoFast struct {
CPUIndex int `json:"cpu-index"`
QomPath string `json:"qom-path"`
Arch string `json:"arch"`
ThreadID int `json:"thread-id"`
Target string `json:"target"`
Props CPUProperties `json:"props"`
}
// MigrationRAM represents migration ram status
type MigrationRAM struct {
Total int64 `json:"total"`
Remaining int64 `json:"remaining"`
Transferred int64 `json:"transferred"`
TotalTime int64 `json:"total-time"`
SetupTime int64 `json:"setup-time"`
ExpectedDowntime int64 `json:"expected-downtime"`
Duplicate int64 `json:"duplicate"`
Normal int64 `json:"normal"`
NormalBytes int64 `json:"normal-bytes"`
DirtySyncCount int64 `json:"dirty-sync-count"`
}
// MigrationDisk represents migration disk status
type MigrationDisk struct {
Total int64 `json:"total"`
Remaining int64 `json:"remaining"`
Transferred int64 `json:"transferred"`
}
// MigrationXbzrleCache represents migration XbzrleCache status
type MigrationXbzrleCache struct {
CacheSize int64 `json:"cache-size"`
Bytes int64 `json:"bytes"`
Pages int64 `json:"pages"`
CacheMiss int64 `json:"cache-miss"`
CacheMissRate int64 `json:"cache-miss-rate"`
Overflow int64 `json:"overflow"`
}
// MigrationStatus represents migration status of a vm
type MigrationStatus struct {
Status string `json:"status"`
Capabilities []map[string]interface{} `json:"capabilities,omitempty"`
RAM MigrationRAM `json:"ram,omitempty"`
Disk MigrationDisk `json:"disk,omitempty"`
XbzrleCache MigrationXbzrleCache `json:"xbzrle-cache,omitempty"`
}
// SchemaInfo represents all QMP wire ABI
type SchemaInfo struct {
MetaType string `json:"meta-type"`
Name string `json:"name"`
}
// StatusInfo represents guest running status
type StatusInfo struct {
Running bool `json:"running"`
SingleStep bool `json:"singlestep"`
Status string `json:"status"`
}
func (q *QMP) readLoop(fromVMCh chan<- []byte) {
scanner := bufio.NewScanner(q.conn)
if q.cfg.MaxCapacity > 0 {
buffer := make([]byte, q.cfg.MaxCapacity)
scanner.Buffer(buffer, q.cfg.MaxCapacity)
}
for scanner.Scan() {
line := scanner.Bytes()
// Since []byte channel type transfer slice info(include slice underlying array pointer, len, cap)
// between channel sender and receiver. scanner.Bytes() returned slice's underlying array
// may point to data that will be overwritten by a subsequent call to Scan(reference from:
// https://golang.org/pkg/bufio/#Scanner.Bytes), which may make receiver read mixed data,
// so we need to copy line to new allocated space and then send to channel receiver
sendLine := make([]byte, len(line))
copy(sendLine, line)
fromVMCh <- sendLine
}
// FIXME: resolve ErrNoProgress message
// q.cfg.Logger.Infof("scanner return error: %v", scanner.Err())
close(fromVMCh)
}
func (q *QMP) processQMPEvent(cmdQueue *list.List, name interface{}, data interface{},
timestamp interface{}) {
strname, ok := name.(string)
if !ok {
return
}
var eventData map[string]interface{}
if data != nil {
eventData, _ = data.(map[string]interface{})
}
cmdEl := cmdQueue.Front()
if cmdEl != nil {
cmd := cmdEl.Value.(*qmpCommand)
filter := cmd.filter
if filter != nil {
if filter.eventName == strname {
match := filter.dataKey == ""
if !match && eventData != nil {
match = eventData[filter.dataKey] == filter.dataValue
}
if match {
if cmd.resultReceived {
q.finaliseCommand(cmdEl, cmdQueue, true)
} else {
cmd.filter = nil
}
}
}
}
}
if q.cfg.EventCh != nil {
ev := QMPEvent{
Name: strname,
Data: eventData,
}
if timestamp != nil {
timestamp, ok := timestamp.(map[string]interface{})
if ok {
seconds, _ := timestamp["seconds"].(float64)
microseconds, _ := timestamp["microseconds"].(float64)
ev.Timestamp = time.Unix(int64(seconds), int64(microseconds))
}
}
q.cfg.EventCh <- ev
}
}
func (q *QMP) finaliseCommandWithResponse(cmdEl *list.Element, cmdQueue *list.List, succeeded bool, response interface{}) {
cmd := cmdEl.Value.(*qmpCommand)
cmdQueue.Remove(cmdEl)
select {
case <-cmd.ctx.Done():
default:
if succeeded {
cmd.res <- qmpResult{response: response}
} else {
cmd.res <- qmpResult{err: fmt.Errorf("QMP command failed: %v", response)}
}
}
if cmdQueue.Len() > 0 {
q.writeNextQMPCommand(cmdQueue)
}
}
func (q *QMP) finaliseCommand(cmdEl *list.Element, cmdQueue *list.List, succeeded bool) {
q.finaliseCommandWithResponse(cmdEl, cmdQueue, succeeded, nil)
}
func (q *QMP) errorDesc(errorData interface{}) (string, error) {
// convert error to json
data, err := json.Marshal(errorData)
if err != nil {
return "", fmt.Errorf("unable to extract error information: %v", err)
}
// see: https://github.com/qemu/qemu/blob/stable-2.12/qapi/qmp-dispatch.c#L125
var qmpErr map[string]string
// convert json to qmpError
if err = json.Unmarshal(data, &qmpErr); err != nil {
return "", fmt.Errorf("unable to convert json to qmpError: %v", err)
}
return qmpErr["desc"], nil
}
func (q *QMP) processQMPInput(line []byte, cmdQueue *list.List) {
var vmData map[string]interface{}
err := json.Unmarshal(line, &vmData)
if err != nil {
q.cfg.Logger.Warningf("Unable to decode response [%s] from VM: %v",
string(line), err)
return
}
if evname, found := vmData["event"]; found {
q.processQMPEvent(cmdQueue, evname, vmData["data"], vmData["timestamp"])
return
}
response, succeeded := vmData["return"]
errData, failed := vmData["error"]
if !succeeded && !failed {
return
}
cmdEl := cmdQueue.Front()
if cmdEl == nil {
q.cfg.Logger.Warningf("Unexpected command response received [%s] from VM",
string(line))
return
}
cmd := cmdEl.Value.(*qmpCommand)
if failed || cmd.filter == nil {
if errData != nil {
desc, err := q.errorDesc(errData)
if err != nil {
q.cfg.Logger.Infof("Get error description failed: %v", err)
} else {
response = desc
}
}
q.finaliseCommandWithResponse(cmdEl, cmdQueue, succeeded, response)
} else {
cmd.resultReceived = true
}
}
func currentCommandDoneCh(cmdQueue *list.List) <-chan struct{} {
cmdEl := cmdQueue.Front()
if cmdEl == nil {
return nil
}
cmd := cmdEl.Value.(*qmpCommand)
return cmd.ctx.Done()
}
func (q *QMP) writeNextQMPCommand(cmdQueue *list.List) {
cmdEl := cmdQueue.Front()
cmd := cmdEl.Value.(*qmpCommand)
cmdData := make(map[string]interface{})
cmdData["execute"] = cmd.name
if cmd.args != nil {
cmdData["arguments"] = cmd.args
}
encodedCmd, err := json.Marshal(&cmdData)
if err != nil {
cmd.res <- qmpResult{
err: fmt.Errorf("unable to marhsall command %s: %v",
cmd.name, err),
}
cmdQueue.Remove(cmdEl)
}
encodedCmd = append(encodedCmd, '\n')
if unixConn, ok := q.conn.(*net.UnixConn); ok && len(cmd.oob) > 0 {
_, _, err = unixConn.WriteMsgUnix(encodedCmd, cmd.oob, nil)
} else {
_, err = q.conn.Write(encodedCmd)
}
if err != nil {
cmd.res <- qmpResult{
err: fmt.Errorf("unable to write command to qmp socket %v", err),
}
cmdQueue.Remove(cmdEl)
}
}
func failOutstandingCommands(cmdQueue *list.List) {
for e := cmdQueue.Front(); e != nil; e = e.Next() {
cmd := e.Value.(*qmpCommand)
select {
case cmd.res <- qmpResult{
err: errors.New("exitting QMP loop, command cancelled"),
}:
case <-cmd.ctx.Done():
}
}
}
func (q *QMP) cancelCurrentCommand(cmdQueue *list.List) {
cmdEl := cmdQueue.Front()
cmd := cmdEl.Value.(*qmpCommand)
if cmd.resultReceived {
q.finaliseCommand(cmdEl, cmdQueue, false)
} else {
cmd.filter = nil
}
}
func (q *QMP) parseVersion(version []byte) *QMPVersion {
var qmp map[string]interface{}
err := json.Unmarshal(version, &qmp)
if err != nil {
q.cfg.Logger.Errorf("Invalid QMP greeting: %s", string(version))
return nil
}
versionMap := qmp
for _, k := range []string{"QMP", "version", "qemu"} {
versionMap, _ = versionMap[k].(map[string]interface{})
if versionMap == nil {
return nil
}
}
micro, _ := versionMap["micro"].(float64)
minor, _ := versionMap["minor"].(float64)
major, _ := versionMap["major"].(float64)
capabilities, _ := qmp["QMP"].(map[string]interface{})["capabilities"].([]interface{})
stringcaps := make([]string, 0, len(capabilities))
for _, c := range capabilities {
if cap, ok := c.(string); ok {
stringcaps = append(stringcaps, cap)
}
}
return &QMPVersion{Major: int(major),
Minor: int(minor),
Micro: int(micro),
Capabilities: stringcaps,
}
}
// The qemu package allows multiple QMP commands to be submitted concurrently
// from different Go routines. Unfortunately, QMP doesn't really support parallel
// commands as there is no way reliable way to associate a command response
// with a request. For this reason we need to submit our commands to
// QMP serially. The qemu package performs this serialisation using a
// queue (cmdQueue owned by mainLoop). We use a queue rather than a simple
// mutex so we can support cancelling of commands (see below) and ordered
// execution of commands, i.e., if command B is issued before command C,
// it should be executed before command C even if both commands are initially
// blocked waiting for command A to finish. This would be hard to achieve with
// a simple mutex.
//
// Cancelling is a little tricky. Commands such as ExecuteQMPCapabilities
// can be cancelled by cancelling or timing out their contexts. When a
// command is cancelled the calling function, e.g., ExecuteQMPCapabilities,
// will return but we may not be able to remove the command's entry from
// the command queue or issue the next command. There are two scenarios
// here.
//
// 1. The command has been processed by QMP, i.e., we have received a
// return or an error, but is still blocking as it is waiting for
// an event. For example, the ExecuteDeviceDel blocks until a DEVICE_DELETED
// event is received. When such a command is cancelled we can remove it
// from the queue and start issuing the next command. When the DEVICE_DELETED
// event eventually arrives it will just be ignored.
//
// 2. The command has not been processed by QMP. In this case the command
// needs to remain on the cmdQueue until the response to this command is
// received from QMP. During this time no new commands can be issued. When the
// response is received, it is discarded (as no one is interested in the result
// any more), the entry is removed from the cmdQueue and we can proceed to
// execute the next command.
func (q *QMP) mainLoop() {
cmdQueue := list.New().Init()
fromVMCh := make(chan []byte)
go q.readLoop(fromVMCh)
defer func() {
if q.cfg.EventCh != nil {
close(q.cfg.EventCh)
}
/* #nosec */
_ = q.conn.Close()
<-fromVMCh
failOutstandingCommands(cmdQueue)
close(q.disconnectedCh)
}()
var cmdDoneCh <-chan struct{}
var version *QMPVersion
ready := false
for {
select {
case cmd, ok := <-q.cmdCh:
if !ok {
return
}
_ = cmdQueue.PushBack(&cmd)
// We only want to execute the new cmd if QMP is
// ready and there are no other commands pending.
// If there are commands pending our new command
// will get run when the pending commands complete.
if ready && cmdQueue.Len() == 1 {
q.writeNextQMPCommand(cmdQueue)
cmdDoneCh = currentCommandDoneCh(cmdQueue)
}
case line, ok := <-fromVMCh:
if !ok {
return
}
if !ready {
// Not ready yet. Check if line is the QMP version.
// Sometimes QMP events are thrown before the QMP version,
// hence it's not a guarantee that the first data read from
// the channel is the QMP version.
version = q.parseVersion(line)
if version != nil {
q.connectedCh <- version
ready = true
}
// Do not process QMP input to avoid deadlocks.
break
}
q.processQMPInput(line, cmdQueue)
cmdDoneCh = currentCommandDoneCh(cmdQueue)
case <-cmdDoneCh:
q.cancelCurrentCommand(cmdQueue)
cmdDoneCh = currentCommandDoneCh(cmdQueue)
}
}
}
func startQMPLoop(conn io.ReadWriteCloser, cfg QMPConfig,
connectedCh chan<- *QMPVersion, disconnectedCh chan struct{}) *QMP {
q := &QMP{
cmdCh: make(chan qmpCommand),
conn: conn,
cfg: cfg,
connectedCh: connectedCh,
disconnectedCh: disconnectedCh,
}
go q.mainLoop()
return q
}
func (q *QMP) executeCommandWithResponse(ctx context.Context, name string, args map[string]interface{},
oob []byte, filter *qmpEventFilter) (interface{}, error) {
var err error
var response interface{}
resCh := make(chan qmpResult)
select {
case <-q.disconnectedCh:
err = errors.New("exitting QMP loop, command cancelled")
case q.cmdCh <- qmpCommand{
ctx: ctx,
res: resCh,
name: name,
args: args,
filter: filter,
oob: oob,
}:
}
if err != nil {
return response, err
}
select {
case res := <-resCh:
err = res.err
response = res.response
case <-ctx.Done():
err = ctx.Err()
}
return response, err
}
func (q *QMP) executeCommand(ctx context.Context, name string, args map[string]interface{},
filter *qmpEventFilter) error {
_, err := q.executeCommandWithResponse(ctx, name, args, nil, filter)
return err
}
// QMPStart connects to a unix domain socket maintained by a QMP instance. It
// waits to receive the QMP welcome message via the socket and spawns some go
// routines to manage the socket. The function returns a *QMP which can be
// used by callers to send commands to the QEMU instance or to close the
// socket and all the go routines that have been spawned to monitor it. A
// *QMPVersion is also returned. This structure contains the version and
// capabilities information returned by the QEMU instance in its welcome
// message.
//
// socket contains the path to the domain socket. cfg contains some options
// that can be specified by the caller, namely where the qemu package should
// send logs and QMP events. disconnectedCh is a channel that must be supplied
// by the caller. It is closed when an error occurs openning or writing to
// or reading from the unix domain socket. This implies that the QEMU instance
// that opened the socket has closed.
//
// If this function returns without error, callers should call QMP.Shutdown
// when they wish to stop monitoring the QMP instance. This is not strictly
// necessary if the QEMU instance exits and the disconnectedCh is closed, but
// doing so will not cause any problems.
//
// Commands can be sent to the QEMU instance via the QMP.Execute methods.
// These commands are executed serially, even if the QMP.Execute methods
// are called from different go routines. The QMP.Execute methods will
// block until they have received a success or failure message from QMP,
// i.e., {"return": {}} or {"error":{}}, and in some cases certain events
// are received.
//
// QEMU currently requires that the "qmp_capabilties" command is sent before any
// other command. Therefore you must call qmp.ExecuteQMPCapabilities() before
// you execute any other command.
func QMPStart(ctx context.Context, socket string, cfg QMPConfig, disconnectedCh chan struct{}) (*QMP, *QMPVersion, error) {
if cfg.Logger == nil {
cfg.Logger = qmpNullLogger{}
}
dialer := net.Dialer{Cancel: ctx.Done()}
conn, err := dialer.Dial("unix", socket)
if err != nil {
cfg.Logger.Warningf("Unable to connect to unix socket (%s): %v", socket, err)
close(disconnectedCh)
return nil, nil, err
}
connectedCh := make(chan *QMPVersion)
q := startQMPLoop(conn, cfg, connectedCh, disconnectedCh)
select {
case <-ctx.Done():
q.Shutdown()
<-disconnectedCh
return nil, nil, fmt.Errorf("canceled by caller")
case <-disconnectedCh:
return nil, nil, fmt.Errorf("lost connection to VM")
case q.version = <-connectedCh:
if q.version == nil {
return nil, nil, fmt.Errorf("failed to find QMP version information")
}
}
if q.version.Major < 4 {
return nil, nil, fmt.Errorf("requires qemu version 4.0 or later, this is qemu (%d.%d)", q.version.Major, q.version.Minor)
}
return q, q.version, nil
}
// Shutdown closes the domain socket used to monitor a QEMU instance and
// terminates all the go routines spawned by QMPStart to manage that instance.
// QMP.Shutdown does not shut down the running instance. Calling QMP.Shutdown
// will result in the disconnectedCh channel being closed, indicating that we
// have lost connection to the QMP instance. In this case it does not indicate
// that the instance has quit.
//
// QMP.Shutdown should not be called concurrently with other QMP methods. It
// should not be called twice on the same QMP instance.
//
// Calling QMP.Shutdown after the disconnectedCh channel is closed is permitted but
// will not have any effect.
func (q *QMP) Shutdown() {
close(q.cmdCh)
}
// ExecuteQMPCapabilities executes the qmp_capabilities command on the instance.
func (q *QMP) ExecuteQMPCapabilities(ctx context.Context) error {
return q.executeCommand(ctx, "qmp_capabilities", nil, nil)
}
// ExecuteStop sends the stop command to the instance.
func (q *QMP) ExecuteStop(ctx context.Context) error {
return q.executeCommand(ctx, "stop", nil, nil)
}
// ExecuteCont sends the cont command to the instance.
func (q *QMP) ExecuteCont(ctx context.Context) error {
return q.executeCommand(ctx, "cont", nil, nil)
}
// ExecuteSystemPowerdown sends the system_powerdown command to the instance.
// This function will block until the SHUTDOWN event is received.
func (q *QMP) ExecuteSystemPowerdown(ctx context.Context) error {
filter := &qmpEventFilter{
eventName: "POWERDOWN",
}
return q.executeCommand(ctx, "system_powerdown", nil, filter)
}
// ExecuteQuit sends the quit command to the instance, terminating
// the QMP instance immediately.
func (q *QMP) ExecuteQuit(ctx context.Context) error {
return q.executeCommand(ctx, "quit", nil, nil)
}
func (q *QMP) blockdevAddBaseArgs(driver, device, blockdevID string, ro bool) (map[string]interface{}, map[string]interface{}) {
var args map[string]interface{}
blockdevArgs := map[string]interface{}{
"driver": "raw",
"read-only": ro,
"file": map[string]interface{}{
"driver": driver,
"filename": device,
},
}
blockdevArgs["node-name"] = blockdevID
args = blockdevArgs
return args, blockdevArgs
}
// ExecuteBlockdevAdd sends a blockdev-add to the QEMU instance. device is the
// path of the device to add, e.g., /dev/rdb0, and blockdevID is an identifier
// used to name the device. As this identifier will be passed directly to QMP,
// it must obey QMP's naming rules, e,g., it must start with a letter.
func (q *QMP) ExecuteBlockdevAdd(ctx context.Context, device, blockdevID string, ro bool) error {
args, _ := q.blockdevAddBaseArgs("host_device", device, blockdevID, ro)
return q.executeCommand(ctx, "blockdev-add", args, nil)
}
// ExecuteBlockdevAddWithCache has two more parameters direct and noFlush
// than ExecuteBlockdevAdd.
// They are cache-related options for block devices that are described in
// https://github.com/qemu/qemu/blob/master/qapi/block-core.json.
// direct denotes whether use of O_DIRECT (bypass the host page cache)
// is enabled. noFlush denotes whether flush requests for the device are
// ignored.
func (q *QMP) ExecuteBlockdevAddWithCache(ctx context.Context, device, blockdevID string, direct, noFlush, ro bool) error {
args, blockdevArgs := q.blockdevAddBaseArgs("host_device", device, blockdevID, ro)
blockdevArgs["cache"] = map[string]interface{}{
"direct": direct,
"no-flush": noFlush,
}
return q.executeCommand(ctx, "blockdev-add", args, nil)
}
// ExecuteBlockdevAddWithDriverCache has three one parameter driver
// than ExecuteBlockdevAddWithCache.
// Parameter driver can set the driver of block device.
func (q *QMP) ExecuteBlockdevAddWithDriverCache(ctx context.Context, driver, device, blockdevID string, direct, noFlush, ro bool) error {
args, blockdevArgs := q.blockdevAddBaseArgs(driver, device, blockdevID, ro)
blockdevArgs["cache"] = map[string]interface{}{
"direct": direct,
"no-flush": noFlush,
}
return q.executeCommand(ctx, "blockdev-add", args, nil)
}
// ExecuteDeviceAdd adds the guest portion of a device to a QEMU instance
// using the device_add command. blockdevID should match the blockdevID passed
// to a previous call to ExecuteBlockdevAdd. devID is the id of the device to
// add. Both strings must be valid QMP identifiers. driver is the name of the
// driver,e.g., virtio-blk-pci, and bus is the name of the bus. bus is optional.
// shared denotes if the drive can be shared allowing it to be passed more than once.
// disableModern indicates if virtio version 1.0 should be replaced by the
// former version 0.9, as there is a KVM bug that occurs when using virtio
// 1.0 in nested environments.
func (q *QMP) ExecuteDeviceAdd(ctx context.Context, blockdevID, devID, driver, bus, romfile string, shared, disableModern bool) error {
args := map[string]interface{}{
"id": devID,
"driver": driver,
"drive": blockdevID,
}
var transport VirtioTransport
if transport.isVirtioCCW(nil) {
args["devno"] = bus
} else if bus != "" {
args["bus"] = bus
}
if shared {
args["share-rw"] = "on"
}
if transport.isVirtioPCI(nil) {
args["romfile"] = romfile
if disableModern {
args["disable-modern"] = disableModern
}
}
return q.executeCommand(ctx, "device_add", args, nil)
}
// ExecuteSCSIDeviceAdd adds the guest portion of a block device to a QEMU instance
// using a SCSI driver with the device_add command. blockdevID should match the
// blockdevID passed to a previous call to ExecuteBlockdevAdd. devID is the id of
// the device to add. Both strings must be valid QMP identifiers. driver is the name of the
// scsi driver,e.g., scsi-hd, and bus is the name of a SCSI controller bus.
// scsiID is the SCSI id, lun is logical unit number. scsiID and lun are optional, a negative value
// for scsiID and lun is ignored. shared denotes if the drive can be shared allowing it
// to be passed more than once.
// disableModern indicates if virtio version 1.0 should be replaced by the
// former version 0.9, as there is a KVM bug that occurs when using virtio
// 1.0 in nested environments.
func (q *QMP) ExecuteSCSIDeviceAdd(ctx context.Context, blockdevID, devID, driver, bus, romfile string, scsiID, lun int, shared, disableModern bool) error {
// TBD: Add drivers for scsi passthrough like scsi-generic and scsi-block
drivers := []string{"scsi-hd", "scsi-cd", "scsi-disk"}
isSCSIDriver := false
for _, d := range drivers {
if driver == d {
isSCSIDriver = true
break
}
}
if !isSCSIDriver {
return fmt.Errorf("invalid SCSI driver provided %s", driver)
}
args := map[string]interface{}{
"id": devID,
"driver": driver,
"drive": blockdevID,
"bus": bus,
}
if scsiID >= 0 {
args["scsi-id"] = scsiID
}
if lun >= 0 {
args["lun"] = lun
}
if shared {
args["share-rw"] = "on"
}
return q.executeCommand(ctx, "device_add", args, nil)
}
// ExecuteBlockdevDel deletes a block device by sending blockdev-del
// command. blockdevID is the id of the block device to be deleted.
// Typically, this will match the id passed to ExecuteBlockdevAdd. It
// must be a valid QMP id.
func (q *QMP) ExecuteBlockdevDel(ctx context.Context, blockdevID string) error {
args := map[string]interface{}{}
args["node-name"] = blockdevID
return q.executeCommand(ctx, "blockdev-del", args, nil)
}
// ExecuteChardevDel deletes a char device by sending a chardev-remove command.
// chardevID is the id of the char device to be deleted. Typically, this will
// match the id passed to ExecuteCharDevUnixSocketAdd. It must be a valid QMP id.
func (q *QMP) ExecuteChardevDel(ctx context.Context, chardevID string) error {
args := map[string]interface{}{
"id": chardevID,
}
return q.executeCommand(ctx, "chardev-remove", args, nil)
}
// ExecuteNetdevAdd adds a Net device to a QEMU instance
// using the netdev_add command. netdevID is the id of the device to add.
// Must be valid QMP identifier.
func (q *QMP) ExecuteNetdevAdd(ctx context.Context, netdevType, netdevID, ifname, downscript, script string, queues int) error {
args := map[string]interface{}{
"type": netdevType,
"id": netdevID,
"ifname": ifname,
"downscript": downscript,
"script": script,
}
if queues > 1 {
args["queues"] = queues
}
return q.executeCommand(ctx, "netdev_add", args, nil)
}
// ExecuteNetdevChardevAdd adds a Net device to a QEMU instance
// using the netdev_add command. netdevID is the id of the device to add.
// Must be valid QMP identifier.
func (q *QMP) ExecuteNetdevChardevAdd(ctx context.Context, netdevType, netdevID, chardev string, queues int) error {
args := map[string]interface{}{
"type": netdevType,
"id": netdevID,
"chardev": chardev,
}
if queues > 1 {
args["queues"] = queues
}
return q.executeCommand(ctx, "netdev_add", args, nil)
}
// ExecuteNetdevAddByFds adds a Net device to a QEMU instance
// using the netdev_add command by fds and vhostfds. netdevID is the id of the device to add.
// Must be valid QMP identifier.
func (q *QMP) ExecuteNetdevAddByFds(ctx context.Context, netdevType, netdevID string, fdNames, vhostFdNames []string) error {
fdNameStr := strings.Join(fdNames, ":")
args := map[string]interface{}{
"type": netdevType,
"id": netdevID,
"fds": fdNameStr,
}
if len(vhostFdNames) > 0 {
vhostFdNameStr := strings.Join(vhostFdNames, ":")
args["vhost"] = true
args["vhostfds"] = vhostFdNameStr
}
return q.executeCommand(ctx, "netdev_add", args, nil)
}
// ExecuteNetdevDel deletes a Net device from a QEMU instance
// using the netdev_del command. netdevID is the id of the device to delete.
func (q *QMP) ExecuteNetdevDel(ctx context.Context, netdevID string) error {
args := map[string]interface{}{
"id": netdevID,