1#!/usr/bin/env python
2
3r"""
4Check for stop conditions.  Return code of 2 if stop conditions are found.
5"""
6
7import sys
8import subprocess
9
10save_path_0 = sys.path[0]
11del sys.path[0]
12
13from gen_print import *
14from gen_valid import *
15from gen_arg import *
16from gen_misc import *
17from gen_cmd import *
18from gen_plug_in_utils import *
19from gen_call_robot import *
20
21# Restore sys.path[0].
22sys.path.insert(0, save_path_0)
23
24# Initialize.
25STOP_REST_FAIL = ''
26STOP_COMMAND = ''
27stop_test_rc = 2
28
29# Create parser object to process command line parameters and args.
30
31# Create parser object.
32parser = argparse.ArgumentParser(
33    usage='%(prog)s [OPTIONS]',
34    description="If the \"Stop\" plug-in is selected by the user, %(prog)s" +
35    " is called by OBMC Boot Test after each boot test.  If %(prog)s returns" +
36    " " + str(stop_test_rc) + ", then OBMC Boot Test will stop.  The user" +
37    " may set environment variable STOP_COMMAND to contain any valid bash" +
38    " command or program.  %(prog)s will run this stop command.  If the stop" +
39    " command returns non-zero, then %(prog)s will return " +
40    str(stop_test_rc) + ".  %(prog)s recognizes some special values for" +
41    " STOP_COMMAND: 1) \"FAIL\" means that OBMC Boot Test should stop" +
42    " whenever a boot test fails. 2) \"ALL\" means that OBMC Boot Test" +
43    " should stop after any boot test.  If environment variable" +
44    " STOP_REST_FAIL is set, OBMC Boot Test will stop if REST commands are" +
45    " no longer working.",
46    formatter_class=argparse.RawTextHelpFormatter,
47    prefix_chars='-+')
48
49# The stock_list will be passed to gen_get_options.  We populate it with the
50# names of stock parm options we want.  These stock parms are pre-defined by
51# gen_get_options.
52stock_list = [("test_mode", 0),
53              ("quiet", get_plug_default("quiet", 0)),
54              ("debug", get_plug_default("debug", 0))]
55
56
57def exit_function(signal_number=0,
58                  frame=None):
59    r"""
60    Execute whenever the program ends normally or with the signals that we
61    catch (i.e. TERM, INT).
62    """
63
64    dprint_executing()
65    dprint_var(signal_number)
66
67    qprint_pgm_footer()
68
69
70def signal_handler(signal_number,
71                   frame):
72    r"""
73    Handle signals.  Without a function to catch a SIGTERM or SIGINT, our
74    program would terminate immediately with return code 143 and without
75    calling our exit_function.
76    """
77
78    # Our convention is to set up exit_function with atexit.register() so
79    # there is no need to explicitly call exit_function from here.
80
81    dprint_executing()
82
83    # Calling exit prevents us from returning to the code that was running
84    # when we received the signal.
85    exit(0)
86
87
88def validate_parms():
89    r"""
90    Validate program parameters, etc.  Return True or False (i.e. pass/fail)
91    accordingly.
92    """
93
94    get_plug_vars()
95
96    if not valid_value(AUTOBOOT_OPENBMC_HOST, ["", None]):
97        return False
98
99    gen_post_validation(exit_function, signal_handler)
100
101    return True
102
103
104def rest_fail():
105    r"""
106    If STOP_REST_FAIL, then this function will determine whether REST commands
107    to the target are working.  If not, this function will stop the program by
108    returning stop_test_rc.
109    """
110
111    if STOP_REST_FAIL != '1':
112        return
113
114    print_timen("Checking to see whether REST commands are working.")
115    init_robot_out_parms(get_plug_in_package_name() + ".")
116    lib_file_path = init_robot_file_path("lib/state.py")
117    set_mod_global(lib_file_path)
118    timeout = '0 seconds'
119    interval = '1 second'
120    keyword_string = "${match_state}=  Create Dictionary  rest=1 ;" +\
121        " ${state}=  Wait State  ${match_state}  " + timeout + "  " +\
122        interval + "  quiet=${1} ; Rpvar  state"
123    set_mod_global(keyword_string)
124
125    cmd_buf = create_robot_cmd_string("extended/run_keyword.robot",
126                                      OPENBMC_HOST, keyword_string,
127                                      lib_file_path, quiet, test_mode, debug,
128                                      outputdir, output, log, report, loglevel)
129    if not robot_cmd_fnc(cmd_buf):
130        print_timen("The caller wishes to stop test execution if REST" +
131                    " commands are failing.")
132        exit(stop_test_rc)
133    print_timen("REST commands are working so no reason as of yet to stop" +
134                " the test.")
135
136
137def esel_stop_check():
138    r"""
139    Run the esel_stop_check program to determine whether any eSEL entries
140    found warrent stopping the test run.  See esel_stop_check help text for
141    details.
142    """
143
144    if STOP_ESEL_STOP_FILE_PATH == "":
145        return
146
147    cmd_buf = "esel_stop_check --esel_stop_file_path=" +\
148        STOP_ESEL_STOP_FILE_PATH
149    shell_rc, out_buf = cmd_fnc_u(cmd_buf, show_err=0)
150    if shell_rc == stop_test_rc:
151        print_timen("The caller wishes to stop test execution based on the" +
152                    " presence of certain esel entries.")
153        exit(stop_test_rc)
154
155
156def main():
157
158    if not gen_get_options(parser, stock_list):
159        return False
160
161    if not validate_parms():
162        return False
163
164    qprint_pgm_header()
165
166    if not debug:
167        qprint_vars(STOP_REST_FAIL, STOP_COMMAND, AUTOBOOT_BOOT_SUCCESS)
168
169    dprint_plug_vars()
170
171    rest_fail()
172
173    esel_stop_check()
174
175    if STOP_COMMAND.upper() == "FAIL":
176        if AUTOBOOT_BOOT_SUCCESS == "0":
177            print_timen("The caller wishes to stop after each boot failure.")
178            exit(stop_test_rc)
179    elif STOP_COMMAND.upper() == "ALL":
180        print_timen("The caller wishes to stop after each boot test.")
181        exit(stop_test_rc)
182    elif len(STOP_COMMAND) > 0:
183        shell_rc, out_buf = cmd_fnc_u(STOP_COMMAND, quiet=quiet, show_err=0)
184        if shell_rc != 0:
185            print_timen("The caller wishes to stop test execution.")
186            exit(stop_test_rc)
187
188    qprint_timen("The caller does not wish to stop the test run.")
189    return True
190
191# Main
192
193
194if not main():
195    exit(1)
196