File size: 4,312 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
#!/usr/bin/env python3

"""
This scripts checks the metadata.json against a set of rules for allowed
values.  This allows degradation in results to be flagged as an error
in the build.

The rules file has the form
{
   "rules": [
       {
           "field" : "<name>",
           "value" : <numeric_value>,
           "compare": "<operator>"
       }, ...
   ]
}

field is the name of a field in the metadata file
value is the reference value to compare to
operator can be one of "<", ">", "<=", ">=", "==", "!=".
The value is converted to a float for comparison if possible
"""

from os.path import isfile
import argparse
import json
import operator
import sys

parser = argparse.ArgumentParser(
    description="Checks metadata from OpenROAD flow against a set of rules"
)
parser.add_argument("--metadata", "-m", required=True, help="The metadata file")
parser.add_argument("--rules", "-r", required=True, nargs="+", help="The rules file")
parser.add_argument(
    "--only-prefix",
    nargs="+",
    default=None,
    help="Check only rules whose field starts with one of these prefixes. "
    "Lets a partial run (e.g. synthesis-only) be gated by a full-flow "
    "rules file without tripping the missing-field error.",
)
args = parser.parse_args()

with open(args.metadata) as metadataFile:
    metadata = json.load(metadataFile)

rules = dict()
for filePath in args.rules:
    if isfile(filePath):
        with open(filePath) as rulesFile:
            rules.update(json.load(rulesFile))
    else:
        print(f"[WARN] File {filePath} not found")

if args.only_prefix:
    rules = {
        field: rule
        for field, rule in rules.items()
        if any(field.startswith(prefix) for prefix in args.only_prefix)
    }

if len(rules) == 0:
    print("No rules")
    sys.exit(1)


def try_number(string):
    """
    Convert to a float if possible
    """
    try:
        return float(string)
    except ValueError:
        return string


ops = {
    "<": operator.lt,
    ">": operator.gt,
    "<=": operator.le,
    ">=": operator.ge,
    "==": operator.eq,
    "!=": operator.ne,
}

ERRORS = 0
WARNS = 0

# Check for new warnings
for field, build_value in metadata.items():
    if field not in rules.keys() and "__warnings__count:" in field:
        print(f"[WARN] {field} fail test: {build_value} (New warning)")
        WARNS += 1

# Check for rules
for field, rule in rules.items():
    compare = rule["compare"]
    op = ops[compare]
    rule_value = try_number(rule["value"])

    if field in metadata.keys():
        build_value = try_number(metadata[field])
    elif "__warnings__count:" in field:
        # Metric is a warning count. If the value is missing,
        # there were zero warnings
        build_value = 0.0
    else:
        print(f"[ERROR] Value not found for {field}.")
        sys.exit(1)

    # Convert to integer if possible
    if isinstance(rule_value, float) and rule_value.is_integer():
        rule_value = int(rule_value)
    if isinstance(build_value, float) and build_value.is_integer():
        build_value = int(build_value)

    try:
        if op(build_value, rule_value):
            PRE = "[INFO]"
            CHECK = "pass"
        elif rule.get("level") == "warning":
            # Warning-level rules never fail the build, but the prior
            # message ("[WARN] field pass test: a == b") was misleading
            # when a != b -- the build_value clearly differed from the
            # rule_value yet "pass" implied a match. Say "differs"
            # instead so the diagnostic reads naturally for fields like
            # the netlist hash where the user wants visibility without
            # an error.
            PRE = "[WARN]"
            CHECK = "differs"
            WARNS += 1
        else:
            PRE = "[ERROR]"
            CHECK = "fail"
            ERRORS += 1
    except TypeError:
        # Handle cases where types are not comparable (e.g., string vs. number)
        PRE = "[ERROR]"
        CHECK = "fail"
        ERRORS += 1
    print(PRE, field, CHECK, "test:", build_value, compare, rule_value)

print(f"Metadata check warnings: {WARNS}")

if ERRORS == 0:
    print(f"All metadata rules passed ({len(rules)} rules)")
else:
    print(f"Failed metadata checks: {ERRORS} out of {len(rules)}")

sys.exit(1 if ERRORS else 0)