tests: replace pycodestyle with black
[vpp.git] / extras / vpp_config / vpplib / QemuUtils.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """QEMU utilities library."""
15 from __future__ import absolute_import, division
16
17 from time import time, sleep
18 import json
19 import logging
20
21 from vpplib.VPPUtil import VPPUtil
22 from vpplib.constants import Constants
23
24
25 class NodeType(object):
26     """Defines node types used in topology dictionaries."""
27
28     # Device Under Test (this node has VPP running on it)
29     DUT = "DUT"
30     # Traffic Generator (this node has traffic generator on it)
31     TG = "TG"
32     # Virtual Machine (this node running on DUT node)
33     VM = "VM"
34
35
36 class QemuUtils(object):
37     """QEMU utilities."""
38
39     # noinspection PyDictCreation
40     def __init__(self, qemu_id=1):
41         self._qemu_id = qemu_id
42         # Path to QEMU binary
43         self._qemu_bin = "/usr/bin/qemu-system-x86_64"
44         # QEMU Machine Protocol socket
45         self._qmp_sock = "/tmp/qmp{0}.sock".format(self._qemu_id)
46         # QEMU Guest Agent socket
47         self._qga_sock = "/tmp/qga{0}.sock".format(self._qemu_id)
48         # QEMU PID file
49         self._pid_file = "/tmp/qemu{0}.pid".format(self._qemu_id)
50         self._qemu_opt = {}
51         # Default 1 CPU.
52         self._qemu_opt["smp"] = "-smp 1,sockets=1,cores=1,threads=1"
53         # Daemonize the QEMU process after initialization. Default one
54         # management interface.
55         self._qemu_opt["options"] = (
56             "-cpu host -daemonize -enable-kvm "
57             "-machine pc,accel=kvm,usb=off,mem-merge=off "
58             "-net nic,macaddr=52:54:00:00:{0:02x}:ff -balloon none".format(
59                 self._qemu_id
60             )
61         )
62         self._qemu_opt["ssh_fwd_port"] = 10021 + qemu_id
63         # Default serial console port
64         self._qemu_opt["serial_port"] = 4555 + qemu_id
65         # Default 512MB virtual RAM
66         self._qemu_opt["mem_size"] = 512
67         # Default huge page mount point, required for Vhost-user interfaces.
68         self._qemu_opt["huge_mnt"] = "/mnt/huge"
69         # Default do not allocate huge pages.
70         self._qemu_opt["huge_allocate"] = False
71         # Default image for CSIT virl setup
72         self._qemu_opt["disk_image"] = "/var/lib/vm/vhost-nested.img"
73         # VM node info dict
74         self._vm_info = {
75             "type": NodeType.VM,
76             "port": self._qemu_opt["ssh_fwd_port"],
77             "username": "cisco",
78             "password": "cisco",
79             "interfaces": {},
80         }
81         # Virtio queue count
82         self._qemu_opt["queues"] = 1
83         self._vhost_id = 0
84         self._ssh = None
85         self._node = None
86         self._socks = [self._qmp_sock, self._qga_sock]
87
88     def qemu_set_bin(self, path):
89         """Set binary path for QEMU.
90
91         :param path: Absolute path in filesystem.
92         :type path: str
93         """
94         self._qemu_bin = path
95
96     def qemu_set_smp(self, cpus, cores, threads, sockets):
97         """Set SMP option for QEMU.
98
99         :param cpus: Number of CPUs.
100         :param cores: Number of CPU cores on one socket.
101         :param threads: Number of threads on one CPU core.
102         :param sockets: Number of discrete sockets in the system.
103         :type cpus: int
104         :type cores: int
105         :type threads: int
106         :type sockets: int
107         """
108         self._qemu_opt["smp"] = "-smp {},cores={},threads={},sockets={}".format(
109             cpus, cores, threads, sockets
110         )
111
112     def qemu_set_ssh_fwd_port(self, fwd_port):
113         """Set host port for guest SSH forwarding.
114
115         :param fwd_port: Port number on host for guest SSH forwarding.
116         :type fwd_port: int
117         """
118         self._qemu_opt["ssh_fwd_port"] = fwd_port
119         self._vm_info["port"] = fwd_port
120
121     def qemu_set_serial_port(self, port):
122         """Set serial console port.
123
124         :param port: Serial console port.
125         :type port: int
126         """
127         self._qemu_opt["serial_port"] = port
128
129     def qemu_set_mem_size(self, mem_size):
130         """Set virtual RAM size.
131
132         :param mem_size: RAM size in Mega Bytes.
133         :type mem_size: int
134         """
135         self._qemu_opt["mem_size"] = int(mem_size)
136
137     def qemu_set_huge_mnt(self, huge_mnt):
138         """Set hugefile mount point.
139
140         :param huge_mnt: System hugefile mount point.
141         :type huge_mnt: int
142         """
143         self._qemu_opt["huge_mnt"] = huge_mnt
144
145     def qemu_set_huge_allocate(self):
146         """Set flag to allocate more huge pages if needed."""
147         self._qemu_opt["huge_allocate"] = True
148
149     def qemu_set_disk_image(self, disk_image):
150         """Set disk image.
151
152         :param disk_image: Path of the disk image.
153         :type disk_image: str
154         """
155         self._qemu_opt["disk_image"] = disk_image
156
157     def qemu_set_affinity(self, *host_cpus):
158         """Set qemu affinity by getting thread PIDs via QMP and taskset to list
159         of CPU cores.
160
161         :param host_cpus: List of CPU cores.
162         :type host_cpus: list
163         """
164         qemu_cpus = self._qemu_qmp_exec("query-cpus")["return"]
165
166         if len(qemu_cpus) != len(host_cpus):
167             logging.debug(
168                 "Host CPU count {0}, Qemu Thread count {1}".format(
169                     len(host_cpus), len(qemu_cpus)
170                 )
171             )
172             raise ValueError("Host CPU count must match Qemu Thread count")
173
174         for qemu_cpu, host_cpu in zip(qemu_cpus, host_cpus):
175             cmd = "taskset -pc {0} {1}".format(host_cpu, qemu_cpu["thread_id"])
176             (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
177             if int(ret_code) != 0:
178                 logging.debug("Set affinity failed {0}".format(stderr))
179                 raise RuntimeError(
180                     "Set affinity failed on {0}".format(self._node["host"])
181                 )
182
183     def qemu_set_scheduler_policy(self):
184         """Set scheduler policy to SCHED_RR with priority 1 for all Qemu CPU
185          processes.
186
187         :raises RuntimeError: Set scheduler policy failed.
188         """
189         qemu_cpus = self._qemu_qmp_exec("query-cpus")["return"]
190
191         for qemu_cpu in qemu_cpus:
192             cmd = "chrt -r -p 1 {0}".format(qemu_cpu["thread_id"])
193             (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
194             if int(ret_code) != 0:
195                 logging.debug("Set SCHED_RR failed {0}".format(stderr))
196                 raise RuntimeError(
197                     "Set SCHED_RR failed on {0}".format(self._node["host"])
198                 )
199
200     def qemu_set_node(self, node):
201         """Set node to run QEMU on.
202
203         :param node: Node to run QEMU on.
204         :type node: dict
205         """
206         self._node = node
207         self._vm_info["host"] = node["host"]
208
209     def qemu_add_vhost_user_if(self, socket, server=True, mac=None):
210         """Add Vhost-user interface.
211
212         :param socket: Path of the unix socket.
213         :param server: If True the socket shall be a listening socket.
214         :param mac: Vhost-user interface MAC address (optional, otherwise is
215             used auto-generated MAC 52:54:00:00:xx:yy).
216         :type socket: str
217         :type server: bool
218         :type mac: str
219         """
220         self._vhost_id += 1
221         # Create unix socket character device.
222         chardev = " -chardev socket,id=char{0},path={1}".format(self._vhost_id, socket)
223         if server is True:
224             chardev += ",server"
225         self._qemu_opt["options"] += chardev
226         # Create Vhost-user network backend.
227         netdev = " -netdev vhost-user,id=vhost{0},chardev=char{0},queues={1}".format(
228             self._vhost_id, self._qemu_opt["queues"]
229         )
230         self._qemu_opt["options"] += netdev
231         # If MAC is not specified use auto-generated MAC address based on
232         # template 52:54:00:00:<qemu_id>:<vhost_id>, e.g. vhost1 MAC of QEMU
233         #  with ID 1 is 52:54:00:00:01:01
234         if mac is None:
235             mac = "52:54:00:00:{0:02x}:{1:02x}".format(self._qemu_id, self._vhost_id)
236         extend_options = (
237             "mq=on,csum=off,gso=off,guest_tso4=off,"
238             "guest_tso6=off,guest_ecn=off,mrg_rxbuf=off"
239         )
240         # Create Virtio network device.
241         device = " -device virtio-net-pci,netdev=vhost{0},mac={1},{2}".format(
242             self._vhost_id, mac, extend_options
243         )
244         self._qemu_opt["options"] += device
245         # Add interface MAC and socket to the node dict
246         if_data = {"mac_address": mac, "socket": socket}
247         if_name = "vhost{}".format(self._vhost_id)
248         self._vm_info["interfaces"][if_name] = if_data
249         # Add socket to the socket list
250         self._socks.append(socket)
251
252     def _qemu_qmp_exec(self, cmd):
253         """Execute QMP command.
254
255         QMP is JSON based protocol which allows to control QEMU instance.
256
257         :param cmd: QMP command to execute.
258         :type cmd: str
259         :return: Command output in python representation of JSON format. The
260             { "return": {} } response is QMP's success response. An error
261             response will contain the "error" keyword instead of "return".
262         """
263         # To enter command mode, the qmp_capabilities command must be issued.
264         qmp_cmd = (
265             'echo "{ \\"execute\\": \\"qmp_capabilities\\" }'
266             '{ \\"execute\\": \\"'
267             + cmd
268             + '\\" }" | sudo -S socat - UNIX-CONNECT:'
269             + self._qmp_sock
270         )
271
272         (ret_code, stdout, stderr) = self._ssh.exec_command(qmp_cmd)
273         if int(ret_code) != 0:
274             logging.debug("QMP execute failed {0}".format(stderr))
275             raise RuntimeError(
276                 'QMP execute "{0}"' " failed on {1}".format(cmd, self._node["host"])
277             )
278         logging.debug(stdout)
279         # Skip capabilities negotiation messages.
280         out_list = stdout.splitlines()
281         if len(out_list) < 3:
282             raise RuntimeError("Invalid QMP output on {0}".format(self._node["host"]))
283         return json.loads(out_list[2])
284
285     def _qemu_qga_flush(self):
286         """Flush the QGA parser state"""
287         qga_cmd = (
288             '(printf "\xFF"; sleep 1) | '
289             "sudo -S socat - UNIX-CONNECT:" + self._qga_sock
290         )
291         # TODO: probably need something else
292         (ret_code, stdout, stderr) = self._ssh.exec_command(qga_cmd)
293         if int(ret_code) != 0:
294             logging.debug("QGA execute failed {0}".format(stderr))
295             raise RuntimeError(
296                 'QGA execute "{0}" ' "failed on {1}".format(qga_cmd, self._node["host"])
297             )
298         logging.debug(stdout)
299         if not stdout:
300             return {}
301         return json.loads(stdout.split("\n", 1)[0])
302
303     def _qemu_qga_exec(self, cmd):
304         """Execute QGA command.
305
306         QGA provide access to a system-level agent via standard QMP commands.
307
308         :param cmd: QGA command to execute.
309         :type cmd: str
310         """
311         qga_cmd = (
312             '(echo "{ \\"execute\\": \\"'
313             + cmd
314             + '\\" }"; sleep 1) | sudo -S socat - UNIX-CONNECT:'
315             + self._qga_sock
316         )
317         (ret_code, stdout, stderr) = self._ssh.exec_command(qga_cmd)
318         if int(ret_code) != 0:
319             logging.debug("QGA execute failed {0}".format(stderr))
320             raise RuntimeError(
321                 'QGA execute "{0}"' " failed on {1}".format(cmd, self._node["host"])
322             )
323         logging.debug(stdout)
324         if not stdout:
325             return {}
326         return json.loads(stdout.split("\n", 1)[0])
327
328     def _wait_until_vm_boot(self, timeout=60):
329         """Wait until QEMU VM is booted.
330
331         Ping QEMU guest agent each 5s until VM booted or timeout.
332
333         :param timeout: Waiting timeout in seconds (optional, default 60s).
334         :type timeout: int
335         """
336         start = time()
337         while True:
338             if time() - start > timeout:
339                 raise RuntimeError(
340                     "timeout, VM {0} not booted on {1}".format(
341                         self._qemu_opt["disk_image"], self._node["host"]
342                     )
343                 )
344             out = None
345             try:
346                 self._qemu_qga_flush()
347                 out = self._qemu_qga_exec("guest-ping")
348             except ValueError:
349                 logging.debug("QGA guest-ping unexpected output {}".format(out))
350             # Empty output - VM not booted yet
351             if not out:
352                 sleep(5)
353             # Non-error return - VM booted
354             elif out.get("return") is not None:
355                 break
356             # Skip error and wait
357             elif out.get("error") is not None:
358                 sleep(5)
359             else:
360                 # If there is an unexpected output from QGA guest-info, try
361                 # again until timeout.
362                 logging.debug("QGA guest-ping unexpected output {}".format(out))
363
364         logging.debug(
365             "VM {0} booted on {1}".format(
366                 self._qemu_opt["disk_image"], self._node["host"]
367             )
368         )
369
370     def _update_vm_interfaces(self):
371         """Update interface names in VM node dict."""
372         # Send guest-network-get-interfaces command via QGA, output example:
373         # {"return": [{"name": "eth0", "hardware-address": "52:54:00:00:04:01"},
374         # {"name": "eth1", "hardware-address": "52:54:00:00:04:02"}]}
375         out = self._qemu_qga_exec("guest-network-get-interfaces")
376         interfaces = out.get("return")
377         mac_name = {}
378         if not interfaces:
379             raise RuntimeError(
380                 "Get VM {0} interface list failed on {1}".format(
381                     self._qemu_opt["disk_image"], self._node["host"]
382                 )
383             )
384         # Create MAC-name dict
385         for interface in interfaces:
386             if "hardware-address" not in interface:
387                 continue
388             mac_name[interface["hardware-address"]] = interface["name"]
389         # Match interface by MAC and save interface name
390         for interface in self._vm_info["interfaces"].values():
391             mac = interface.get("mac_address")
392             if_name = mac_name.get(mac)
393             if if_name is None:
394                 logging.debug("Interface name for MAC {} not found".format(mac))
395             else:
396                 interface["name"] = if_name
397
398     def _huge_page_check(self, allocate=False):
399         """Huge page check."""
400         huge_mnt = self._qemu_opt.get("huge_mnt")
401         mem_size = self._qemu_opt.get("mem_size")
402
403         # Get huge pages information
404         huge_size = self._get_huge_page_size()
405         huge_free = self._get_huge_page_free(huge_size)
406         huge_total = self._get_huge_page_total(huge_size)
407
408         # Check if memory reqested by qemu is available on host
409         if (mem_size * 1024) > (huge_free * huge_size):
410             # If we want to allocate hugepage dynamically
411             if allocate:
412                 mem_needed = abs((huge_free * huge_size) - (mem_size * 1024))
413                 huge_to_allocate = ((mem_needed // huge_size) * 2) + huge_total
414                 max_map_count = huge_to_allocate * 4
415                 # Increase maximum number of memory map areas a
416                 # process may have
417                 cmd = 'echo "{0}" | sudo tee /proc/sys/vm/max_map_count'.format(
418                     max_map_count
419                 )
420                 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
421                 # Increase hugepage count
422                 cmd = 'echo "{0}" | sudo tee /proc/sys/vm/nr_hugepages'.format(
423                     huge_to_allocate
424                 )
425                 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
426                 if int(ret_code) != 0:
427                     logging.debug("Mount huge pages failed {0}".format(stderr))
428                     raise RuntimeError(
429                         "Mount huge pages failed on {0}".format(self._node["host"])
430                     )
431             # If we do not want to allocate dynamicaly end with error
432             else:
433                 raise RuntimeError(
434                     "Not enough free huge pages: {0}, "
435                     "{1} MB".format(huge_free, huge_free * huge_size)
436                 )
437         # Check if huge pages mount point exist
438         has_huge_mnt = False
439         (_, output, _) = self._ssh.exec_command("cat /proc/mounts")
440         for line in output.splitlines():
441             # Try to find something like:
442             # none /mnt/huge hugetlbfs rw,relatime,pagesize=2048k 0 0
443             mount = line.split()
444             if mount[2] == "hugetlbfs" and mount[1] == huge_mnt:
445                 has_huge_mnt = True
446                 break
447         # If huge page mount point not exist create one
448         if not has_huge_mnt:
449             cmd = "mkdir -p {0}".format(huge_mnt)
450             (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
451             if int(ret_code) != 0:
452                 logging.debug("Create mount dir failed: {0}".format(stderr))
453                 raise RuntimeError(
454                     "Create mount dir failed on {0}".format(self._node["host"])
455                 )
456             cmd = "mount -t hugetlbfs -o pagesize=2048k none {0}".format(huge_mnt)
457             (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
458             if int(ret_code) != 0:
459                 logging.debug("Mount huge pages failed {0}".format(stderr))
460                 raise RuntimeError(
461                     "Mount huge pages failed on {0}".format(self._node["host"])
462                 )
463
464     def _get_huge_page_size(self):
465         """Get default size of huge pages in system.
466
467         :returns: Default size of free huge pages in system.
468         :rtype: int
469         :raises: RuntimeError if reading failed for three times.
470         """
471         # TODO: remove to dedicated library
472         cmd_huge_size = "grep Hugepagesize /proc/meminfo | awk '{ print $2 }'"
473         for _ in range(3):
474             (ret, out, _) = self._ssh.exec_command_sudo(cmd_huge_size)
475             if ret == 0:
476                 try:
477                     huge_size = int(out)
478                 except ValueError:
479                     logging.debug("Reading huge page size information failed")
480                 else:
481                     break
482         else:
483             raise RuntimeError("Getting huge page size information failed.")
484         return huge_size
485
486     def _get_huge_page_free(self, huge_size):
487         """Get total number of huge pages in system.
488
489         :param huge_size: Size of hugepages.
490         :type huge_size: int
491         :returns: Number of free huge pages in system.
492         :rtype: int
493         :raises: RuntimeError if reading failed for three times.
494         """
495         # TODO: add numa aware option
496         # TODO: remove to dedicated library
497         cmd_huge_free = (
498             "cat /sys/kernel/mm/hugepages/hugepages-{0}kB/"
499             "free_hugepages".format(huge_size)
500         )
501         for _ in range(3):
502             (ret, out, _) = self._ssh.exec_command_sudo(cmd_huge_free)
503             if ret == 0:
504                 try:
505                     huge_free = int(out)
506                 except ValueError:
507                     logging.debug("Reading free huge pages information failed")
508                 else:
509                     break
510         else:
511             raise RuntimeError("Getting free huge pages information failed.")
512         return huge_free
513
514     def _get_huge_page_total(self, huge_size):
515         """Get total number of huge pages in system.
516
517         :param huge_size: Size of hugepages.
518         :type huge_size: int
519         :returns: Total number of huge pages in system.
520         :rtype: int
521         :raises: RuntimeError if reading failed for three times.
522         """
523         # TODO: add numa aware option
524         # TODO: remove to dedicated library
525         cmd_huge_total = (
526             "cat /sys/kernel/mm/hugepages/hugepages-{0}kB/"
527             "nr_hugepages".format(huge_size)
528         )
529         for _ in range(3):
530             (ret, out, _) = self._ssh.exec_command_sudo(cmd_huge_total)
531             if ret == 0:
532                 try:
533                     huge_total = int(out)
534                 except ValueError:
535                     logging.debug("Reading total huge pages information failed")
536                 else:
537                     break
538         else:
539             raise RuntimeError("Getting total huge pages information failed.")
540         return huge_total
541
542     def qemu_start(self):
543         """Start QEMU and wait until VM boot.
544
545         :return: VM node info.
546         :rtype: dict
547         .. note:: First set at least node to run QEMU on.
548         .. warning:: Starts only one VM on the node.
549         """
550         # SSH forwarding
551         ssh_fwd = "-net user,hostfwd=tcp::{0}-:22".format(
552             self._qemu_opt.get("ssh_fwd_port")
553         )
554         # Memory and huge pages
555         mem = (
556             "-object memory-backend-file,id=mem,size={0}M,mem-path={1},"
557             "share=on -m {0} -numa node,memdev=mem".format(
558                 self._qemu_opt.get("mem_size"), self._qemu_opt.get("huge_mnt")
559             )
560         )
561
562         # By default check only if hugepages are available.
563         # If 'huge_allocate' is set to true try to allocate as well.
564         self._huge_page_check(allocate=self._qemu_opt.get("huge_allocate"))
565
566         # Disk option
567         drive = "-drive file={0},format=raw,cache=none,if=virtio".format(
568             self._qemu_opt.get("disk_image")
569         )
570         # Setup QMP via unix socket
571         qmp = "-qmp unix:{0},server,nowait".format(self._qmp_sock)
572         # Setup serial console
573         serial = (
574             "-chardev socket,host=127.0.0.1,port={0},id=gnc0,server,"
575             "nowait -device isa-serial,chardev=gnc0".format(
576                 self._qemu_opt.get("serial_port")
577             )
578         )
579         # Setup QGA via chardev (unix socket) and isa-serial channel
580         qga = (
581             "-chardev socket,path={0},server,nowait,id=qga0 "
582             "-device isa-serial,chardev=qga0".format(self._qga_sock)
583         )
584         # Graphic setup
585         graphic = "-monitor none -display none -vga none"
586         # PID file
587         pid = "-pidfile {}".format(self._pid_file)
588
589         # Run QEMU
590         cmd = "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}".format(
591             self._qemu_bin,
592             self._qemu_opt.get("smp"),
593             mem,
594             ssh_fwd,
595             self._qemu_opt.get("options"),
596             drive,
597             qmp,
598             serial,
599             qga,
600             graphic,
601             pid,
602         )
603         (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd, timeout=300)
604         if int(ret_code) != 0:
605             logging.debug("QEMU start failed {0}".format(stderr))
606             raise RuntimeError("QEMU start failed on {0}".format(self._node["host"]))
607         logging.debug("QEMU running")
608         # Wait until VM boot
609         try:
610             self._wait_until_vm_boot()
611         except RuntimeError:
612             self.qemu_kill_all()
613             self.qemu_clear_socks()
614             raise
615         # Update interface names in VM node dict
616         self._update_vm_interfaces()
617         # Return VM node dict
618         return self._vm_info
619
620     def qemu_quit(self):
621         """Quit the QEMU emulator."""
622         out = self._qemu_qmp_exec("quit")
623         err = out.get("error")
624         if err is not None:
625             raise RuntimeError(
626                 "QEMU quit failed on {0}, error: {1}".format(
627                     self._node["host"], json.dumps(err)
628                 )
629             )
630
631     def qemu_system_powerdown(self):
632         """Power down the system (if supported)."""
633         out = self._qemu_qmp_exec("system_powerdown")
634         err = out.get("error")
635         if err is not None:
636             raise RuntimeError(
637                 "QEMU system powerdown failed on {0}, "
638                 "error: {1}".format(self._node["host"], json.dumps(err))
639             )
640
641     def qemu_system_reset(self):
642         """Reset the system."""
643         out = self._qemu_qmp_exec("system_reset")
644         err = out.get("error")
645         if err is not None:
646             raise RuntimeError(
647                 "QEMU system reset failed on {0}, "
648                 "error: {1}".format(self._node["host"], json.dumps(err))
649             )
650
651     def qemu_kill(self):
652         """Kill qemu process."""
653         # Note: in QEMU start phase there are 3 QEMU processes because we
654         # daemonize QEMU
655         self._ssh.exec_command_sudo("chmod +r {}".format(self._pid_file))
656         self._ssh.exec_command_sudo("kill -SIGKILL $(cat {})".format(self._pid_file))
657         # Delete PID file
658         cmd = "rm -f {}".format(self._pid_file)
659         self._ssh.exec_command_sudo(cmd)
660
661     def qemu_kill_all(self, node=None):
662         """Kill all qemu processes on DUT node if specified.
663
664         :param node: Node to kill all QEMU processes on.
665         :type node: dict
666         """
667         if node:
668             self.qemu_set_node(node)
669         self._ssh.exec_command_sudo("pkill -SIGKILL qemu")
670
671     def qemu_clear_socks(self):
672         """Remove all sockets created by QEMU."""
673         # If serial console port still open kill process
674         cmd = "fuser -k {}/tcp".format(self._qemu_opt.get("serial_port"))
675         self._ssh.exec_command_sudo(cmd)
676         # Delete all created sockets
677         for sock in self._socks:
678             cmd = "rm -f {}".format(sock)
679             self._ssh.exec_command_sudo(cmd)
680
681     def qemu_system_status(self):
682         """Return current VM status.
683
684         VM should be in following status:
685
686             - debug: QEMU running on a debugger
687             - finish-migrate: paused to finish the migration process
688             - inmigrate: waiting for an incoming migration
689             - internal-error: internal error has occurred
690             - io-error: the last IOP has failed
691             - paused: paused
692             - postmigrate: paused following a successful migrate
693             - prelaunch: QEMU was started with -S and guest has not started
694             - restore-vm: paused to restore VM state
695             - running: actively running
696             - save-vm: paused to save the VM state
697             - shutdown: shut down (and -no-shutdown is in use)
698             - suspended: suspended (ACPI S3)
699             - watchdog: watchdog action has been triggered
700             - guest-panicked: panicked as a result of guest OS panic
701
702         :return: VM status.
703         :rtype: str
704         """
705         out = self._qemu_qmp_exec("query-status")
706         ret = out.get("return")
707         if ret is not None:
708             return ret.get("status")
709         else:
710             err = out.get("error")
711             raise RuntimeError(
712                 "QEMU query-status failed on {0}, "
713                 "error: {1}".format(self._node["host"], json.dumps(err))
714             )
715
716     @staticmethod
717     def build_qemu(node, force_install=False, apply_patch=False):
718         """Build QEMU from sources.
719
720         :param node: Node to build QEMU on.
721         :param force_install: If True, then remove previous build.
722         :param apply_patch: If True, then apply patches from qemu_patches dir.
723         :type node: dict
724         :type force_install: bool
725         :type apply_patch: bool
726         :raises: RuntimeError if building QEMU failed.
727         """
728
729         directory = " --directory={0}".format(Constants.QEMU_INSTALL_DIR)
730         version = " --version={0}".format(Constants.QEMU_INSTALL_VERSION)
731         force = " --force" if force_install else ""
732         patch = " --patch" if apply_patch else ""
733
734         (ret_code, stdout, stderr) = VPPUtil.exec_command(
735             "sudo -E sh -c '{0}/{1}/qemu_build.sh{2}{3}{4}{5}'".format(
736                 Constants.REMOTE_FW_DIR,
737                 Constants.RESOURCES_LIB_SH,
738                 version,
739                 directory,
740                 force,
741                 patch,
742             ),
743             1000,
744         )
745
746         if int(ret_code) != 0:
747             logging.debug("QEMU build failed {0}".format(stdout + stderr))
748             raise RuntimeError("QEMU build failed on {0}".format(node["host"]))