1#!/usr/bin/env python3
2#
3# Copyright (C) 2016 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17"""Downloads simpleperf prebuilts from the build server."""
18import argparse
19import logging
20import os
21import shutil
22import stat
23import textwrap
24
25THIS_DIR = os.path.realpath(os.path.dirname(__file__))
26
27
28class InstallEntry(object):
29    def __init__(self, target, name, install_path, need_strip=False):
30        self.target = target
31        self.name = name
32        self.install_path = install_path
33        self.need_strip = need_strip
34
35
36INSTALL_LIST = [
37    # simpleperf on device.
38    InstallEntry('MODULES-IN-system-extras-simpleperf',
39                 'simpleperf/android/arm64/simpleperf_ndk',
40                 'android/arm64/simpleperf'),
41    InstallEntry('MODULES-IN-system-extras-simpleperf_arm',
42                 'simpleperf/android/arm/simpleperf_ndk32',
43                 'android/arm/simpleperf'),
44    InstallEntry('MODULES-IN-system-extras-simpleperf_x86',
45                 'simpleperf/android/x86_64/simpleperf_ndk',
46                 'android/x86_64/simpleperf'),
47    InstallEntry('MODULES-IN-system-extras-simpleperf_x86',
48                 'simpleperf/android/x86/simpleperf_ndk32',
49                 'android/x86/simpleperf'),
50    InstallEntry('MODULES-IN-system-extras-simpleperf_riscv64',
51                 'simpleperf_ndk',
52                 'android/riscv64/simpleperf'),
53
54    # simpleperf on host.
55    InstallEntry('MODULES-IN-system-extras-simpleperf',
56                 'simpleperf/linux/x86_64/simpleperf',
57                 'linux/x86_64/simpleperf', True),
58    InstallEntry('MODULES-IN-system-extras-simpleperf_mac',
59                 'simpleperf/darwin/x86_64/simpleperf',
60                 'darwin/x86_64/simpleperf'),
61
62    # libsimpleperf_report.so on host
63    InstallEntry('MODULES-IN-system-extras-simpleperf',
64                 'simpleperf/linux/x86_64/libsimpleperf_report.so',
65                 'linux/x86_64/libsimpleperf_report.so', True),
66    InstallEntry('MODULES-IN-system-extras-simpleperf_mac',
67                 'simpleperf/darwin/x86_64/libsimpleperf_report.dylib',
68                 'darwin/x86_64/libsimpleperf_report.dylib'),
69]
70
71
72def logger():
73    """Returns the main logger for this module."""
74    return logging.getLogger(__name__)
75
76
77def check_call(cmd):
78    """Proxy for subprocess.check_call with logging."""
79    import subprocess
80    logger().debug('check_call `%s`', ' '.join(cmd))
81    subprocess.check_call(cmd)
82
83
84def fetch_artifact(branch, build, target, name):
85    """Fetches and artifact from the build server."""
86    if target.startswith('local:'):
87        shutil.copyfile(target[6:], name)
88        return
89    logger().info('Fetching %s from %s %s (artifacts matching %s)', build,
90                  target, branch, name)
91    fetch_artifact_path = '/google/data/ro/projects/android/fetch_artifact'
92    cmd = [fetch_artifact_path, '--branch', branch, '--target', target,
93           '--bid', build, name]
94    check_call(cmd)
95
96
97def start_branch(build):
98    """Creates a new branch in the project."""
99    branch_name = 'update-' + (build or 'latest')
100    logger().info('Creating branch %s', branch_name)
101    check_call(['repo', 'start', branch_name, '.'])
102
103
104def commit(branch, build, add_paths):
105    """Commits the new prebuilts."""
106    logger().info('Making commit')
107    check_call(['git', 'add'] + add_paths)
108    message = textwrap.dedent("""\
109        simpleperf: update simpleperf prebuilts to build {build}.
110
111        Taken from branch {branch}.""").format(branch=branch, build=build)
112    check_call(['git', 'commit', '-m', message])
113
114
115def remove_old_release(install_dir):
116    """Removes the old prebuilts."""
117    if os.path.exists(install_dir):
118        logger().info('Removing old install directory "%s"', install_dir)
119        check_call(['git', 'rm', '-rf', '--ignore-unmatch', install_dir])
120
121    # Need to check again because git won't remove directories if they have
122    # non-git files in them.
123    if os.path.exists(install_dir):
124        shutil.rmtree(install_dir)
125
126
127def install_new_release(branch, build, install_dir):
128    """Installs the new release."""
129    for entry in INSTALL_LIST:
130        install_entry(branch, build, install_dir, entry)
131
132
133def install_entry(branch, build, install_dir, entry):
134    """Installs the device specific components of the release."""
135    target = entry.target
136    name = entry.name
137    install_path = os.path.join(install_dir, entry.install_path)
138    need_strip = entry.need_strip
139
140    fetch_artifact(branch, build, target, name)
141    name = os.path.basename(name)
142    exe_stat = os.stat(name)
143    os.chmod(name, exe_stat.st_mode | stat.S_IEXEC)
144    if need_strip:
145        check_call(['strip', name])
146    dirname = os.path.dirname(install_path)
147    if not os.path.isdir(dirname):
148        os.makedirs(dirname)
149    shutil.move(name, install_path)
150
151
152def get_args():
153    """Parses and returns command line arguments."""
154    parser = argparse.ArgumentParser()
155
156    parser.add_argument(
157        '-b', '--branch', default='aosp-simpleperf-release',
158        help='Branch to pull build from.')
159    parser.add_argument('--build', required=True, help='Build number to pull.')
160    parser.add_argument(
161        '--use-current-branch', action='store_true',
162        help='Perform the update in the current branch. Do not repo start.')
163    parser.add_argument(
164        '-v', '--verbose', action='count', default=0,
165        help='Increase output verbosity.')
166
167    return parser.parse_args()
168
169
170def main():
171    """Program entry point."""
172    os.chdir(THIS_DIR)
173
174    args = get_args()
175    verbose_map = (logging.WARNING, logging.INFO, logging.DEBUG)
176    verbosity = args.verbose
177    if verbosity > 2:
178        verbosity = 2
179    logging.basicConfig(level=verbose_map[verbosity])
180
181    install_dir = 'bin'
182
183    if not args.use_current_branch:
184        start_branch(args.build)
185    remove_old_release(install_dir)
186    install_new_release(args.branch, args.build, install_dir)
187    artifacts = [install_dir]
188    commit(args.branch, args.build, artifacts)
189
190
191if __name__ == '__main__':
192    main()
193