File: custom_logger.py

package info (click to toggle)
mesa 26.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 325,884 kB
  • sloc: ansic: 2,260,508; xml: 1,035,283; cpp: 528,036; python: 83,447; asm: 40,568; yacc: 12,040; lisp: 3,663; lex: 3,461; sh: 1,035; makefile: 224
file content (353 lines) | stat: -rw-r--r-- 12,910 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import argparse
import logging
from datetime import datetime
from pathlib import Path

from structured_logger import StructuredLogger


class CustomLogger:
    def __init__(self, log_file):
        self.log_file = log_file
        self.logger = StructuredLogger(file_name=self.log_file)

    def get_last_dut_job(self):
        """
        Gets the details of the most recent DUT job.

        Returns:
            dict: Details of the most recent DUT job.

        Raises:
            ValueError: If no DUT jobs are found in the logger's data.
        """
        try:
            job = self.logger.data["dut_jobs"][-1]
        except KeyError:
            raise ValueError(
                "No DUT jobs found. Please create a job via create_dut_job call."
            )

        return job

    def update(self, **kwargs):
        """
        Updates the log file with provided key-value pairs.

        Args:
            **kwargs: Key-value pairs to be updated.

        """
        with self.logger.edit_context():
            for key, value in kwargs.items():
                self.logger.data[key] = value

    def create_dut_job(self, **kwargs):
        """
        Creates a new DUT job with provided key-value pairs.

        Args:
            **kwargs: Key-value pairs for the new DUT job.

        """
        with self.logger.edit_context():
            if "dut_jobs" not in self.logger.data:
                self.logger.data["dut_jobs"] = []
            new_job = {
                "status": "",
                "submitter_start_time": datetime.now().isoformat(),
                "dut_submit_time": "",
                "dut_start_time": "",
                "dut_end_time": "",
                "dut_duration_time": "",
                "dut_name": "",
                "dut_state": "pending",
                "dut_job_phases": [],
                **kwargs,
            }
            self.logger.data["dut_jobs"].append(new_job)

    def update_dut_job(self, key, value):
        """
        Updates the last DUT job with a key-value pair.

        Args:
            key : The key to be updated.
            value: The value to be assigned.

        """
        with self.logger.edit_context():
            job = self.get_last_dut_job()
            job[key] = value

    def update_status_fail(self, reason=""):
        """
        Sets the status of the last DUT job to 'fail' and logs the failure reason.

        Args:
            reason (str, optional): The reason for the failure. Defaults to "".

        """
        with self.logger.edit_context():
            job = self.get_last_dut_job()
            job["status"] = "fail"
            job["dut_job_fail_reason"] = reason

    def create_job_phase(self, phase_name):
        """
        Creates a new job phase for the last DUT job.

        Args:
            phase_name : The name of the new job phase.

        """
        with self.logger.edit_context():
            job = self.get_last_dut_job()
            if job["dut_job_phases"] and job["dut_job_phases"][-1]["end_time"] == "":
                # If the last phase exists and its end time is empty, set the end time
                timestamp = datetime.now().isoformat()
                job["dut_job_phases"][-1]["end_time"] = timestamp
                job["dut_job_phases"][-1]["duration_time"] = self.get_duration_time(job["dut_job_phases"][-1]["start_time"], timestamp)

            # Create a new phase
            phase_data = {
                "name": phase_name,
                "start_time": datetime.now().isoformat(),
                "end_time": "",
                "duration_time": "",
            }
            job["dut_job_phases"].append(phase_data)

    def check_dut_timings(self, job):
        """
        Check the timing sequence of a job to ensure logical consistency.

        The function verifies that the job's submission time is not earlier than its start time and that
        the job's end time is not earlier than its start time. If either of these conditions is found to be true,
        an error is logged for each instance of inconsistency.

        Args:
        job (dict): A dictionary containing timing information of a job. Expected keys are 'dut_start_time',
                    'dut_submit_time', and 'dut_end_time'.

        Returns:
        None: This function does not return a value; it logs errors if timing inconsistencies are detected.

        The function checks the following:
        - If 'dut_start_time' and 'dut_submit_time' are both present and correctly sequenced.
        - If 'dut_start_time' and 'dut_end_time' are both present and correctly sequenced.
        """

        # Check if the start time and submit time exist
        if job.get("dut_start_time") and job.get("dut_submit_time"):
            # If they exist, check if the submission time is before the start time
            if job["dut_start_time"] < job["dut_submit_time"]:
                logging.error("Job submission is happening before job start.")

        # Check if the start time and end time exist
        if job.get("dut_start_time") and job.get("dut_end_time"):
            # If they exist, check if the end time is after the start time
            if job["dut_end_time"] < job["dut_start_time"]:
                logging.error("Job ended before it started.")

    def get_duration_time(self, start_time, end_time):
        """
        Computes duration time, in minutes and seconds.
        """
        try:
            start = datetime.fromisoformat(start_time)
            end = datetime.fromisoformat(end_time)
            duration = end - start
            return str(duration)
        except ValueError:
            return ""

    # Method to update DUT start, submit and end time
    def update_dut_time(self, value, custom_time):
        """
        Updates DUT start, submit, and end times.

        Args:
            value : Specifies which DUT time to update. Options: 'start', 'submit', 'end'.
            custom_time : Custom time to set. If None, use current time.

        Raises:
            ValueError: If an invalid argument is provided for value.

        """
        with self.logger.edit_context():
            job = self.get_last_dut_job()
            timestamp = custom_time if custom_time else datetime.now().isoformat()
            if value == "start":
                job["dut_start_time"] = timestamp
                job["dut_state"] = "running"
            elif value == "submit":
                job["dut_submit_time"] = timestamp
                job["dut_state"] = "submitted"
            elif value == "end":
                job["dut_end_time"] = timestamp
                job["dut_state"] = "finished"
                job["dut_duration_time"] = self.get_duration_time(job["dut_start_time"], job["dut_end_time"])
            else:
                raise ValueError(
                    "Error: Invalid argument provided for --update-dut-time. Use 'start', 'submit', 'end'."
                )
            # check the sanity of the partial structured log
            self.check_dut_timings(job)

    def close_dut_job(self):
        """
        Closes the most recent DUT (Device Under Test) job in the logger's data.

        The method performs the following operations:
        1. Validates if there are any DUT jobs in the logger's data.
        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.

        Raises:
            ValueError: If no DUT jobs are found in the logger's data.
        """
        with self.logger.edit_context():
            job = self.get_last_dut_job()
            # Check if the last phase exists and its end time is empty, then set the end time
            if job["dut_job_phases"] and job["dut_job_phases"][-1]["end_time"] == "":
                timestamp = datetime.now().isoformat()
                job["dut_job_phases"][-1]["end_time"] = timestamp
                job["dut_job_phases"][-1]["duration_time"] = self.get_duration_time(job["dut_job_phases"][-1]["start_time"], timestamp)

    def close(self):
        """
        Closes the most recent DUT (Device Under Test) job in the logger's data.

        The method performs the following operations:
        1. Determines the combined status of all DUT jobs.
        2. Sets the submitter's end time to the current time.
        3. Updates the DUT attempt counter to reflect the total number of DUT jobs.

        """
        with self.logger.edit_context():
            job_status = []
            for job in self.logger.data["dut_jobs"]:
                if "status" in job:
                    job_status.append(job["status"])

            if not job_status:
                job_combined_status = "null"
            else:
                # Get job_combined_status
                if "pass" in job_status:
                    job_combined_status = "pass"
                else:
                    job_combined_status = "fail"

            self.logger.data["job_combined_status"] = job_combined_status
            self.logger.data["dut_attempt_counter"] = len(self.logger.data["dut_jobs"])
            job["submitter_end_time"] = datetime.now().isoformat()


