2
1

emulator.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import os
  2. import pexpect
  3. import pexpect.replwrap
  4. import infra
  5. BR_PROMPT = '[BRTEST# '
  6. BR_CONTINUATION_PROMPT = '[BRTEST+ '
  7. def _repl_sh_child(child, orig_prompt, extra_init_cmd):
  8. """Wrap the shell prompt to handle command output
  9. Based on pexpect.replwrap._repl_sh() (ISC licensed)
  10. https://github.com/pexpect/pexpect/blob/aa989594e1e413f45c18b26ded1783f7d5990fe5/pexpect/replwrap.py#L115
  11. """
  12. # If the user runs 'env', the value of PS1 will be in the output. To avoid
  13. # replwrap seeing that as the next prompt, we'll embed the marker characters
  14. # for invisible characters in the prompt; these show up when inspecting the
  15. # environment variable, but not when bash displays the prompt.
  16. non_printable_insert = '\\[\\]'
  17. ps1 = BR_PROMPT[:5] + non_printable_insert + BR_PROMPT[5:]
  18. ps2 = (BR_CONTINUATION_PROMPT[:5] + non_printable_insert +
  19. BR_CONTINUATION_PROMPT[5:])
  20. prompt_change = "PS1='{0}' PS2='{1}' PROMPT_COMMAND=''".format(ps1, ps2)
  21. # Note: this will run various commands, each with the default timeout defined
  22. # when qemu was spawned.
  23. return pexpect.replwrap.REPLWrapper(
  24. child,
  25. orig_prompt,
  26. prompt_change,
  27. new_prompt=BR_PROMPT,
  28. continuation_prompt=BR_CONTINUATION_PROMPT,
  29. extra_init_cmd=extra_init_cmd
  30. )
  31. class Emulator(object):
  32. def __init__(self, builddir, downloaddir, logtofile, timeout_multiplier):
  33. self.qemu = None
  34. self.repl = None
  35. self.downloaddir = downloaddir
  36. self.logfile = infra.open_log_file(builddir, "run", logtofile)
  37. # We use elastic runners on the cloud to runs our tests. Those runners
  38. # can take a long time to run the emulator. Use a timeout multiplier
  39. # when running the tests to avoid sporadic failures.
  40. self.timeout_multiplier = timeout_multiplier
  41. # Start Qemu to boot the system
  42. #
  43. # arch: Qemu architecture to use
  44. #
  45. # kernel: path to the kernel image, or the special string
  46. # 'builtin'. 'builtin' means a pre-built kernel image will be
  47. # downloaded from ARTIFACTS_URL and suitable options are
  48. # automatically passed to qemu and added to the kernel cmdline. So
  49. # far only armv5, armv7 and i386 builtin kernels are available.
  50. # If None, then no kernel is used, and we assume a bootable device
  51. # will be specified.
  52. #
  53. # kernel_cmdline: array of kernel arguments to pass to Qemu -append option
  54. #
  55. # options: array of command line options to pass to Qemu
  56. #
  57. def boot(self, arch, kernel=None, kernel_cmdline=None, options=None):
  58. if arch in ["armv7", "armv5"]:
  59. qemu_arch = "arm"
  60. else:
  61. qemu_arch = arch
  62. qemu_cmd = ["qemu-system-{}".format(qemu_arch),
  63. "-serial", "stdio",
  64. "-display", "none",
  65. "-m", "256"]
  66. if options:
  67. qemu_cmd += options
  68. if kernel_cmdline is None:
  69. kernel_cmdline = []
  70. if kernel:
  71. if kernel == "builtin":
  72. if arch in ["armv7", "armv5"]:
  73. kernel_cmdline.append("console=ttyAMA0")
  74. if arch == "armv7":
  75. kernel = infra.download(self.downloaddir,
  76. "kernel-vexpress-5.10.202")
  77. dtb = infra.download(self.downloaddir,
  78. "vexpress-v2p-ca9-5.10.202.dtb")
  79. qemu_cmd += ["-dtb", dtb]
  80. qemu_cmd += ["-M", "vexpress-a9"]
  81. elif arch == "armv5":
  82. kernel = infra.download(self.downloaddir,
  83. "kernel-versatile-5.10.202")
  84. dtb = infra.download(self.downloaddir,
  85. "versatile-pb-5.10.202.dtb")
  86. qemu_cmd += ["-dtb", dtb]
  87. qemu_cmd += ["-M", "versatilepb"]
  88. qemu_cmd += ["-device", "virtio-rng-pci"]
  89. qemu_cmd += ["-kernel", kernel]
  90. if kernel_cmdline:
  91. qemu_cmd += ["-append", " ".join(kernel_cmdline)]
  92. self.logfile.write(f"> host cpu count: {os.cpu_count()}\n")
  93. ldavg = os.getloadavg()
  94. ldavg_str = f"{ldavg[0]:.2f}, {ldavg[1]:.2f}, {ldavg[2]:.2f}"
  95. self.logfile.write(f"> host loadavg: {ldavg_str}\n")
  96. self.logfile.write(f"> timeout multiplier: {self.timeout_multiplier}\n")
  97. self.logfile.write("> starting qemu with '%s'\n" % " ".join(qemu_cmd))
  98. self.qemu = pexpect.spawn(qemu_cmd[0], qemu_cmd[1:],
  99. timeout=5 * self.timeout_multiplier,
  100. encoding='utf-8',
  101. codec_errors='replace',
  102. env={"QEMU_AUDIO_DRV": "none"})
  103. # We want only stdout into the log to avoid double echo
  104. self.qemu.logfile_read = self.logfile
  105. # Wait for the login prompt to appear, and then login as root with
  106. # the provided password, or no password if not specified.
  107. def login(self, password=None, timeout=60):
  108. # The login prompt can take some time to appear when running multiple
  109. # instances in parallel, so set the timeout to a large value
  110. index = self.qemu.expect(["buildroot login:", pexpect.TIMEOUT],
  111. timeout=timeout * self.timeout_multiplier)
  112. if index != 0:
  113. self.logfile.write("==> System does not boot")
  114. raise SystemError("System does not boot")
  115. self.qemu.sendline("root")
  116. if password:
  117. self.qemu.expect("Password:")
  118. self.qemu.sendline(password)
  119. self.connect_shell()
  120. def connect_shell(self):
  121. extra_init_cmd = " && ".join([
  122. 'export PAGER=cat',
  123. 'dmesg -n 1',
  124. # Prevent the shell from wrapping the commands at 80 columns.
  125. 'stty columns 29999',
  126. # Fix the prompt of any subshells that get run
  127. 'printf "%s\n" "PS1=\'$PS1\'" "PS2=\'$PS2\'" "PROMPT_COMMAND=\'\'" >>/etc/profile'
  128. ])
  129. self.repl = _repl_sh_child(self.qemu, '# ', extra_init_cmd)
  130. if not self.repl:
  131. raise SystemError("Cannot initialize REPL prompt")
  132. # Run the given 'cmd' with a 'timeout' on the target
  133. # return a tuple (output, exit_code)
  134. def run(self, cmd, timeout=-1):
  135. if timeout != -1:
  136. timeout *= self.timeout_multiplier
  137. output = self.repl.run_command(cmd, timeout=timeout)
  138. # Remove double carriage return from qemu stdout so str.splitlines()
  139. # works as expected.
  140. output = output.replace("\r\r", "\r").splitlines()[1:]
  141. exit_code = self.repl.run_command("echo $?")
  142. exit_code = self.qemu.before.splitlines()[2]
  143. exit_code = int(exit_code)
  144. return output, exit_code
  145. def stop(self):
  146. if self.qemu is None:
  147. return
  148. self.qemu.terminate(force=True)