blob: 774903af5a300d2eca63d261c349367438bb0627 [file] [log] [blame]
Michael Walsh888be1f2019-03-26 12:02:36 -05001#!/usr/bin/env python
2
3r"""
4See help text for details.
5"""
6
7import sys
8import subprocess
Michael Walsh64fbc9c2019-04-05 16:20:26 -05009import re
Michael Walsh888be1f2019-03-26 12:02:36 -050010
Michael Walsh60d08f32019-11-25 16:51:39 -060011save_dir_path = sys.path.pop(0)
Michael Walsh888be1f2019-03-26 12:02:36 -050012
Michael Walsh60d08f32019-11-25 16:51:39 -060013modules = ['gen_arg', 'gen_print', 'gen_valid', 'gen_misc', 'gen_cmd', 'var_funcs']
14for module in modules:
15 exec("from " + module + " import *")
Michael Walsh888be1f2019-03-26 12:02:36 -050016
Michael Walsh60d08f32019-11-25 16:51:39 -060017sys.path.insert(0, save_dir_path)
Michael Walsh888be1f2019-03-26 12:02:36 -050018
19parser = argparse.ArgumentParser(
20 usage='%(prog)s [OPTIONS]',
21 description="%(prog)s will create a status file path name adhering to the"
22 + " following pattern: <status dir path>/<prefix>.yymmdd."
23 + "hhmmss.status. It will then run the command string and"
24 + " direct its stdout/stderr to the status file and optionally"
25 + " to stdout. This dual output streaming will be"
26 + " accomplished using either the \"script\" or the \"tee\""
27 + " program. %(prog)s will also set and export environment"
28 + " variable \"AUTO_STATUS_FILE_PATH\" for the benefit of"
29 + " child programs.",
30 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
31 prefix_chars='-+')
32
33parser.add_argument(
34 '--status_dir_path',
35 default='',
36 help="The path to the directory where the status file will be created."
37 + "%(default)s The default value is obtained from environment"
38 + " variable \"${STATUS_DIR_PATH}\", if set or from \"${HOME}/"
39 + "status/\".")
40
41parser.add_argument(
42 '--prefix',
43 default='',
44 help="The prefix for the generated file name.%(default)s The default value"
45 + " is the command portion (i.e. the first token) of the command"
46 + " string.")
47
48parser.add_argument(
49 '--status_file_name',
50 default='',
51 help="This allows the user to explicitly specify the status file name. If"
52 + " this argument is not used, %(prog)s composes a status file name."
53 + " If this argument is specified, the \"--prefix\" argument is"
54 + " ignored.")
55
56parser.add_argument(
57 '--stdout',
58 default=1,
59 type=int,
60 choices=[1, 0],
61 help="Indicates that stdout/stderr from the command string execution"
62 + " should be written to stdout as well as to the status file.")
63
64parser.add_argument(
65 '--tee',
66 default=0,
67 type=int,
68 choices=[1, 0],
69 help="Indicates that \"tee\" rather than \"script\" should be used.")
70
71parser.add_argument(
72 '--show_url',
73 default=0,
74 type=int,
75 choices=[1, 0],
76 help="Indicates that the status file path shown should be shown in the"
77 + " form of a url. If the output is to be viewed from a browser,"
78 + " this may well become a clickable link. Note that the"
79 + " get_file_path_url.py program must be found in the \"PATH\""
80 + " environment variable for this argument to be effective.")
81
82parser.add_argument(
83 'command_string',
84 default='',
85 nargs='*',
86 help="The command string to be run.%(default)s")
87
88# Populate stock_list with options we want.
89stock_list = [("test_mode", 0), ("quiet", 1), ("debug", 0)]
90
91
Michael Walsh888be1f2019-03-26 12:02:36 -050092def validate_parms():
93 r"""
94 Validate program parameters, etc.
95 """
96
97 global status_dir_path
98 global command_string
99
100 # Convert command_string from list to string.
101 command_string = " ".join(command_string)
102 set_pgm_arg(command_string)
103 valid_value(command_string)
104
105 if status_dir_path == "":
106 status_dir_path = \
107 os.environ.get("STATUS_DIR_PATH",
108 os.environ.get("HOME") + "/status/")
109 status_dir_path = add_trailing_slash(status_dir_path)
110 set_pgm_arg(status_dir_path)
111 valid_dir_path(status_dir_path)
112
113 global prefix
114 global status_file_name
115 if status_file_name == "":
116 if prefix == "":
117 prefix = command_string.split(" ")[0]
Michael Walsh410b1782019-10-22 15:56:18 -0500118 # File extensions (e.g. ".sh", ".py", .etc), look clumsy in status file names.
Michael Walsh64fbc9c2019-04-05 16:20:26 -0500119 extension_regex = "\\.[a-zA-Z0-9]{1,3}$"
120 prefix = re.sub(extension_regex, "", prefix)
Michael Walsh888be1f2019-03-26 12:02:36 -0500121 set_pgm_arg(prefix)
122 status_file_name = prefix + "." + file_date_time_stamp() + ".status"
123 set_pgm_arg(status_file_name)
124
125 global status_file_path
126
127 status_file_path = status_dir_path + status_file_name
128 # Set environment variable for the benefit of child programs.
129 os.environ['AUTO_STATUS_FILE_PATH'] = status_file_path
130 # Set deprecated but still used AUTOSCRIPT_STATUS_FILE_PATH value.
131 os.environ['AUTOSCRIPT_STATUS_FILE_PATH'] = status_file_path
132
Michael Walsh888be1f2019-03-26 12:02:36 -0500133
134def script_func(command_string, status_file_path):
135 r"""
Michael Walsh410b1782019-10-22 15:56:18 -0500136 Run the command string producing both stdout and file output via the script command and return the
137 shell_rc.
Michael Walsh888be1f2019-03-26 12:02:36 -0500138
139 Description of argument(s):
140 command_string The command string to be run.
Michael Walsh410b1782019-10-22 15:56:18 -0500141 status_file_path The path to the status file which is to contain a copy of all stdout.
Michael Walsh888be1f2019-03-26 12:02:36 -0500142 """
143
144 cmd_buf = "script -a -q -f " + status_file_path + " -c '" \
145 + escape_bash_quotes(command_string) + " ; printf \"\\n" \
146 + sprint_varx(ret_code_str, "${?}").rstrip("\n") + "\\n\"'"
147 qprint_issuing(cmd_buf)
148 sub_proc = subprocess.Popen(cmd_buf, shell=True)
149 sub_proc.communicate()
150 shell_rc = sub_proc.returncode
151
Michael Walsh410b1782019-10-22 15:56:18 -0500152 # Retrieve return code by examining ret_code_str output statement from status file.
Michael Walsh888be1f2019-03-26 12:02:36 -0500153 # Example text to be analyzed.
154 # auto_status_file_ret_code: 127
155 cmd_buf = "tail -n 10 " + status_file_path + " | egrep -a \"" \
156 + ret_code_str + ":[ ]+\""
157 rc, output = shell_cmd(cmd_buf)
158 key, value = parse_key_value(output)
159 shell_rc = int(value)
160
161 return shell_rc
162
163
164def tee_func(command_string, status_file_path):
165 r"""
Michael Walsh410b1782019-10-22 15:56:18 -0500166 Run the command string producing both stdout and file output via the tee command and return the shell_rc.
Michael Walsh888be1f2019-03-26 12:02:36 -0500167
168 Description of argument(s):
169 command_string The command string to be run.
Michael Walsh410b1782019-10-22 15:56:18 -0500170 status_file_path The path to the status file which is to contain a copy of all stdout.
Michael Walsh888be1f2019-03-26 12:02:36 -0500171 """
172
173 cmd_buf = "set -o pipefail ; " + command_string + " 2>&1 | tee -a " \
174 + status_file_path
175 qprint_issuing(cmd_buf)
176 sub_proc = subprocess.Popen(cmd_buf, shell=True)
177 sub_proc.communicate()
178 shell_rc = sub_proc.returncode
179
180 print
181 print_varx(ret_code_str, shell_rc)
182 with open(status_file_path, "a") as status_file:
183 # Append ret code string and status_file_path to end of status file.
184 status_file.write("\n" + sprint_varx(ret_code_str, shell_rc))
185
186 return shell_rc
187
188
189def main():
190
Michael Walsh60d08f32019-11-25 16:51:39 -0600191 gen_setup()
Michael Walsh888be1f2019-03-26 12:02:36 -0500192
193 global ret_code_str
194 ret_code_str = re.sub("\\.py$", "", pgm_name) + "_ret_code"
195
196 global show_url
197 if show_url:
198 shell_rc, output = shell_cmd("which get_file_path_url.py", show_err=0)
199 if shell_rc != 0:
200 show_url = 0
201 set_pgm_arg(show_url)
202 else:
203 shell_rc, status_file_url = shell_cmd("get_file_path_url.py "
204 + status_file_path)
205 status_file_url = status_file_url.rstrip("\n")
206
207 # Print status file path/url to stdout and to status file.
208 with open(status_file_path, "w+") as status_file:
209 if show_url:
210 print_var(status_file_url)
211 status_file.write(sprint_var(status_file_url))
212 else:
213 print_var(status_file_path)
214 status_file.write(sprint_var(status_file_path))
215
216 if stdout:
217 if tee:
218 shell_rc = tee_func(command_string, status_file_path)
219 else:
220 shell_rc = script_func(command_string, status_file_path)
221 if show_url:
222 print_var(status_file_url)
223 else:
224 print_var(status_file_path)
225 else:
226 cmd_buf = command_string + " >> " + status_file_path + " 2>&1"
227 shell_rc, output = shell_cmd(cmd_buf, show_err=0)
228 with open(status_file_path, "a") as status_file:
229 # Append ret code string and status_file_path to end of status
230 # file.
231 status_file.write("\n" + sprint_varx(ret_code_str, shell_rc))
232
233 # Append status_file_path print statement to end of status file.
234 with open(status_file_path, "a") as status_file:
235 if show_url:
236 status_file.write(sprint_var(status_file_url))
237 else:
238 status_file.write(sprint_var(status_file_path))
239 exit(shell_rc)
240
241
242main()