Debian Codegraph @

qemu/qmp_test.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 "bytes"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "log"
25 "os"
26 "reflect"
27 "sync"
28 "testing"
29 "time"
30
31 "context"
32 )
33
34 const (
35 microStr = "50"
36 minorStr = "9"
37 majorStr = "2"
38 micro = 50
39 minor = 9
40 major = 2
41 cap1 = "one"
42 cap2 = "two"
43 qmpHello = `{ "QMP": { "version": { "qemu": { "micro": ` + microStr + `, "minor": ` + minorStr + `, "major": ` + majorStr + ` }, "package": ""}, "capabilities": ["` + cap1 + `","` + cap2 + `"]}}` + "\n"
44 )
45
46 type qmpTestLogger struct{}
47
48 func (l qmpTestLogger) V(level int32) bool {
49 return true
50 }
51
52 func (l qmpTestLogger) Infof(format string, v ...interface{}) {
53 log.Printf(format, v...)
54 }
55
56 func (l qmpTestLogger) Warningf(format string, v ...interface{}) {
57 l.Infof(format, v...)
58 }
59
60 func (l qmpTestLogger) Errorf(format string, v ...interface{}) {
61 l.Infof(format, v...)
62 }
63
64 type qmpTestCommand struct {
65 name string
66 args map[string]interface{}
67 }
68
69 type qmpTestEvent struct {
70 name string
71 data map[string]interface{}
72 timestamp map[string]interface{}
73 after time.Duration
74 }
75
76 type qmpTestResult struct {
77 result string
78 data interface{}
79 }
80
81 type qmpTestCommandBuffer struct {
82 newDataCh chan []byte
83 t *testing.T
84 buf *bytes.Buffer
85 cmds []qmpTestCommand
86 events []qmpTestEvent
87 results []qmpTestResult
88 currentCmd int
89 forceFail chan struct{}
90 }
91
92 func newQMPTestCommandBuffer(t *testing.T) *qmpTestCommandBuffer {
93 b := &qmpTestCommandBuffer{
94 newDataCh: make(chan []byte, 1),
95 t: t,
96 buf: bytes.NewBuffer([]byte{}),
97 forceFail: make(chan struct{}),
98 }
99 b.cmds = make([]qmpTestCommand, 0, 8)
100 b.events = make([]qmpTestEvent, 0, 8)
101 b.results = make([]qmpTestResult, 0, 8)
102 b.newDataCh <- []byte(qmpHello)
103 return b
104 }
105
106 func newQMPTestCommandBufferNoGreeting(t *testing.T) *qmpTestCommandBuffer {
107 b := &qmpTestCommandBuffer{
108 newDataCh: make(chan []byte, 1),
109 t: t,
110 buf: bytes.NewBuffer([]byte{}),
111 forceFail: make(chan struct{}),
112 }
113 b.cmds = make([]qmpTestCommand, 0, 8)
114 b.events = make([]qmpTestEvent, 0, 8)
115 b.results = make([]qmpTestResult, 0, 8)
116 return b
117 }
118
119 func (b *qmpTestCommandBuffer) startEventLoop(wg *sync.WaitGroup) {
120 wg.Add(1)
121 go func() {
122 for _, ev := range b.events {
123 time.Sleep(ev.after)
124 eventMap := map[string]interface{}{
125 "event": ev.name,
126 }
127
128 if ev.data != nil {
129 eventMap["data"] = ev.data
130 }
131
132 if ev.timestamp != nil {
133 eventMap["timestamp"] = ev.timestamp
134 }
135
136 encodedEvent, err := json.Marshal(&eventMap)
137 if err != nil {
138 b.t.Errorf("Unable to encode event: %v", err)
139 }
140 encodedEvent = append(encodedEvent, '\n')
141 b.newDataCh <- encodedEvent
142 }
143 wg.Done()
144 }()
145 }
146
147 func (b *qmpTestCommandBuffer) AddCommand(name string, args map[string]interface{},
148 result string, data interface{}) {
149 b.cmds = append(b.cmds, qmpTestCommand{name, args})
150 b.results = append(b.results, qmpTestResult{result, data})
151 }
152
153 func (b *qmpTestCommandBuffer) AddEvent(name string, after time.Duration,
154 data map[string]interface{}, timestamp map[string]interface{}) {
155 b.events = append(b.events, qmpTestEvent{
156 name: name,
157 data: data,
158 timestamp: timestamp,
159 after: after,
160 })
161 }
162
163 func (b *qmpTestCommandBuffer) Close() error {
164 close(b.newDataCh)
165 return nil
166 }
167
168 func (b *qmpTestCommandBuffer) Read(p []byte) (n int, err error) {
169 if b.buf.Len() == 0 {
170 ok := false
171 var data []byte
172 select {
173 case <-b.forceFail:
174 return 0, errors.New("Connection shutdown")
175 case data, ok = <-b.newDataCh:
176 select {
177 case <-b.forceFail:
178 return 0, errors.New("Connection shutdown")
179 default:
180 }
181 }
182 if !ok {
183 return 0, nil
184 }
185 _, err := b.buf.Write(data)
186 if err != nil {
187 if err != nil {
188 b.t.Errorf("Unable to buffer result: %v", err)
189 }
190 }
191 }
192 return b.buf.Read(p)
193 }
194
195 func (b *qmpTestCommandBuffer) Write(p []byte) (int, error) {
196 var cmdJSON map[string]interface{}
197 currentCmd := b.currentCmd
198 b.currentCmd++
199 if currentCmd >= len(b.cmds) {
200 b.t.Fatalf("Unexpected command")
201 }
202 err := json.Unmarshal(p, &cmdJSON)
203 if err != nil {
204 b.t.Fatalf("Unexpected command")
205 }
206 cmdName := cmdJSON["execute"]
207 gotCmdName := cmdName.(string)
208 result := b.results[currentCmd].result
209 if gotCmdName != b.cmds[currentCmd].name {
210 b.t.Errorf("Unexpected command. Expected %s found %s",
211 b.cmds[currentCmd].name, gotCmdName)
212 result = "error"
213 }
214 resultMap := make(map[string]interface{})
215 resultMap[result] = b.results[currentCmd].data
216 encodedRes, err := json.Marshal(&resultMap)
217 if err != nil {
218 b.t.Errorf("Unable to encode result: %v", err)
219 }
220 encodedRes = append(encodedRes, '\n')
221 b.newDataCh <- encodedRes
222 return len(p), nil
223 }
224
225 func checkVersion(t *testing.T, connectedCh <-chan *QMPVersion) *QMPVersion {
226 var version *QMPVersion
227 select {
228 case <-time.After(time.Second):
229 t.Fatal("Timed out waiting for qmp to connect")
230 case version = <-connectedCh:
231 }
232
233 if version == nil {
234 t.Fatal("Invalid version information received")
235 }
236 if version.Micro != micro || version.Minor != minor ||
237 version.Major != major {
238 t.Fatal("Invalid version number")
239 }
240
241 if len(version.Capabilities) != 2 {
242 if version.Capabilities[0] != cap1 || version.Capabilities[1] != cap2 {
243 t.Fatal("Invalid capabilities")
244 }
245 }
246
247 return version
248 }
249
250 // Checks that a QMP Loop can be started and shutdown.
251 //
252 // We start a QMPLoop and shut it down.
253 //
254 // Loop should start up and shutdown correctly. The version information
255 // returned from startQMPLoop should be correct.
256 func TestQMPStartStopLoop(t *testing.T) {
257 connectedCh := make(chan *QMPVersion)
258 disconnectedCh := make(chan struct{})
259 buf := newQMPTestCommandBuffer(t)
260 cfg := QMPConfig{Logger: qmpTestLogger{}}
261 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
262 checkVersion(t, connectedCh)
263 q.Shutdown()
264 <-disconnectedCh
265 }
266
267 // Checks that a call to QMPStart with an invalid path exits gracefully.
268 //
269 // We call QMPStart with an invalid path.
270 //
271 // An error should be returned and the disconnected channel should be closed.
272 func TestQMPStartBadPath(t *testing.T) {
273 cfg := QMPConfig{Logger: qmpTestLogger{}}
274 disconnectedCh := make(chan struct{})
275 q, _, err := QMPStart(context.Background(), "", cfg, disconnectedCh)
276 if err == nil {
277 t.Errorf("Expected error")
278 q.Shutdown()
279 }
280 <-disconnectedCh
281 }
282
283 // Checks that the qmp_capabilities command is correctly sent.
284 //
285 // We start a QMPLoop, send the qmp_capabilities command and stop the
286 // loop.
287 //
288 // The qmp_capabilities should be correctly sent and the QMP loop
289 // should exit gracefully.
290 func TestQMPCapabilities(t *testing.T) {
291 connectedCh := make(chan *QMPVersion)
292 disconnectedCh := make(chan struct{})
293 buf := newQMPTestCommandBuffer(t)
294 buf.AddCommand("qmp_capabilities", nil, "return", nil)
295 cfg := QMPConfig{Logger: qmpTestLogger{}}
296 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
297 checkVersion(t, connectedCh)
298 err := q.ExecuteQMPCapabilities(context.Background())
299 if err != nil {
300 t.Fatalf("Unexpected error %v", err)
301 }
302 q.Shutdown()
303 <-disconnectedCh
304 }
305
306 // Checks that an error returned by a QMP command is correctly handled.
307 //
308 // We start a QMPLoop, send the qmp_capabilities command and stop the
309 // loop.
310 //
311 // The qmp_capabilities command fails and yet we should exit gracefully.
312 func TestQMPBadCapabilities(t *testing.T) {
313 connectedCh := make(chan *QMPVersion)
314 disconnectedCh := make(chan struct{})
315 buf := newQMPTestCommandBuffer(t)
316 buf.AddCommand("qmp_capabilities", nil, "error", nil)
317 cfg := QMPConfig{Logger: qmpTestLogger{}}
318 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
319 checkVersion(t, connectedCh)
320 err := q.ExecuteQMPCapabilities(context.Background())
321 if err == nil {
322 t.Fatalf("Expected error")
323 }
324 q.Shutdown()
325 <-disconnectedCh
326 }
327
328 // Checks that the stop command is correctly sent.
329 //
330 // We start a QMPLoop, send the stop command and stop the
331 // loop.
332 //
333 // The stop command should be correctly sent and the QMP loop
334 // should exit gracefully.
335 func TestQMPStop(t *testing.T) {
336 connectedCh := make(chan *QMPVersion)
337 disconnectedCh := make(chan struct{})
338 buf := newQMPTestCommandBuffer(t)
339 buf.AddCommand("stop", nil, "return", nil)
340 cfg := QMPConfig{Logger: qmpTestLogger{}}
341 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
342 checkVersion(t, connectedCh)
343 err := q.ExecuteStop(context.Background())
344 if err != nil {
345 t.Fatalf("Unexpected error %v", err)
346 }
347 q.Shutdown()
348 <-disconnectedCh
349 }
350
351 // Checks that the cont command is correctly sent.
352 //
353 // We start a QMPLoop, send the cont command and stop the
354 // loop.
355 //
356 // The cont command should be correctly sent and the QMP loop
357 // should exit gracefully.
358 func TestQMPCont(t *testing.T) {
359 connectedCh := make(chan *QMPVersion)
360 disconnectedCh := make(chan struct{})
361 buf := newQMPTestCommandBuffer(t)
362 buf.AddCommand("cont", nil, "return", nil)
363 cfg := QMPConfig{Logger: qmpTestLogger{}}
364 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
365 checkVersion(t, connectedCh)
366 err := q.ExecuteCont(context.Background())
367 if err != nil {
368 t.Fatalf("Unexpected error %v", err)
369 }
370 q.Shutdown()
371 <-disconnectedCh
372 }
373
374 // Checks that the quit command is correctly sent.
375 //
376 // We start a QMPLoop, send the quit command and wait for the loop to exit.
377 //
378 // The quit command should be correctly sent and the QMP loop should exit
379 // gracefully without the test calling q.Shutdown().
380 func TestQMPQuit(t *testing.T) {
381 connectedCh := make(chan *QMPVersion)
382 disconnectedCh := make(chan struct{})
383 buf := newQMPTestCommandBuffer(t)
384 buf.AddCommand("quit", nil, "return", nil)
385 cfg := QMPConfig{Logger: qmpTestLogger{}}
386 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
387 checkVersion(t, connectedCh)
388 err := q.ExecuteQuit(context.Background())
389 if err != nil {
390 t.Fatalf("Unexpected error %v", err)
391 }
392 close(buf.forceFail)
393 <-disconnectedCh
394 }
395
396 // Checks that the blockdev-add command is correctly sent.
397 //
398 // We start a QMPLoop, send the blockdev-add command and stop the loop.
399 //
400 // The blockdev-add command should be correctly sent and the QMP loop should
401 // exit gracefully.
402 func TestQMPBlockdevAdd(t *testing.T) {
403 connectedCh := make(chan *QMPVersion)
404 disconnectedCh := make(chan struct{})
405 buf := newQMPTestCommandBuffer(t)
406 buf.AddCommand("blockdev-add", nil, "return", nil)
407 cfg := QMPConfig{Logger: qmpTestLogger{}}
408 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
409 q.version = checkVersion(t, connectedCh)
410 err := q.ExecuteBlockdevAdd(context.Background(), "/dev/rbd0",
411 fmt.Sprintf("drive_%s", volumeUUID), false)
412 if err != nil {
413 t.Fatalf("Unexpected error %v", err)
414 }
415 q.Shutdown()
416 <-disconnectedCh
417 }
418
419 // Checks that the blockdev-add with cache options command is correctly sent.
420 //
421 // We start a QMPLoop, send the blockdev-add with cache options
422 // command and stop the loop.
423 //
424 // The blockdev-add with cache options command should be correctly sent and
425 // the QMP loop should exit gracefully.
426 func TestQMPBlockdevAddWithCache(t *testing.T) {
427 connectedCh := make(chan *QMPVersion)
428 disconnectedCh := make(chan struct{})
429 buf := newQMPTestCommandBuffer(t)
430 buf.AddCommand("blockdev-add", nil, "return", nil)
431 cfg := QMPConfig{Logger: qmpTestLogger{}}
432 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
433 q.version = checkVersion(t, connectedCh)
434 err := q.ExecuteBlockdevAddWithCache(context.Background(), "/dev/rbd0",
435 fmt.Sprintf("drive_%s", volumeUUID), true, true, false)
436 if err != nil {
437 t.Fatalf("Unexpected error %v", err)
438 }
439 q.Shutdown()
440 <-disconnectedCh
441 }
442
443 // Checks that the netdev_add command is correctly sent.
444 //
445 // We start a QMPLoop, send the netdev_add command and stop the loop.
446 //
447 // The netdev_add command should be correctly sent and the QMP loop should
448 // exit gracefully.
449 func TestQMPNetdevAdd(t *testing.T) {
450 connectedCh := make(chan *QMPVersion)
451 disconnectedCh := make(chan struct{})
452 buf := newQMPTestCommandBuffer(t)
453 buf.AddCommand("netdev_add", nil, "return", nil)
454 cfg := QMPConfig{Logger: qmpTestLogger{}}
455 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
456 q.version = checkVersion(t, connectedCh)
457 err := q.ExecuteNetdevAdd(context.Background(), "tap", "br0", "tap0", "no", "no", 8)
458 if err != nil {
459 t.Fatalf("Unexpected error %v", err)
460 }
461 q.Shutdown()
462 <-disconnectedCh
463 }
464
465 // Checks that the netdev_add command is correctly sent.
466 //
467 // We start a QMPLoop, send the netdev_add command and stop the loop.
468 //
469 // The netdev_add command should be correctly sent and the QMP loop should
470 // exit gracefully.
471 func TestQMPNetdevChardevAdd(t *testing.T) {
472 connectedCh := make(chan *QMPVersion)
473 disconnectedCh := make(chan struct{})
474 buf := newQMPTestCommandBuffer(t)
475 buf.AddCommand("netdev_add", nil, "return", nil)
476 cfg := QMPConfig{Logger: qmpTestLogger{}}
477 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
478 q.version = checkVersion(t, connectedCh)
479 err := q.ExecuteNetdevChardevAdd(context.Background(), "tap", "br0", "chr0", 8)
480 if err != nil {
481 t.Fatalf("Unexpected error %v", err)
482 }
483 q.Shutdown()
484 <-disconnectedCh
485 }
486
487 // Checks that the netdev_add command with fds is correctly sent.
488 //
489 // We start a QMPLoop, send the netdev_add command with fds and stop the loop.
490 //
491 // The netdev_add command with fds should be correctly sent and the QMP loop should
492 // exit gracefully.
493 func TestQMPNetdevAddByFds(t *testing.T) {
494 connectedCh := make(chan *QMPVersion)
495 disconnectedCh := make(chan struct{})
496 buf := newQMPTestCommandBuffer(t)
497 buf.AddCommand("netdev_add", nil, "return", nil)
498 buf.AddCommand("netdev_add", nil, "return", nil)
499 cfg := QMPConfig{Logger: qmpTestLogger{}}
500 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
501 q.version = checkVersion(t, connectedCh)
502 err := q.ExecuteNetdevAddByFds(context.Background(), "tap", "br0", nil, []string{})
503 if err != nil {
504 t.Fatalf("Unexpected error %v", err)
505 }
506 err = q.ExecuteNetdevAddByFds(context.Background(), "tap", "br1", nil, []string{"3"})
507 if err != nil {
508 t.Fatalf("Unexpected error %v", err)
509 }
510 q.Shutdown()
511 <-disconnectedCh
512 }
513
514 // Checks that the netdev_del command is correctly sent.
515 //
516 // We start a QMPLoop, send the netdev_del command and stop the loop.
517 //
518 // The netdev_del command should be correctly sent and the QMP loop should
519 // exit gracefully.
520 func TestQMPNetdevDel(t *testing.T) {
521 connectedCh := make(chan *QMPVersion)
522 disconnectedCh := make(chan struct{})
523 buf := newQMPTestCommandBuffer(t)
524 buf.AddCommand("netdev_del", nil, "return", nil)
525 cfg := QMPConfig{Logger: qmpTestLogger{}}
526 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
527 q.version = checkVersion(t, connectedCh)
528 err := q.ExecuteNetdevDel(context.Background(), "br0")
529 if err != nil {
530 t.Fatalf("Unexpected error %v", err)
531 }
532 q.Shutdown()
533 <-disconnectedCh
534 }
535
536 func TestQMPNetPCIDeviceAdd(t *testing.T) {
537 connectedCh := make(chan *QMPVersion)
538 disconnectedCh := make(chan struct{})
539 buf := newQMPTestCommandBuffer(t)
540 buf.AddCommand("device_add", nil, "return", nil)
541 cfg := QMPConfig{Logger: qmpTestLogger{}}
542 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
543 checkVersion(t, connectedCh)
544 err := q.ExecuteNetPCIDeviceAdd(context.Background(), "br0", "virtio-0", "02:42:ac:11:00:02", "0x7", "", "", 8, false)
545 if err != nil {
546 t.Fatalf("Unexpected error %v", err)
547 }
548 q.Shutdown()
549 <-disconnectedCh
550 }
551
552 func TestQMPNetCCWDeviceAdd(t *testing.T) {
553 connectedCh := make(chan *QMPVersion)
554 disconnectedCh := make(chan struct{})
555 buf := newQMPTestCommandBuffer(t)
556 buf.AddCommand("device_add", nil, "return", nil)
557 cfg := QMPConfig{Logger: qmpTestLogger{}}
558 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
559 checkVersion(t, connectedCh)
560 err := q.ExecuteNetCCWDeviceAdd(context.Background(), "br0", "virtio-0", "02:42:ac:11:00:02", DevNo, 8)
561 if err != nil {
562 t.Fatalf("Unexpected error %v", err)
563 }
564 q.Shutdown()
565 <-disconnectedCh
566 }
567
568 // Checks that the device_add command is correctly sent.
569 //
570 // We start a QMPLoop, send the device_add command and stop the loop.
571 //
572 // The device_add command should be correctly sent and the QMP loop should
573 // exit gracefully.
574 func TestQMPDeviceAdd(t *testing.T) {
575 connectedCh := make(chan *QMPVersion)
576 disconnectedCh := make(chan struct{})
577 buf := newQMPTestCommandBuffer(t)
578 buf.AddCommand("device_add", nil, "return", nil)
579 cfg := QMPConfig{Logger: qmpTestLogger{}}
580 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
581 q.version = checkVersion(t, connectedCh)
582 blockdevID := fmt.Sprintf("drive_%s", volumeUUID)
583 devID := fmt.Sprintf("device_%s", volumeUUID)
584 err := q.ExecuteDeviceAdd(context.Background(), blockdevID, devID,
585 "virtio-blk-pci", "", "", true, false)
586 if err != nil {
587 t.Fatalf("Unexpected error %v", err)
588 }
589 q.Shutdown()
590 <-disconnectedCh
591 }
592
593 // Checks that the device_add command for scsi is correctly sent.
594 //
595 // We start a QMPLoop, send the device_add command and stop the loop.
596 //
597 // The device_add command should be correctly sent and the QMP loop should
598 // exit gracefully.
599 func TestQMPSCSIDeviceAdd(t *testing.T) {
600 connectedCh := make(chan *QMPVersion)
601 disconnectedCh := make(chan struct{})
602 buf := newQMPTestCommandBuffer(t)
603 buf.AddCommand("device_add", nil, "return", nil)
604 cfg := QMPConfig{Logger: qmpTestLogger{}}
605 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
606 q.version = checkVersion(t, connectedCh)
607 blockdevID := fmt.Sprintf("drive_%s", volumeUUID)
608 devID := fmt.Sprintf("device_%s", volumeUUID)
609 err := q.ExecuteSCSIDeviceAdd(context.Background(), blockdevID, devID,
610 "scsi-hd", "scsi0.0", "", 1, 2, true, false)
611 if err != nil {
612 t.Fatalf("Unexpected error %v", err)
613 }
614 q.Shutdown()
615 <-disconnectedCh
616 }
617
618 // Checks that the blockdev-del command is correctly sent.
619 //
620 // We start a QMPLoop, send the blockdev-del command and stop the loop.
621 //
622 // The blockdev-del command should be correctly sent and the QMP loop should
623 // exit gracefully.
624 func TestQMPBlockdevDel(t *testing.T) {
625 connectedCh := make(chan *QMPVersion)
626 disconnectedCh := make(chan struct{})
627 buf := newQMPTestCommandBuffer(t)
628 buf.AddCommand("blockdev-del", nil, "return", nil)
629 cfg := QMPConfig{Logger: qmpTestLogger{}}
630 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
631 q.version = checkVersion(t, connectedCh)
632 err := q.ExecuteBlockdevDel(context.Background(),
633 fmt.Sprintf("drive_%s", volumeUUID))
634 if err != nil {
635 t.Fatalf("Unexpected error %v", err)
636 }
637 q.Shutdown()
638 <-disconnectedCh
639 }
640
641 // Checks that the chardev-remove command is correctly sent.
642 //
643 // We start a QMPLoop, send the chardev-remove command and stop the loop.
644 //
645 // The chardev-remove command should be correctly sent and the QMP loop should
646 // exit gracefully.
647 func TestQMPChardevDel(t *testing.T) {
648 connectedCh := make(chan *QMPVersion)
649 disconnectedCh := make(chan struct{})
650 buf := newQMPTestCommandBuffer(t)
651 buf.AddCommand("chardev-remove", nil, "return", nil)
652 cfg := QMPConfig{Logger: qmpTestLogger{}}
653 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
654 q.version = checkVersion(t, connectedCh)
655 err := q.ExecuteChardevDel(context.Background(), "chardev-0")
656 if err != nil {
657 t.Fatalf("Unexpected error %v", err)
658 }
659 q.Shutdown()
660 <-disconnectedCh
661 }
662
663 // Checks that the device_del command is correctly sent.
664 //
665 // We start a QMPLoop, send the device_del command and wait for it to complete.
666 // This command generates some events so we start a separate go routine to check
667 // that they are received.
668 //
669 // The device_del command should be correctly sent and the QMP loop should
670 // exit gracefully. We should also receive two events on the eventCh.
671 func TestQMPDeviceDel(t *testing.T) {
672 const (
673 seconds = int64(1352167040730)
674 microsecondsEv1 = 123456
675 microsecondsEv2 = 123556
676 device = "device_" + volumeUUID
677 path = "/dev/rbd0"
678 )
679
680 var wg sync.WaitGroup
681 connectedCh := make(chan *QMPVersion)
682 disconnectedCh := make(chan struct{})
683 buf := newQMPTestCommandBuffer(t)
684 buf.AddCommand("device_del", nil, "return", nil)
685 buf.AddEvent("DEVICE_DELETED", time.Millisecond*200,
686 map[string]interface{}{
687 "path": path,
688 },
689 map[string]interface{}{
690 "seconds": seconds,
691 "microseconds": microsecondsEv1,
692 })
693 buf.AddEvent("DEVICE_DELETED", time.Millisecond*200,
694 map[string]interface{}{
695 "device": device,
696 "path": path,
697 },
698 map[string]interface{}{
699 "seconds": seconds,
700 "microseconds": microsecondsEv2,
701 })
702 eventCh := make(chan QMPEvent)
703 cfg := QMPConfig{EventCh: eventCh, Logger: qmpTestLogger{}}
704 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
705 wg.Add(1)
706 go func() {
707 for i := 0; i < 2; i++ {
708 select {
709 case <-eventCh:
710 case <-time.After(time.Second):
711 t.Error("Timedout waiting for event")
712 }
713 }
714 wg.Done()
715 }()
716 checkVersion(t, connectedCh)
717 buf.startEventLoop(&wg)
718 err := q.ExecuteDeviceDel(context.Background(),
719 fmt.Sprintf("device_%s", volumeUUID))
720 if err != nil {
721 t.Fatalf("Unexpected error %v", err)
722 }
723 q.Shutdown()
724 <-disconnectedCh
725 wg.Wait()
726 }
727
728 // Checks that contexts can be used to timeout a command.
729 //
730 // We start a QMPLoop and send the device_del command with a context that times
731 // out after 1 second. We don't however arrangefor any DEVICE_DELETED events
732 // to be sent so the device_del command should not complete normally. We then
733 // shutdown the QMP loop.
734 //
735 // The device_del command should timeout after 1 second and the QMP loop
736 // should exit gracefully.
737 func TestQMPDeviceDelTimeout(t *testing.T) {
738 var wg sync.WaitGroup
739 connectedCh := make(chan *QMPVersion)
740 disconnectedCh := make(chan struct{})
741 buf := newQMPTestCommandBuffer(t)
742 buf.AddCommand("device_del", nil, "return", nil)
743 cfg := QMPConfig{Logger: qmpTestLogger{}}
744 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
745 checkVersion(t, connectedCh)
746 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
747 err := q.ExecuteDeviceDel(ctx,
748 fmt.Sprintf("device_%s", volumeUUID))
749 cancel()
750 if err != context.DeadlineExceeded {
751 t.Fatalf("Timeout expected found %v", err)
752 }
753 q.Shutdown()
754 <-disconnectedCh
755 wg.Wait()
756 }
757
758 // Checks that contexts can be used to cancel a command.
759 //
760 // We start a QMPLoop and send two qmp_capabilities commands, cancelling
761 // the first. The second is allowed to proceed normally.
762 //
763 // The first call to ExecuteQMPCapabilities should fail with
764 // context.Canceled. The second should succeed.
765 func TestQMPCancel(t *testing.T) {
766 connectedCh := make(chan *QMPVersion)
767 disconnectedCh := make(chan struct{})
768 buf := newQMPTestCommandBuffer(t)
769 buf.AddCommand("qmp_capabilities", nil, "return", nil)
770 buf.AddCommand("qmp_capabilities", nil, "return", nil)
771 cfg := QMPConfig{Logger: qmpTestLogger{}}
772 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
773 checkVersion(t, connectedCh)
774 ctx, cancel := context.WithCancel(context.Background())
775 cancel()
776 err := q.ExecuteQMPCapabilities(ctx)
777 if err != context.Canceled {
778 t.Fatalf("Unexpected error %v", err)
779 }
780 err = q.ExecuteQMPCapabilities(context.Background())
781 if err != nil {
782 t.Fatalf("Unexpected error %v", err)
783 }
784 q.Shutdown()
785 <-disconnectedCh
786 }
787
788 // Checks that the system_powerdown command is correctly sent.
789 //
790 // We start a QMPLoop, send the system_powerdown command and stop the loop.
791 //
792 // The system_powerdown command should be correctly sent and should return
793 // as we've provisioned a SHUTDOWN event. The QMP loop should exit gracefully.
794 func TestQMPSystemPowerdown(t *testing.T) {
795 const (
796 seconds = int64(1352167040730)
797 microsecondsEv1 = 123456
798 )
799
800 var wg sync.WaitGroup
801 connectedCh := make(chan *QMPVersion)
802 disconnectedCh := make(chan struct{})
803 buf := newQMPTestCommandBuffer(t)
804 buf.AddCommand("system_powerdown", nil, "return", nil)
805 buf.AddEvent("POWERDOWN", time.Millisecond*100,
806 nil,
807 map[string]interface{}{
808 "seconds": seconds,
809 "microseconds": microsecondsEv1,
810 })
811 cfg := QMPConfig{Logger: qmpTestLogger{}}
812 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
813 checkVersion(t, connectedCh)
814 buf.startEventLoop(&wg)
815 err := q.ExecuteSystemPowerdown(context.Background())
816 if err != nil {
817 t.Fatalf("Unexpected error %v", err)
818 }
819 q.Shutdown()
820 <-disconnectedCh
821 wg.Wait()
822 }
823
824 // Checks that event commands can be cancelled.
825 //
826 // We start a QMPLoop, send the system_powerdown command. This command
827 // will time out after 1 second as the SHUTDOWN event never arrives.
828 // We then send a quit command to terminate the session.
829 //
830 // The system_powerdown command should be correctly sent but should block
831 // waiting for the SHUTDOWN event and should be successfully cancelled.
832 // The quit command should be successfully received and the QMP loop should
833 // exit gracefully.
834 func TestQMPEventedCommandCancel(t *testing.T) {
835 var wg sync.WaitGroup
836 connectedCh := make(chan *QMPVersion)
837 disconnectedCh := make(chan struct{})
838 buf := newQMPTestCommandBuffer(t)
839 buf.AddCommand("system_powerdown", nil, "return", nil)
840 buf.AddCommand("quit", nil, "return", nil)
841 cfg := QMPConfig{Logger: qmpTestLogger{}}
842 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
843 checkVersion(t, connectedCh)
844 buf.startEventLoop(&wg)
845 ctx, cancelFN := context.WithTimeout(context.Background(), time.Second)
846 err := q.ExecuteSystemPowerdown(ctx)
847 cancelFN()
848 if err == nil {
849 t.Fatalf("Expected SystemPowerdown to fail")
850 }
851 err = q.ExecuteQuit(context.Background())
852 if err != nil {
853 t.Fatalf("Unexpected error %v", err)
854 }
855 q.Shutdown()
856 <-disconnectedCh
857 wg.Wait()
858 }
859
860 // Checks that queued commands execute after an evented command is cancelled.
861 //
862 // This test is similar to the previous test with the exception that it
863 // tries to ensure that a second command is placed on the QMP structure's
864 // command queue before the evented command is cancelled. This allows us
865 // to test a slightly different use case. We start a QMPLoop, send the
866 // system_powerdown command. We do this by sending the command directly
867 // down the QMP.cmdCh rather than calling a higher level function as this
868 // allows us to ensure that we have another command queued before we
869 // timeout the first command. We then send a qmp_capabilities command and
870 // then we shutdown.
871 //
872 // The system_powerdown command should be correctly sent but should block
873 // waiting for the SHUTDOWN event and should be successfully cancelled.
874 // The query_capabilities command should be successfully received and the
875 // QMP loop should exit gracefully.
876 func TestQMPEventedCommandCancelConcurrent(t *testing.T) {
877 var wg sync.WaitGroup
878 connectedCh := make(chan *QMPVersion)
879 disconnectedCh := make(chan struct{})
880 buf := newQMPTestCommandBuffer(t)
881
882 buf.AddCommand("system_powerdown", nil, "error", nil)
883 buf.AddCommand("qmp_capabilities", nil, "return", nil)
884
885 cfg := QMPConfig{Logger: qmpTestLogger{}}
886 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
887 checkVersion(t, connectedCh)
888 buf.startEventLoop(&wg)
889
890 resCh := make(chan qmpResult)
891 ctx, cancelFn := context.WithTimeout(context.Background(), time.Second)
892 q.cmdCh <- qmpCommand{
893 ctx: ctx,
894 res: resCh,
895 name: "system_powerdown",
896 filter: &qmpEventFilter{
897 eventName: "SHUTDOWN",
898 },
899 }
900
901 var cmdWg sync.WaitGroup
902 cmdWg.Add(1)
903 go func() {
904 err := q.ExecuteQMPCapabilities(context.Background())
905 if err != nil {
906 t.Errorf("Unexpected error %v", err)
907 }
908 cmdWg.Done()
909 }()
910
911 <-resCh
912 cancelFn()
913 cmdWg.Wait()
914 q.Shutdown()
915 <-disconnectedCh
916 wg.Wait()
917 }
918
919 // Checks that events can be received and parsed.
920 //
921 // Two events are provisioned and the QMPLoop is started with an valid eventCh.
922 // We wait for both events to be received and check that their contents are
923 // correct. We then shutdown the QMP loop.
924 //
925 // Both events are received and their contents are correct. The QMP loop should
926 // shut down gracefully.
927 func TestQMPEvents(t *testing.T) {
928 const (
929 seconds = int64(1352167040730)
930 microsecondsEv1 = 123456
931 microsecondsEv2 = 123556
932 device = "device_" + volumeUUID
933 path = "/dev/rbd0"
934 )
935 var wg sync.WaitGroup
936 connectedCh := make(chan *QMPVersion)
937 disconnectedCh := make(chan struct{})
938 buf := newQMPTestCommandBuffer(t)
939 buf.AddEvent("DEVICE_DELETED", time.Millisecond*100,
940 map[string]interface{}{
941 "device": device,
942 "path": path,
943 },
944 map[string]interface{}{
945 "seconds": seconds,
946 "microseconds": microsecondsEv1,
947 })
948 buf.AddEvent("POWERDOWN", time.Millisecond*200, nil,
949 map[string]interface{}{
950 "seconds": seconds,
951 "microseconds": microsecondsEv2,
952 })
953 eventCh := make(chan QMPEvent)
954 cfg := QMPConfig{EventCh: eventCh, Logger: qmpTestLogger{}}
955 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
956 checkVersion(t, connectedCh)
957 buf.startEventLoop(&wg)
958
959 ev := <-eventCh
960 if ev.Name != "DEVICE_DELETED" {
961 t.Errorf("incorrect event name received. Expected %s, found %s",
962 "DEVICE_DELETED", ev.Name)
963 }
964 if ev.Timestamp != time.Unix(seconds, microsecondsEv1) {
965 t.Error("incorrect timestamp")
966 }
967 deviceName := ev.Data["device"].(string)
968 if deviceName != device {
969 t.Errorf("Unexpected device field. Expected %s, found %s",
970 "device_"+volumeUUID, device)
971 }
972 pathName := ev.Data["path"].(string)
973 if pathName != path {
974 t.Errorf("Unexpected path field. Expected %s, found %s",
975 "/dev/rbd0", path)
976 }
977
978 ev = <-eventCh
979 if ev.Name != "POWERDOWN" {
980 t.Errorf("incorrect event name received. Expected %s, found %s",
981 "POWERDOWN", ev.Name)
982 }
983 if ev.Timestamp != time.Unix(seconds, microsecondsEv2) {
984 t.Error("incorrect timestamp")
985 }
986 if ev.Data != nil {
987 t.Errorf("event data expected to be nil")
988 }
989
990 q.Shutdown()
991
992 select {
993 case _, ok := <-eventCh:
994 if ok {
995 t.Errorf("Expected eventCh to be closed")
996 }
997 case <-time.After(time.Second):
998 t.Error("Timed out waiting for eventCh to close")
999 }
1000
1001 <-disconnectedCh
1002 wg.Wait()
1003 }
1004
1005 // Checks that commands issued after the QMP loop exits fail (and don't hang)
1006 //
1007 // We start the QMP loop but force it to fail immediately simulating a QEMU
1008 // instance exit. We then send two qmp_cabilities commands.
1009 //
1010 // Both commands should fail with an error. The QMP loop should exit.
1011 func TestQMPLostLoop(t *testing.T) {
1012 connectedCh := make(chan *QMPVersion)
1013 disconnectedCh := make(chan struct{})
1014 buf := newQMPTestCommandBuffer(t)
1015
1016 cfg := QMPConfig{Logger: qmpTestLogger{}}
1017 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1018 checkVersion(t, connectedCh)
1019 close(buf.forceFail)
1020 buf.AddCommand("qmp_capabilities", nil, "return", nil)
1021 err := q.ExecuteQMPCapabilities(context.Background())
1022 if err == nil {
1023 t.Error("Expected executeQMPCapabilities to fail")
1024 }
1025 <-disconnectedCh
1026 buf.AddCommand("qmp_capabilities", nil, "return", nil)
1027 err = q.ExecuteQMPCapabilities(context.Background())
1028 if err == nil {
1029 t.Error("Expected executeQMPCapabilities to fail")
1030 }
1031 }
1032
1033 // Checks that PCI devices are correctly added using device_add.
1034 //
1035 // We start a QMPLoop, send the device_add command and stop the loop.
1036 //
1037 // The device_add command should be correctly sent and the QMP loop should
1038 // exit gracefully.
1039 func TestQMPPCIDeviceAdd(t *testing.T) {
1040 connectedCh := make(chan *QMPVersion)
1041 disconnectedCh := make(chan struct{})
1042 buf := newQMPTestCommandBuffer(t)
1043 buf.AddCommand("device_add", nil, "return", nil)
1044 cfg := QMPConfig{Logger: qmpTestLogger{}}
1045 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1046 q.version = checkVersion(t, connectedCh)
1047 blockdevID := fmt.Sprintf("drive_%s", volumeUUID)
1048 devID := fmt.Sprintf("device_%s", volumeUUID)
1049 err := q.ExecutePCIDeviceAdd(context.Background(), blockdevID, devID,
1050 "virtio-blk-pci", "0x1", "", "", 1, true, false)
1051 if err != nil {
1052 t.Fatalf("Unexpected error %v", err)
1053 }
1054 q.Shutdown()
1055 <-disconnectedCh
1056 }
1057
1058 // Checks that PCI VFIO mediated devices are correctly added using device_add.
1059 //
1060 // We start a QMPLoop, send the device_add command and stop the loop.
1061 //
1062 // The device_add command should be correctly sent and the QMP loop should
1063 // exit gracefully.
1064 func TestQMPPCIVFIOMediatedDeviceAdd(t *testing.T) {
1065 connectedCh := make(chan *QMPVersion)
1066 disconnectedCh := make(chan struct{})
1067 buf := newQMPTestCommandBuffer(t)
1068 buf.AddCommand("device_add", nil, "return", nil)
1069 cfg := QMPConfig{Logger: qmpTestLogger{}}
1070 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1071 checkVersion(t, connectedCh)
1072 sysfsDev := "/sys/bus/pci/devices/0000:00:02.0/a297db4a-f4c2-11e6-90f6-d3b88d6c9525"
1073 devID := fmt.Sprintf("device_%s", volumeUUID)
1074 err := q.ExecutePCIVFIOMediatedDeviceAdd(context.Background(), devID, sysfsDev, "0x1", "", "")
1075 if err != nil {
1076 t.Fatalf("Unexpected error %v", err)
1077 }
1078 q.Shutdown()
1079 <-disconnectedCh
1080 }
1081
1082 func TestQMPPCIVFIOPCIeDeviceAdd(t *testing.T) {
1083 connectedCh := make(chan *QMPVersion)
1084 disconnectedCh := make(chan struct{})
1085 buf := newQMPTestCommandBuffer(t)
1086 buf.AddCommand("device_add", nil, "return", nil)
1087 cfg := QMPConfig{Logger: qmpTestLogger{}}
1088 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1089 checkVersion(t, connectedCh)
1090 bdf := "04:00.0"
1091 bus := "rp0"
1092 addr := "0x1"
1093 romfile := ""
1094 devID := fmt.Sprintf("device_%s", volumeUUID)
1095 err := q.ExecutePCIVFIODeviceAdd(context.Background(), devID, bdf, addr, bus, romfile)
1096 if err != nil {
1097 t.Fatalf("Unexpected error %v", err)
1098 }
1099 q.Shutdown()
1100 <-disconnectedCh
1101 }
1102
1103 func TestQMPAPVFIOMediatedDeviceAdd(t *testing.T) {
1104 connectedCh := make(chan *QMPVersion)
1105 disconnectedCh := make(chan struct{})
1106 buf := newQMPTestCommandBuffer(t)
1107 buf.AddCommand("device_add", nil, "return", nil)
1108 cfg := QMPConfig{Logger: qmpTestLogger{}}
1109 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1110 checkVersion(t, connectedCh)
1111 sysfsDev := "/sys/devices/vfio_ap/matrix/a297db4a-f4c2-11e6-90f6-d3b88d6c9525"
1112 err := q.ExecuteAPVFIOMediatedDeviceAdd(context.Background(), sysfsDev)
1113 if err != nil {
1114 t.Fatalf("Unexpected error %v", err)
1115 }
1116 q.Shutdown()
1117 <-disconnectedCh
1118 }
1119
1120 // Checks that CPU are correctly added using device_add
1121 func TestQMPCPUDeviceAdd(t *testing.T) {
1122 drivers := []string{"host-x86_64-cpu", "host-s390x-cpu", "host-powerpc64-cpu"}
1123 cpuID := "cpu-0"
1124 socketID := "0"
1125 dieID := "0"
1126 coreID := "1"
1127 threadID := "0"
1128 for _, d := range drivers {
1129 connectedCh := make(chan *QMPVersion)
1130 disconnectedCh := make(chan struct{})
1131 buf := newQMPTestCommandBuffer(t)
1132 buf.AddCommand("device_add", nil, "return", nil)
1133 cfg := QMPConfig{Logger: qmpTestLogger{}}
1134 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1135 checkVersion(t, connectedCh)
1136 err := q.ExecuteCPUDeviceAdd(context.Background(), d, cpuID, socketID, dieID, coreID, threadID, "")
1137 if err != nil {
1138 t.Fatalf("Unexpected error %v", err)
1139 }
1140 q.Shutdown()
1141 <-disconnectedCh
1142 }
1143 }
1144
1145 // Checks that hotpluggable CPUs are listed correctly
1146 func TestQMPExecuteQueryHotpluggableCPUs(t *testing.T) {
1147 connectedCh := make(chan *QMPVersion)
1148 disconnectedCh := make(chan struct{})
1149 buf := newQMPTestCommandBuffer(t)
1150 hotCPU := HotpluggableCPU{
1151 Type: "host-x86",
1152 VcpusCount: 5,
1153 Properties: CPUProperties{
1154 Node: 1,
1155 Socket: 3,
1156 Die: 1,
1157 Core: 2,
1158 Thread: 4,
1159 },
1160 QOMPath: "/abc/123/rgb",
1161 }
1162 buf.AddCommand("query-hotpluggable-cpus", nil, "return", []interface{}{hotCPU})
1163 cfg := QMPConfig{Logger: qmpTestLogger{}}
1164 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1165 checkVersion(t, connectedCh)
1166 hotCPUs, err := q.ExecuteQueryHotpluggableCPUs(context.Background())
1167 if err != nil {
1168 t.Fatalf("Unexpected error: %v", err)
1169 }
1170 if len(hotCPUs) != 1 {
1171 t.Fatalf("Expected hot CPUs length equals to 1\n")
1172 }
1173 if reflect.DeepEqual(hotCPUs[0], hotCPU) == false {
1174 t.Fatalf("Expected %v equals to %v", hotCPUs[0], hotCPU)
1175 }
1176 q.Shutdown()
1177 <-disconnectedCh
1178 }
1179
1180 // Checks that memory devices are listed correctly
1181 func TestQMPExecuteQueryMemoryDevices(t *testing.T) {
1182 connectedCh := make(chan *QMPVersion)
1183 disconnectedCh := make(chan struct{})
1184 buf := newQMPTestCommandBuffer(t)
1185 memoryDevices := MemoryDevices{
1186 Type: "dimm",
1187 Data: MemoryDevicesData{
1188 Slot: 1,
1189 Node: 0,
1190 Addr: 1234,
1191 Memdev: "dimm1",
1192 ID: "mem1",
1193 Hotpluggable: true,
1194 Hotplugged: false,
1195 Size: 1234,
1196 },
1197 }
1198 buf.AddCommand("query-memory-devices", nil, "return", []interface{}{memoryDevices})
1199 cfg := QMPConfig{Logger: qmpTestLogger{}}
1200 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1201 checkVersion(t, connectedCh)
1202 memDevices, err := q.ExecQueryMemoryDevices(context.Background())
1203 if err != nil {
1204 t.Fatalf("Unexpected error: %v", err)
1205 }
1206 if len(memDevices) != 1 {
1207 t.Fatalf("Expected memory devices length equals to 1\n")
1208 }
1209 if reflect.DeepEqual(memDevices[0], memoryDevices) == false {
1210 t.Fatalf("Expected %v equals to %v", memDevices[0], memoryDevices)
1211 }
1212 q.Shutdown()
1213 <-disconnectedCh
1214 }
1215
1216 // Checks that cpus are listed correctly
1217 func TestQMPExecuteQueryCpus(t *testing.T) {
1218 connectedCh := make(chan *QMPVersion)
1219 disconnectedCh := make(chan struct{})
1220 buf := newQMPTestCommandBuffer(t)
1221 cpuInfo := CPUInfo{
1222 CPU: 1,
1223 Current: false,
1224 Halted: false,
1225 Arch: "x86_64",
1226 QomPath: "/tmp/testQom",
1227 Pc: 123456,
1228 ThreadID: 123457,
1229 Props: CPUProperties{
1230 Node: 0,
1231 Socket: 1,
1232 Core: 1,
1233 Thread: 1966,
1234 },
1235 }
1236 buf.AddCommand("query-cpus", nil, "return", []interface{}{cpuInfo})
1237 cfg := QMPConfig{Logger: qmpTestLogger{}}
1238 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1239 checkVersion(t, connectedCh)
1240 cpus, err := q.ExecQueryCpus(context.Background())
1241 if err != nil {
1242 t.Fatalf("Unexpected error: %v", err)
1243 }
1244 if len(cpus) != 1 {
1245 t.Fatalf("Expected memory devices length equals to 1\n")
1246 }
1247 if reflect.DeepEqual(cpus[0], cpuInfo) == false {
1248 t.Fatalf("Expected %v equals to %v", cpus[0], cpuInfo)
1249 }
1250 q.Shutdown()
1251 <-disconnectedCh
1252 }
1253
1254 // Checks that cpus are listed correctly
1255 func TestQMPExecuteQueryCpusFast(t *testing.T) {
1256 connectedCh := make(chan *QMPVersion)
1257 disconnectedCh := make(chan struct{})
1258 buf := newQMPTestCommandBuffer(t)
1259 cpuInfoFast := CPUInfoFast{
1260 CPUIndex: 1,
1261 Arch: "x86",
1262 Target: "x86_64",
1263 QomPath: "/tmp/testQom",
1264 ThreadID: 123457,
1265 Props: CPUProperties{
1266 Node: 0,
1267 Socket: 1,
1268 Core: 1,
1269 Thread: 1966,
1270 },
1271 }
1272 buf.AddCommand("query-cpus-fast", nil, "return", []interface{}{cpuInfoFast})
1273 cfg := QMPConfig{Logger: qmpTestLogger{}}
1274 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1275 checkVersion(t, connectedCh)
1276 cpus, err := q.ExecQueryCpusFast(context.Background())
1277 if err != nil {
1278 t.Fatalf("Unexpected error: %v", err)
1279 }
1280 if len(cpus) != 1 {
1281 t.Fatalf("Expected memory devices length equals to 1\n")
1282 }
1283 if reflect.DeepEqual(cpus[0], cpuInfoFast) == false {
1284 t.Fatalf("Expected %v equals to %v", cpus[0], cpuInfoFast)
1285 }
1286 q.Shutdown()
1287 <-disconnectedCh
1288 }
1289
1290 // Checks that migrate capabilities can be set
1291 func TestExecSetMigrationCaps(t *testing.T) {
1292 connectedCh := make(chan *QMPVersion)
1293 disconnectedCh := make(chan struct{})
1294 buf := newQMPTestCommandBuffer(t)
1295 buf.AddCommand("migrate-set-capabilities", nil, "return", nil)
1296 cfg := QMPConfig{Logger: qmpTestLogger{}}
1297 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1298 checkVersion(t, connectedCh)
1299 caps := []map[string]interface{}{
1300 {
1301 "capability": "bypass-shared-memory",
1302 "state": true,
1303 },
1304 }
1305 err := q.ExecSetMigrationCaps(context.Background(), caps)
1306 if err != nil {
1307 t.Fatalf("Unexpected error: %v", err)
1308 }
1309 q.Shutdown()
1310 <-disconnectedCh
1311 }
1312
1313 // Checks that migrate arguments can be set
1314 func TestExecSetMigrateArguments(t *testing.T) {
1315 connectedCh := make(chan *QMPVersion)
1316 disconnectedCh := make(chan struct{})
1317 buf := newQMPTestCommandBuffer(t)
1318 buf.AddCommand("migrate", nil, "return", nil)
1319 cfg := QMPConfig{Logger: qmpTestLogger{}}
1320 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1321 checkVersion(t, connectedCh)
1322 err := q.ExecSetMigrateArguments(context.Background(), "exec:foobar")
1323 if err != nil {
1324 t.Fatalf("Unexpected error: %v", err)
1325 }
1326 q.Shutdown()
1327 <-disconnectedCh
1328 }
1329
1330 // Checks add memory device
1331 func TestExecMemdevAdd(t *testing.T) {
1332 connectedCh := make(chan *QMPVersion)
1333 disconnectedCh := make(chan struct{})
1334 buf := newQMPTestCommandBuffer(t)
1335 buf.AddCommand("object-add", nil, "return", nil)
1336 buf.AddCommand("device_add", nil, "return", nil)
1337 cfg := QMPConfig{Logger: qmpTestLogger{}}
1338 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1339 checkVersion(t, connectedCh)
1340 err := q.ExecMemdevAdd(context.Background(), "memory-backend-ram", "mem0", "", 128, true, "virtio-mem-pci", "virtiomem0", "0x1", "pci-bridge-0")
1341 if err != nil {
1342 t.Fatalf("Unexpected error: %v", err)
1343 }
1344 q.Shutdown()
1345 <-disconnectedCh
1346 }
1347
1348 // Checks hotplug memory
1349 func TestExecHotplugMemory(t *testing.T) {
1350 connectedCh := make(chan *QMPVersion)
1351 disconnectedCh := make(chan struct{})
1352 buf := newQMPTestCommandBuffer(t)
1353 buf.AddCommand("object-add", nil, "return", nil)
1354 buf.AddCommand("device_add", nil, "return", nil)
1355 cfg := QMPConfig{Logger: qmpTestLogger{}}
1356 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1357 checkVersion(t, connectedCh)
1358 err := q.ExecHotplugMemory(context.Background(), "memory-backend-ram", "mem0", "", 128, true)
1359 if err != nil {
1360 t.Fatalf("Unexpected error: %v", err)
1361 }
1362 q.Shutdown()
1363 <-disconnectedCh
1364 }
1365
1366 // Checks vsock-pci hotplug
1367 func TestExecutePCIVSockAdd(t *testing.T) {
1368 connectedCh := make(chan *QMPVersion)
1369 disconnectedCh := make(chan struct{})
1370 buf := newQMPTestCommandBuffer(t)
1371 buf.AddCommand("device_add", nil, "return", nil)
1372 cfg := QMPConfig{Logger: qmpTestLogger{}}
1373 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1374 checkVersion(t, connectedCh)
1375 err := q.ExecutePCIVSockAdd(context.Background(), "vsock-pci0", "3", "1", "1", "1", "", true)
1376 if err != nil {
1377 t.Fatalf("Unexpected error %v", err)
1378 }
1379 q.Shutdown()
1380 <-disconnectedCh
1381 }
1382
1383 // Checks vhost-user-pci hotplug
1384 func TestExecutePCIVhostUserDevAdd(t *testing.T) {
1385 connectedCh := make(chan *QMPVersion)
1386 disconnectedCh := make(chan struct{})
1387 buf := newQMPTestCommandBuffer(t)
1388 buf.AddCommand("device_add", nil, "return", nil)
1389 cfg := QMPConfig{Logger: qmpTestLogger{}}
1390 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1391 checkVersion(t, connectedCh)
1392 driver := "vhost-user-blk-pci"
1393 devID := "vhost-user-blk0"
1394 chardevID := "vhost-user-blk-char0"
1395 err := q.ExecutePCIVhostUserDevAdd(context.Background(), driver, devID, chardevID, "1", "1")
1396 if err != nil {
1397 t.Fatalf("Unexpected error %v", err)
1398 }
1399 q.Shutdown()
1400 <-disconnectedCh
1401 }
1402
1403 // Checks getfd
1404 func TestExecuteGetFdD(t *testing.T) {
1405 connectedCh := make(chan *QMPVersion)
1406 disconnectedCh := make(chan struct{})
1407 buf := newQMPTestCommandBuffer(t)
1408 buf.AddCommand("getfd", nil, "return", nil)
1409 cfg := QMPConfig{Logger: qmpTestLogger{}}
1410 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1411 checkVersion(t, connectedCh)
1412 err := q.ExecuteGetFD(context.Background(), "foo", os.NewFile(0, "foo"))
1413 if err != nil {
1414 t.Fatalf("Unexpected error %v", err)
1415 }
1416 q.Shutdown()
1417 <-disconnectedCh
1418 }
1419
1420 // Checks chardev-add unix socket
1421 func TestExecuteCharDevUnixSocketAdd(t *testing.T) {
1422 connectedCh := make(chan *QMPVersion)
1423 disconnectedCh := make(chan struct{})
1424 buf := newQMPTestCommandBuffer(t)
1425 buf.AddCommand("chardev-add", nil, "return", nil)
1426 cfg := QMPConfig{Logger: qmpTestLogger{}}
1427 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1428 checkVersion(t, connectedCh)
1429 err := q.ExecuteCharDevUnixSocketAdd(context.Background(), "foo", "foo.sock", false, true)
1430 if err != nil {
1431 t.Fatalf("Unexpected error %v", err)
1432 }
1433 q.Shutdown()
1434 <-disconnectedCh
1435 }
1436
1437 // Checks virtio serial port hotplug
1438 func TestExecuteVirtSerialPortAdd(t *testing.T) {
1439 connectedCh := make(chan *QMPVersion)
1440 disconnectedCh := make(chan struct{})
1441 buf := newQMPTestCommandBuffer(t)
1442 buf.AddCommand("device_add", nil, "return", nil)
1443 cfg := QMPConfig{Logger: qmpTestLogger{}}
1444 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1445 checkVersion(t, connectedCh)
1446 err := q.ExecuteVirtSerialPortAdd(context.Background(), "foo", "foo.channel", "foo")
1447 if err != nil {
1448 t.Fatalf("Unexpected error %v", err)
1449 }
1450 q.Shutdown()
1451 <-disconnectedCh
1452 }
1453
1454 // Check migration incoming
1455 func TestExecuteMigrationIncoming(t *testing.T) {
1456 connectedCh := make(chan *QMPVersion)
1457 disconnectedCh := make(chan struct{})
1458 buf := newQMPTestCommandBuffer(t)
1459 buf.AddCommand("migrate-incoming", nil, "return", nil)
1460 cfg := QMPConfig{Logger: qmpTestLogger{}}
1461 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1462 checkVersion(t, connectedCh)
1463 err := q.ExecuteMigrationIncoming(context.Background(), "uri")
1464 if err != nil {
1465 t.Fatalf("Unexpected error %v", err)
1466 }
1467 q.Shutdown()
1468 <-disconnectedCh
1469 }
1470
1471 // Checks migration status
1472 func TestExecuteQueryMigration(t *testing.T) {
1473 connectedCh := make(chan *QMPVersion)
1474 disconnectedCh := make(chan struct{})
1475 buf := newQMPTestCommandBuffer(t)
1476 status := MigrationStatus{
1477 Status: "completed",
1478 RAM: MigrationRAM{
1479 Total: 100,
1480 Remaining: 101,
1481 Transferred: 101,
1482 TotalTime: 101,
1483 SetupTime: 101,
1484 ExpectedDowntime: 101,
1485 Duplicate: 101,
1486 Normal: 101,
1487 NormalBytes: 101,
1488 DirtySyncCount: 101,
1489 },
1490 Disk: MigrationDisk{
1491 Total: 200,
1492 Remaining: 200,
1493 Transferred: 200,
1494 },
1495 XbzrleCache: MigrationXbzrleCache{
1496 CacheSize: 300,
1497 Bytes: 300,
1498 Pages: 300,
1499 CacheMiss: 300,
1500 CacheMissRate: 300,
1501 Overflow: 300,
1502 },
1503 }
1504 caps := map[string]interface{}{"foo": true}
1505 status.Capabilities = append(status.Capabilities, caps)
1506 buf.AddCommand("query-migrate", nil, "return", interface{}(status))
1507 cfg := QMPConfig{Logger: qmpTestLogger{}}
1508 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1509 checkVersion(t, connectedCh)
1510 s, err := q.ExecuteQueryMigration(context.Background())
1511 if err != nil {
1512 t.Fatalf("Unexpected error %v", err)
1513 }
1514 if !reflect.DeepEqual(s, status) {
1515 t.Fatalf("expected %v got %v", status, s)
1516 }
1517 q.Shutdown()
1518 <-disconnectedCh
1519 }
1520
1521 // Checks balloon
1522 func TestExecuteBalloon(t *testing.T) {
1523 connectedCh := make(chan *QMPVersion)
1524 disconnectedCh := make(chan struct{})
1525 buf := newQMPTestCommandBuffer(t)
1526 buf.AddCommand("balloon", nil, "return", nil)
1527 cfg := QMPConfig{Logger: qmpTestLogger{}}
1528
1529 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1530 checkVersion(t, connectedCh)
1531 err := q.ExecuteBalloon(context.Background(), 1073741824)
1532 if err != nil {
1533 t.Fatalf("Unexpected error %v", err)
1534 }
1535 q.Shutdown()
1536 <-disconnectedCh
1537 }
1538
1539 func TestErrorDesc(t *testing.T) {
1540 errDesc := "Somthing err messages"
1541 errData := map[string]string{
1542 "class": "GenericError",
1543 "desc": errDesc,
1544 }
1545
1546 connectedCh := make(chan *QMPVersion)
1547 disconnectedCh := make(chan struct{})
1548 buf := newQMPTestCommandBuffer(t)
1549 cfg := QMPConfig{Logger: qmpTestLogger{}}
1550 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1551 checkVersion(t, connectedCh)
1552
1553 desc, err := q.errorDesc(errData)
1554 if err != nil {
1555 t.Fatalf("Unexpected error '%v'", err)
1556 }
1557 if desc != errDesc {
1558 t.Fatalf("expected '%v'\n got '%v'", errDesc, desc)
1559 }
1560
1561 q.Shutdown()
1562 <-disconnectedCh
1563 }
1564
1565 func TestExecCommandFailed(t *testing.T) {
1566 errDesc := "unable to map backing store for guest RAM: Cannot allocate memory"
1567 errData := map[string]string{
1568 "class": "GenericError",
1569 "desc": errDesc,
1570 }
1571
1572 connectedCh := make(chan *QMPVersion)
1573 disconnectedCh := make(chan struct{})
1574 buf := newQMPTestCommandBuffer(t)
1575 buf.AddCommand("object-add", nil, "error", errData)
1576 cfg := QMPConfig{Logger: qmpTestLogger{}}
1577 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1578 checkVersion(t, connectedCh)
1579
1580 _, err := q.executeCommandWithResponse(context.Background(), "object-add", nil, nil, nil)
1581 if err == nil {
1582 t.Fatalf("expected error but got nil")
1583 }
1584
1585 expectedString := "QMP command failed: " + errDesc
1586 if err.Error() != expectedString {
1587 t.Fatalf("expected '%v' but got '%v'", expectedString, err)
1588 }
1589
1590 q.Shutdown()
1591 <-disconnectedCh
1592 }
1593
1594 func TestExecCommandFailedWithInnerError(t *testing.T) {
1595 errData := map[string]string{
1596 "class": "GenericError",
1597 "descFieldInvalid": "Invalid",
1598 }
1599
1600 connectedCh := make(chan *QMPVersion)
1601 disconnectedCh := make(chan struct{})
1602 buf := newQMPTestCommandBuffer(t)
1603 buf.AddCommand("object-add", nil, "error", errData)
1604 cfg := QMPConfig{Logger: qmpTestLogger{}}
1605 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1606 checkVersion(t, connectedCh)
1607
1608 _, err := q.executeCommandWithResponse(context.Background(), "object-add", nil, nil, nil)
1609 if err == nil {
1610 t.Fatalf("expected error but got nil")
1611 }
1612
1613 expectedString := "QMP command failed: "
1614 if err.Error() != expectedString {
1615 t.Fatalf("expected '%v' but got '%v'", expectedString, err)
1616 }
1617
1618 q.Shutdown()
1619 <-disconnectedCh
1620 }
1621
1622 // Checks NVDIMM device add
1623 func TestExecuteNVDIMMDeviceAdd(t *testing.T) {
1624 connectedCh := make(chan *QMPVersion)
1625 disconnectedCh := make(chan struct{})
1626 buf := newQMPTestCommandBuffer(t)
1627 buf.AddCommand("object-add", nil, "return", nil)
1628 buf.AddCommand("device_add", nil, "return", nil)
1629 cfg := QMPConfig{Logger: qmpTestLogger{}}
1630 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1631 checkVersion(t, connectedCh)
1632 pmem := true
1633 err := q.ExecuteNVDIMMDeviceAdd(context.Background(), "nvdimm0", "/dev/rbd0", 1024, &pmem)
1634 if err != nil {
1635 t.Fatalf("Unexpected error: %v", err)
1636 }
1637 q.Shutdown()
1638 <-disconnectedCh
1639 }
1640
1641 func TestMainLoopEventBeforeGreeting(t *testing.T) {
1642 const (
1643 seconds = int64(1352167040730)
1644 microseconds = 123456
1645 )
1646
1647 connectedCh := make(chan *QMPVersion)
1648 disconnectedCh := make(chan struct{})
1649 buf := newQMPTestCommandBufferNoGreeting(t)
1650
1651 // Add events
1652 var wg sync.WaitGroup
1653 buf.AddEvent("VSERPORT_CHANGE", time.Millisecond*100,
1654 map[string]interface{}{
1655 "open": false,
1656 "id": "channel0",
1657 },
1658 map[string]interface{}{
1659 "seconds": seconds,
1660 "microseconds": microseconds,
1661 })
1662 buf.AddEvent("POWERDOWN", time.Millisecond*200, nil,
1663 map[string]interface{}{
1664 "seconds": seconds,
1665 "microseconds": microseconds,
1666 })
1667
1668 // register a channel to receive events
1669 eventCh := make(chan QMPEvent)
1670 cfg := QMPConfig{EventCh: eventCh, Logger: qmpTestLogger{}}
1671 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1672
1673 // Start events, this will lead to a deadlock if mainLoop is not implemented
1674 // correctly
1675 buf.startEventLoop(&wg)
1676 wg.Wait()
1677
1678 // Send greeting and check version
1679 buf.newDataCh <- []byte(qmpHello)
1680 checkVersion(t, connectedCh)
1681
1682 q.Shutdown()
1683 <-disconnectedCh
1684 }
1685
1686 func TestQMPExecQueryQmpSchema(t *testing.T) {
1687 connectedCh := make(chan *QMPVersion)
1688 disconnectedCh := make(chan struct{})
1689 buf := newQMPTestCommandBuffer(t)
1690 schemaInfo := []SchemaInfo{
1691 {
1692 MetaType: "command",
1693 Name: "object-add",
1694 },
1695 {
1696 MetaType: "event",
1697 Name: "VSOCK_RUNNING",
1698 },
1699 }
1700 buf.AddCommand("query-qmp-schema", nil, "return", schemaInfo)
1701 cfg := QMPConfig{
1702 Logger: qmpTestLogger{},
1703 MaxCapacity: 1024,
1704 }
1705 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1706 checkVersion(t, connectedCh)
1707 info, err := q.ExecQueryQmpSchema(context.Background())
1708 if err != nil {
1709 t.Fatalf("Unexpected error: %v", err)
1710 }
1711 if len(schemaInfo) != 2 {
1712 t.Fatalf("Expected schema infos length equals to 2\n")
1713 }
1714 if reflect.DeepEqual(info, schemaInfo) == false {
1715 t.Fatalf("Expected %v equals to %v", info, schemaInfo)
1716 }
1717 q.Shutdown()
1718 <-disconnectedCh
1719 }
1720
1721 func TestQMPExecQueryQmpStatus(t *testing.T) {
1722 connectedCh := make(chan *QMPVersion)
1723 disconnectedCh := make(chan struct{})
1724 buf := newQMPTestCommandBuffer(t)
1725 statusInfo := StatusInfo{
1726 Running: true,
1727 SingleStep: false,
1728 Status: "running",
1729 }
1730 buf.AddCommand("query-status", nil, "return", statusInfo)
1731 cfg := QMPConfig{
1732 Logger: qmpTestLogger{},
1733 MaxCapacity: 1024,
1734 }
1735 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1736 checkVersion(t, connectedCh)
1737 info, err := q.ExecuteQueryStatus(context.Background())
1738 if err != nil {
1739 t.Fatalf("Unexpected error: %v", err)
1740 }
1741 if reflect.DeepEqual(info, statusInfo) == false {
1742 t.Fatalf("Expected %v equals to %v", info, statusInfo)
1743 }
1744 q.Shutdown()
1745 <-disconnectedCh
1746 }
1747
1748 // Checks qom-set
1749 func TestExecQomSet(t *testing.T) {
1750 connectedCh := make(chan *QMPVersion)
1751 disconnectedCh := make(chan struct{})
1752 buf := newQMPTestCommandBuffer(t)
1753 buf.AddCommand("qom-set", nil, "return", nil)
1754 cfg := QMPConfig{Logger: qmpTestLogger{}}
1755 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1756 checkVersion(t, connectedCh)
1757 err := q.ExecQomSet(context.Background(), "virtiomem0", "requested-size", 1024)
1758 if err != nil {
1759 t.Fatalf("Unexpected error: %v", err)
1760 }
1761 q.Shutdown()
1762 <-disconnectedCh
1763 }
1764
1765 // Checks qom-get
1766 func TestExecQomGet(t *testing.T) {
1767 connectedCh := make(chan *QMPVersion)
1768 disconnectedCh := make(chan struct{})
1769 buf := newQMPTestCommandBuffer(t)
1770 buf.AddCommand("qom-get", nil, "return", "container")
1771 cfg := QMPConfig{Logger: qmpTestLogger{}}
1772 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1773 checkVersion(t, connectedCh)
1774 val, err := q.ExecQomGet(context.Background(), "/", "type")
1775 if err != nil {
1776 t.Fatalf("Unexpected error: %v", err)
1777 }
1778 vals, ok := val.(string)
1779 if !ok {
1780 t.Fatalf("Unexpected type in qom-get")
1781 }
1782 if vals != "container" {
1783 t.Fatalf("Unpexected value in qom-get")
1784 }
1785 q.Shutdown()
1786 <-disconnectedCh
1787 }
1788
1789 // Checks dump-guest-memory
1790 func TestExecuteDumpGuestMemory(t *testing.T) {
1791 connectedCh := make(chan *QMPVersion)
1792 disconnectedCh := make(chan struct{})
1793 buf := newQMPTestCommandBuffer(t)
1794 buf.AddCommand("dump-guest-memory", nil, "return", nil)
1795 cfg := QMPConfig{Logger: qmpTestLogger{}}
1796 q := startQMPLoop(buf, cfg, connectedCh, disconnectedCh)
1797 checkVersion(t, connectedCh)
1798
1799 err := q.ExecuteDumpGuestMemory(context.Background(), "file:/tmp/dump.xxx.yyy", false, "elf")
1800 if err != nil {
1801 t.Fatalf("Unexpected error: %v", err)
1802 }
1803
1804 q.Shutdown()
1805 <-disconnectedCh
1806 }