1#!/usr/bin/env python3
2
3r"""
4This program will get the system serial number from an OBMC machine and print it to stdout.
5"""
6
7import os
8import sys
9
10import requests
11
12save_path_0 = sys.path[0]
13del sys.path[0]
14
15from gen_arg import *  # NOQA
16from gen_print import *  # NOQA
17from gen_valid import *  # NOQA
18
19# Restore sys.path[0].
20sys.path.insert(0, save_path_0)
21
22logging.captureWarnings(True)
23
24parser = argparse.ArgumentParser(
25    usage="%(prog)s [OPTIONS]",
26    description="%(prog)s will get the system serial number from an OBMC"
27    + " machine and print it to stdout as follows:\n\n"
28    + "mch_ser_num:<ser num>",
29    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
30    prefix_chars="-+",
31)
32
33parser.add_argument(
34    "--openbmc_username",
35    default="root",
36    help="The username for communicating with the OpenBMC machine.",
37)
38
39parser.add_argument(
40    "--openbmc_password",
41    default="0penBmc",
42    help="The password for communicating with the OpenBMC machine.",
43)
44
45parser.add_argument(
46    "openbmc_host", help="The host name or IP address of the OpenBMC machine."
47)
48
49# Populate stock_list with options we want.
50stock_list = [("test_mode", 0), ("quiet", 1)]
51
52
53def exit_function(signal_number=0, frame=None):
54    r"""
55    Execute whenever the program ends normally or with the signals that we catch (i.e. TERM, INT).
56    """
57
58    dprint_executing()
59    dprint_var(signal_number)
60
61    qprint_pgm_footer()
62
63
64def signal_handler(signal_number, frame):
65    r"""
66    Handle signals.  Without a function to catch a SIGTERM or SIGINT, our program would terminate immediately
67    with return code 143 and without calling our exit_function.
68    """
69
70    # Our convention is to set up exit_function with atexit.register() so there is no need to explicitly
71    # call exit_function from here.
72
73    dprint_executing()
74
75    # Calling exit prevents us from returning to the code that was running when we received the signal.
76    exit(0)
77
78
79def validate_parms():
80    r"""
81    Validate program parameters, etc.  Return True or False (i.e. pass/fail) accordingly.
82    """
83
84    gen_post_validation(exit_function, signal_handler)
85
86    return True
87
88
89def create_http_prefix(host):
90    r"""
91    Create and return an http prefix string.
92
93    Description of argument(s):
94    host                            The host being communicated with via the curl command.
95    """
96
97    return "https://" + host + "/"
98
99
100def main():
101    if not gen_get_options(parser, stock_list):
102        return False
103
104    if not validate_parms():
105        return False
106
107    qprint_pgm_header()
108
109    session = requests.Session()
110
111    http_prefix = create_http_prefix(openbmc_host)
112
113    command = http_prefix + "login"
114    qprint_issuing(command)
115    resp = session.post(
116        command,
117        json={"data": [openbmc_username, openbmc_password]},
118        verify=False,
119    )
120    if resp.json()["status"] != "ok":
121        json = resp.json()
122        print_error_report("http request failed:\n" + sprint_var(command))
123        raise Exception("Login failed.\n")
124
125    command = http_prefix + "xyz/openbmc_project/inventory/system"
126    qprint_issuing(command)
127    resp = session.get(command, verify=False)
128    json = resp.json()
129    if json["status"] != "ok":
130        print_error_report("http request failed:\n" + sprint_var(command))
131        raise Exception("http request failed.\n")
132
133    try:
134        mch_ser_num = json["data"]["SerialNumber"]
135    except KeyError:
136        print_error_report(
137            "Failed to find 'SerialNumber' key in the"
138            + " following data:\n"
139            + sprint_var(json)
140        )
141        return False
142    print_var(mch_ser_num, 0, 0, 0)
143
144    return True
145
146
147# Main
148
149if not main():
150    exit(1)
151