emulator.py 6.5 KB

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