Debian Codegraph @

tests/serial-console-connection

raw
1 #!/usr/bin/env python3
2 import argparse
3 import re
4 import serial
5 import os
6 import shutil
7 import subprocess
8 import sys
9 import time
10
11 parser = argparse.ArgumentParser(
12 description="Connect to serial console to execute stuff",
13 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
14 )
15 parser.add_argument(
16 "--qemu-log",
17 dest="qemu_log",
18 required=True,
19 help="QEMU log to look for serial port info in",
20 )
21 parser.add_argument(
22 "--hostname", default="trixie", help="hostname of the system for login process"
23 )
24 parser.add_argument("--user", default="root", help="user name to use for login")
25 parser.add_argument("--password", default="grml", help="password for login")
26 parser.add_argument(
27 "--timeout",
28 default="180",
29 type=int,
30 help="Maximum time for finding the login prompt, in seconds",
31 )
32 parser.add_argument(
33 "--screenshot",
34 default="screenshot.jpg",
35 help="file name for screenshot captured via VNC on error",
36 )
37 parser.add_argument(
38 "--tries",
39 default="12",
40 type=int,
41 help="Number of retries for finding the login prompt",
42 )
43 parser.add_argument(
44 "--poweroff",
45 action="store_true",
46 default=False,
47 help='send "poweroff" command after all other commands',
48 )
49 parser.add_argument("command", nargs="+", help="command to execute after logging in")
50
51
52 def print_ser_lines(ser):
53 for line in ser.readlines():
54 print("<<", line) # line will be a binary string
55
56
57 def write_ser_line(ser, text):
58 print(">>", text)
59 ser.write(("%s\n" % text).encode())
60 ser.flush()
61
62
63 def wait_ser_text(ser, texts, timeout):
64 if isinstance(texts, str):
65 texts = [texts]
66
67 ts_max = time.time() + timeout
68 ser.timeout = 1
69 texts_encoded = [text.encode("utf-8") for text in texts]
70 found = False
71 print(time.time(), "D: expecting one of", texts_encoded)
72 while ts_max > time.time() and found is False:
73 for line in ser.readlines():
74 print(time.time(), "<<", line) # line will be a binary string
75 for index, text in enumerate(texts_encoded):
76 if text in line:
77 found = texts[index]
78 break
79 return found
80
81
82 def login(ser, hostname, user, password, timeout):
83 login_prompt = "%s login:" % hostname
84 shell_prompt = "%s@%s" % (user, hostname)
85
86 write_ser_line(ser, "") # send newline
87
88 found = wait_ser_text(ser, [shell_prompt, login_prompt], timeout=timeout * 4)
89 if found == shell_prompt:
90 return
91 elif found is False:
92 raise ValueError("timeout waiting for login prompt")
93
94 print("Logging in...")
95 write_ser_line(ser, user)
96 if not wait_ser_text(ser, "Password:", timeout=timeout):
97 raise ValueError("timeout waiting for password prompt")
98
99 write_ser_line(ser, password)
100 time.sleep(1)
101
102 print(time.time(), "Waiting for shell prompt...")
103 if not wait_ser_text(ser, shell_prompt, timeout=timeout * 4):
104 raise ValueError("timeout waiting for shell prompt")
105
106
107 def capture_vnc_screenshot(screenshot_file):
108 if not shutil.which("vncsnapshot"):
109 print("WARN: vncsnapshot not available, skipping vnc snapshot capturing.")
110 return
111
112 print("Trying to capture screenshot via vncsnapshot to", screenshot_file)
113
114 proc = subprocess.Popen(["vncsnapshot", "localhost", screenshot_file])
115 proc.wait()
116 if proc.returncode != 0:
117 print("WARN: failed to capture vnc snapshot :(")
118 else:
119 print("Screenshot file '%s' available" % os.path.abspath(screenshot_file))
120
121
122 def find_serial_port_from_qemu_log(qemu_log, tries):
123 port = None
124 for i in range(tries):
125 print("Waiting for qemu to present serial console [try %s]" % (i, ))
126 with open(qemu_log, "r", encoding="utf-8") as fp:
127 qemu_log_messages = fp.read().splitlines()
128 for line in qemu_log_messages:
129 m = re.match("char device redirected to ([^ ]+)", line)
130 if m:
131 port = m.group(1)
132 break
133 if port:
134 break
135 time.sleep(5)
136
137 print("qemu log (up to char device redirect) follows:")
138 print("\n".join(qemu_log_messages))
139 print()
140 return port # might be None, caller has to deal with it
141
142
143 def main():
144 args = parser.parse_args()
145 hostname = args.hostname
146 password = args.password
147 qemu_log = args.qemu_log
148 user = args.user
149 commands = args.command
150 screenshot_file = args.screenshot
151
152 port = find_serial_port_from_qemu_log(qemu_log, args.tries)
153 if not port:
154 print()
155 print("E: no serial port found in qemu log", qemu_log)
156 sys.exit(1)
157
158 ser = serial.Serial(port, 115200)
159 ser.flushInput()
160 ser.flushOutput()
161
162 success = False
163 ts_start = time.time()
164 for i in range(args.tries):
165 try:
166 print("Logging into %s via serial console [try %s]" % (port, i))
167 login(ser, hostname, user, password, 30)
168 success = True
169 break
170 except Exception as except_inst:
171 print("Login failure (try %s):" % (i,), except_inst)
172 time.sleep(5)
173 if time.time() - ts_start > args.timeout:
174 print("E: Timeout reached waiting for login prompt")
175 break
176
177 if success:
178 write_ser_line(ser, "")
179 ser.timeout = 30
180 print_ser_lines(ser)
181 print("Running commands...")
182 for command in commands:
183 write_ser_line(ser, command)
184 print_ser_lines(ser)
185 if args.poweroff:
186 print("Sending final poweroff command...")
187 write_ser_line(ser, "poweroff")
188 ser.flush()
189 # after poweroff, the serial device will probably vanish. do not attempt reading from it anymore.
190
191 if not success:
192 print("W: Running tests failed, saving screenshot")
193 capture_vnc_screenshot(screenshot_file)
194 sys.exit(1)
195
196
197 if __name__ == "__main__":
198 main()