summaryrefslogtreecommitdiff
path: root/firmware_builder.py
blob: 243534230a95c98945cbcf80303a6f5e4fc364a9 (plain)
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Build, bundle, or test all of the EC boards.

This is the entry point for the custom firmware builder workflow recipe.  It
gets invoked by chromite/api/controller/firmware.py.
"""

import argparse
import multiprocessing
import os
import subprocess
import sys

from google.protobuf import json_format

from chromite.api.gen.chromite.api import firmware_pb2

DEFAULT_BUNDLE_DIRECTORY = '/tmp/artifact_bundles'
DEFAULT_BUNDLE_METADATA_FILE = '/tmp/artifact_bundle_metadata'


def build(opts):
    """Builds all EC firmware targets"""
    # TODO(b/169178847): Add appropriate metric information
    metrics = firmware_pb2.FwBuildMetricList()
    with open(opts.metrics, 'w') as f:
        f.write(json_format.MessageToJson(metrics))
    subprocess.run(['make', 'buildall_only', '-j{}'.format(opts.cpus)],
                   cwd=os.path.dirname(__file__),
                   check=True)


def bundle(opts):
    """Bundles the artifacts from each target into its own tarball."""
    bundle_dir = opts.output_dir if opts.output_dir else DEFAULT_BUNDLE_DIRECTORY
    if not os.path.isdir(bundle_dir):
        os.mkdir(bundle_dir)
    for build_target in os.listdir(
            os.path.join(os.path.dirname(__file__), 'build')):
        subprocess.run([
            'tar', 'cvfj',
            os.path.join(
                bundle_dir, ''.join([
                    build_target, '.firmware_from_source.tar.bz2'
                ])), '--exclude=\'*.o\'', '.'
        ],
                       cwd=os.path.join(os.path.dirname(__file__), 'build',
                                        build_target),
                       check=True)
    bundle_metadata_file = opts.metadata if opts.metadata else DEFAULT_BUNDLE_METADATA_FILE
    # TODO(kmshelton): Populate the metatadata contents when it is defined in
    # infra/proto/src/chromite/api/firmware.proto.
    os.mknod(bundle_metadata_file)


def test(opts):
    """Runs all of the unit tests for EC firmware"""
    # TODO(b/169178847): Add appropriate metric information
    metrics = firmware_pb2.FwTestMetricList()
    with open(opts.metrics, 'w') as f:
        f.write(json_format.MessageToJson(metrics))

    # Verify all posix-based unit tests build and pass
    subprocess.run(['make', 'runtests', '-j{}'.format(opts.cpus)],
                   cwd=os.path.dirname(__file__),
                   check=True)

    # Verify compilation of the on-device unit test binaries.
    # TODO(b/172501728) These should build  for all boards, but they've bit
    # rotted, so we only build the ones that compile.
    subprocess.run(
        ['make', 'BOARD=bloonchipper', 'tests', '-j{}'.format(opts.cpus)],
        cwd=os.path.dirname(__file__),
        check=True)


def main(args):
    """Builds, bundles, or tests all of the EC targets and reports build metrics."""
    opts = parse_args(args)

    if not hasattr(opts, 'func'):
        print("Must select a valid sub command!")
        return -1

    # Run selected sub command function
    try:
        opts.func(opts)
    except subprocess.CalledProcessError:
        return 1
    else:
        return 0


def parse_args(args):
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument(
        '--cpus',
        default=multiprocessing.cpu_count(),
        help='The number of cores to use.',
    )

    parser.add_argument(
        '--metrics',
        dest='metrics',
        required=True,
        help='File to write the json-encoded MetricsList proto message.',
    )

    parser.add_argument(
        '--metadata',
        required=False,
        help=
        'Full pathname for the file in which to write build artifact metadata.',
    )

    parser.add_argument(
        '--output-dir',
        required=False,
        help=
        'Full pathanme for the directory in which to bundle build artifacts.',
    )

    # Would make this required=True, but not available until 3.7
    sub_cmds = parser.add_subparsers()

    build_cmd = sub_cmds.add_parser('build',
                                    help='Builds all firmware targets')
    build_cmd.set_defaults(func=build)

    build_cmd = sub_cmds.add_parser('bundle',
                                    help='Creates a tarball containing build '
                                    'artifacts from all firmware targets')
    build_cmd.set_defaults(func=bundle)

    test_cmd = sub_cmds.add_parser('test', help='Runs all firmware unit tests')
    test_cmd.set_defaults(func=test)

    return parser.parse_args(args)


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))