blob: e1da7ae72bf8d87b2ebe662de1251cfc58c0bb05 [file] [log] [blame]
John DeNisco68b0ee32017-09-27 16:35:23 -04001# 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."""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020015from __future__ import absolute_import, division
John DeNisco68b0ee32017-09-27 16:35:23 -040016
17from time import time, sleep
18import json
19import logging
20
21from vpplib.VPPUtil import VPPUtil
22from vpplib.constants import Constants
23
24
25class NodeType(object):
26 """Defines node types used in topology dictionaries."""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020027
John DeNisco68b0ee32017-09-27 16:35:23 -040028 # Device Under Test (this node has VPP running on it)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020029 DUT = "DUT"
John DeNisco68b0ee32017-09-27 16:35:23 -040030 # Traffic Generator (this node has traffic generator on it)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020031 TG = "TG"
John DeNisco68b0ee32017-09-27 16:35:23 -040032 # Virtual Machine (this node running on DUT node)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020033 VM = "VM"
John DeNisco68b0ee32017-09-27 16:35:23 -040034
35
36class QemuUtils(object):
37 """QEMU utilities."""
38
John DeNiscoa7da67f2018-01-26 14:55:33 -050039 # noinspection PyDictCreation
John DeNisco68b0ee32017-09-27 16:35:23 -040040 def __init__(self, qemu_id=1):
41 self._qemu_id = qemu_id
42 # Path to QEMU binary
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020043 self._qemu_bin = "/usr/bin/qemu-system-x86_64"
John DeNisco68b0ee32017-09-27 16:35:23 -040044 # QEMU Machine Protocol socket
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020045 self._qmp_sock = "/tmp/qmp{0}.sock".format(self._qemu_id)
John DeNisco68b0ee32017-09-27 16:35:23 -040046 # QEMU Guest Agent socket
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020047 self._qga_sock = "/tmp/qga{0}.sock".format(self._qemu_id)
John DeNisco68b0ee32017-09-27 16:35:23 -040048 # QEMU PID file
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020049 self._pid_file = "/tmp/qemu{0}.pid".format(self._qemu_id)
John DeNisco68b0ee32017-09-27 16:35:23 -040050 self._qemu_opt = {}
51 # Default 1 CPU.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020052 self._qemu_opt["smp"] = "-smp 1,sockets=1,cores=1,threads=1"
John DeNisco68b0ee32017-09-27 16:35:23 -040053 # Daemonize the QEMU process after initialization. Default one
54 # management interface.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020055 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
John DeNisco68b0ee32017-09-27 16:35:23 -040063 # Default serial console port
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020064 self._qemu_opt["serial_port"] = 4555 + qemu_id
John DeNisco68b0ee32017-09-27 16:35:23 -040065 # Default 512MB virtual RAM
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020066 self._qemu_opt["mem_size"] = 512
John DeNisco68b0ee32017-09-27 16:35:23 -040067 # Default huge page mount point, required for Vhost-user interfaces.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020068 self._qemu_opt["huge_mnt"] = "/mnt/huge"
John DeNisco68b0ee32017-09-27 16:35:23 -040069 # Default do not allocate huge pages.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020070 self._qemu_opt["huge_allocate"] = False
John DeNisco68b0ee32017-09-27 16:35:23 -040071 # Default image for CSIT virl setup
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020072 self._qemu_opt["disk_image"] = "/var/lib/vm/vhost-nested.img"
John DeNisco68b0ee32017-09-27 16:35:23 -040073 # VM node info dict
74 self._vm_info = {
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020075 "type": NodeType.VM,
76 "port": self._qemu_opt["ssh_fwd_port"],
77 "username": "cisco",
78 "password": "cisco",
79 "interfaces": {},
John DeNisco68b0ee32017-09-27 16:35:23 -040080 }
81 # Virtio queue count
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020082 self._qemu_opt["queues"] = 1
John DeNisco68b0ee32017-09-27 16:35:23 -040083 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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200108 self._qemu_opt["smp"] = "-smp {},cores={},threads={},sockets={}".format(
109 cpus, cores, threads, sockets
110 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400111
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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200118 self._qemu_opt["ssh_fwd_port"] = fwd_port
119 self._vm_info["port"] = fwd_port
John DeNisco68b0ee32017-09-27 16:35:23 -0400120
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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200127 self._qemu_opt["serial_port"] = port
John DeNisco68b0ee32017-09-27 16:35:23 -0400128
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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200135 self._qemu_opt["mem_size"] = int(mem_size)
John DeNisco68b0ee32017-09-27 16:35:23 -0400136
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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200143 self._qemu_opt["huge_mnt"] = huge_mnt
John DeNisco68b0ee32017-09-27 16:35:23 -0400144
145 def qemu_set_huge_allocate(self):
146 """Set flag to allocate more huge pages if needed."""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200147 self._qemu_opt["huge_allocate"] = True
John DeNisco68b0ee32017-09-27 16:35:23 -0400148
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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200155 self._qemu_opt["disk_image"] = disk_image
John DeNisco68b0ee32017-09-27 16:35:23 -0400156
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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200164 qemu_cpus = self._qemu_qmp_exec("query-cpus")["return"]
John DeNisco68b0ee32017-09-27 16:35:23 -0400165
166 if len(qemu_cpus) != len(host_cpus):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200167 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")
John DeNisco68b0ee32017-09-27 16:35:23 -0400173
174 for qemu_cpu, host_cpu in zip(qemu_cpus, host_cpus):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200175 cmd = "taskset -pc {0} {1}".format(host_cpu, qemu_cpu["thread_id"])
John DeNisco68b0ee32017-09-27 16:35:23 -0400176 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
177 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200178 logging.debug("Set affinity failed {0}".format(stderr))
179 raise RuntimeError(
180 "Set affinity failed on {0}".format(self._node["host"])
181 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400182
183 def qemu_set_scheduler_policy(self):
184 """Set scheduler policy to SCHED_RR with priority 1 for all Qemu CPU
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200185 processes.
John DeNisco68b0ee32017-09-27 16:35:23 -0400186
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200187 :raises RuntimeError: Set scheduler policy failed.
John DeNisco68b0ee32017-09-27 16:35:23 -0400188 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200189 qemu_cpus = self._qemu_qmp_exec("query-cpus")["return"]
John DeNisco68b0ee32017-09-27 16:35:23 -0400190
191 for qemu_cpu in qemu_cpus:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200192 cmd = "chrt -r -p 1 {0}".format(qemu_cpu["thread_id"])
John DeNisco68b0ee32017-09-27 16:35:23 -0400193 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
194 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200195 logging.debug("Set SCHED_RR failed {0}".format(stderr))
196 raise RuntimeError(
197 "Set SCHED_RR failed on {0}".format(self._node["host"])
198 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400199
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
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200207 self._vm_info["host"] = node["host"]
John DeNisco68b0ee32017-09-27 16:35:23 -0400208
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.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200222 chardev = " -chardev socket,id=char{0},path={1}".format(self._vhost_id, socket)
John DeNisco68b0ee32017-09-27 16:35:23 -0400223 if server is True:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200224 chardev += ",server"
225 self._qemu_opt["options"] += chardev
John DeNisco68b0ee32017-09-27 16:35:23 -0400226 # Create Vhost-user network backend.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200227 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
John DeNisco68b0ee32017-09-27 16:35:23 -0400231 # 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:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200235 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 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400240 # Create Virtio network device.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200241 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
John DeNisco68b0ee32017-09-27 16:35:23 -0400245 # Add interface MAC and socket to the node dict
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200246 if_data = {"mac_address": mac, "socket": socket}
247 if_name = "vhost{}".format(self._vhost_id)
248 self._vm_info["interfaces"][if_name] = if_data
John DeNisco68b0ee32017-09-27 16:35:23 -0400249 # 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.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200264 qmp_cmd = (
265 'echo "{ \\"execute\\": \\"qmp_capabilities\\" }'
266 '{ \\"execute\\": \\"'
267 + cmd
268 + '\\" }" | sudo -S socat - UNIX-CONNECT:'
269 + self._qmp_sock
270 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400271
272 (ret_code, stdout, stderr) = self._ssh.exec_command(qmp_cmd)
273 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200274 logging.debug("QMP execute failed {0}".format(stderr))
275 raise RuntimeError(
276 'QMP execute "{0}"' " failed on {1}".format(cmd, self._node["host"])
277 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400278 logging.debug(stdout)
279 # Skip capabilities negotiation messages.
280 out_list = stdout.splitlines()
281 if len(out_list) < 3:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200282 raise RuntimeError("Invalid QMP output on {0}".format(self._node["host"]))
John DeNisco68b0ee32017-09-27 16:35:23 -0400283 return json.loads(out_list[2])
284
285 def _qemu_qga_flush(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200286 """Flush the QGA parser state"""
287 qga_cmd = (
288 '(printf "\xFF"; sleep 1) | '
289 "sudo -S socat - UNIX-CONNECT:" + self._qga_sock
290 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400291 # TODO: probably need something else
292 (ret_code, stdout, stderr) = self._ssh.exec_command(qga_cmd)
293 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200294 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 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400298 logging.debug(stdout)
299 if not stdout:
300 return {}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200301 return json.loads(stdout.split("\n", 1)[0])
John DeNisco68b0ee32017-09-27 16:35:23 -0400302
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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200311 qga_cmd = (
312 '(echo "{ \\"execute\\": \\"'
313 + cmd
314 + '\\" }"; sleep 1) | sudo -S socat - UNIX-CONNECT:'
315 + self._qga_sock
316 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400317 (ret_code, stdout, stderr) = self._ssh.exec_command(qga_cmd)
318 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200319 logging.debug("QGA execute failed {0}".format(stderr))
320 raise RuntimeError(
321 'QGA execute "{0}"' " failed on {1}".format(cmd, self._node["host"])
322 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400323 logging.debug(stdout)
324 if not stdout:
325 return {}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200326 return json.loads(stdout.split("\n", 1)[0])
John DeNisco68b0ee32017-09-27 16:35:23 -0400327
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:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200339 raise RuntimeError(
340 "timeout, VM {0} not booted on {1}".format(
341 self._qemu_opt["disk_image"], self._node["host"]
342 )
343 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400344 out = None
345 try:
346 self._qemu_qga_flush()
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200347 out = self._qemu_qga_exec("guest-ping")
John DeNisco68b0ee32017-09-27 16:35:23 -0400348 except ValueError:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200349 logging.debug("QGA guest-ping unexpected output {}".format(out))
John DeNisco68b0ee32017-09-27 16:35:23 -0400350 # Empty output - VM not booted yet
351 if not out:
352 sleep(5)
353 # Non-error return - VM booted
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200354 elif out.get("return") is not None:
John DeNisco68b0ee32017-09-27 16:35:23 -0400355 break
356 # Skip error and wait
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200357 elif out.get("error") is not None:
John DeNisco68b0ee32017-09-27 16:35:23 -0400358 sleep(5)
359 else:
360 # If there is an unexpected output from QGA guest-info, try
361 # again until timeout.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200362 logging.debug("QGA guest-ping unexpected output {}".format(out))
John DeNisco68b0ee32017-09-27 16:35:23 -0400363
Paul Vinciguerra339bc6b2018-12-19 02:05:25 -0800364 logging.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200365 "VM {0} booted on {1}".format(
366 self._qemu_opt["disk_image"], self._node["host"]
367 )
368 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400369
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"}]}
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200375 out = self._qemu_qga_exec("guest-network-get-interfaces")
376 interfaces = out.get("return")
John DeNisco68b0ee32017-09-27 16:35:23 -0400377 mac_name = {}
378 if not interfaces:
Paul Vinciguerra339bc6b2018-12-19 02:05:25 -0800379 raise RuntimeError(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200380 "Get VM {0} interface list failed on {1}".format(
381 self._qemu_opt["disk_image"], self._node["host"]
382 )
383 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400384 # Create MAC-name dict
385 for interface in interfaces:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200386 if "hardware-address" not in interface:
John DeNisco68b0ee32017-09-27 16:35:23 -0400387 continue
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200388 mac_name[interface["hardware-address"]] = interface["name"]
John DeNisco68b0ee32017-09-27 16:35:23 -0400389 # Match interface by MAC and save interface name
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200390 for interface in self._vm_info["interfaces"].values():
391 mac = interface.get("mac_address")
John DeNisco68b0ee32017-09-27 16:35:23 -0400392 if_name = mac_name.get(mac)
393 if if_name is None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200394 logging.debug("Interface name for MAC {} not found".format(mac))
John DeNisco68b0ee32017-09-27 16:35:23 -0400395 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200396 interface["name"] = if_name
John DeNisco68b0ee32017-09-27 16:35:23 -0400397
398 def _huge_page_check(self, allocate=False):
399 """Huge page check."""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200400 huge_mnt = self._qemu_opt.get("huge_mnt")
401 mem_size = self._qemu_opt.get("mem_size")
John DeNisco68b0ee32017-09-27 16:35:23 -0400402
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))
Paul Vinciguerra339bc6b2018-12-19 02:05:25 -0800413 huge_to_allocate = ((mem_needed // huge_size) * 2) + huge_total
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200414 max_map_count = huge_to_allocate * 4
Paul Vinciguerra339bc6b2018-12-19 02:05:25 -0800415 # Increase maximum number of memory map areas a
416 # process may have
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200417 cmd = 'echo "{0}" | sudo tee /proc/sys/vm/max_map_count'.format(
418 max_map_count
419 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400420 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
421 # Increase hugepage count
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200422 cmd = 'echo "{0}" | sudo tee /proc/sys/vm/nr_hugepages'.format(
423 huge_to_allocate
424 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400425 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
426 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200427 logging.debug("Mount huge pages failed {0}".format(stderr))
Paul Vinciguerra339bc6b2018-12-19 02:05:25 -0800428 raise RuntimeError(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200429 "Mount huge pages failed on {0}".format(self._node["host"])
430 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400431 # If we do not want to allocate dynamicaly end with error
432 else:
433 raise RuntimeError(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200434 "Not enough free huge pages: {0}, "
435 "{1} MB".format(huge_free, huge_free * huge_size)
John DeNisco68b0ee32017-09-27 16:35:23 -0400436 )
437 # Check if huge pages mount point exist
438 has_huge_mnt = False
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200439 (_, output, _) = self._ssh.exec_command("cat /proc/mounts")
John DeNisco68b0ee32017-09-27 16:35:23 -0400440 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()
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200444 if mount[2] == "hugetlbfs" and mount[1] == huge_mnt:
John DeNisco68b0ee32017-09-27 16:35:23 -0400445 has_huge_mnt = True
446 break
447 # If huge page mount point not exist create one
448 if not has_huge_mnt:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200449 cmd = "mkdir -p {0}".format(huge_mnt)
John DeNisco68b0ee32017-09-27 16:35:23 -0400450 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
451 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200452 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)
John DeNisco68b0ee32017-09-27 16:35:23 -0400457 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
458 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200459 logging.debug("Mount huge pages failed {0}".format(stderr))
460 raise RuntimeError(
461 "Mount huge pages failed on {0}".format(self._node["host"])
462 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400463
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:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200479 logging.debug("Reading huge page size information failed")
John DeNisco68b0ee32017-09-27 16:35:23 -0400480 else:
481 break
482 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200483 raise RuntimeError("Getting huge page size information failed.")
John DeNisco68b0ee32017-09-27 16:35:23 -0400484 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
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200497 cmd_huge_free = (
498 "cat /sys/kernel/mm/hugepages/hugepages-{0}kB/"
499 "free_hugepages".format(huge_size)
500 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400501 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:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200507 logging.debug("Reading free huge pages information failed")
John DeNisco68b0ee32017-09-27 16:35:23 -0400508 else:
509 break
510 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200511 raise RuntimeError("Getting free huge pages information failed.")
John DeNisco68b0ee32017-09-27 16:35:23 -0400512 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
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200525 cmd_huge_total = (
526 "cat /sys/kernel/mm/hugepages/hugepages-{0}kB/"
527 "nr_hugepages".format(huge_size)
528 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400529 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:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200535 logging.debug("Reading total huge pages information failed")
John DeNisco68b0ee32017-09-27 16:35:23 -0400536 else:
537 break
538 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200539 raise RuntimeError("Getting total huge pages information failed.")
John DeNisco68b0ee32017-09-27 16:35:23 -0400540 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
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200551 ssh_fwd = "-net user,hostfwd=tcp::{0}-:22".format(
552 self._qemu_opt.get("ssh_fwd_port")
553 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400554 # Memory and huge pages
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200555 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 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400561
562 # By default check only if hugepages are available.
563 # If 'huge_allocate' is set to true try to allocate as well.
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200564 self._huge_page_check(allocate=self._qemu_opt.get("huge_allocate"))
John DeNisco68b0ee32017-09-27 16:35:23 -0400565
566 # Disk option
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200567 drive = "-drive file={0},format=raw,cache=none,if=virtio".format(
568 self._qemu_opt.get("disk_image")
569 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400570 # Setup QMP via unix socket
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200571 qmp = "-qmp unix:{0},server,nowait".format(self._qmp_sock)
John DeNisco68b0ee32017-09-27 16:35:23 -0400572 # Setup serial console
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200573 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 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400579 # Setup QGA via chardev (unix socket) and isa-serial channel
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200580 qga = (
581 "-chardev socket,path={0},server,nowait,id=qga0 "
582 "-device isa-serial,chardev=qga0".format(self._qga_sock)
583 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400584 # Graphic setup
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200585 graphic = "-monitor none -display none -vga none"
John DeNisco68b0ee32017-09-27 16:35:23 -0400586 # PID file
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200587 pid = "-pidfile {}".format(self._pid_file)
John DeNisco68b0ee32017-09-27 16:35:23 -0400588
589 # Run QEMU
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200590 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 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400603 (ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd, timeout=300)
604 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200605 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")
John DeNisco68b0ee32017-09-27 16:35:23 -0400608 # 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."""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200622 out = self._qemu_qmp_exec("quit")
623 err = out.get("error")
John DeNisco68b0ee32017-09-27 16:35:23 -0400624 if err is not None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200625 raise RuntimeError(
626 "QEMU quit failed on {0}, error: {1}".format(
627 self._node["host"], json.dumps(err)
628 )
629 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400630
631 def qemu_system_powerdown(self):
632 """Power down the system (if supported)."""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200633 out = self._qemu_qmp_exec("system_powerdown")
634 err = out.get("error")
John DeNisco68b0ee32017-09-27 16:35:23 -0400635 if err is not None:
636 raise RuntimeError(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200637 "QEMU system powerdown failed on {0}, "
638 "error: {1}".format(self._node["host"], json.dumps(err))
John DeNisco68b0ee32017-09-27 16:35:23 -0400639 )
640
641 def qemu_system_reset(self):
642 """Reset the system."""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200643 out = self._qemu_qmp_exec("system_reset")
644 err = out.get("error")
John DeNisco68b0ee32017-09-27 16:35:23 -0400645 if err is not None:
646 raise RuntimeError(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200647 "QEMU system reset failed on {0}, "
648 "error: {1}".format(self._node["host"], json.dumps(err))
649 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400650
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
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200655 self._ssh.exec_command_sudo("chmod +r {}".format(self._pid_file))
656 self._ssh.exec_command_sudo("kill -SIGKILL $(cat {})".format(self._pid_file))
John DeNisco68b0ee32017-09-27 16:35:23 -0400657 # Delete PID file
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200658 cmd = "rm -f {}".format(self._pid_file)
John DeNisco68b0ee32017-09-27 16:35:23 -0400659 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)
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200669 self._ssh.exec_command_sudo("pkill -SIGKILL qemu")
John DeNisco68b0ee32017-09-27 16:35:23 -0400670
671 def qemu_clear_socks(self):
672 """Remove all sockets created by QEMU."""
673 # If serial console port still open kill process
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200674 cmd = "fuser -k {}/tcp".format(self._qemu_opt.get("serial_port"))
John DeNisco68b0ee32017-09-27 16:35:23 -0400675 self._ssh.exec_command_sudo(cmd)
676 # Delete all created sockets
677 for sock in self._socks:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200678 cmd = "rm -f {}".format(sock)
John DeNisco68b0ee32017-09-27 16:35:23 -0400679 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 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200705 out = self._qemu_qmp_exec("query-status")
706 ret = out.get("return")
John DeNisco68b0ee32017-09-27 16:35:23 -0400707 if ret is not None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200708 return ret.get("status")
John DeNisco68b0ee32017-09-27 16:35:23 -0400709 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200710 err = out.get("error")
John DeNisco68b0ee32017-09-27 16:35:23 -0400711 raise RuntimeError(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200712 "QEMU query-status failed on {0}, "
713 "error: {1}".format(self._node["host"], json.dumps(err))
714 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400715
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
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200729 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 ""
John DeNisco68b0ee32017-09-27 16:35:23 -0400733
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200734 (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 )
John DeNisco68b0ee32017-09-27 16:35:23 -0400745
746 if int(ret_code) != 0:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200747 logging.debug("QEMU build failed {0}".format(stdout + stderr))
748 raise RuntimeError("QEMU build failed on {0}".format(node["host"]))