1#!/usr/bin/env python3
2#
3# Copyright © 2020 Google LLC
4#
5# Permission is hereby granted, free of charge, to any person obtaining a
6# copy of this software and associated documentation files (the "Software"),
7# to deal in the Software without restriction, including without limitation
8# the rights to use, copy, modify, merge, publish, distribute, sublicense,
9# and/or sell copies of the Software, and to permit persons to whom the
10# Software is furnished to do so, subject to the following conditions:
11#
12# The above copyright notice and this permission notice (including the next
13# paragraph) shall be included in all copies or substantial portions of the
14# Software.
15#
16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22# IN THE SOFTWARE.
23
24import argparse
25import queue
26import re
27from serial_buffer import SerialBuffer
28import sys
29import threading
30
31
32class CrosServoRun:
33    def __init__(self, cpu, ec):
34        # Merged FIFO for the two serial buffers, fed by threads.
35        self.serial_queue = queue.Queue()
36        self.sentinel = object()
37        self.threads_done = 0
38
39        self.ec_ser = SerialBuffer(
40            ec, "results/serial-ec.txt", "R SERIAL-EC> ")
41        self.cpu_ser = SerialBuffer(
42            cpu, "results/serial.txt", "R SERIAL-CPU> ")
43
44        self.iter_feed_ec = threading.Thread(
45            target=self.iter_feed_queue, daemon=True, args=(self.ec_ser.lines(),))
46        self.iter_feed_ec.start()
47
48        self.iter_feed_cpu = threading.Thread(
49            target=self.iter_feed_queue, daemon=True, args=(self.cpu_ser.lines(),))
50        self.iter_feed_cpu.start()
51
52    # Feed lines from our serial queues into the merged queue, marking when our
53    # input is done.
54    def iter_feed_queue(self, it):
55        for i in it:
56            self.serial_queue.put(i)
57        self.serial_queue.put(sentinel)
58
59    # Return the next line from the queue, counting how many threads have
60    # terminated and joining when done
61    def get_serial_queue_line(self):
62        line = self.serial_queue.get()
63        if line == self.sentinel:
64            self.threads_done = self.threads_done + 1
65            if self.threads_done == 2:
66                self.iter_feed_cpu.join()
67                self.iter_feed_ec.join()
68        return line
69
70    # Returns an iterator for getting the next line.
71    def serial_queue_lines(self):
72        return iter(self.get_serial_queue_line, self.sentinel)
73
74    def ec_write(self, s):
75        print("W SERIAL-EC> %s" % s)
76        self.ec_ser.serial.write(s.encode())
77
78    def cpu_write(self, s):
79        print("W SERIAL-CPU> %s" % s)
80        self.cpu_ser.serial.write(s.encode())
81
82    def run(self):
83        # Flush any partial commands in the EC's prompt, then ask for a reboot.
84        self.ec_write("\n")
85        self.ec_write("reboot\n")
86
87        # This is emitted right when the bootloader pauses to check for input.
88        # Emit a ^N character to request network boot, because we don't have a
89        # direct-to-netboot firmware on cheza.
90        for line in self.serial_queue_lines():
91            if re.search("load_archive: loading locale_en.bin", line):
92                self.cpu_write("\016")
93                break
94
95            # The Cheza boards have issues with failing to bring up power to
96            # the system sometimes, possibly dependent on ambient temperature
97            # in the farm.
98            if re.search("POWER_GOOD not seen in time", line):
99                print("Detected intermittent poweron failure, restarting run...")
100                return 2
101
102        tftp_failures = 0
103        for line in self.serial_queue_lines():
104            if re.search("---. end Kernel panic", line):
105                return 1
106
107            # The Cheza firmware seems to occasionally get stuck looping in
108            # this error state during TFTP booting, possibly based on amount of
109            # network traffic around it, but it'll usually recover after a
110            # reboot.
111            if re.search("R8152: Bulk read error 0xffffffbf", line):
112                tftp_failures += 1
113                if tftp_failures >= 100:
114                    print("Detected intermittent tftp failure, restarting run...")
115                    return 2
116
117            result = re.search("bare-metal result: (\S*)", line)
118            if result:
119                if result.group(1) == "pass":
120                    return 0
121                else:
122                    return 1
123
124        print("Reached the end of the CPU serial log without finding a result")
125        return 1
126
127
128def main():
129    parser = argparse.ArgumentParser()
130    parser.add_argument('--cpu', type=str,
131                        help='CPU Serial device', required=True)
132    parser.add_argument(
133        '--ec', type=str, help='EC Serial device', required=True)
134    args = parser.parse_args()
135
136    servo = CrosServoRun(args.cpu, args.ec)
137
138    while True:
139        retval = servo.run()
140        if retval != 2:
141            break
142
143    # power down the CPU on the device
144    servo.ec_write("power off\n")
145
146    sys.exit(retval)
147
148
149if __name__ == '__main__':
150    main()
151