aboutsummaryrefslogtreecommitdiffstats
path: root/fpga/usrp3/tools/utils/repeat_fpga_build.py
blob: 7f013ec616e96807774e71dce9a418c09644b7ef (plain) (blame)
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
#!/usr/bin/env python3
#
# Copyright 2023 Ettus Research, a National Instrument Brand
#
# SPDX-License-Identifier: GPL-3.0-or-later
#

"""
Repeatedly runs the requested build until it builds successfully and meets
timing, up to a maximum number of tries. Builds will be retried when they
fail with timing errors or other errors that might not reoccur. Builds will
stop if a an unrecognized error occurs.
"""

import sys
import argparse
import subprocess
import logging
import re
import random


def parse_args():
    """Parse the command line arguments.

    Returns:
        Populated namespace containing the arguments and their values.
    """
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        "--target",
        "-t",
        type=str,
        help="FPGA make target to build (e.g., X310_XG).",
    )
    parser.add_argument(
        "--image-core",
        "-y",
        type=str,
        help="For using the image builder instead of make, use this to specify "
        "the image core YAML.",
    )
    parser.add_argument(
        "--num",
        "-n",
        type=int,
        default=4,
        required=False,
        help="Number of times to attempt the build.",
    )
    parser.add_argument(
        "--persistent",
        "-p",
        action="store_true",
        default=False,
        help=(
            "Continue retrying builds regardless of which error occurs, "
            "up to the specified number of attempts."
        ),
    )
    parser.add_argument(
        "--seed",
        "-s",
        type=int,
        default=0,
        required=False,
        help="Initial seed value to use.",
    )
    return parser.parse_args()


def prepare_build(target, image_core):
    """
    Run tasks to prepare the build. In particular, execute the RFNoC image builder
    if desired.
    """
    if image_core:
        logging.info("Calling rfnoc_image_builder to prepare FPGA build.")
        cmd = [
            "rfnoc_image_builder",
            "--yaml-config",
            image_core,
            "--generate-only",
            "--no-hash",
            "--no-date",
        ]
        if target:
            cmd += ["--target", target]
        result = subprocess.run(
            cmd,
            check=False,
            encoding="utf-8",
            capture_output=True,
        )
        logging.info("rfnoc_image_builder output:")
        logging.info("stdout:\n%s", result.stdout)
        logging.info("stderr:\n%s", result.stderr)
        if result.returncode:
            logging.error("Image builder failed! Consult output for details.")
        result.check_returncode()
        # Parse the image builder output to get the make command we need to build the FPGA
        make_command = re.search(r"(?<=: )make.*$", result.stderr, flags=re.M).group(0)
        logging.info("Using make command: %s", make_command)
    else:
        assert target
        make_command = f"make {target}"
    return {
        "make_command": make_command,
    }


def run_fpga_build(build_seed, cfg):
    """Performs one iteration of an FPGA build.

    Args:
        build_seed: 32-bit signed integer to seed the FPGA build.
        cfg: Build configuration info

    Returns:
        0: The build succeeded.
        1: There was a timing or other error that might not reoccur.
        2: There was some other error that should cause us to stop trying.
    """
    output = ""
    make_cmd = cfg["make_command"]
    cmd = f'/bin/bash -c "{make_cmd} BUILD_SEED={build_seed}"'
    with subprocess.Popen(
        cmd,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        bufsize=1,
        universal_newlines=True,
    ) as proc:
        for line in proc.stdout:
            print(line, end="")
            output += line
    if proc.returncode != 0:
        # Regular expressions for error strings to search for that would tell
        # us we should try again.
        transient_errors = [
            # Standard timing error:
            "The design did not satisfy timing constraints",
            # Known issue fixed in Vivado 2021.2:
            (
                "Router encountered a fatal exception of type .*"
                "Trying to tool lock on already tool locked arc"
            ),
        ]
        for error_string in transient_errors:
            if re.search(error_string, output):
                return 1
        return 2
    return 0


def next_build_seed(previous_seed):
    """Determines the next seed to use based on the previous seed. This creates
    a reproducible sequence of values with a specific initial value.

    Args:
        previous_seed: The previous integer seed from which to determine the
            new seed.

    Returns:
        The next build seed value in the range of a 32-bit signed integer.
    """
    random.seed(previous_seed)
    return random.randint(-0x80000000, 0x7FFFFFFF)


def main():
    """Run the requested builds.

    Returns:
        The status of the last build (0 if successful, non-zero if the build
        failed).
    """
    logging.basicConfig(format="[REPEAT BUILD][%(levelname)s] %(message)s")
    logging.root.setLevel(logging.INFO)
    args = parse_args()
    if not args.target and not args.image_core:
        logging.error("Either --target or --image-core must be provided!")
        return 1
    build_seed = args.seed
    status = 128
    cfg = prepare_build(args.target, args.image_core)
    try:
        for build_num in range(1, args.num + 1):
            logging.info("Starting FPGA build %d with seed %s", build_num, build_seed)
            status = run_fpga_build(build_seed, cfg)
            logging.info("Finished FPGA build %d", build_num)
            if status == 0:
                logging.info("FPGA build succeeded on attempt number %s", build_num)
                break
            if build_num == args.num:
                logging.error("Reached maximum number of FPGA build attempts")
            elif status == 1:
                logging.info("FPGA build will be restarted due to unsuccessful attempt")
            elif status == 2 and not args.persistent:
                logging.error("Stopping due to unexpected FPGA build error")
                break
            build_seed = next_build_seed(build_seed)
    except KeyboardInterrupt:
        logging.info("Received SIGINT. Aborting . . .")
        # Return normal Bash value for SIGINT (128+2)
        return 130
    return status


if __name__ == "__main__":
    sys.exit(main())