File size: 10,212 Bytes
784ee2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Generate reports from current logs
"""

import argparse
import os
import re

os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

LOGS_FOLDER = "logs"
REPORTS_FOLDER = "reports"
REPORT_FILENAME = "report.log"
SINGLE_REPORT_FILENAME = f"{REPORTS_FOLDER}/report.log"
SUMMARY_FILENAME = f"{REPORTS_FOLDER}/report-summary.log"
DRC_FILENAME = "5_route_drc.rpt"
LAST_EXPECTED_LOG = ["6_report.log", "generate_abstract.log"]
METRICS_LOG_FMT = "metadata-generate.log"
METRICS_CHECK_FMT = "{}/metadata-check.log"
REGEX_ERROR = re.compile(r"^\[error ?(\w+-\d+)?\]", re.IGNORECASE)
REGEX_WARNING = re.compile(r"^\[warning ?(\w+-\d+)?\]", re.IGNORECASE)
SKIPPED_FLOW_VARIANT_KEYWORDS = ["test", "tune"]
STATUS_GREEN = "Passing"
STATUS_RED = "Failing"

HELP_TEXT = """
Scans "./logs" and "./reports" folders for errors and warnings.
"""
parser = argparse.ArgumentParser(description=HELP_TEXT)

HELP_TEXT = """
Level 0: report error message id and drc types.
Level 1: report full error messages.
Level 2: report full error messages and warning messages id.
Level 3: report full error messages and full warning messages.
"""
parser.add_argument(
    "--verbose", "-v", required=False, default=0, action="count", help=HELP_TEXT
)

parser.add_argument(
    "--quiet",
    "-q",
    required=False,
    default=False,
    action="store_true",
    help="Do not print report to stdout.",
)

parser.add_argument(
    "--summary",
    "-s",
    required=False,
    default=False,
    action="store_true",
    help="Only write summary file.",
)

args = parser.parse_args()


def parse_messages(filename, print_missing=True):
    """
    TODO: docs
    """
    errors = list()
    warnings = list()
    try:
        with open(filename, "r") as file:
            lines = file.readlines()
        for line in lines:
            if re.search(REGEX_ERROR, line):
                errors.append(line.strip())
            elif re.search(REGEX_WARNING, line):
                warnings.append(line.strip())
    except BaseException:
        if print_missing:
            print(f"Failed to open {filename}.")
    return errors, warnings


def append_text(list_, text, sup, regex, verbose):
    """
    TODO
    """
    if len(list_) == 0:
        return text
    text += f"  Found {len(list_)} {sup}.\n"
    if verbose >= 1:  # print full message
        for item in list_:
            text += f"      {item}\n"
    else:  # only print the id
        set_ = set()
        long_set = set()
        for item in list_:
            message = re.match(regex, item).group(1)
            if message is None:
                message = item
            if len(message) > 10:  # considering a std msg id XYZ-0000
                long_set.add(message)
            else:
                set_.add(message)
        set_ = sorted(set_, reverse=True)
        if set_:
            text += f"      {', '.join(set_)}\n"
        for item in long_set:
            text += f"      {item}\n"
    return text


def gen_report(name, data):
    """
    TODO: docs
    """

    if args.verbose >= 2 or data["status"] != STATUS_GREEN:
        output = f"{name}\n"
        if data["finished"]:
            output += "  Flow reached last stage.\n"
        else:
            output += f"  Last log file {data['last_log']}\n"
    else:
        output = ""

    output = append_text(
        data["log_errors"], output, "errors in the logs", REGEX_ERROR, args.verbose
    )
    output = append_text(
        data["metrics_logs_errors"],
        output,
        "errors in the metrics logs",
        REGEX_ERROR,
        args.verbose,
    )
    output = append_text(
        data["metrics_errors"], output, "metrics failures", REGEX_ERROR, args.verbose
    )
    output = append_text(
        data["calibre_errors"], output, "calibre failures", REGEX_ERROR, args.verbose
    )

    if args.verbose >= 2:
        output = append_text(
            data["log_warnings"],
            output,
            "warnings in the logs",
            REGEX_WARNING,
            args.verbose - 2,
        )
        output = append_text(
            data["metrics_logs_warnings"],
            output,
            "warnings in the metrics logs",
            REGEX_WARNING,
            args.verbose - 2,
        )
        output = append_text(
            data["metrics_warnings"],
            output,
            "metrics warnings",
            REGEX_WARNING,
            args.verbose - 2,
        )
        output = append_text(
            data["calibre_warnings"],
            output,
            "calibre warnings",
            REGEX_WARNING,
            args.verbose - 2,
        )

    if len(data["drcs"].keys()) > 0:
        if data["status"] == STATUS_GREEN:
            output += "  Design has the violations under the allowed limit: "
        else:
            output += "  Design has the violations over the allowed limit: "
        for drc, count in data["drcs"].items():
            output += f"{drc} ({count}) "
        output += "\n"

    return output.strip()


def write_report(path, content):
    """
    TODO: docs
    """
    content = content.strip()
    with open(path, "w") as file:
        file.write(content)
    if args.verbose:
        content += f"\n  Generated report file: {path}\n"
    with open(SINGLE_REPORT_FILENAME, "a") as file:
        file.write(content)
        file.write("\n")
    if not args.quiet and content != "":
        print(content)


def get_summary(status, text):
    """
    TODO: docs
    """
    tmp = ""
    for name, data in design_list.items():
        if data["status"] == status:
            content = gen_report(name, data)
            if content != "":
                tmp += content + "\n"
                # add empty line for readability
                if args.verbose >= 2 or status == STATUS_RED:
                    tmp += "\n"
    if tmp != "":
        text += "-" * 30 + "\n"
        text += " " * 7 + f"{status} designs\n"
        text += "-" * 30 + "\n"
        text += tmp

    return text


def write_summary():
    """
    Write summary and individual report files with data on design_list
    """
    summary = "\n"
    summary += "=" * 60 + "\n"
    summary += " " * 26 + "SUMMARY\n"
    summary += "=" * 60 + "\n"
    summary += f"\nNumber of designs: {len(design_list.keys())}\n\n"

    summary = get_summary(STATUS_RED, summary)
    summary += "\n"
    summary = get_summary(STATUS_GREEN, summary)

    if not args.quiet:
        if os.path.isfile(SUMMARY_FILENAME):
            print(f"Overwriting report summary {SUMMARY_FILENAME}.")
        print(summary)
    with open(SUMMARY_FILENAME, "w") as file:
        file.write(summary)
    if not args.quiet and args.verbose:
        print("Generated report summary file:", SUMMARY_FILENAME)


design_list = dict()

for log_dir, dirs, files in sorted(os.walk(LOGS_FOLDER, topdown=False)):
    dir_list = log_dir.split(os.sep)
    # Handles autotuner folders, which do not have `report.log` natively.
    # TODO: Can we log something for autotuner?
    if len(dir_list) != 4 or any(
        word in dir_list[-1] for word in SKIPPED_FLOW_VARIANT_KEYWORDS
    ):
        continue
    report_dir = log_dir.replace(LOGS_FOLDER, REPORTS_FOLDER)

    # basic info about current design
    platform, design, variant = dir_list[1:]
    d = dict()
    d["output_file"] = os.path.join(report_dir, REPORT_FILENAME)

    # check if design ran to completion without errors or warnings
    d["log_errors"] = list()
    d["log_warnings"] = list()
    d["last_log"] = ""
    for name_ in sorted(files):
        temp_e, temp_w = parse_messages(os.path.join(log_dir, name_))
        d["log_errors"] += temp_e
        d["log_warnings"] += temp_w
        if name_.endswith(".log"):
            d["last_log"] = name_
    d["finished"] = d["last_log"] in LAST_EXPECTED_LOG

    # check if metrics generation had issues
    d["metrics_logs_errors"], d["metrics_logs_warnings"] = parse_messages(
        os.path.join(report_dir, METRICS_LOG_FMT),
        print_missing=d["finished"],
    )

    # check if metrics passed
    d["metrics_errors"], d["metrics_warnings"] = parse_messages(
        METRICS_CHECK_FMT.format(report_dir), print_missing=d["finished"]
    )

    # check if calibre was run and if drc check passed
    d["calibre_errors"], d["calibre_warnings"] = parse_messages(
        os.path.join(log_dir, "calibre/save-to-drc-db.log"), print_missing=False
    )

    # check if there were drc violations
    d["drcs"] = dict()
    try:
        drc_report_file = os.path.join(report_dir, DRC_FILENAME)
        with open(drc_report_file, "r") as file_:
            for line_ in file_.readlines():
                if "violation type:" in line_:
                    type_ = line_.split("violation type:", 1)[1].strip()
                    if type_ in d["drcs"].keys():
                        d["drcs"][type_] += 1
                    else:
                        d["drcs"][type_] = 1
    except BaseException:
        if d["finished"]:
            print(f"Failed to open {DRC_FILENAME}.")

    if d["log_errors"] or d["metrics_errors"] or d["calibre_errors"]:
        d["status"] = STATUS_RED
    else:
        if not d["finished"]:
            d["status"] = STATUS_RED
            last_lines = "Could not find last lines of the log file."
            with open(os.path.join(log_dir, d["last_log"]), "r") as last_file:
                last_lines = last_file.readlines()[-10:]
                last_lines = "          ".join(last_lines)
            message = "[ERROR CI-0000] No error message found. "
            message += "Here are the last 10 lines of the log.\n"
            d["log_errors"] = [message + last_lines]
        else:
            d["status"] = STATUS_GREEN

    design_list[f"{platform} {design} ({variant})"] = d

if not os.path.isdir(REPORTS_FOLDER):
    os.mkdir(REPORTS_FOLDER)

if args.summary:
    write_summary()
else:
    if os.path.isfile(SINGLE_REPORT_FILENAME):
        if not args.quiet:
            print(f"Overwriting report {SINGLE_REPORT_FILENAME}.")
        os.remove(SINGLE_REPORT_FILENAME)
    for name_, data_ in design_list.items():
        write_report(data_["output_file"], gen_report(name_, data_))