def process_args(args):
    # Function to process key-value pairs and call corresponding logger methods
    def process_key_value_pairs(args_list, action_func):
        if not args_list:
            raise ValueError(
                f"No key-value pairs provided for {action_func.__name__.replace('_', '-')}"
            )
        if len(args_list) % 2 != 0:
            raise ValueError(
                f"Incomplete key-value pairs for {action_func.__name__.replace('_', '-')}"
            )
        kwargs = dict(zip(args_list[::2], args_list[1::2]))
        action_func(**kwargs)

    # Create a CustomLogger object with the specified log file path
    custom_logger = CustomLogger(Path(args.log_file))

    if args.update:
        process_key_value_pairs(args.update, custom_logger.update)

    if args.create_dut_job:
        process_key_value_pairs(args.create_dut_job, custom_logger.create_dut_job)

    if args.update_dut_job:
        key, value = args.update_dut_job
        custom_logger.update_dut_job(key, value)

    if args.create_job_phase:
        custom_logger.create_job_phase(args.create_job_phase)

    if args.update_status_fail:
        custom_logger.update_status_fail(args.update_status_fail)

    if args.update_dut_time:
        if len(args.update_dut_time) == 2:
            action, custom_time = args.update_dut_time
        elif len(args.update_dut_time) == 1:
            action, custom_time = args.update_dut_time[0], None
        else:
            raise ValueError("Invalid number of values for --update-dut-time")

        if action in ["start", "end", "submit"]:
            custom_logger.update_dut_time(action, custom_time)
        else:
            raise ValueError(
                "Error: Invalid argument provided for --update-dut-time. Use 'start', 'submit', 'end'."
            )

    if args.close_dut_job:
        custom_logger.close_dut_job()

    if args.close:
        custom_logger.close()


def main():
    parser = argparse.ArgumentParser(description="Custom Logger Command Line Tool")
    parser.add_argument("log_file", help="Path to the log file")
    parser.add_argument(
        "--update",
        nargs=argparse.ZERO_OR_MORE,
        metavar=("key", "value"),
        help="Update a key-value pair e.g., --update key1 value1 key2 value2)",
    )
    parser.add_argument(
        "--create-dut-job",
        nargs=argparse.ZERO_OR_MORE,
        metavar=("key", "value"),
        help="Create a new DUT job with key-value pairs (e.g., --create-dut-job key1 value1 key2 value2)",
    )
    parser.add_argument(
        "--update-dut-job",
        nargs=argparse.ZERO_OR_MORE,
        metavar=("key", "value"),
        help="Update a key-value pair in DUT job",
    )
    parser.add_argument(
        "--create-job-phase",
        help="Create a new job phase (e.g., --create-job-phase name)",
    )
    parser.add_argument(
        "--update-status-fail",
        help="Update fail as the status and log the failure reason (e.g., --update-status-fail reason)",
    )
    parser.add_argument(
        "--update-dut-time",
        nargs=argparse.ZERO_OR_MORE,
        metavar=("action", "custom_time"),
        help="Update DUT start and end time. Provide action ('start', 'submit', 'end') and custom_time (e.g., '2023-01-01T12:00:00')",
    )
    parser.add_argument(
        "--close-dut-job",
        action="store_true",
        help="Close the dut job by updating end time of last dut job)",
    )
    parser.add_argument(
        "--close",
        action="store_true",
        help="Updates combined status, submitter's end time and DUT attempt counter",
    )
    args = parser.parse_args()

    process_args(args)


if __name__ == "__main__":
    main()