Debian Codegraph @

bin/ci/custom_logger.py

raw
1 import argparse
2 import logging
3 from datetime import datetime
4 from pathlib import Path
5
6 from structured_logger import StructuredLogger
7
8
9 class CustomLogger:
10 def __init__(self, log_file):
11 self.log_file = log_file
12 self.logger = StructuredLogger(file_name=self.log_file)
13
14 def get_last_dut_job(self):
15 """
16 Gets the details of the most recent DUT job.
17
18 Returns:
19 dict: Details of the most recent DUT job.
20
21 Raises:
22 ValueError: If no DUT jobs are found in the logger's data.
23 """
24 try:
25 job = self.logger.data["dut_jobs"][-1]
26 except KeyError:
27 raise ValueError(
28 "No DUT jobs found. Please create a job via create_dut_job call."
29 )
30
31 return job
32
33 def update(self, **kwargs):
34 """
35 Updates the log file with provided key-value pairs.
36
37 Args:
38 **kwargs: Key-value pairs to be updated.
39
40 """
41 with self.logger.edit_context():
42 for key, value in kwargs.items():
43 self.logger.data[key] = value
44
45 def create_dut_job(self, **kwargs):
46 """
47 Creates a new DUT job with provided key-value pairs.
48
49 Args:
50 **kwargs: Key-value pairs for the new DUT job.
51
52 """
53 with self.logger.edit_context():
54 if "dut_jobs" not in self.logger.data:
55 self.logger.data["dut_jobs"] = []
56 new_job = {
57 "status": "",
58 "submitter_start_time": datetime.now().isoformat(),
59 "dut_submit_time": "",
60 "dut_start_time": "",
61 "dut_end_time": "",
62 "dut_duration_time": "",
63 "dut_name": "",
64 "dut_state": "pending",
65 "dut_job_phases": [],
66 **kwargs,
67 }
68 self.logger.data["dut_jobs"].append(new_job)
69
70 def update_dut_job(self, key, value):
71 """
72 Updates the last DUT job with a key-value pair.
73
74 Args:
75 key : The key to be updated.
76 value: The value to be assigned.
77
78 """
79 with self.logger.edit_context():
80 job = self.get_last_dut_job()
81 job[key] = value
82
83 def update_status_fail(self, reason=""):
84 """
85 Sets the status of the last DUT job to 'fail' and logs the failure reason.
86
87 Args:
88 reason (str, optional): The reason for the failure. Defaults to "".
89
90 """
91 with self.logger.edit_context():
92 job = self.get_last_dut_job()
93 job["status"] = "fail"
94 job["dut_job_fail_reason"] = reason
95
96 def create_job_phase(self, phase_name):
97 """
98 Creates a new job phase for the last DUT job.
99
100 Args:
101 phase_name : The name of the new job phase.
102
103 """
104 with self.logger.edit_context():
105 job = self.get_last_dut_job()
106 if job["dut_job_phases"] and job["dut_job_phases"][-1]["end_time"] == "":
107 # If the last phase exists and its end time is empty, set the end time
108 timestamp = datetime.now().isoformat()
109 job["dut_job_phases"][-1]["end_time"] = timestamp
110 job["dut_job_phases"][-1]["duration_time"] = self.get_duration_time(job["dut_job_phases"][-1]["start_time"], timestamp)
111
112 # Create a new phase
113 phase_data = {
114 "name": phase_name,
115 "start_time": datetime.now().isoformat(),
116 "end_time": "",
117 "duration_time": "",
118 }
119 job["dut_job_phases"].append(phase_data)
120
121 def check_dut_timings(self, job):
122 """
123 Check the timing sequence of a job to ensure logical consistency.
124
125 The function verifies that the job's submission time is not earlier than its start time and that
126 the job's end time is not earlier than its start time. If either of these conditions is found to be true,
127 an error is logged for each instance of inconsistency.
128
129 Args:
130 job (dict): A dictionary containing timing information of a job. Expected keys are 'dut_start_time',
131 'dut_submit_time', and 'dut_end_time'.
132
133 Returns:
134 None: This function does not return a value; it logs errors if timing inconsistencies are detected.
135
136 The function checks the following:
137 - If 'dut_start_time' and 'dut_submit_time' are both present and correctly sequenced.
138 - If 'dut_start_time' and 'dut_end_time' are both present and correctly sequenced.
139 """
140
141 # Check if the start time and submit time exist
142 if job.get("dut_start_time") and job.get("dut_submit_time"):
143 # If they exist, check if the submission time is before the start time
144 if job["dut_start_time"] < job["dut_submit_time"]:
145 logging.error("Job submission is happening before job start.")
146
147 # Check if the start time and end time exist
148 if job.get("dut_start_time") and job.get("dut_end_time"):
149 # If they exist, check if the end time is after the start time
150 if job["dut_end_time"] < job["dut_start_time"]:
151 logging.error("Job ended before it started.")
152
153 def get_duration_time(self, start_time, end_time):
154 """
155 Computes duration time, in minutes and seconds.
156 """
157 try:
158 start = datetime.fromisoformat(start_time)
159 end = datetime.fromisoformat(end_time)
160 duration = end - start
161 return str(duration)
162 except ValueError:
163 return ""
164
165 # Method to update DUT start, submit and end time
166 def update_dut_time(self, value, custom_time):
167 """
168 Updates DUT start, submit, and end times.
169
170 Args:
171 value : Specifies which DUT time to update. Options: 'start', 'submit', 'end'.
172 custom_time : Custom time to set. If None, use current time.
173
174 Raises:
175 ValueError: If an invalid argument is provided for value.
176
177 """
178 with self.logger.edit_context():
179 job = self.get_last_dut_job()
180 timestamp = custom_time if custom_time else datetime.now().isoformat()
181 if value == "start":
182 job["dut_start_time"] = timestamp
183 job["dut_state"] = "running"
184 elif value == "submit":
185 job["dut_submit_time"] = timestamp
186 job["dut_state"] = "submitted"
187 elif value == "end":
188 job["dut_end_time"] = timestamp
189 job["dut_state"] = "finished"
190 job["dut_duration_time"] = self.get_duration_time(job["dut_start_time"], job["dut_end_time"])
191 else:
192 raise ValueError(
193 "Error: Invalid argument provided for --update-dut-time. Use 'start', 'submit', 'end'."
194 )
195 # check the sanity of the partial structured log
196 self.check_dut_timings(job)
197
198 def close_dut_job(self):
199 """
200 Closes the most recent DUT (Device Under Test) job in the logger's data.
201
202 The method performs the following operations:
203 1. Validates if there are any DUT jobs in the logger's data.
204 2. If the last phase of the most recent DUT job has an empty end time, it sets the end time to the current time.
205
206 Raises:
207 ValueError: If no DUT jobs are found in the logger's data.
208 """
209 with self.logger.edit_context():
210 job = self.get_last_dut_job()
211 # Check if the last phase exists and its end time is empty, then set the end time
212 if job["dut_job_phases"] and job["dut_job_phases"][-1]["end_time"] == "":
213 timestamp = datetime.now().isoformat()
214 job["dut_job_phases"][-1]["end_time"] = timestamp
215 job["dut_job_phases"][-1]["duration_time"] = self.get_duration_time(job["dut_job_phases"][-1]["start_time"], timestamp)
216
217 def close(self):
218 """
219 Closes the most recent DUT (Device Under Test) job in the logger's data.
220
221 The method performs the following operations:
222 1. Determines the combined status of all DUT jobs.
223 2. Sets the submitter's end time to the current time.
224 3. Updates the DUT attempt counter to reflect the total number of DUT jobs.
225
226 """
227 with self.logger.edit_context():
228 job_status = []
229 for job in self.logger.data["dut_jobs"]:
230 if "status" in job:
231 job_status.append(job["status"])
232
233 if not job_status:
234 job_combined_status = "null"
235 else:
236 # Get job_combined_status
237 if "pass" in job_status:
238 job_combined_status = "pass"
239 else:
240 job_combined_status = "fail"
241
242 self.logger.data["job_combined_status"] = job_combined_status
243 self.logger.data["dut_attempt_counter"] = len(self.logger.data["dut_jobs"])
244 job["submitter_end_time"] = datetime.now().isoformat()
245
246
247 def process_args(args):
248 # Function to process key-value pairs and call corresponding logger methods
249 def process_key_value_pairs(args_list, action_func):
250 if not args_list:
251 raise ValueError(
252 f"No key-value pairs provided for {action_func.__name__.replace('_', '-')}"
253 )
254 if len(args_list) % 2 != 0:
255 raise ValueError(
256 f"Incomplete key-value pairs for {action_func.__name__.replace('_', '-')}"
257 )
258 kwargs = dict(zip(args_list[::2], args_list[1::2]))
259 action_func(**kwargs)
260
261 # Create a CustomLogger object with the specified log file path
262 custom_logger = CustomLogger(Path(args.log_file))
263
264 if args.update:
265 process_key_value_pairs(args.update, custom_logger.update)
266
267 if args.create_dut_job:
268 process_key_value_pairs(args.create_dut_job, custom_logger.create_dut_job)
269
270 if args.update_dut_job:
271 key, value = args.update_dut_job
272 custom_logger.update_dut_job(key, value)
273
274 if args.create_job_phase:
275 custom_logger.create_job_phase(args.create_job_phase)
276
277 if args.update_status_fail:
278 custom_logger.update_status_fail(args.update_status_fail)
279
280 if args.update_dut_time:
281 if len(args.update_dut_time) == 2:
282 action, custom_time = args.update_dut_time
283 elif len(args.update_dut_time) == 1:
284 action, custom_time = args.update_dut_time[0], None
285 else:
286 raise ValueError("Invalid number of values for --update-dut-time")
287
288 if action in ["start", "end", "submit"]:
289 custom_logger.update_dut_time(action, custom_time)
290 else:
291 raise ValueError(
292 "Error: Invalid argument provided for --update-dut-time. Use 'start', 'submit', 'end'."
293 )
294
295 if args.close_dut_job:
296 custom_logger.close_dut_job()
297
298 if args.close:
299 custom_logger.close()
300
301
302 def main():
303 parser = argparse.ArgumentParser(description="Custom Logger Command Line Tool")
304 parser.add_argument("log_file", help="Path to the log file")
305 parser.add_argument(
306 "--update",
307 nargs=argparse.ZERO_OR_MORE,
308 metavar=("key", "value"),
309 help="Update a key-value pair e.g., --update key1 value1 key2 value2)",
310 )
311 parser.add_argument(
312 "--create-dut-job",
313 nargs=argparse.ZERO_OR_MORE,
314 metavar=("key", "value"),
315 help="Create a new DUT job with key-value pairs (e.g., --create-dut-job key1 value1 key2 value2)",
316 )
317 parser.add_argument(
318 "--update-dut-job",
319 nargs=argparse.ZERO_OR_MORE,
320 metavar=("key", "value"),
321 help="Update a key-value pair in DUT job",
322 )
323 parser.add_argument(
324 "--create-job-phase",
325 help="Create a new job phase (e.g., --create-job-phase name)",
326 )
327 parser.add_argument(
328 "--update-status-fail",
329 help="Update fail as the status and log the failure reason (e.g., --update-status-fail reason)",
330 )
331 parser.add_argument(
332 "--update-dut-time",
333 nargs=argparse.ZERO_OR_MORE,
334 metavar=("action", "custom_time"),
335 help="Update DUT start and end time. Provide action ('start', 'submit', 'end') and custom_time (e.g., '2023-01-01T12:00:00')",
336 )
337 parser.add_argument(
338 "--close-dut-job",
339 action="store_true",
340 help="Close the dut job by updating end time of last dut job)",
341 )
342 parser.add_argument(
343 "--close",
344 action="store_true",
345 help="Updates combined status, submitter's end time and DUT attempt counter",
346 )
347 args = parser.parse_args()
348
349 process_args(args)
350
351
352 if __name__ == "__main__":
353 main()