blob: 47a08194d0ddc966216a577ae0c8fc2fdc4b9466 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Script utility functions
2#
3# Copyright (C) 2014 Intel Corporation
4#
Brad Bishopc342db32019-05-15 21:57:59 -04005# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -05006#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05007
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05008import argparse
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08009import glob
10import logging
11import os
Brad Bishopd7bf8c12018-02-25 22:55:05 -050012import random
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080013import shlex
14import shutil
Brad Bishopd7bf8c12018-02-25 22:55:05 -050015import string
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080016import subprocess
17import sys
18import tempfile
Brad Bishop79641f22019-09-10 07:20:22 -040019import threading
Brad Bishop19323692019-04-05 15:28:33 -040020import importlib
Andrew Geissler595f6302022-01-24 19:11:47 +000021import importlib.machinery
22import importlib.util
Patrick Williamsc124f4f2015-09-15 14:41:29 -050023
Brad Bishop79641f22019-09-10 07:20:22 -040024class KeepAliveStreamHandler(logging.StreamHandler):
25 def __init__(self, keepalive=True, **kwargs):
26 super().__init__(**kwargs)
27 if keepalive is True:
28 keepalive = 5000 # default timeout
29 self._timeout = threading.Condition()
30 self._stop = False
31
32 # background thread waits on condition, if the condition does not
33 # happen emit a keep alive message
34 def thread():
35 while not self._stop:
36 with self._timeout:
37 if not self._timeout.wait(keepalive):
38 self.emit(logging.LogRecord("keepalive", logging.INFO,
39 None, None, "Keepalive message", None, None))
40
41 self._thread = threading.Thread(target = thread, daemon = True)
42 self._thread.start()
43
44 def close(self):
45 # mark the thread to stop and notify it
46 self._stop = True
47 with self._timeout:
48 self._timeout.notify()
49 # wait for it to join
50 self._thread.join()
51 super().close()
52
53 def emit(self, record):
54 super().emit(record)
55 # trigger timer reset
56 with self._timeout:
57 self._timeout.notify()
58
59def logger_create(name, stream=None, keepalive=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050060 logger = logging.getLogger(name)
Brad Bishop79641f22019-09-10 07:20:22 -040061 if keepalive is not None:
62 loggerhandler = KeepAliveStreamHandler(stream=stream, keepalive=keepalive)
63 else:
64 loggerhandler = logging.StreamHandler(stream=stream)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050065 loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
66 logger.addHandler(loggerhandler)
67 logger.setLevel(logging.INFO)
68 return logger
69
70def logger_setup_color(logger, color='auto'):
71 from bb.msg import BBLogFormatter
Brad Bishop19323692019-04-05 15:28:33 -040072
73 for handler in logger.handlers:
74 if (isinstance(handler, logging.StreamHandler) and
75 isinstance(handler.formatter, BBLogFormatter)):
76 if color == 'always' or (color == 'auto' and handler.stream.isatty()):
77 handler.formatter.enable_color()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050078
79
80def load_plugins(logger, plugins, pluginpath):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050081
82 def load_plugin(name):
83 logger.debug('Loading plugin %s' % name)
Brad Bishop19323692019-04-05 15:28:33 -040084 spec = importlib.machinery.PathFinder.find_spec(name, path=[pluginpath] )
85 if spec:
Andrew Geissler595f6302022-01-24 19:11:47 +000086 mod = importlib.util.module_from_spec(spec)
87 spec.loader.exec_module(mod)
88 return mod
Patrick Williamsc124f4f2015-09-15 14:41:29 -050089
Brad Bishop6e60e8b2018-02-01 10:27:11 -050090 def plugin_name(filename):
91 return os.path.splitext(os.path.basename(filename))[0]
92
93 known_plugins = [plugin_name(p.__name__) for p in plugins]
Patrick Williamsc124f4f2015-09-15 14:41:29 -050094 logger.debug('Loading plugins from %s...' % pluginpath)
95 for fn in glob.glob(os.path.join(pluginpath, '*.py')):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050096 name = plugin_name(fn)
97 if name != '__init__' and name not in known_plugins:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050098 plugin = load_plugin(name)
99 if hasattr(plugin, 'plugin_init'):
100 plugin.plugin_init(plugins)
101 plugins.append(plugin)
102
Brad Bishop19323692019-04-05 15:28:33 -0400103
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500104def git_convert_standalone_clone(repodir):
105 """If specified directory is a git repository, ensure it's a standalone clone"""
106 import bb.process
107 if os.path.exists(os.path.join(repodir, '.git')):
108 alternatesfile = os.path.join(repodir, '.git', 'objects', 'info', 'alternates')
109 if os.path.exists(alternatesfile):
110 # This will have been cloned with -s, so we need to convert it so none
111 # of the contents is shared
112 bb.process.run('git repack -a', cwd=repodir)
113 os.remove(alternatesfile)
114
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500115def _get_temp_recipe_dir(d):
116 # This is a little bit hacky but we need to find a place where we can put
117 # the recipe so that bitbake can find it. We're going to delete it at the
118 # end so it doesn't really matter where we put it.
119 bbfiles = d.getVar('BBFILES').split()
120 fetchrecipedir = None
121 for pth in bbfiles:
122 if pth.endswith('.bb'):
123 pthdir = os.path.dirname(pth)
124 if os.access(os.path.dirname(os.path.dirname(pthdir)), os.W_OK):
125 fetchrecipedir = pthdir.replace('*', 'recipetool')
126 if pthdir.endswith('workspace/recipes/*'):
127 # Prefer the workspace
128 break
129 return fetchrecipedir
130
131class FetchUrlFailure(Exception):
132 def __init__(self, url):
133 self.url = url
134 def __str__(self):
135 return "Failed to fetch URL %s" % self.url
136
137def fetch_url(tinfoil, srcuri, srcrev, destdir, logger, preserve_tmp=False, mirrors=False):
138 """
139 Fetch the specified URL using normal do_fetch and do_unpack tasks, i.e.
140 any dependencies that need to be satisfied in order to support the fetch
141 operation will be taken care of
142 """
143
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500144 import bb
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500145
146 checksums = {}
147 fetchrecipepn = None
148
149 # We need to put our temp directory under ${BASE_WORKDIR} otherwise
150 # we may have problems with the recipe-specific sysroot population
151 tmpparent = tinfoil.config_data.getVar('BASE_WORKDIR')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500152 bb.utils.mkdirhier(tmpparent)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500153 tmpdir = tempfile.mkdtemp(prefix='recipetool-', dir=tmpparent)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500154 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500155 tmpworkdir = os.path.join(tmpdir, 'work')
156 logger.debug('fetch_url: temp dir is %s' % tmpdir)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500157
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500158 fetchrecipedir = _get_temp_recipe_dir(tinfoil.config_data)
159 if not fetchrecipedir:
160 logger.error('Searched BBFILES but unable to find a writeable place to put temporary recipe')
161 sys.exit(1)
162 fetchrecipe = None
163 bb.utils.mkdirhier(fetchrecipedir)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500164 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500165 # Generate a dummy recipe so we can follow more or less normal paths
166 # for do_fetch and do_unpack
167 # I'd use tempfile functions here but underscores can be produced by that and those
168 # aren't allowed in recipe file names except to separate the version
169 rndstring = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
170 fetchrecipe = os.path.join(fetchrecipedir, 'tmp-recipetool-%s.bb' % rndstring)
171 fetchrecipepn = os.path.splitext(os.path.basename(fetchrecipe))[0]
172 logger.debug('Generating initial recipe %s for fetching' % fetchrecipe)
173 with open(fetchrecipe, 'w') as f:
174 # We don't want to have to specify LIC_FILES_CHKSUM
175 f.write('LICENSE = "CLOSED"\n')
176 # We don't need the cross-compiler
177 f.write('INHIBIT_DEFAULT_DEPS = "1"\n')
178 # We don't have the checksums yet so we can't require them
179 f.write('BB_STRICT_CHECKSUM = "ignore"\n')
180 f.write('SRC_URI = "%s"\n' % srcuri)
181 f.write('SRCREV = "%s"\n' % srcrev)
182 f.write('WORKDIR = "%s"\n' % tmpworkdir)
183 # Set S out of the way so it doesn't get created under the workdir
184 f.write('S = "%s"\n' % os.path.join(tmpdir, 'emptysrc'))
185 if not mirrors:
186 # We do not need PREMIRRORS since we are almost certainly
187 # fetching new source rather than something that has already
188 # been fetched. Hence, we disable them by default.
189 # However, we provide an option for users to enable it.
190 f.write('PREMIRRORS = ""\n')
191 f.write('MIRRORS = ""\n')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500192
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500193 logger.info('Fetching %s...' % srcuri)
194
195 # FIXME this is too noisy at the moment
196
197 # Parse recipes so our new recipe gets picked up
198 tinfoil.parse_recipes()
199
200 def eventhandler(event):
201 if isinstance(event, bb.fetch2.MissingChecksumEvent):
202 checksums.update(event.checksums)
203 return True
204 return False
205
206 # Run the fetch + unpack tasks
207 res = tinfoil.build_targets(fetchrecipepn,
208 'do_unpack',
209 handle_events=True,
210 extra_events=['bb.fetch2.MissingChecksumEvent'],
211 event_callback=eventhandler)
212 if not res:
213 raise FetchUrlFailure(srcuri)
214
215 # Remove unneeded directories
216 rd = tinfoil.parse_recipe(fetchrecipepn)
217 if rd:
218 pathvars = ['T', 'RECIPE_SYSROOT', 'RECIPE_SYSROOT_NATIVE']
219 for pathvar in pathvars:
220 path = rd.getVar(pathvar)
Patrick Williams93c203f2021-10-06 16:15:23 -0500221 if os.path.exists(path):
222 shutil.rmtree(path)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500223 finally:
224 if fetchrecipe:
225 try:
226 os.remove(fetchrecipe)
227 except FileNotFoundError:
228 pass
229 try:
230 os.rmdir(fetchrecipedir)
231 except OSError as e:
232 import errno
233 if e.errno != errno.ENOTEMPTY:
234 raise
235
236 bb.utils.mkdirhier(destdir)
237 for fn in os.listdir(tmpworkdir):
238 shutil.move(os.path.join(tmpworkdir, fn), destdir)
239
240 finally:
241 if not preserve_tmp:
242 shutil.rmtree(tmpdir)
243 tmpdir = None
244
245 return checksums, tmpdir
246
247
248def run_editor(fn, logger=None):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600249 if isinstance(fn, str):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800250 files = [fn]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500251 else:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800252 files = fn
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500253
254 editor = os.getenv('VISUAL', os.getenv('EDITOR', 'vi'))
255 try:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800256 #print(shlex.split(editor) + files)
257 return subprocess.check_call(shlex.split(editor) + files)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500258 except subprocess.CalledProcessError as exc:
259 logger.error("Execution of '%s' failed: %s" % (editor, exc))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500260 return 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600261
262def is_src_url(param):
263 """
264 Check if a parameter is a URL and return True if so
265 NOTE: be careful about changing this as it will influence how devtool/recipetool command line handling works
266 """
267 if not param:
268 return False
269 elif '://' in param:
270 return True
271 elif param.startswith('git@') or ('@' in param and param.endswith('.git')):
272 return True
273 return False
Brad Bishop6dbb3162019-11-25 09:41:34 -0500274
275def filter_src_subdirs(pth):
276 """
277 Filter out subdirectories of initial unpacked source trees that we do not care about.
278 Used by devtool and recipetool.
279 """
280 dirlist = os.listdir(pth)
281 filterout = ['git.indirectionsymlink', 'source-date-epoch']
282 dirlist = [x for x in dirlist if x not in filterout]
283 return dirlist