+ :type qemu_id: int
+ :type smp: int
+ :type mem: int
+ :type vnf: str
+ :type img: str
+ """
+ self._vhost_id = 0
+ self._node = node
+ self._arch = Topology.get_node_arch(self._node)
+ self._opt = dict()
+
+ # Architecture specific options
+ if self._arch == u"aarch64":
+ dpdk_target = u"arm64-armv8a"
+ self._opt[u"machine_args"] = \
+ u"virt,accel=kvm,usb=off,mem-merge=off,gic-version=3"
+ self._opt[u"console"] = u"ttyAMA0"
+ else:
+ dpdk_target = u"x86_64-native"
+ self._opt[u"machine_args"] = u"pc,accel=kvm,usb=off,mem-merge=off"
+ self._opt[u"console"] = u"ttyS0"
+ self._testpmd_path = f"{Constants.QEMU_VM_DPDK}/" \
+ f"{dpdk_target}-linux-gcc/app"
+ self._vm_info = {
+ u"host": node[u"host"],
+ u"type": NodeType.VM,
+ u"port": 10021 + qemu_id,
+ u"serial": 4555 + qemu_id,
+ u"username": 'cisco',
+ u"password": 'cisco',
+ u"interfaces": {},
+ }
+ if node[u"port"] != 22:
+ self._vm_info[u"host_port"] = node[u"port"]
+ self._vm_info[u"host_username"] = node[u"username"]
+ self._vm_info[u"host_password"] = node[u"password"]
+ # Input Options.
+ self._opt[u"qemu_id"] = qemu_id
+ self._opt[u"mem"] = int(mem)
+ self._opt[u"smp"] = int(smp)
+ self._opt[u"img"] = img
+ self._opt[u"vnf"] = vnf
+ # Temporary files.
+ self._temp = dict()
+ self._temp[u"pidfile"] = f"/run/qemu_{qemu_id}.pid"
+ if img == Constants.QEMU_VM_IMAGE:
+ self._opt[u"vm_type"] = u"nestedvm"
+ self._temp[u"qmp"] = f"/run/qmp_{qemu_id}.sock"
+ self._temp[u"qga"] = f"/run/qga_{qemu_id}.sock"
+ elif img == Constants.QEMU_VM_KERNEL:
+ self._opt[u"img"], _ = exec_cmd_no_error(
+ node, f"ls -1 {Constants.QEMU_VM_KERNEL}* | tail -1",
+ message=u"Qemu Kernel VM image not found!"
+ )
+ self._opt[u"vm_type"] = u"kernelvm"
+ self._temp[u"log"] = f"/tmp/serial_{qemu_id}.log"
+ self._temp[u"ini"] = f"/etc/vm_init_{qemu_id}.conf"
+ self._opt[u"initrd"], _ = exec_cmd_no_error(
+ node, f"ls -1 {Constants.QEMU_VM_KERNEL_INITRD}* | tail -1",
+ message=u"Qemu Kernel initrd image not found!"
+ )
+ else:
+ raise RuntimeError(f"QEMU: Unknown VM image option: {img}")
+ # Computed parameters for QEMU command line.
+ self._params = OptionString(prefix=u"-")
+ self.add_params()
+
+ def add_params(self):
+ """Set QEMU command line parameters."""
+ self.add_default_params()
+ if self._opt.get(u"vm_type", u"") == u"nestedvm":
+ self.add_nestedvm_params()
+ elif self._opt.get(u"vm_type", u"") == u"kernelvm":
+ self.add_kernelvm_params()
+ else:
+ raise RuntimeError(u"QEMU: Unsupported VM type!")
+
+ def add_default_params(self):
+ """Set default QEMU command line parameters."""
+ self._params.add(u"daemonize")
+ self._params.add(u"nodefaults")
+ self._params.add_with_value(
+ u"name", f"vnf{self._opt.get(u'qemu_id')},debug-threads=on"
+ )
+ self._params.add(u"no-user-config")
+ self._params.add_with_value(u"monitor", u"none")
+ self._params.add_with_value(u"display", u"none")
+ self._params.add_with_value(u"vga", u"none")
+ self._params.add(u"enable-kvm")
+ self._params.add_with_value(u"pidfile", self._temp.get(u"pidfile"))
+ self._params.add_with_value(u"cpu", u"host")
+
+ self._params.add_with_value(u"machine", self._opt.get(u"machine_args"))
+ self._params.add_with_value(
+ u"smp", f"{self._opt.get(u'smp')},sockets=1,"
+ f"cores={self._opt.get(u'smp')},threads=1"
+ )
+ self._params.add_with_value(
+ u"object", f"memory-backend-file,id=mem,"
+ f"size={self._opt.get(u'mem')}M,mem-path=/dev/hugepages,share=on"
+ )
+ self._params.add_with_value(u"m", f"{self._opt.get(u'mem')}M")
+ self._params.add_with_value(u"numa", u"node,memdev=mem")
+ self._params.add_with_value(u"balloon", u"none")
+
+ def add_nestedvm_params(self):
+ """Set NestedVM QEMU parameters."""
+ self._params.add_with_value(
+ u"net",
+ f"nic,macaddr=52:54:00:00:{self._opt.get(u'qemu_id'):02x}:ff"
+ )
+ self._params.add_with_value(
+ u"net", f"user,hostfwd=tcp::{self._vm_info[u'port']}-:22"
+ )
+ locking = u",file.locking=off"
+ self._params.add_with_value(
+ u"drive", f"file={self._opt.get(u'img')},"
+ f"format=raw,cache=none,if=virtio{locking}"
+ )
+ self._params.add_with_value(
+ u"qmp", f"unix:{self._temp.get(u'qmp')},server,nowait"
+ )
+ self._params.add_with_value(
+ u"chardev", f"socket,host=127.0.0.1,"
+ f"port={self._vm_info[u'serial']},id=gnc0,server,nowait")
+ self._params.add_with_value(u"device", u"isa-serial,chardev=gnc0")
+ self._params.add_with_value(
+ u"chardev", f"socket,path={self._temp.get(u'qga')},"
+ f"server,nowait,id=qga0"
+ )
+ self._params.add_with_value(u"device", u"isa-serial,chardev=qga0")
+
+ def add_kernelvm_params(self):
+ """Set KernelVM QEMU parameters."""
+ self._params.add_with_value(
+ u"serial", f"file:{self._temp.get(u'log')}"
+ )
+ self._params.add_with_value(
+ u"fsdev", u"local,id=root9p,path=/,security_model=none"
+ )
+ self._params.add_with_value(
+ u"device", u"virtio-9p-pci,fsdev=root9p,mount_tag=virtioroot"
+ )
+ self._params.add_with_value(u"kernel", f"{self._opt.get(u'img')}")
+ self._params.add_with_value(u"initrd", f"{self._opt.get(u'initrd')}")
+ self._params.add_with_value(
+ u"append", f"'ro rootfstype=9p rootflags=trans=virtio "
+ f"root=virtioroot console={self._opt.get(u'console')} "
+ f"tsc=reliable hugepages=256 "
+ f"init={self._temp.get(u'ini')} fastboot'"
+ )
+
+ def create_kernelvm_config_vpp(self, **kwargs):
+ """Create QEMU VPP config files.
+
+ :param kwargs: Key-value pairs to replace content of VPP configuration
+ file.
+ :type kwargs: dict
+ """
+ startup = f"/etc/vpp/vm_startup_{self._opt.get(u'qemu_id')}.conf"
+ running = f"/etc/vpp/vm_running_{self._opt.get(u'qemu_id')}.exec"
+
+ self._temp[u"startup"] = startup
+ self._temp[u"running"] = running
+ self._opt[u"vnf_bin"] = f"/usr/bin/vpp -c {startup}"
+
+ # Create VPP startup configuration.
+ vpp_config = VppConfigGenerator()
+ vpp_config.set_node(self._node)
+ vpp_config.add_unix_nodaemon()
+ vpp_config.add_unix_cli_listen()
+ vpp_config.add_unix_exec(running)
+ vpp_config.add_socksvr()
+ vpp_config.add_cpu_main_core(u"0")
+ if self._opt.get(u"smp") > 1:
+ vpp_config.add_cpu_corelist_workers(f"1-{self._opt.get(u'smp')-1}")
+ vpp_config.add_dpdk_dev(u"0000:00:06.0", u"0000:00:07.0")
+ vpp_config.add_dpdk_dev_default_rxq(kwargs[u"queues"])
+ vpp_config.add_dpdk_log_level(u"debug")
+ if not kwargs[u"jumbo_frames"]:
+ vpp_config.add_dpdk_no_multi_seg()
+ vpp_config.add_dpdk_no_tx_checksum_offload()
+ vpp_config.add_plugin(u"disable", u"default")
+ vpp_config.add_plugin(u"enable", u"dpdk_plugin.so")
+ vpp_config.write_config(startup)
+
+ # Create VPP running configuration.
+ template = f"{Constants.RESOURCES_TPL_VM}/{self._opt.get(u'vnf')}.exec"
+ exec_cmd_no_error(self._node, f"rm -f {running}", sudo=True)
+
+ with open(template, u"rt") as src_file:
+ src = Template(src_file.read())
+ exec_cmd_no_error(
+ self._node, f"echo '{src.safe_substitute(**kwargs)}' | "
+ f"sudo tee {running}"
+ )
+
+ def create_kernelvm_config_testpmd_io(self, **kwargs):
+ """Create QEMU testpmd-io command line.
+
+ :param kwargs: Key-value pairs to construct command line parameters.
+ :type kwargs: dict
+ """
+ pmd_max_pkt_len = u"9200" if kwargs[u"jumbo_frames"] else u"1518"
+ testpmd_cmd = DpdkUtil.get_testpmd_cmdline(
+ eal_corelist=f"0-{self._opt.get(u'smp') - 1}",
+ eal_driver=False,
+ eal_pci_whitelist0=u"0000:00:06.0",
+ eal_pci_whitelist1=u"0000:00:07.0",
+ eal_in_memory=True,
+ pmd_num_mbufs=16384,
+ pmd_fwd_mode=u"io",
+ pmd_nb_ports=u"2",
+ pmd_portmask=u"0x3",
+ pmd_max_pkt_len=pmd_max_pkt_len,
+ pmd_mbuf_size=u"16384",
+ pmd_rxq=kwargs[u"queues"],
+ pmd_txq=kwargs[u"queues"],
+ pmd_tx_offloads='0x0',
+ pmd_nb_cores=str(self._opt.get(u"smp") - 1)
+ )
+
+ self._opt[u"vnf_bin"] = f"{self._testpmd_path}/{testpmd_cmd}"
+
+ def create_kernelvm_config_testpmd_mac(self, **kwargs):
+ """Create QEMU testpmd-mac command line.
+
+ :param kwargs: Key-value pairs to construct command line parameters.
+ :type kwargs: dict
+ """
+ pmd_max_pkt_len = u"9200" if kwargs[u"jumbo_frames"] else u"1518"
+ testpmd_cmd = DpdkUtil.get_testpmd_cmdline(
+ eal_corelist=f"0-{self._opt.get(u'smp') - 1}",
+ eal_driver=False,
+ eal_pci_whitelist0=u"0000:00:06.0",
+ eal_pci_whitelist1=u"0000:00:07.0",
+ eal_in_memory=True,
+ pmd_num_mbufs=16384,
+ pmd_fwd_mode=u"mac",
+ pmd_nb_ports=u"2",
+ pmd_portmask=u"0x3",
+ pmd_max_pkt_len=pmd_max_pkt_len,
+ pmd_mbuf_size=u"16384",
+ pmd_eth_peer_0=f"0,{kwargs[u'vif1_mac']}",
+ pmd_eth_peer_1=f"1,{kwargs[u'vif2_mac']}",
+ pmd_rxq=kwargs[u"queues"],
+ pmd_txq=kwargs[u"queues"],
+ pmd_tx_offloads=u"0x0",
+ pmd_nb_cores=str(self._opt.get(u"smp") - 1)
+ )
+
+ self._opt[u"vnf_bin"] = f"{self._testpmd_path}/{testpmd_cmd}"
+
+ def create_kernelvm_init(self, **kwargs):
+ """Create QEMU init script.
+
+ :param kwargs: Key-value pairs to replace content of init startup file.
+ :type kwargs: dict
+ """
+ template = f"{Constants.RESOURCES_TPL_VM}/init.sh"
+ init = self._temp.get(u"ini")
+ exec_cmd_no_error(self._node, f"rm -f {init}", sudo=True)
+
+ with open(template, u"rt") as src_file:
+ src = Template(src_file.read())
+ exec_cmd_no_error(
+ self._node, f"echo '{src.safe_substitute(**kwargs)}' | "
+ f"sudo tee {init}"
+ )
+ exec_cmd_no_error(self._node, f"chmod +x {init}", sudo=True)
+
+ def configure_kernelvm_vnf(self, **kwargs):
+ """Create KernelVM VNF configurations.
+
+ :param kwargs: Key-value pairs for templating configs.
+ :type kwargs: dict
+ """
+ if u"vpp" in self._opt.get(u"vnf"):
+ self.create_kernelvm_config_vpp(**kwargs)
+ elif u"testpmd_io" in self._opt.get(u"vnf"):
+ self.create_kernelvm_config_testpmd_io(**kwargs)
+ elif u"testpmd_mac" in self._opt.get(u"vnf"):
+ self.create_kernelvm_config_testpmd_mac(**kwargs)
+ else:
+ raise RuntimeError(u"QEMU: Unsupported VNF!")
+ self.create_kernelvm_init(vnf_bin=self._opt.get(u"vnf_bin"))
+
+ def get_qemu_pids(self):
+ """Get QEMU CPU pids.
+
+ :returns: List of QEMU CPU pids.
+ :rtype: list of str
+ """
+ command = f"grep -rwl 'CPU' /proc/$(sudo cat " \
+ f"{self._temp.get(u'pidfile')})/task/*/comm "
+ command += r"| xargs dirname | sed -e 's/\/.*\///g' | uniq"
+
+ stdout, _ = exec_cmd_no_error(self._node, command)
+ return stdout.splitlines()
+
+ def qemu_set_affinity(self, *host_cpus):
+ """Set qemu affinity by getting thread PIDs via QMP and taskset to list
+ of CPU cores. Function tries to execute 3 times to avoid race condition
+ in getting thread PIDs.
+
+ :param host_cpus: List of CPU cores.
+ :type host_cpus: list
+ """
+ for _ in range(3):
+ try:
+ qemu_cpus = self.get_qemu_pids()
+
+ if len(qemu_cpus) != len(host_cpus):
+ sleep(1)
+ continue
+ for qemu_cpu, host_cpu in zip(qemu_cpus, host_cpus):
+ command = f"taskset -pc {host_cpu} {qemu_cpu}"
+ message = f"QEMU: Set affinity failed " \
+ f"on {self._node[u'host']}!"
+ exec_cmd_no_error(
+ self._node, command, sudo=True, message=message
+ )
+ break
+ except (RuntimeError, ValueError):
+ self.qemu_kill_all()
+ raise
+ else:
+ self.qemu_kill_all()
+ raise RuntimeError(u"Failed to set Qemu threads affinity!")
+
+ def qemu_set_scheduler_policy(self):
+ """Set scheduler policy to SCHED_RR with priority 1 for all Qemu CPU
+ processes.
+
+ :raises RuntimeError: Set scheduler policy failed.