blob: fbf6a4bc3854aa719387219f2a4f47fc9aa7d552 [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001#!/usr/bin/env python3
2
3# Buildtools and buildtools extended installer helper script
4#
5# Copyright (C) 2017-2020 Intel Corporation
6#
7# SPDX-License-Identifier: GPL-2.0-only
8#
9# NOTE: --with-extended-buildtools is on by default
10#
11# Example usage (extended buildtools from milestone):
12# (1) using --url and --filename
13# $ install-buildtools \
14# --url http://downloads.yoctoproject.org/releases/yocto/milestones/yocto-3.1_M3/buildtools \
15# --filename x86_64-buildtools-extended-nativesdk-standalone-3.0+snapshot-20200315.sh
16# (2) using --base-url, --release, --installer-version and --build-date
17# $ install-buildtools \
18# --base-url http://downloads.yoctoproject.org/releases/yocto \
19# --release yocto-3.1_M3 \
20# --installer-version 3.0+snapshot
21# --build-date 202000315
22#
23# Example usage (standard buildtools from release):
24# (3) using --url and --filename
25# $ install-buildtools --without-extended-buildtools \
26# --url http://downloads.yoctoproject.org/releases/yocto/yocto-3.0.2/buildtools \
27# --filename x86_64-buildtools-nativesdk-standalone-3.0.2.sh
28# (4) using --base-url, --release and --installer-version
29# $ install-buildtools --without-extended-buildtools \
30# --base-url http://downloads.yoctoproject.org/releases/yocto \
31# --release yocto-3.0.2 \
32# --installer-version 3.0.2
33#
34
35import argparse
36import logging
37import os
38import platform
39import re
40import shutil
41import shlex
42import stat
43import subprocess
44import sys
45import tempfile
46from urllib.parse import quote
47
48scripts_path = os.path.dirname(os.path.realpath(__file__))
49lib_path = scripts_path + '/lib'
50sys.path = sys.path + [lib_path]
51import scriptutils
52import scriptpath
53
54
55PROGNAME = 'install-buildtools'
56logger = scriptutils.logger_create(PROGNAME, stream=sys.stdout)
57
58DEFAULT_INSTALL_DIR = os.path.join(os.path.split(scripts_path)[0],'buildtools')
59DEFAULT_BASE_URL = 'http://downloads.yoctoproject.org/releases/yocto'
60DEFAULT_RELEASE = 'yocto-3.2_M1'
61DEFAULT_INSTALLER_VERSION = '3.1+snapshot'
62DEFAULT_BUILDDATE = '20200617'
63
64# Python version sanity check
65if not (sys.version_info.major == 3 and sys.version_info.minor >= 4):
66 logger.error("This script requires Python 3.4 or greater")
67 logger.error("You have Python %s.%s" %
68 (sys.version_info.major, sys.version_info.minor))
69 sys.exit(1)
70
71# The following three functions are copied directly from
72# bitbake/lib/bb/utils.py, in order to allow this script
73# to run on versions of python earlier than what bitbake
74# supports (e.g. less than Python 3.5 for YP 3.1 release)
75
76def _hasher(method, filename):
77 import mmap
78
79 with open(filename, "rb") as f:
80 try:
81 with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
82 for chunk in iter(lambda: mm.read(8192), b''):
83 method.update(chunk)
84 except ValueError:
85 # You can't mmap() an empty file so silence this exception
86 pass
87 return method.hexdigest()
88
89
90def md5_file(filename):
91 """
92 Return the hex string representation of the MD5 checksum of filename.
93 """
94 import hashlib
95 return _hasher(hashlib.md5(), filename)
96
97def sha256_file(filename):
98 """
99 Return the hex string representation of the 256-bit SHA checksum of
100 filename.
101 """
102 import hashlib
103 return _hasher(hashlib.sha256(), filename)
104
105
106def main():
107 global DEFAULT_INSTALL_DIR
108 global DEFAULT_BASE_URL
109 global DEFAULT_RELEASE
110 global DEFAULT_INSTALLER_VERSION
111 global DEFAULT_BUILDDATE
112 filename = ""
113 release = ""
114 buildtools_url = ""
115 install_dir = ""
116 arch = platform.machine()
117
118 parser = argparse.ArgumentParser(
119 description="Buildtools installation helper",
120 add_help=False)
121 parser.add_argument('-u', '--url',
122 help='URL from where to fetch buildtools SDK installer, not '
123 'including filename (optional)\n'
124 'Requires --filename.',
125 action='store')
126 parser.add_argument('-f', '--filename',
127 help='filename for the buildtools SDK installer to be installed '
128 '(optional)\nRequires --url',
129 action='store')
130 parser.add_argument('-d', '--directory',
131 default=DEFAULT_INSTALL_DIR,
132 help='directory where buildtools SDK will be installed (optional)',
133 action='store')
134 parser.add_argument('-r', '--release',
135 default=DEFAULT_RELEASE,
136 help='Yocto Project release string for SDK which will be '
137 'installed (optional)',
138 action='store')
139 parser.add_argument('-V', '--installer-version',
140 default=DEFAULT_INSTALLER_VERSION,
141 help='version string for the SDK to be installed (optional)',
142 action='store')
143 parser.add_argument('-b', '--base-url',
144 default=DEFAULT_BASE_URL,
145 help='base URL from which to fetch SDK (optional)', action='store')
146 parser.add_argument('-t', '--build-date',
147 default=DEFAULT_BUILDDATE,
148 help='Build date of pre-release SDK (optional)', action='store')
149 group = parser.add_mutually_exclusive_group()
150 group.add_argument('--with-extended-buildtools', action='store_true',
151 dest='with_extended_buildtools',
152 default=True,
153 help='enable extended buildtools tarball (on by default)')
154 group.add_argument('--without-extended-buildtools', action='store_false',
155 dest='with_extended_buildtools',
156 help='disable extended buildtools (traditional buildtools tarball)')
157 parser.add_argument('-c', '--check', help='enable md5 checksum checking',
158 default=True,
159 action='store_true')
160 parser.add_argument('-D', '--debug', help='enable debug output',
161 action='store_true')
162 parser.add_argument('-q', '--quiet', help='print only errors',
163 action='store_true')
164
165 parser.add_argument('-h', '--help', action='help',
166 default=argparse.SUPPRESS,
167 help='show this help message and exit')
168
169 args = parser.parse_args()
170
171 if args.debug:
172 logger.setLevel(logging.DEBUG)
173 elif args.quiet:
174 logger.setLevel(logging.ERROR)
175
176 if args.url and args.filename:
177 logger.debug("--url and --filename detected. Ignoring --base-url "
178 "--release --installer-version arguments.")
179 filename = args.filename
180 buildtools_url = "%s/%s" % (args.url, filename)
181 else:
182 if args.base_url:
183 base_url = args.base_url
184 else:
185 base_url = DEFAULT_BASE_URL
186 if args.release:
187 # check if this is a pre-release "milestone" SDK
188 m = re.search(r"^(?P<distro>[a-zA-Z\-]+)(?P<version>[0-9.]+)(?P<milestone>_M[1-9])$",
189 args.release)
190 logger.debug("milestone regex: %s" % m)
191 if m and m.group('milestone'):
192 logger.debug("release[distro]: %s" % m.group('distro'))
193 logger.debug("release[version]: %s" % m.group('version'))
194 logger.debug("release[milestone]: %s" % m.group('milestone'))
195 if not args.build_date:
196 logger.error("Milestone installers require --build-date")
197 else:
198 if args.with_extended_buildtools:
199 filename = "%s-buildtools-extended-nativesdk-standalone-%s-%s.sh" % (
200 arch, args.installer_version, args.build_date)
201 else:
202 filename = "%s-buildtools-nativesdk-standalone-%s-%s.sh" % (
203 arch, args.installer_version, args.build_date)
204 safe_filename = quote(filename)
205 buildtools_url = "%s/milestones/%s/buildtools/%s" % (base_url, args.release, safe_filename)
206 # regular release SDK
207 else:
208 if args.with_extended_buildtools:
209 filename = "%s-buildtools-extended-nativesdk-standalone-%s.sh" % (arch, args.installer_version)
210 else:
211 filename = "%s-buildtools-nativesdk-standalone-%s.sh" % (arch, args.installer_version)
212 safe_filename = quote(filename)
213 buildtools_url = "%s/%s/buildtools/%s" % (base_url, args.release, safe_filename)
214
215 tmpsdk_dir = tempfile.mkdtemp()
216 try:
217 # Fetch installer
218 logger.info("Fetching buildtools installer")
219 tmpbuildtools = os.path.join(tmpsdk_dir, filename)
220 ret = subprocess.call("wget -q -O %s %s" %
221 (tmpbuildtools, buildtools_url), shell=True)
222 if ret != 0:
223 logger.error("Could not download file from %s" % buildtools_url)
224 return ret
225
226 # Verify checksum
227 if args.check:
228 logger.info("Fetching buildtools installer checksum")
229 checksum_type = ""
230 for checksum_type in ["md5sum", "sha256sum"]:
231 check_url = "{}.{}".format(buildtools_url, checksum_type)
232 checksum_filename = "{}.{}".format(filename, checksum_type)
233 tmpbuildtools_checksum = os.path.join(tmpsdk_dir, checksum_filename)
234 ret = subprocess.call("wget -q -O %s %s" %
235 (tmpbuildtools_checksum, check_url), shell=True)
236 if ret == 0:
237 break
238 else:
239 if ret != 0:
240 logger.error("Could not download file from %s" % check_url)
241 return ret
242 regex = re.compile(r"^(?P<checksum>[0-9a-f]+)\s+(?P<path>.*/)?(?P<filename>.*)$")
243 with open(tmpbuildtools_checksum, 'rb') as f:
244 original = f.read()
245 m = re.search(regex, original.decode("utf-8"))
246 logger.debug("checksum regex match: %s" % m)
247 logger.debug("checksum: %s" % m.group('checksum'))
248 logger.debug("path: %s" % m.group('path'))
249 logger.debug("filename: %s" % m.group('filename'))
250 if filename != m.group('filename'):
251 logger.error("Filename does not match name in checksum")
252 return 1
253 checksum = m.group('checksum')
254 if checksum_type == "md5sum":
255 checksum_value = md5_file(tmpbuildtools)
256 else:
257 checksum_value = sha256_file(tmpbuildtools)
258 if checksum == checksum_value:
259 logger.info("Checksum success")
260 else:
261 logger.error("Checksum %s expected. Actual checksum is %s." %
262 (checksum, checksum_value))
263 return 1
264
265 # Make installer executable
266 logger.info("Making installer executable")
267 st = os.stat(tmpbuildtools)
268 os.chmod(tmpbuildtools, st.st_mode | stat.S_IEXEC)
269 logger.debug(os.stat(tmpbuildtools))
270 if args.directory:
271 install_dir = args.directory
272 ret = subprocess.call("%s -d %s -y" %
273 (tmpbuildtools, install_dir), shell=True)
274 else:
275 install_dir = "/opt/poky/%s" % args.installer_version
276 ret = subprocess.call("%s -y" % tmpbuildtools, shell=True)
277 if ret != 0:
278 logger.error("Could not run buildtools installer")
279 return ret
280
281 # Setup the environment
282 logger.info("Setting up the environment")
283 regex = re.compile(r'^(?P<export>export )?(?P<env_var>[A-Z_]+)=(?P<env_val>.+)$')
284 with open("%s/environment-setup-%s-pokysdk-linux" %
285 (install_dir, arch), 'rb') as f:
286 for line in f:
287 match = regex.search(line.decode('utf-8'))
288 logger.debug("export regex: %s" % match)
289 if match:
290 env_var = match.group('env_var')
291 logger.debug("env_var: %s" % env_var)
292 env_val = match.group('env_val')
293 logger.debug("env_val: %s" % env_val)
294 os.environ[env_var] = env_val
295
296 # Test installation
297 logger.info("Testing installation")
298 tool = ""
299 m = re.search("extended", tmpbuildtools)
300 logger.debug("extended regex: %s" % m)
301 if args.with_extended_buildtools and not m:
302 logger.info("Ignoring --with-extended-buildtools as filename "
303 "does not contain 'extended'")
304 if args.with_extended_buildtools and m:
305 tool = 'gcc'
306 else:
307 tool = 'tar'
308 logger.debug("install_dir: %s" % install_dir)
309 cmd = shlex.split("/usr/bin/which %s" % tool)
310 logger.debug("cmd: %s" % cmd)
311 logger.debug("tool: %s" % tool)
312 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
313 output, errors = proc.communicate()
314 logger.debug("proc.args: %s" % proc.args)
315 logger.debug("proc.communicate(): output %s" % output)
316 logger.debug("proc.communicate(): errors %s" % errors)
317 which_tool = output.decode('utf-8')
318 logger.debug("which %s: %s" % (tool, which_tool))
319 ret = proc.returncode
320 if not which_tool.startswith(install_dir):
321 logger.error("Something went wrong: %s not found in %s" %
322 (tool, install_dir))
323 if ret != 0:
324 logger.error("Something went wrong: installation failed")
325 else:
326 logger.info("Installation successful. Remember to source the "
327 "environment setup script now and in any new session.")
328 return ret
329
330 finally:
331 # cleanup tmp directory
332 shutil.rmtree(tmpsdk_dir)
333
334
335if __name__ == '__main__':
336 try:
337 ret = main()
338 except Exception:
339 ret = 1
340 import traceback
341
342 traceback.print_exc()
343 sys.exit(ret)