Compare commits

..

1 Commits

Author SHA1 Message Date
Bernhard Rosenkränzer
a8095c99ab gcc: upgrade 11.2 -> current 12 snapshot
gcc 12 is expected to be released this month or early next month.
Update so we're prepared.
This keeps/ports all patches currently applied to 11.2 that haven't
landed upstream yet.

[v2: Back out the zephyr DWARF-4 workaround]

(From OE-Core rev: 540116ca70fb71ac489b61b74b3a397ff92f27e2)

Signed-off-by: Bernhard Rosenkränzer <bernhard.rosenkraenzer.ext@huawei.com>
Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
2022-04-09 19:50:45 +01:00
5386 changed files with 149802 additions and 366884 deletions

5
.gitignore vendored
View File

@@ -32,8 +32,3 @@ bitbake/lib/toaster/contrib/tts/backlog.txt
bitbake/lib/toaster/contrib/tts/log/* bitbake/lib/toaster/contrib/tts/log/*
bitbake/lib/toaster/contrib/tts/.cache/* bitbake/lib/toaster/contrib/tts/.cache/*
bitbake/lib/bb/tests/runqueue-tests/bitbake-cookerdaemon.log bitbake/lib/bb/tests/runqueue-tests/bitbake-cookerdaemon.log
_toaster_clones/
downloads/
sstate-cache/
toaster.sqlite
.vscode/

View File

@@ -1,2 +1,2 @@
# Template settings # Template settings
TEMPLATECONF=${TEMPLATECONF:-meta-poky/conf/templates/default} TEMPLATECONF=${TEMPLATECONF:-meta-poky/conf}

View File

@@ -53,6 +53,7 @@ Maintainers needed
* wic * wic
* Patchwork * Patchwork
* Patchtest * Patchtest
* Prelink-cross
* Matchbox * Matchbox
* Sato * Sato
* Autobuilder * Autobuilder

35
Makefile Normal file
View File

@@ -0,0 +1,35 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
DESTDIR = final
ifeq ($(shell if which $(SPHINXBUILD) >/dev/null 2>&1; then echo 1; else echo 0; fi),0)
$(error "The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed")
endif
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile.sphinx clean publish
publish: Makefile.sphinx html singlehtml
rm -rf $(BUILDDIR)/$(DESTDIR)/
mkdir -p $(BUILDDIR)/$(DESTDIR)/
cp -r $(BUILDDIR)/html/* $(BUILDDIR)/$(DESTDIR)/
cp $(BUILDDIR)/singlehtml/index.html $(BUILDDIR)/$(DESTDIR)/singleindex.html
sed -i -e 's@index.html#@singleindex.html#@g' $(BUILDDIR)/$(DESTDIR)/singleindex.html
clean:
@rm -rf $(BUILDDIR)
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile.sphinx
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

View File

@@ -16,13 +16,9 @@ which can be found at:
Contributing Contributing
------------ ------------
Please refer to our contributor guide here: https://docs.yoctoproject.org/dev/contributor-guide/ Please refer to
for full details on how to submit changes. https://www.openembedded.org/wiki/How_to_submit_a_patch_to_OpenEmbedded
for guidelines on how to submit patches.
As a quick guide, patches should be sent to openembedded-core@lists.openembedded.org
The git command to do that would be:
git send-email -M -1 --to openembedded-core@lists.openembedded.org --subject-prefix='scarthgap][PATCH'
Mailing list: Mailing list:

View File

@@ -1,22 +0,0 @@
How to Report a Potential Vulnerability?
========================================
If you would like to report a public issue (for example, one with a released
CVE number), please report it using the
[https://bugzilla.yoctoproject.org/enter_bug.cgi?product=Security Security Bugzilla]
If you are dealing with a not-yet released or urgent issue, please send a
message to security AT yoctoproject DOT org, including as many details as
possible: the layer or software module affected, the recipe and its version,
and any example code, if available.
Branches maintained with security fixes
---------------------------------------
See [https://wiki.yoctoproject.org/wiki/Stable_Release_and_LTS Stable release and LTS]
for detailed info regarding the policies and maintenance of Stable branches.
The [https://wiki.yoctoproject.org/wiki/Releases Release page] contains a list of all
releases of the Yocto Project. Versions in grey are no longer actively maintained with
security patches, but well-tested patches may still be accepted for them for
significant issues.

View File

@@ -13,23 +13,18 @@ Bitbake plain documentation can be found under the doc directory or its integrat
html version at the Yocto Project website: html version at the Yocto Project website:
https://docs.yoctoproject.org https://docs.yoctoproject.org
Bitbake requires Python version 3.8 or newer.
Contributing Contributing
------------ ------------
Please refer to our contributor guide here: https://docs.yoctoproject.org/contributor-guide/ Please refer to
for full details on how to submit changes. https://www.openembedded.org/wiki/How_to_submit_a_patch_to_OpenEmbedded
for guidelines on how to submit patches, just note that the latter documentation is intended
for OpenEmbedded (and its core) not bitbake patches (bitbake-devel@lists.openembedded.org)
but in general main guidelines apply. Once the commit(s) have been created, the way to send
the patch is through git-send-email. For example, to send the last commit (HEAD) on current
branch, type:
As a quick guide, patches should be sent to bitbake-devel@lists.openembedded.org git send-email -M -1 --to bitbake-devel@lists.openembedded.org
The git command to do that would be:
git send-email -M -1 --to bitbake-devel@lists.openembedded.org --subject-prefix='2.8][PATCH'
If you're sending a patch related to the BitBake manual, make sure you copy
the Yocto Project documentation mailing list:
git send-email -M -1 --to bitbake-devel@lists.openembedded.org --cc docs@lists.yoctoproject.org
Mailing list: Mailing list:
@@ -39,25 +34,10 @@ Source code:
https://git.openembedded.org/bitbake/ https://git.openembedded.org/bitbake/
Testing Testing:
-------
Bitbake has a testsuite located in lib/bb/tests/ whichs aim to try and prevent regressions. Bitbake has a testsuite located in lib/bb/tests/ whichs aim to try and prevent regressions.
You can run this with "bitbake-selftest". In particular the fetcher is well covered since You can run this with "bitbake-selftest". In particular the fetcher is well covered since
it has so many corner cases. The datastore has many tests too. Testing with the testsuite is it has so many corner cases. The datastore has many tests too. Testing with the testsuite is
recommended before submitting patches, particularly to the fetcher and datastore. We also recommended before submitting patches, particularly to the fetcher and datastore. We also
appreciate new test cases and may require them for more obscure issues. appreciate new test cases and may require them for more obscure issues.
To run the tests "zstd" and "git" must be installed.
The assumption is made that this testsuite is run from an initialized OpenEmbedded build
environment (i.e. `source oe-init-build-env` is used). If this is not the case, run the
testsuite as follows:
export PATH=$(pwd)/bin:$PATH
bin/bitbake-selftest
The testsuite can alternatively be executed using pytest, e.g. obtained from PyPI (in this
case, the PATH is configured automatically):
pytest

View File

@@ -1,24 +0,0 @@
How to Report a Potential Vulnerability?
========================================
If you would like to report a public issue (for example, one with a released
CVE number), please report it using the
[https://bugzilla.yoctoproject.org/enter_bug.cgi?product=Security Security Bugzilla].
If you have a patch ready, submit it following the same procedure as any other
patch as described in README.md.
If you are dealing with a not-yet released or urgent issue, please send a
message to security AT yoctoproject DOT org, including as many details as
possible: the layer or software module affected, the recipe and its version,
and any example code, if available.
Branches maintained with security fixes
---------------------------------------
See [https://wiki.yoctoproject.org/wiki/Stable_Release_and_LTS Stable release and LTS]
for detailed info regarding the policies and maintenance of Stable branches.
The [https://wiki.yoctoproject.org/wiki/Releases Release page] contains a list of all
releases of the Yocto Project. Versions in grey are no longer actively maintained with
security patches, but well-tested patches may still be accepted for them for
significant issues.

View File

@@ -25,9 +25,10 @@ except RuntimeError as exc:
from bb import cookerdata from bb import cookerdata
from bb.main import bitbake_main, BitBakeConfigParameters, BBMainException from bb.main import bitbake_main, BitBakeConfigParameters, BBMainException
bb.utils.check_system_locale() if sys.getfilesystemencoding() != "utf-8":
sys.exit("Please use a locale setting which supports UTF-8 (such as LANG=en_US.UTF-8).\nPython can't change the filesystem locale after loading so we need a UTF-8 when Python starts or things won't work.")
__version__ = "2.8.1" __version__ = "2.0.0"
if __name__ == "__main__": if __name__ == "__main__":
if __version__ != bb.__version__: if __version__ != bb.__version__:

View File

@@ -11,7 +11,6 @@
import os import os
import sys import sys
import warnings import warnings
warnings.simplefilter("default") warnings.simplefilter("default")
import argparse import argparse
import logging import logging
@@ -28,7 +27,6 @@ logger = bb.msg.logger_create(myname)
is_dump = myname == 'bitbake-dumpsig' is_dump = myname == 'bitbake-dumpsig'
def find_siginfo(tinfoil, pn, taskname, sigs=None): def find_siginfo(tinfoil, pn, taskname, sigs=None):
result = None result = None
tinfoil.set_event_mask(['bb.event.FindSigInfoResult', tinfoil.set_event_mask(['bb.event.FindSigInfoResult',
@@ -54,7 +52,6 @@ def find_siginfo(tinfoil, pn, taskname, sigs=None):
sys.exit(2) sys.exit(2)
return result return result
def find_siginfo_task(bbhandler, pn, taskname, sig1=None, sig2=None): def find_siginfo_task(bbhandler, pn, taskname, sig1=None, sig2=None):
""" Find the most recent signature files for the specified PN/task """ """ Find the most recent signature files for the specified PN/task """
@@ -66,23 +63,19 @@ def find_siginfo_task(bbhandler, pn, taskname, sig1=None, sig2=None):
if not sigfiles: if not sigfiles:
logger.error('No sigdata files found matching %s %s matching either %s or %s' % (pn, taskname, sig1, sig2)) logger.error('No sigdata files found matching %s %s matching either %s or %s' % (pn, taskname, sig1, sig2))
sys.exit(1) sys.exit(1)
elif sig1 not in sigfiles: elif not sig1 in sigfiles:
logger.error('No sigdata files found matching %s %s with signature %s' % (pn, taskname, sig1)) logger.error('No sigdata files found matching %s %s with signature %s' % (pn, taskname, sig1))
sys.exit(1) sys.exit(1)
elif sig2 not in sigfiles: elif not sig2 in sigfiles:
logger.error('No sigdata files found matching %s %s with signature %s' % (pn, taskname, sig2)) logger.error('No sigdata files found matching %s %s with signature %s' % (pn, taskname, sig2))
sys.exit(1) sys.exit(1)
latestfiles = [sigfiles[sig1], sigfiles[sig2]]
latestfiles = [sigfiles[sig1]['path'], sigfiles[sig2]['path']]
else: else:
sigfiles = find_siginfo(bbhandler, pn, taskname) filedates = find_siginfo(bbhandler, pn, taskname)
latestsigs = sorted(sigfiles.keys(), key=lambda h: sigfiles[h]['time'])[-2:] latestfiles = sorted(filedates.keys(), key=lambda f: filedates[f])[-2:]
if not latestsigs: if not latestfiles:
logger.error('No sigdata files found matching %s %s' % (pn, taskname)) logger.error('No sigdata files found matching %s %s' % (pn, taskname))
sys.exit(1) sys.exit(1)
latestfiles = [sigfiles[latestsigs[0]]['path']]
if len(latestsigs) > 1:
latestfiles.append(sigfiles[latestsigs[1]]['path'])
return latestfiles return latestfiles
@@ -95,12 +88,12 @@ def recursecb(key, hash1, hash2):
recout = [] recout = []
if not hashfiles: if not hashfiles:
recout.append("Unable to find matching sigdata for %s with hashes %s or %s" % (key, hash1, hash2)) recout.append("Unable to find matching sigdata for %s with hashes %s or %s" % (key, hash1, hash2))
elif hash1 not in hashfiles: elif not hash1 in hashfiles:
recout.append("Unable to find matching sigdata for %s with hash %s" % (key, hash1)) recout.append("Unable to find matching sigdata for %s with hash %s" % (key, hash1))
elif hash2 not in hashfiles: elif not hash2 in hashfiles:
recout.append("Unable to find matching sigdata for %s with hash %s" % (key, hash2)) recout.append("Unable to find matching sigdata for %s with hash %s" % (key, hash2))
else: else:
out2 = bb.siggen.compare_sigfiles(hashfiles[hash1]['path'], hashfiles[hash2]['path'], recursecb, color=color) out2 = bb.siggen.compare_sigfiles(hashfiles[hash1], hashfiles[hash2], recursecb, color=color)
for change in out2: for change in out2:
for line in change.splitlines(): for line in change.splitlines():
recout.append(' ' + line) recout.append(' ' + line)
@@ -164,8 +157,7 @@ if options.taskargs:
with bb.tinfoil.Tinfoil() as tinfoil: with bb.tinfoil.Tinfoil() as tinfoil:
tinfoil.prepare(config_only=True) tinfoil.prepare(config_only=True)
if not options.dump and options.sigargs: if not options.dump and options.sigargs:
files = find_siginfo_task(tinfoil, options.taskargs[0], options.taskargs[1], options.sigargs[0], files = find_siginfo_task(tinfoil, options.taskargs[0], options.taskargs[1], options.sigargs[0], options.sigargs[1])
options.sigargs[1])
else: else:
files = find_siginfo_task(tinfoil, options.taskargs[0], options.taskargs[1]) files = find_siginfo_task(tinfoil, options.taskargs[0], options.taskargs[1])
@@ -174,8 +166,7 @@ if options.taskargs:
output = bb.siggen.dump_sigfile(files[-1]) output = bb.siggen.dump_sigfile(files[-1])
else: else:
if len(files) < 2: if len(files) < 2:
logger.error('Only one matching sigdata file found for the specified task (%s %s)' % ( logger.error('Only one matching sigdata file found for the specified task (%s %s)' % (options.taskargs[0], options.taskargs[1]))
options.taskargs[0], options.taskargs[1]))
sys.exit(1) sys.exit(1)
# Recurse into signature comparison # Recurse into signature comparison

View File

@@ -25,36 +25,26 @@ if __name__ == "__main__":
parser.add_argument('-u', '--unexpand', help='Do not expand the value (with --value)', action="store_true") parser.add_argument('-u', '--unexpand', help='Do not expand the value (with --value)', action="store_true")
parser.add_argument('-f', '--flag', help='Specify a variable flag to query (with --value)', default=None) parser.add_argument('-f', '--flag', help='Specify a variable flag to query (with --value)', default=None)
parser.add_argument('--value', help='Only report the value, no history and no variable name', action="store_true") parser.add_argument('--value', help='Only report the value, no history and no variable name', action="store_true")
parser.add_argument('-q', '--quiet', help='Silence bitbake server logging', action="store_true")
parser.add_argument('--ignore-undefined', help='Suppress any errors related to undefined variables', action="store_true")
args = parser.parse_args() args = parser.parse_args()
if not args.value: if args.unexpand and not args.value:
if args.unexpand: print("--unexpand only makes sense with --value")
sys.exit("--unexpand only makes sense with --value") sys.exit(1)
if args.flag: if args.flag and not args.value:
sys.exit("--flag only makes sense with --value") print("--flag only makes sense with --value")
sys.exit(1)
quiet = args.quiet or args.value with bb.tinfoil.Tinfoil(tracking=True) as tinfoil:
with bb.tinfoil.Tinfoil(tracking=True, setup_logging=not quiet) as tinfoil:
if args.recipe: if args.recipe:
tinfoil.prepare(quiet=3 if quiet else 2) tinfoil.prepare(quiet=2)
d = tinfoil.parse_recipe(args.recipe) d = tinfoil.parse_recipe(args.recipe)
else: else:
tinfoil.prepare(quiet=2, config_only=True) tinfoil.prepare(quiet=2, config_only=True)
d = tinfoil.config_data d = tinfoil.config_data
value = None
if args.flag: if args.flag:
value = d.getVarFlag(args.variable, args.flag, expand=not args.unexpand) print(str(d.getVarFlag(args.variable, args.flag, expand=(not args.unexpand))))
if value is None and not args.ignore_undefined: elif args.value:
sys.exit(f"The flag '{args.flag}' is not defined for variable '{args.variable}'") print(str(d.getVar(args.variable, expand=(not args.unexpand))))
else:
value = d.getVar(args.variable, expand=not args.unexpand)
if value is None and not args.ignore_undefined:
sys.exit(f"The variable '{args.variable}' is not defined")
if args.value:
print(str(value if value is not None else ""))
else: else:
bb.data.emit_var(args.variable, d=d, all=True) bb.data.emit_var(args.variable, d=d, all=True)

View File

@@ -14,8 +14,6 @@ import sys
import threading import threading
import time import time
import warnings import warnings
import netrc
import json
warnings.simplefilter("default") warnings.simplefilter("default")
try: try:
@@ -38,42 +36,18 @@ except ImportError:
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lib')) sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lib'))
import hashserv import hashserv
import bb.asyncrpc
DEFAULT_ADDRESS = 'unix://./hashserve.sock' DEFAULT_ADDRESS = 'unix://./hashserve.sock'
METHOD = 'stress.test.method' METHOD = 'stress.test.method'
def print_user(u):
print(f"Username: {u['username']}")
if "permissions" in u:
print("Permissions: " + " ".join(u["permissions"]))
if "token" in u:
print(f"Token: {u['token']}")
def main(): def main():
def handle_get(args, client):
result = client.get_taskhash(args.method, args.taskhash, all_properties=True)
if not result:
return 0
print(json.dumps(result, sort_keys=True, indent=4))
return 0
def handle_get_outhash(args, client):
result = client.get_outhash(args.method, args.outhash, args.taskhash)
if not result:
return 0
print(json.dumps(result, sort_keys=True, indent=4))
return 0
def handle_stats(args, client): def handle_stats(args, client):
if args.reset: if args.reset:
s = client.reset_stats() s = client.reset_stats()
else: else:
s = client.get_stats() s = client.get_stats()
print(json.dumps(s, sort_keys=True, indent=4)) pprint.pprint(s)
return 0 return 0
def handle_stress(args, client): def handle_stress(args, client):
@@ -82,7 +56,8 @@ def main():
nonlocal missed_hashes nonlocal missed_hashes
nonlocal max_time nonlocal max_time
with hashserv.create_client(args.address) as client: client = hashserv.create_client(args.address)
for i in range(args.requests): for i in range(args.requests):
taskhash = hashlib.sha256() taskhash = hashlib.sha256()
taskhash.update(args.taskhash_seed.encode('utf-8')) taskhash.update(args.taskhash_seed.encode('utf-8'))
@@ -138,114 +113,12 @@ def main():
with lock: with lock:
pbar.update() pbar.update()
def handle_remove(args, client):
where = {k: v for k, v in args.where}
if where:
result = client.remove(where)
print("Removed %d row(s)" % (result["count"]))
else:
print("No query specified")
def handle_clean_unused(args, client):
result = client.clean_unused(args.max_age)
print("Removed %d rows" % (result["count"]))
return 0
def handle_refresh_token(args, client):
r = client.refresh_token(args.username)
print_user(r)
def handle_set_user_permissions(args, client):
r = client.set_user_perms(args.username, args.permissions)
print_user(r)
def handle_get_user(args, client):
r = client.get_user(args.username)
print_user(r)
def handle_get_all_users(args, client):
users = client.get_all_users()
print("{username:20}| {permissions}".format(username="Username", permissions="Permissions"))
print(("-" * 20) + "+" + ("-" * 20))
for u in users:
print("{username:20}| {permissions}".format(username=u["username"], permissions=" ".join(u["permissions"])))
def handle_new_user(args, client):
r = client.new_user(args.username, args.permissions)
print_user(r)
def handle_delete_user(args, client):
r = client.delete_user(args.username)
print_user(r)
def handle_get_db_usage(args, client):
usage = client.get_db_usage()
print(usage)
tables = sorted(usage.keys())
print("{name:20}| {rows:20}".format(name="Table name", rows="Rows"))
print(("-" * 20) + "+" + ("-" * 20))
for t in tables:
print("{name:20}| {rows:<20}".format(name=t, rows=usage[t]["rows"]))
print()
total_rows = sum(t["rows"] for t in usage.values())
print(f"Total rows: {total_rows}")
def handle_get_db_query_columns(args, client):
columns = client.get_db_query_columns()
print("\n".join(sorted(columns)))
def handle_gc_status(args, client):
result = client.gc_status()
if not result["mark"]:
print("No Garbage collection in progress")
return 0
print("Current Mark: %s" % result["mark"])
print("Total hashes to keep: %d" % result["keep"])
print("Total hashes to remove: %s" % result["remove"])
return 0
def handle_gc_mark(args, client):
where = {k: v for k, v in args.where}
result = client.gc_mark(args.mark, where)
print("New hashes marked: %d" % result["count"])
return 0
def handle_gc_sweep(args, client):
result = client.gc_sweep(args.mark)
print("Removed %d rows" % result["count"])
return 0
def handle_unihash_exists(args, client):
result = client.unihash_exists(args.unihash)
if args.quiet:
return 0 if result else 1
print("true" if result else "false")
return 0
parser = argparse.ArgumentParser(description='Hash Equivalence Client') parser = argparse.ArgumentParser(description='Hash Equivalence Client')
parser.add_argument('--address', default=DEFAULT_ADDRESS, help='Server address (default "%(default)s")') parser.add_argument('--address', default=DEFAULT_ADDRESS, help='Server address (default "%(default)s")')
parser.add_argument('--log', default='WARNING', help='Set logging level') parser.add_argument('--log', default='WARNING', help='Set logging level')
parser.add_argument('--login', '-l', metavar="USERNAME", help="Authenticate as USERNAME")
parser.add_argument('--password', '-p', metavar="TOKEN", help="Authenticate using token TOKEN")
parser.add_argument('--become', '-b', metavar="USERNAME", help="Impersonate user USERNAME (if allowed) when performing actions")
parser.add_argument('--no-netrc', '-n', action="store_false", dest="netrc", help="Do not use .netrc")
subparsers = parser.add_subparsers() subparsers = parser.add_subparsers()
get_parser = subparsers.add_parser('get', help="Get the unihash for a taskhash")
get_parser.add_argument("method", help="Method to query")
get_parser.add_argument("taskhash", help="Task hash to query")
get_parser.set_defaults(func=handle_get)
get_outhash_parser = subparsers.add_parser('get-outhash', help="Get output hash information")
get_outhash_parser.add_argument("method", help="Method to query")
get_outhash_parser.add_argument("outhash", help="Output hash to query")
get_outhash_parser.add_argument("taskhash", help="Task hash to query")
get_outhash_parser.set_defaults(func=handle_get_outhash)
stats_parser = subparsers.add_parser('stats', help='Show server stats') stats_parser = subparsers.add_parser('stats', help='Show server stats')
stats_parser.add_argument('--reset', action='store_true', stats_parser.add_argument('--reset', action='store_true',
help='Reset server stats') help='Reset server stats')
@@ -264,64 +137,6 @@ def main():
help='Include string in outhash') help='Include string in outhash')
stress_parser.set_defaults(func=handle_stress) stress_parser.set_defaults(func=handle_stress)
remove_parser = subparsers.add_parser('remove', help="Remove hash entries")
remove_parser.add_argument("--where", "-w", metavar="KEY VALUE", nargs=2, action="append", default=[],
help="Remove entries from table where KEY == VALUE")
remove_parser.set_defaults(func=handle_remove)
clean_unused_parser = subparsers.add_parser('clean-unused', help="Remove unused database entries")
clean_unused_parser.add_argument("max_age", metavar="SECONDS", type=int, help="Remove unused entries older than SECONDS old")
clean_unused_parser.set_defaults(func=handle_clean_unused)
refresh_token_parser = subparsers.add_parser('refresh-token', help="Refresh auth token")
refresh_token_parser.add_argument("--username", "-u", help="Refresh the token for another user (if authorized)")
refresh_token_parser.set_defaults(func=handle_refresh_token)
set_user_perms_parser = subparsers.add_parser('set-user-perms', help="Set new permissions for user")
set_user_perms_parser.add_argument("--username", "-u", help="Username", required=True)
set_user_perms_parser.add_argument("permissions", metavar="PERM", nargs="*", default=[], help="New permissions")
set_user_perms_parser.set_defaults(func=handle_set_user_permissions)
get_user_parser = subparsers.add_parser('get-user', help="Get user")
get_user_parser.add_argument("--username", "-u", help="Username")
get_user_parser.set_defaults(func=handle_get_user)
get_all_users_parser = subparsers.add_parser('get-all-users', help="List all users")
get_all_users_parser.set_defaults(func=handle_get_all_users)
new_user_parser = subparsers.add_parser('new-user', help="Create new user")
new_user_parser.add_argument("--username", "-u", help="Username", required=True)
new_user_parser.add_argument("permissions", metavar="PERM", nargs="*", default=[], help="New permissions")
new_user_parser.set_defaults(func=handle_new_user)
delete_user_parser = subparsers.add_parser('delete-user', help="Delete user")
delete_user_parser.add_argument("--username", "-u", help="Username", required=True)
delete_user_parser.set_defaults(func=handle_delete_user)
db_usage_parser = subparsers.add_parser('get-db-usage', help="Database Usage")
db_usage_parser.set_defaults(func=handle_get_db_usage)
db_query_columns_parser = subparsers.add_parser('get-db-query-columns', help="Show columns that can be used in database queries")
db_query_columns_parser.set_defaults(func=handle_get_db_query_columns)
gc_status_parser = subparsers.add_parser("gc-status", help="Show garbage collection status")
gc_status_parser.set_defaults(func=handle_gc_status)
gc_mark_parser = subparsers.add_parser('gc-mark', help="Mark hashes to be kept for garbage collection")
gc_mark_parser.add_argument("mark", help="Mark for this garbage collection operation")
gc_mark_parser.add_argument("--where", "-w", metavar="KEY VALUE", nargs=2, action="append", default=[],
help="Keep entries in table where KEY == VALUE")
gc_mark_parser.set_defaults(func=handle_gc_mark)
gc_sweep_parser = subparsers.add_parser('gc-sweep', help="Perform garbage collection and delete any entries that are not marked")
gc_sweep_parser.add_argument("mark", help="Mark for this garbage collection operation")
gc_sweep_parser.set_defaults(func=handle_gc_sweep)
unihash_exists_parser = subparsers.add_parser('unihash-exists', help="Check if a unihash is known to the server")
unihash_exists_parser.add_argument("--quiet", action="store_true", help="Don't print status. Instead, exit with 0 if unihash exists and 1 if it does not")
unihash_exists_parser.add_argument("unihash", help="Unihash to check")
unihash_exists_parser.set_defaults(func=handle_unihash_exists)
args = parser.parse_args() args = parser.parse_args()
logger = logging.getLogger('hashserv') logger = logging.getLogger('hashserv')
@@ -335,30 +150,11 @@ def main():
console.setLevel(level) console.setLevel(level)
logger.addHandler(console) logger.addHandler(console)
login = args.login
password = args.password
if login is None and args.netrc:
try:
n = netrc.netrc()
auth = n.authenticators(args.address)
if auth is not None:
login, _, password = auth
except FileNotFoundError:
pass
except netrc.NetrcParseError as e:
sys.stderr.write(f"Error parsing {e.filename}:{e.lineno}: {e.msg}\n")
func = getattr(args, 'func', None) func = getattr(args, 'func', None)
if func: if func:
try: client = hashserv.create_client(args.address)
with hashserv.create_client(args.address, login, password) as client:
if args.become:
client.become_user(args.become)
return func(args, client) return func(args, client)
except bb.asyncrpc.InvokeError as e:
print(f"ERROR: {e}")
return 1
return 0 return 0

View File

@@ -11,161 +11,56 @@ import logging
import argparse import argparse
import sqlite3 import sqlite3
import warnings import warnings
warnings.simplefilter("default") warnings.simplefilter("default")
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), "lib")) sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lib'))
import hashserv import hashserv
from hashserv.server import DEFAULT_ANON_PERMS
VERSION = "1.0.0" VERSION = "1.0.0"
DEFAULT_BIND = "unix://./hashserve.sock" DEFAULT_BIND = 'unix://./hashserve.sock'
def main(): def main():
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(description='Hash Equivalence Reference Server. Version=%s' % VERSION,
description="Hash Equivalence Reference Server. Version=%s" % VERSION, epilog='''The bind address is the path to a unix domain socket if it is
formatter_class=argparse.RawTextHelpFormatter, prefixed with "unix://". Otherwise, it is an IP address
epilog=""" and port in form ADDRESS:PORT. To bind to all addresses, leave
The bind address may take one of the following formats: the ADDRESS empty, e.g. "--bind :8686". To bind to a specific
unix://PATH - Bind to unix domain socket at PATH IPv6 address, enclose the address in "[]", e.g.
ws://ADDRESS:PORT - Bind to websocket on ADDRESS:PORT "--bind [::1]:8686"'''
ADDRESS:PORT - Bind to raw TCP socket on ADDRESS:PORT
To bind to all addresses, leave the ADDRESS empty, e.g. "--bind :8686" or
"--bind ws://:8686". To bind to a specific IPv6 address, enclose the address in
"[]", e.g. "--bind [::1]:8686" or "--bind ws://[::1]:8686"
Note that the default Anonymous permissions are designed to not break existing
server instances when upgrading, but are not particularly secure defaults. If
you want to use authentication, it is recommended that you use "--anon-perms
@read" to only give anonymous users read access, or "--anon-perms @none" to
give un-authenticated users no access at all.
Setting "--anon-perms @all" or "--anon-perms @user-admin" is not allowed, since
this would allow anonymous users to manage all users accounts, which is a bad
idea.
If you are using user authentication, you should run your server in websockets
mode with an SSL terminating load balancer in front of it (as this server does
not implement SSL). Otherwise all usernames and passwords will be transmitted
in the clear. When configured this way, clients can connect using a secure
websocket, as in "wss://SERVER:PORT"
The following permissions are supported by the server:
@none - No permissions
@read - The ability to read equivalent hashes from the server
@report - The ability to report equivalent hashes to the server
@db-admin - Manage the hash database(s). This includes cleaning the
database, removing hashes, etc.
@user-admin - The ability to manage user accounts. This includes, creating
users, deleting users, resetting login tokens, and assigning
permissions.
@all - All possible permissions, including any that may be added
in the future
""",
) )
parser.add_argument( parser.add_argument('-b', '--bind', default=DEFAULT_BIND, help='Bind address (default "%(default)s")')
"-b", parser.add_argument('-d', '--database', default='./hashserv.db', help='Database file (default "%(default)s")')
"--bind", parser.add_argument('-l', '--log', default='WARNING', help='Set logging level')
default=os.environ.get("HASHSERVER_BIND", DEFAULT_BIND), parser.add_argument('-u', '--upstream', help='Upstream hashserv to pull hashes from')
help='Bind address (default $HASHSERVER_BIND, "%(default)s")', parser.add_argument('-r', '--read-only', action='store_true', help='Disallow write operations from clients')
)
parser.add_argument(
"-d",
"--database",
default=os.environ.get("HASHSERVER_DB", "./hashserv.db"),
help='Database file (default $HASHSERVER_DB, "%(default)s")',
)
parser.add_argument(
"-l",
"--log",
default=os.environ.get("HASHSERVER_LOG_LEVEL", "WARNING"),
help='Set logging level (default $HASHSERVER_LOG_LEVEL, "%(default)s")',
)
parser.add_argument(
"-u",
"--upstream",
default=os.environ.get("HASHSERVER_UPSTREAM", None),
help="Upstream hashserv to pull hashes from ($HASHSERVER_UPSTREAM)",
)
parser.add_argument(
"-r",
"--read-only",
action="store_true",
help="Disallow write operations from clients ($HASHSERVER_READ_ONLY)",
)
parser.add_argument(
"--db-username",
default=os.environ.get("HASHSERVER_DB_USERNAME", None),
help="Database username ($HASHSERVER_DB_USERNAME)",
)
parser.add_argument(
"--db-password",
default=os.environ.get("HASHSERVER_DB_PASSWORD", None),
help="Database password ($HASHSERVER_DB_PASSWORD)",
)
parser.add_argument(
"--anon-perms",
metavar="PERM[,PERM[,...]]",
default=os.environ.get("HASHSERVER_ANON_PERMS", ",".join(DEFAULT_ANON_PERMS)),
help='Permissions to give anonymous users (default $HASHSERVER_ANON_PERMS, "%(default)s")',
)
parser.add_argument(
"--admin-user",
default=os.environ.get("HASHSERVER_ADMIN_USER", None),
help="Create default admin user with name ADMIN_USER ($HASHSERVER_ADMIN_USER)",
)
parser.add_argument(
"--admin-password",
default=os.environ.get("HASHSERVER_ADMIN_PASSWORD", None),
help="Create default admin user with password ADMIN_PASSWORD ($HASHSERVER_ADMIN_PASSWORD)",
)
args = parser.parse_args() args = parser.parse_args()
logger = logging.getLogger("hashserv") logger = logging.getLogger('hashserv')
level = getattr(logging, args.log.upper(), None) level = getattr(logging, args.log.upper(), None)
if not isinstance(level, int): if not isinstance(level, int):
raise ValueError("Invalid log level: %s (Try ERROR/WARNING/INFO/DEBUG)" % args.log) raise ValueError('Invalid log level: %s' % args.log)
logger.setLevel(level) logger.setLevel(level)
console = logging.StreamHandler() console = logging.StreamHandler()
console.setLevel(level) console.setLevel(level)
logger.addHandler(console) logger.addHandler(console)
read_only = (os.environ.get("HASHSERVER_READ_ONLY", "0") == "1") or args.read_only server = hashserv.create_server(args.bind, args.database, upstream=args.upstream, read_only=args.read_only)
if "," in args.anon_perms:
anon_perms = args.anon_perms.split(",")
else:
anon_perms = args.anon_perms.split()
server = hashserv.create_server(
args.bind,
args.database,
upstream=args.upstream,
read_only=read_only,
db_username=args.db_username,
db_password=args.db_password,
anon_perms=anon_perms,
admin_username=args.admin_user,
admin_password=args.admin_password,
)
server.serve_forever() server.serve_forever()
return 0 return 0
if __name__ == "__main__": if __name__ == '__main__':
try: try:
ret = main() ret = main()
except Exception: except Exception:
ret = 1 ret = 1
import traceback import traceback
traceback.print_exc() traceback.print_exc()
sys.exit(ret) sys.exit(ret)

View File

@@ -68,11 +68,11 @@ def main():
registered = False registered = False
for plugin in plugins: for plugin in plugins:
if hasattr(plugin, 'tinfoil_init'):
plugin.tinfoil_init(tinfoil)
if hasattr(plugin, 'register_commands'): if hasattr(plugin, 'register_commands'):
registered = True registered = True
plugin.register_commands(subparsers) plugin.register_commands(subparsers)
if hasattr(plugin, 'tinfoil_init'):
plugin.tinfoil_init(tinfoil)
if not registered: if not registered:
logger.error("No commands registered - missing plugins?") logger.error("No commands registered - missing plugins?")

View File

@@ -1,83 +1,53 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
import os import os
import sys,logging import sys,logging
import argparse import optparse
import warnings import warnings
warnings.simplefilter("default") warnings.simplefilter("default")
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), "lib")) sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)),'lib'))
import prserv import prserv
import prserv.serv import prserv.serv
VERSION = "1.1.0" __version__="1.0.0"
PRHOST_DEFAULT="0.0.0.0" PRHOST_DEFAULT='0.0.0.0'
PRPORT_DEFAULT=8585 PRPORT_DEFAULT=8585
def main(): def main():
parser = argparse.ArgumentParser( parser = optparse.OptionParser(
description="BitBake PR Server. Version=%s" % VERSION, version="Bitbake PR Service Core version %s, %%prog version %s" % (prserv.__version__, __version__),
formatter_class=argparse.RawTextHelpFormatter) usage = "%prog < --start | --stop > [options]")
parser.add_argument( parser.add_option("-f", "--file", help="database filename(default: prserv.sqlite3)", action="store",
"-f", dest="dbfile", type="string", default="prserv.sqlite3")
"--file", parser.add_option("-l", "--log", help="log filename(default: prserv.log)", action="store",
default="prserv.sqlite3", dest="logfile", type="string", default="prserv.log")
help="database filename (default: prserv.sqlite3)", parser.add_option("--loglevel", help="logging level, i.e. CRITICAL, ERROR, WARNING, INFO, DEBUG",
) action = "store", type="string", dest="loglevel", default = "INFO")
parser.add_argument( parser.add_option("--start", help="start daemon",
"-l", action="store_true", dest="start")
"--log", parser.add_option("--stop", help="stop daemon",
default="prserv.log", action="store_true", dest="stop")
help="log filename(default: prserv.log)", parser.add_option("--host", help="ip address to bind", action="store",
) dest="host", type="string", default=PRHOST_DEFAULT)
parser.add_argument( parser.add_option("--port", help="port number(default: 8585)", action="store",
"--loglevel", dest="port", type="int", default=PRPORT_DEFAULT)
default="INFO", parser.add_option("-r", "--read-only", help="open database in read-only mode",
help="logging level, i.e. CRITICAL, ERROR, WARNING, INFO, DEBUG", action="store_true")
)
parser.add_argument(
"--start",
action="store_true",
help="start daemon",
)
parser.add_argument(
"--stop",
action="store_true",
help="stop daemon",
)
parser.add_argument(
"--host",
help="ip address to bind",
default=PRHOST_DEFAULT,
)
parser.add_argument(
"--port",
type=int,
default=PRPORT_DEFAULT,
help="port number (default: 8585)",
)
parser.add_argument(
"-r",
"--read-only",
action="store_true",
help="open database in read-only mode",
)
args = parser.parse_args() options, args = parser.parse_args(sys.argv)
prserv.init_logger(os.path.abspath(args.log), args.loglevel) prserv.init_logger(os.path.abspath(options.logfile),options.loglevel)
if args.start: if options.start:
ret=prserv.serv.start_daemon(args.file, args.host, args.port, os.path.abspath(args.log), args.read_only) ret=prserv.serv.start_daemon(options.dbfile, options.host, options.port,os.path.abspath(options.logfile), options.read_only)
elif args.stop: elif options.stop:
ret=prserv.serv.stop_daemon(args.host, args.port) ret=prserv.serv.stop_daemon(options.host, options.port)
else: else:
ret=parser.print_help() ret=parser.print_help()
return ret return ret

View File

@@ -12,12 +12,11 @@ warnings.simplefilter("default")
import logging import logging
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])), 'lib')) sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])), 'lib'))
import bb if sys.getfilesystemencoding() != "utf-8":
sys.exit("Please use a locale setting which supports UTF-8 (such as LANG=en_US.UTF-8).\nPython can't change the filesystem locale after loading so we need a UTF-8 when Python starts or things won't work.")
bb.utils.check_system_locale()
# Users shouldn't be running this code directly # Users shouldn't be running this code directly
if len(sys.argv) != 11 or not sys.argv[1].startswith("decafbad"): if len(sys.argv) != 10 or not sys.argv[1].startswith("decafbad"):
print("bitbake-server is meant for internal execution by bitbake itself, please don't use it standalone.") print("bitbake-server is meant for internal execution by bitbake itself, please don't use it standalone.")
sys.exit(1) sys.exit(1)
@@ -29,8 +28,7 @@ logfile = sys.argv[4]
lockname = sys.argv[5] lockname = sys.argv[5]
sockname = sys.argv[6] sockname = sys.argv[6]
timeout = float(sys.argv[7]) timeout = float(sys.argv[7])
profile = bool(int(sys.argv[8])) xmlrpcinterface = (sys.argv[8], int(sys.argv[9]))
xmlrpcinterface = (sys.argv[9], int(sys.argv[10]))
if xmlrpcinterface[0] == "None": if xmlrpcinterface[0] == "None":
xmlrpcinterface = (None, xmlrpcinterface[1]) xmlrpcinterface = (None, xmlrpcinterface[1])
@@ -51,5 +49,5 @@ logger = logging.getLogger("BitBake")
handler = bb.event.LogHandler() handler = bb.event.LogHandler()
logger.addHandler(handler) logger.addHandler(handler)
bb.server.process.execServer(lockfd, readypipeinfd, lockname, sockname, timeout, xmlrpcinterface, profile) bb.server.process.execServer(lockfd, readypipeinfd, lockname, sockname, timeout, xmlrpcinterface)

View File

@@ -1,7 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
@@ -24,7 +22,8 @@ import subprocess
from multiprocessing import Lock from multiprocessing import Lock
from threading import Thread from threading import Thread
bb.utils.check_system_locale() if sys.getfilesystemencoding() != "utf-8":
sys.exit("Please use a locale setting which supports UTF-8 (such as LANG=en_US.UTF-8).\nPython can't change the filesystem locale after loading so we need a UTF-8 when Python starts or things won't work.")
# Users shouldn't be running this code directly # Users shouldn't be running this code directly
if len(sys.argv) != 2 or not sys.argv[1].startswith("decafbad"): if len(sys.argv) != 2 or not sys.argv[1].startswith("decafbad"):
@@ -91,19 +90,19 @@ def worker_fire_prepickled(event):
worker_thread_exit = False worker_thread_exit = False
def worker_flush(worker_queue): def worker_flush(worker_queue):
worker_queue_int = bytearray() worker_queue_int = b""
global worker_pipe, worker_thread_exit global worker_pipe, worker_thread_exit
while True: while True:
try: try:
worker_queue_int.extend(worker_queue.get(True, 1)) worker_queue_int = worker_queue_int + worker_queue.get(True, 1)
except queue.Empty: except queue.Empty:
pass pass
while (worker_queue_int or not worker_queue.empty()): while (worker_queue_int or not worker_queue.empty()):
try: try:
(_, ready, _) = select.select([], [worker_pipe], [], 1) (_, ready, _) = select.select([], [worker_pipe], [], 1)
if not worker_queue.empty(): if not worker_queue.empty():
worker_queue_int.extend(worker_queue.get()) worker_queue_int = worker_queue_int + worker_queue.get()
written = os.write(worker_pipe, worker_queue_int) written = os.write(worker_pipe, worker_queue_int)
worker_queue_int = worker_queue_int[written:] worker_queue_int = worker_queue_int[written:]
except (IOError, OSError) as e: except (IOError, OSError) as e:
@@ -121,10 +120,11 @@ def worker_child_fire(event, d):
data = b"<event>" + pickle.dumps(event) + b"</event>" data = b"<event>" + pickle.dumps(event) + b"</event>"
try: try:
with bb.utils.lock_timeout(worker_pipe_lock): worker_pipe_lock.acquire()
while(len(data)): while(len(data)):
written = worker_pipe.write(data) written = worker_pipe.write(data)
data = data[written:] data = data[written:]
worker_pipe_lock.release()
except IOError: except IOError:
sigterm_handler(None, None) sigterm_handler(None, None)
raise raise
@@ -143,17 +143,7 @@ def sigterm_handler(signum, frame):
os.killpg(0, signal.SIGTERM) os.killpg(0, signal.SIGTERM)
sys.exit() sys.exit()
def fork_off_task(cfg, data, databuilder, workerdata, extraconfigdata, runtask): def fork_off_task(cfg, data, databuilder, workerdata, fn, task, taskname, taskhash, unihash, appends, taskdepdata, extraconfigdata, quieterrors=False, dry_run_exec=False):
fn = runtask['fn']
task = runtask['task']
taskname = runtask['taskname']
taskhash = runtask['taskhash']
unihash = runtask['unihash']
appends = runtask['appends']
layername = runtask['layername']
taskdepdata = runtask['taskdepdata']
quieterrors = runtask['quieterrors']
# We need to setup the environment BEFORE the fork, since # We need to setup the environment BEFORE the fork, since
# a fork() or exec*() activates PSEUDO... # a fork() or exec*() activates PSEUDO...
@@ -165,7 +155,8 @@ def fork_off_task(cfg, data, databuilder, workerdata, extraconfigdata, runtask):
uid = os.getuid() uid = os.getuid()
gid = os.getgid() gid = os.getgid()
taskdep = runtask['taskdep']
taskdep = workerdata["taskdeps"][fn]
if 'umask' in taskdep and taskname in taskdep['umask']: if 'umask' in taskdep and taskname in taskdep['umask']:
umask = taskdep['umask'][taskname] umask = taskdep['umask'][taskname]
elif workerdata["umask"]: elif workerdata["umask"]:
@@ -177,25 +168,25 @@ def fork_off_task(cfg, data, databuilder, workerdata, extraconfigdata, runtask):
except TypeError: except TypeError:
pass pass
dry_run = cfg.dry_run or runtask['dry_run'] dry_run = cfg.dry_run or dry_run_exec
# We can't use the fakeroot environment in a dry run as it possibly hasn't been built # We can't use the fakeroot environment in a dry run as it possibly hasn't been built
if 'fakeroot' in taskdep and taskname in taskdep['fakeroot'] and not dry_run: if 'fakeroot' in taskdep and taskname in taskdep['fakeroot'] and not dry_run:
fakeroot = True fakeroot = True
envvars = (runtask['fakerootenv'] or "").split() envvars = (workerdata["fakerootenv"][fn] or "").split()
for key, value in (var.split('=',1) for var in envvars): for key, value in (var.split('=') for var in envvars):
envbackup[key] = os.environ.get(key) envbackup[key] = os.environ.get(key)
os.environ[key] = value os.environ[key] = value
fakeenv[key] = value fakeenv[key] = value
fakedirs = (runtask['fakerootdirs'] or "").split() fakedirs = (workerdata["fakerootdirs"][fn] or "").split()
for p in fakedirs: for p in fakedirs:
bb.utils.mkdirhier(p) bb.utils.mkdirhier(p)
logger.debug2('Running %s:%s under fakeroot, fakedirs: %s' % logger.debug2('Running %s:%s under fakeroot, fakedirs: %s' %
(fn, taskname, ', '.join(fakedirs))) (fn, taskname, ', '.join(fakedirs)))
else: else:
envvars = (runtask['fakerootnoenv'] or "").split() envvars = (workerdata["fakerootnoenv"][fn] or "").split()
for key, value in (var.split('=',1) for var in envvars): for key, value in (var.split('=') for var in envvars):
envbackup[key] = os.environ.get(key) envbackup[key] = os.environ.get(key)
os.environ[key] = value os.environ[key] = value
fakeenv[key] = value fakeenv[key] = value
@@ -237,16 +228,15 @@ def fork_off_task(cfg, data, databuilder, workerdata, extraconfigdata, runtask):
# Let SIGHUP exit as SIGTERM # Let SIGHUP exit as SIGTERM
signal.signal(signal.SIGHUP, sigterm_handler) signal.signal(signal.SIGHUP, sigterm_handler)
# No stdin & stdout # No stdin
# stdout is used as a status report channel and must not be used by child processes. newsi = os.open(os.devnull, os.O_RDWR)
dumbio = os.open(os.devnull, os.O_RDWR) os.dup2(newsi, sys.stdin.fileno())
os.dup2(dumbio, sys.stdin.fileno())
os.dup2(dumbio, sys.stdout.fileno())
if umask is not None: if umask:
os.umask(umask) os.umask(umask)
try: try:
bb_cache = bb.cache.NoCache(databuilder)
(realfn, virtual, mc) = bb.cache.virtualfn2realfn(fn) (realfn, virtual, mc) = bb.cache.virtualfn2realfn(fn)
the_data = databuilder.mcdata[mc] the_data = databuilder.mcdata[mc]
the_data.setVar("BB_WORKERCONTEXT", "1") the_data.setVar("BB_WORKERCONTEXT", "1")
@@ -265,14 +255,13 @@ def fork_off_task(cfg, data, databuilder, workerdata, extraconfigdata, runtask):
bb.parse.siggen.set_taskhashes(workerdata["newhashes"]) bb.parse.siggen.set_taskhashes(workerdata["newhashes"])
ret = 0 ret = 0
the_data = databuilder.parseRecipe(fn, appends, layername) the_data = bb_cache.loadDataFull(fn, appends)
the_data.setVar('BB_TASKHASH', taskhash) the_data.setVar('BB_TASKHASH', taskhash)
the_data.setVar('BB_UNIHASH', unihash) the_data.setVar('BB_UNIHASH', unihash)
bb.parse.siggen.setup_datacache_from_datastore(fn, the_data)
bb.utils.set_process_name("%s:%s" % (the_data.getVar("PN"), taskname.replace("do_", ""))) bb.utils.set_process_name("%s:%s" % (the_data.getVar("PN"), taskname.replace("do_", "")))
if not bb.utils.to_boolean(the_data.getVarFlag(taskname, 'network')): if not the_data.getVarFlag(taskname, 'network', False):
if bb.utils.is_local_uid(uid): if bb.utils.is_local_uid(uid):
logger.debug("Attempting to disable network for %s" % taskname) logger.debug("Attempting to disable network for %s" % taskname)
bb.utils.disable_network(uid, gid) bb.utils.disable_network(uid, gid)
@@ -307,10 +296,6 @@ def fork_off_task(cfg, data, databuilder, workerdata, extraconfigdata, runtask):
if not quieterrors: if not quieterrors:
logger.critical(traceback.format_exc()) logger.critical(traceback.format_exc())
os._exit(1) os._exit(1)
sys.stdout.flush()
sys.stderr.flush()
try: try:
if dry_run: if dry_run:
return 0 return 0
@@ -352,12 +337,12 @@ class runQueueWorkerPipe():
if pipeout: if pipeout:
pipeout.close() pipeout.close()
bb.utils.nonblockingfd(self.input) bb.utils.nonblockingfd(self.input)
self.queue = bytearray() self.queue = b""
def read(self): def read(self):
start = len(self.queue) start = len(self.queue)
try: try:
self.queue.extend(self.input.read(102400) or b"") self.queue = self.queue + (self.input.read(102400) or b"")
except (OSError, IOError) as e: except (OSError, IOError) as e:
if e.errno != errno.EAGAIN: if e.errno != errno.EAGAIN:
raise raise
@@ -385,7 +370,7 @@ class BitbakeWorker(object):
def __init__(self, din): def __init__(self, din):
self.input = din self.input = din
bb.utils.nonblockingfd(self.input) bb.utils.nonblockingfd(self.input)
self.queue = bytearray() self.queue = b""
self.cookercfg = None self.cookercfg = None
self.databuilder = None self.databuilder = None
self.data = None self.data = None
@@ -419,7 +404,7 @@ class BitbakeWorker(object):
if len(r) == 0: if len(r) == 0:
# EOF on pipe, server must have terminated # EOF on pipe, server must have terminated
self.sigterm_exception(signal.SIGTERM, None) self.sigterm_exception(signal.SIGTERM, None)
self.queue.extend(r) self.queue = self.queue + r
except (OSError, IOError): except (OSError, IOError):
pass pass
if len(self.queue): if len(self.queue):
@@ -439,30 +424,18 @@ class BitbakeWorker(object):
while self.process_waitpid(): while self.process_waitpid():
continue continue
def handle_item(self, item, func): def handle_item(self, item, func):
opening_tag = b"<" + item + b">" if self.queue.startswith(b"<" + item + b">"):
if not self.queue.startswith(opening_tag):
return
tag_len = len(opening_tag)
if len(self.queue) < tag_len + 4:
# we need to receive more data
return
header = self.queue[tag_len:tag_len + 4]
payload_len = int.from_bytes(header, 'big')
# closing tag has length (tag_len + 1)
if len(self.queue) < tag_len * 2 + 1 + payload_len:
# we need to receive more data
return
index = self.queue.find(b"</" + item + b">") index = self.queue.find(b"</" + item + b">")
if index != -1: while index != -1:
try: try:
func(self.queue[(tag_len + 4):index]) func(self.queue[(len(item) + 2):index])
except pickle.UnpicklingError: except pickle.UnpicklingError:
workerlog_write("Unable to unpickle data: %s\n" % ":".join("{:02x}".format(c) for c in self.queue)) workerlog_write("Unable to unpickle data: %s\n" % ":".join("{:02x}".format(c) for c in self.queue))
raise raise
self.queue = self.queue[(index + len(b"</") + len(item) + len(b">")):] self.queue = self.queue[(index + len(item) + 3):]
index = self.queue.find(b"</" + item + b">")
def handle_cookercfg(self, data): def handle_cookercfg(self, data):
self.cookercfg = pickle.loads(data) self.cookercfg = pickle.loads(data)
@@ -482,7 +455,6 @@ class BitbakeWorker(object):
for mc in self.databuilder.mcdata: for mc in self.databuilder.mcdata:
self.databuilder.mcdata[mc].setVar("PRSERV_HOST", self.workerdata["prhost"]) self.databuilder.mcdata[mc].setVar("PRSERV_HOST", self.workerdata["prhost"])
self.databuilder.mcdata[mc].setVar("BB_HASHSERVE", self.workerdata["hashservaddr"]) self.databuilder.mcdata[mc].setVar("BB_HASHSERVE", self.workerdata["hashservaddr"])
self.databuilder.mcdata[mc].setVar("__bbclasstype", "recipe")
def handle_newtaskhashes(self, data): def handle_newtaskhashes(self, data):
self.workerdata["newhashes"] = pickle.loads(data) self.workerdata["newhashes"] = pickle.loads(data)
@@ -500,15 +472,11 @@ class BitbakeWorker(object):
sys.exit(0) sys.exit(0)
def handle_runtask(self, data): def handle_runtask(self, data):
runtask = pickle.loads(data) fn, task, taskname, taskhash, unihash, quieterrors, appends, taskdepdata, dry_run_exec = pickle.loads(data)
fn = runtask['fn']
task = runtask['task']
taskname = runtask['taskname']
workerlog_write("Handling runtask %s %s %s\n" % (task, fn, taskname)) workerlog_write("Handling runtask %s %s %s\n" % (task, fn, taskname))
pid, pipein, pipeout = fork_off_task(self.cookercfg, self.data, self.databuilder, self.workerdata, self.extraconfigdata, runtask) pid, pipein, pipeout = fork_off_task(self.cookercfg, self.data, self.databuilder, self.workerdata, fn, task, taskname, taskhash, unihash, appends, taskdepdata, self.extraconfigdata, quieterrors, dry_run_exec)
self.build_pids[pid] = task self.build_pids[pid] = task
self.build_pipes[pid] = runQueueWorkerPipe(pipein, pipeout) self.build_pipes[pid] = runQueueWorkerPipe(pipein, pipeout)

View File

@@ -1,7 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
@@ -24,17 +22,15 @@ warnings.simplefilter("default")
version = 1.0 version = 1.0
git_cmd = ['git', '-c', 'safe.bareRepository=all']
def main(): def main():
if sys.version_info < (3, 4, 0): if sys.version_info < (3, 4, 0):
sys.exit('Python 3.4 or greater is required') sys.exit('Python 3.4 or greater is required')
git_dir = check_output(git_cmd + ['rev-parse', '--git-dir']).rstrip() git_dir = check_output(['git', 'rev-parse', '--git-dir']).rstrip()
shallow_file = os.path.join(git_dir, 'shallow') shallow_file = os.path.join(git_dir, 'shallow')
if os.path.exists(shallow_file): if os.path.exists(shallow_file):
try: try:
check_output(git_cmd + ['fetch', '--unshallow']) check_output(['git', 'fetch', '--unshallow'])
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
try: try:
os.unlink(shallow_file) os.unlink(shallow_file)
@@ -43,21 +39,21 @@ def main():
raise raise
args = process_args() args = process_args()
revs = check_output(git_cmd + ['rev-list'] + args.revisions).splitlines() revs = check_output(['git', 'rev-list'] + args.revisions).splitlines()
make_shallow(shallow_file, args.revisions, args.refs) make_shallow(shallow_file, args.revisions, args.refs)
ref_revs = check_output(git_cmd + ['rev-list'] + args.refs).splitlines() ref_revs = check_output(['git', 'rev-list'] + args.refs).splitlines()
remaining_history = set(revs) & set(ref_revs) remaining_history = set(revs) & set(ref_revs)
for rev in remaining_history: for rev in remaining_history:
if check_output(git_cmd + ['rev-parse', '{}^@'.format(rev)]): if check_output(['git', 'rev-parse', '{}^@'.format(rev)]):
sys.exit('Error: %s was not made shallow' % rev) sys.exit('Error: %s was not made shallow' % rev)
filter_refs(args.refs) filter_refs(args.refs)
if args.shrink: if args.shrink:
shrink_repo(git_dir) shrink_repo(git_dir)
subprocess.check_call(git_cmd + ['fsck', '--unreachable']) subprocess.check_call(['git', 'fsck', '--unreachable'])
def process_args(): def process_args():
@@ -74,12 +70,12 @@ def process_args():
args = parser.parse_args() args = parser.parse_args()
if args.refs: if args.refs:
args.refs = check_output(git_cmd + ['rev-parse', '--symbolic-full-name'] + args.refs).splitlines() args.refs = check_output(['git', 'rev-parse', '--symbolic-full-name'] + args.refs).splitlines()
else: else:
args.refs = get_all_refs(lambda r, t, tt: t == 'commit' or tt == 'commit') args.refs = get_all_refs(lambda r, t, tt: t == 'commit' or tt == 'commit')
args.refs = list(filter(lambda r: not r.endswith('/HEAD'), args.refs)) args.refs = list(filter(lambda r: not r.endswith('/HEAD'), args.refs))
args.revisions = check_output(git_cmd + ['rev-parse'] + ['%s^{}' % i for i in args.revisions]).splitlines() args.revisions = check_output(['git', 'rev-parse'] + ['%s^{}' % i for i in args.revisions]).splitlines()
return args return args
@@ -97,7 +93,7 @@ def make_shallow(shallow_file, revisions, refs):
def get_all_refs(ref_filter=None): def get_all_refs(ref_filter=None):
"""Return all the existing refs in this repository, optionally filtering the refs.""" """Return all the existing refs in this repository, optionally filtering the refs."""
ref_output = check_output(git_cmd + ['for-each-ref', '--format=%(refname)\t%(objecttype)\t%(*objecttype)']) ref_output = check_output(['git', 'for-each-ref', '--format=%(refname)\t%(objecttype)\t%(*objecttype)'])
ref_split = [tuple(iter_extend(l.rsplit('\t'), 3)) for l in ref_output.splitlines()] ref_split = [tuple(iter_extend(l.rsplit('\t'), 3)) for l in ref_output.splitlines()]
if ref_filter: if ref_filter:
ref_split = (e for e in ref_split if ref_filter(*e)) ref_split = (e for e in ref_split if ref_filter(*e))
@@ -115,7 +111,7 @@ def filter_refs(refs):
all_refs = get_all_refs() all_refs = get_all_refs()
to_remove = set(all_refs) - set(refs) to_remove = set(all_refs) - set(refs)
if to_remove: if to_remove:
check_output(['xargs', '-0', '-n', '1'] + git_cmd + ['update-ref', '-d', '--no-deref'], check_output(['xargs', '-0', '-n', '1', 'git', 'update-ref', '-d', '--no-deref'],
input=''.join(l + '\0' for l in to_remove)) input=''.join(l + '\0' for l in to_remove))
@@ -128,7 +124,7 @@ def follow_history_intersections(revisions, refs):
if rev in seen: if rev in seen:
continue continue
parents = check_output(git_cmd + ['rev-parse', '%s^@' % rev]).splitlines() parents = check_output(['git', 'rev-parse', '%s^@' % rev]).splitlines()
yield rev yield rev
seen.add(rev) seen.add(rev)
@@ -136,12 +132,12 @@ def follow_history_intersections(revisions, refs):
if not parents: if not parents:
continue continue
check_refs = check_output(git_cmd + ['merge-base', '--independent'] + sorted(refs)).splitlines() check_refs = check_output(['git', 'merge-base', '--independent'] + sorted(refs)).splitlines()
for parent in parents: for parent in parents:
for ref in check_refs: for ref in check_refs:
print("Checking %s vs %s" % (parent, ref)) print("Checking %s vs %s" % (parent, ref))
try: try:
merge_base = check_output(git_cmd + ['merge-base', parent, ref]).rstrip() merge_base = check_output(['git', 'merge-base', parent, ref]).rstrip()
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
continue continue
else: else:
@@ -161,14 +157,14 @@ def iter_except(func, exception, start=None):
def shrink_repo(git_dir): def shrink_repo(git_dir):
"""Shrink the newly shallow repository, removing the unreachable objects.""" """Shrink the newly shallow repository, removing the unreachable objects."""
subprocess.check_call(git_cmd + ['reflog', 'expire', '--expire-unreachable=now', '--all']) subprocess.check_call(['git', 'reflog', 'expire', '--expire-unreachable=now', '--all'])
subprocess.check_call(git_cmd + ['repack', '-ad']) subprocess.check_call(['git', 'repack', '-ad'])
try: try:
os.unlink(os.path.join(git_dir, 'objects', 'info', 'alternates')) os.unlink(os.path.join(git_dir, 'objects', 'info', 'alternates'))
except OSError as exc: except OSError as exc:
if exc.errno != errno.ENOENT: if exc.errno != errno.ENOENT:
raise raise
subprocess.check_call(git_cmd + ['prune', '--expire', 'now']) subprocess.check_call(['git', 'prune', '--expire', 'now'])
if __name__ == '__main__': if __name__ == '__main__':

View File

@@ -84,7 +84,7 @@ webserverStartAll()
echo "Starting webserver..." echo "Starting webserver..."
$MANAGE runserver --noreload "$ADDR_PORT" \ $MANAGE runserver --noreload "$ADDR_PORT" \
</dev/null >>${TOASTER_LOGS_DIR}/web.log 2>&1 \ </dev/null >>${BUILDDIR}/toaster_web.log 2>&1 \
& echo $! >${BUILDDIR}/.toastermain.pid & echo $! >${BUILDDIR}/.toastermain.pid
sleep 1 sleep 1
@@ -181,14 +181,6 @@ WEBSERVER=1
export TOASTER_BUILDSERVER=1 export TOASTER_BUILDSERVER=1
ADDR_PORT="localhost:8000" ADDR_PORT="localhost:8000"
TOASTERDIR=`dirname $BUILDDIR` TOASTERDIR=`dirname $BUILDDIR`
# ${BUILDDIR}/toaster_logs/ became the default location for toaster logs
# This is needed for implemented django-log-viewer: https://pypi.org/project/django-log-viewer/
# If the directory does not exist, create it.
TOASTER_LOGS_DIR="${BUILDDIR}/toaster_logs/"
if [ ! -d $TOASTER_LOGS_DIR ]
then
mkdir $TOASTER_LOGS_DIR
fi
unset CMD unset CMD
for param in $*; do for param in $*; do
case $param in case $param in
@@ -307,7 +299,7 @@ case $CMD in
export BITBAKE_UI='toasterui' export BITBAKE_UI='toasterui'
if [ $TOASTER_BUILDSERVER -eq 1 ] ; then if [ $TOASTER_BUILDSERVER -eq 1 ] ; then
$MANAGE runbuilds \ $MANAGE runbuilds \
</dev/null >>${TOASTER_LOGS_DIR}/toaster_runbuilds.log 2>&1 \ </dev/null >>${BUILDDIR}/toaster_runbuilds.log 2>&1 \
& echo $! >${BUILDDIR}/.runbuilds.pid & echo $! >${BUILDDIR}/.runbuilds.pid
else else
echo "Toaster build server not started." echo "Toaster build server not started."

View File

@@ -30,23 +30,79 @@ sys.path.insert(0, join(dirname(dirname(abspath(__file__))), 'lib'))
import bb.cooker import bb.cooker
from bb.ui import toasterui from bb.ui import toasterui
from bb.ui import eventreplay
class EventPlayer:
"""Emulate a connection to a bitbake server."""
def __init__(self, eventfile, variables):
self.eventfile = eventfile
self.variables = variables
self.eventmask = []
def waitEvent(self, _timeout):
"""Read event from the file."""
line = self.eventfile.readline().strip()
if not line:
return
try:
event_str = json.loads(line)['vars'].encode('utf-8')
event = pickle.loads(codecs.decode(event_str, 'base64'))
event_name = "%s.%s" % (event.__module__, event.__class__.__name__)
if event_name not in self.eventmask:
return
return event
except ValueError as err:
print("Failed loading ", line)
raise err
def runCommand(self, command_line):
"""Emulate running a command on the server."""
name = command_line[0]
if name == "getVariable":
var_name = command_line[1]
variable = self.variables.get(var_name)
if variable:
return variable['v'], None
return None, "Missing variable %s" % var_name
elif name == "getAllKeysWithFlags":
dump = {}
flaglist = command_line[1]
for key, val in self.variables.items():
try:
if not key.startswith("__"):
dump[key] = {
'v': val['v'],
'history' : val['history'],
}
for flag in flaglist:
dump[key][flag] = val[flag]
except Exception as err:
print(err)
return (dump, None)
elif name == 'setEventMask':
self.eventmask = command_line[-1]
return True, None
else:
raise Exception("Command %s not implemented" % command_line[0])
def getEventHandle(self):
"""
This method is called by toasterui.
The return value is passed to self.runCommand but not used there.
"""
pass
def main(argv): def main(argv):
with open(argv[-1]) as eventfile: with open(argv[-1]) as eventfile:
# load variables from the first line # load variables from the first line
variables = None variables = json.loads(eventfile.readline().strip())['allvariables']
while line := eventfile.readline().strip():
try:
variables = json.loads(line)['allvariables']
break
except (KeyError, json.JSONDecodeError):
continue
if not variables:
sys.exit("Cannot find allvariables entry in event log file %s" % argv[-1])
eventfile.seek(0)
params = namedtuple('ConfigParams', ['observe_only'])(True) params = namedtuple('ConfigParams', ['observe_only'])(True)
player = eventreplay.EventPlayer(eventfile, variables) player = EventPlayer(eventfile, variables)
return toasterui.main(player, player, params) return toasterui.main(player, player, params)

View File

@@ -40,7 +40,7 @@ set cpo&vim
let s:maxoff = 50 " maximum number of lines to look backwards for () let s:maxoff = 50 " maximum number of lines to look backwards for ()
function! GetBBPythonIndent(lnum) function GetPythonIndent(lnum)
" If this line is explicitly joined: If the previous line was also joined, " If this line is explicitly joined: If the previous line was also joined,
" line it up with that one, otherwise add two 'shiftwidth' " line it up with that one, otherwise add two 'shiftwidth'
@@ -257,7 +257,7 @@ let b:did_indent = 1
setlocal indentkeys+=0\" setlocal indentkeys+=0\"
function! BitbakeIndent(lnum) function BitbakeIndent(lnum)
if !has('syntax_items') if !has('syntax_items')
return -1 return -1
endif endif
@@ -315,7 +315,7 @@ function! BitbakeIndent(lnum)
endif endif
if index(["bbPyDefRegion", "bbPyFuncRegion"], name) != -1 if index(["bbPyDefRegion", "bbPyFuncRegion"], name) != -1
let ret = GetBBPythonIndent(a:lnum) let ret = GetPythonIndent(a:lnum)
" Should normally always be indented by at least one shiftwidth; but allow " Should normally always be indented by at least one shiftwidth; but allow
" return of -1 (defer to autoindent) or -2 (force indent to 0) " return of -1 (defer to autoindent) or -2 (force indent to 0)
if ret == 0 if ret == 0

View File

@@ -63,14 +63,13 @@ syn region bbVarFlagFlag matchgroup=bbArrayBrackets start="\[" end="\]\s*
" Includes and requires " Includes and requires
syn keyword bbInclude inherit include require contained syn keyword bbInclude inherit include require contained
syn match bbIncludeRest ".*$" contained contains=bbString,bbVarDeref,bbVarPyValue syn match bbIncludeRest ".*$" contained contains=bbString,bbVarDeref
syn match bbIncludeLine "^\(inherit\|include\|require\)\s\+" contains=bbInclude nextgroup=bbIncludeRest syn match bbIncludeLine "^\(inherit\|include\|require\)\s\+" contains=bbInclude nextgroup=bbIncludeRest
" Add taks and similar " Add taks and similar
syn keyword bbStatement addtask deltask addhandler after before EXPORT_FUNCTIONS contained syn keyword bbStatement addtask deltask addhandler after before EXPORT_FUNCTIONS contained
syn match bbStatementRest /[^\\]*$/ skipwhite contained contains=bbStatement,bbVarDeref,bbVarPyValue syn match bbStatementRest ".*$" skipwhite contained contains=bbStatement
syn region bbStatementRestCont start=/.*\\$/ end=/^[^\\]*$/ contained contains=bbStatement,bbVarDeref,bbVarPyValue,bbContinue keepend syn match bbStatementLine "^\(addtask\|deltask\|addhandler\|after\|before\|EXPORT_FUNCTIONS\)\s\+" contains=bbStatement nextgroup=bbStatementRest
syn match bbStatementLine "^\(addtask\|deltask\|addhandler\|after\|before\|EXPORT_FUNCTIONS\)\s\+" contains=bbStatement nextgroup=bbStatementRest,bbStatementRestCont
" OE Important Functions " OE Important Functions
syn keyword bbOEFunctions do_fetch do_unpack do_patch do_configure do_compile do_stage do_install do_package contained syn keyword bbOEFunctions do_fetch do_unpack do_patch do_configure do_compile do_stage do_install do_package contained
@@ -123,7 +122,6 @@ hi def link bbPyFlag Type
hi def link bbPyDef Statement hi def link bbPyDef Statement
hi def link bbStatement Statement hi def link bbStatement Statement
hi def link bbStatementRest Identifier hi def link bbStatementRest Identifier
hi def link bbStatementRestCont Identifier
hi def link bbOEFunctions Special hi def link bbOEFunctions Special
hi def link bbVarPyValue PreProc hi def link bbVarPyValue PreProc
hi def link bbOverrideOperator Operator hi def link bbOverrideOperator Operator

View File

@@ -47,8 +47,8 @@ To install all required packages run:
To build the documentation locally, run: To build the documentation locally, run:
$ cd doc $ cd documentation
$ make html $ make -f Makefile.sphinx html
The resulting HTML index page will be _build/html/index.html, and you The resulting HTML index page will be _build/html/index.html, and you
can browse your own copy of the locally generated documentation with can browse your own copy of the locally generated documentation with

View File

@@ -1,9 +0,0 @@
<footer>
<hr/>
<div role="contentinfo">
<p>&copy; Copyright {{ copyright }}
<br>Last updated on {{ last_updated }} from the <a href="https://git.openembedded.org/bitbake/">bitbake</a> git repository.
</p>
</div>
</footer>

View File

@@ -552,8 +552,8 @@ through dependency chains are more complex and are generally
accomplished with a Python function. The code in accomplished with a Python function. The code in
``meta/lib/oe/sstatesig.py`` shows two examples of this and also ``meta/lib/oe/sstatesig.py`` shows two examples of this and also
illustrates how you can insert your own policy into the system if so illustrates how you can insert your own policy into the system if so
desired. This file defines the basic signature generator desired. This file defines the two basic signature generators
OpenEmbedded-Core uses: "OEBasicHash". By default, there OpenEmbedded-Core uses: "OEBasic" and "OEBasicHash". By default, there
is a dummy "noop" signature handler enabled in BitBake. This means that is a dummy "noop" signature handler enabled in BitBake. This means that
behavior is unchanged from previous versions. ``OE-Core`` uses the behavior is unchanged from previous versions. ``OE-Core`` uses the
"OEBasicHash" signature handler by default through this setting in the "OEBasicHash" signature handler by default through this setting in the
@@ -561,13 +561,14 @@ behavior is unchanged from previous versions. ``OE-Core`` uses the
BB_SIGNATURE_HANDLER ?= "OEBasicHash" BB_SIGNATURE_HANDLER ?= "OEBasicHash"
The main feature of the "OEBasicHash" :term:`BB_SIGNATURE_HANDLER` is that The "OEBasicHash" :term:`BB_SIGNATURE_HANDLER` is the same as the "OEBasic"
it adds the task hash to the stamp files. Thanks to this, any metadata version but adds the task hash to the stamp files. This results in any
change will change the task hash, automatically causing the task to be run metadata change that changes the task hash, automatically causing the
again. This removes the need to bump :term:`PR` values, and changes to task to be run again. This removes the need to bump
metadata automatically ripple across the build. :term:`PR` values, and changes to metadata automatically
ripple across the build.
It is also worth noting that the end result of signature It is also worth noting that the end result of these signature
generators is to make some dependency and hash information available to generators is to make some dependency and hash information available to
the build. This information includes: the build. This information includes:
@@ -586,11 +587,10 @@ or possibly those defined in the metadata/signature handler itself. The
simplest parameter to pass is "none", which causes a set of signature simplest parameter to pass is "none", which causes a set of signature
information to be written out into ``STAMPS_DIR`` corresponding to the information to be written out into ``STAMPS_DIR`` corresponding to the
targets specified. The other currently available parameter is targets specified. The other currently available parameter is
"printdiff", which causes BitBake to try to establish the most recent "printdiff", which causes BitBake to try to establish the closest
signature match it can (e.g. in the sstate cache) and then run signature match it can (e.g. in the sstate cache) and then run
compare the matched signatures to determine the stamps and delta ``bitbake-diffsigs`` over the matches to determine the stamps and delta
where these two stamp trees diverge. This can be used to determine why where these two stamp trees diverge.
tasks need to be re-run in situations where that is not expected.
.. note:: .. note::
@@ -657,7 +657,7 @@ builds are when execute, bitbake also supports user defined
configuration of the `Python configuration of the `Python
logging <https://docs.python.org/3/library/logging.html>`__ facilities logging <https://docs.python.org/3/library/logging.html>`__ facilities
through the :term:`BB_LOGCONFIG` variable. This through the :term:`BB_LOGCONFIG` variable. This
variable defines a JSON or YAML `logging variable defines a json or yaml `logging
configuration <https://docs.python.org/3/library/logging.config.html>`__ configuration <https://docs.python.org/3/library/logging.config.html>`__
that will be intelligently merged into the default configuration. The that will be intelligently merged into the default configuration. The
logging configuration is merged using the following rules: logging configuration is merged using the following rules:
@@ -691,9 +691,9 @@ logging configuration is merged using the following rules:
adds a filter called ``BitBake.defaultFilter``, both filters will be adds a filter called ``BitBake.defaultFilter``, both filters will be
applied to the logger applied to the logger
As a first example, you can create a ``hashequiv.json`` user logging As an example, consider the following user logging configuration file
configuration file to log all Hash Equivalence related messages of ``VERBOSE`` which logs all Hash Equivalence related messages of VERBOSE or higher to
or higher priority to a file called ``hashequiv.log``:: a file called ``hashequiv.log`` ::
{ {
"version": 1, "version": 1,
@@ -722,40 +722,3 @@ or higher priority to a file called ``hashequiv.log``::
} }
} }
} }
Then set the :term:`BB_LOGCONFIG` variable in ``conf/local.conf``::
BB_LOGCONFIG = "hashequiv.json"
Another example is this ``warn.json`` file to log all ``WARNING`` and
higher priority messages to a ``warn.log`` file::
{
"version": 1,
"formatters": {
"warnlogFormatter": {
"()": "bb.msg.BBLogFormatter",
"format": "%(levelname)s: %(message)s"
}
},
"handlers": {
"warnlog": {
"class": "logging.FileHandler",
"formatter": "warnlogFormatter",
"level": "WARNING",
"filename": "warn.log"
}
},
"loggers": {
"BitBake": {
"handlers": ["warnlog"]
}
},
"@disable_existing_loggers": false
}
Note that BitBake's helper classes for structured logging are implemented in
``lib/bb/msg.py``.

View File

@@ -424,8 +424,8 @@ This fetcher supports the following parameters:
- *"nobranch":* Tells the fetcher to not check the SHA validation for - *"nobranch":* Tells the fetcher to not check the SHA validation for
the branch when set to "1". The default is "0". Set this option for the branch when set to "1". The default is "0". Set this option for
the recipe that refers to the commit that is valid for any namespace the recipe that refers to the commit that is valid for a tag instead
(branch, tag, ...) instead of the branch. of the branch.
- *"bareclone":* Tells the fetcher to clone a bare clone into the - *"bareclone":* Tells the fetcher to clone a bare clone into the
destination directory without checking out a working tree. Only the destination directory without checking out a working tree. Only the
@@ -476,14 +476,6 @@ Here are some example URLs::
easy to share metadata without removing passwords. SSH keys, ``~/.netrc`` easy to share metadata without removing passwords. SSH keys, ``~/.netrc``
and ``~/.ssh/config`` files can be used as alternatives. and ``~/.ssh/config`` files can be used as alternatives.
Using tags with the git fetcher may cause surprising behaviour. Bitbake needs to
resolve the tag to a specific revision and to do that, it has to connect to and use
the upstream repository. This is because the revision the tags point at can change and
we've seen cases of this happening in well known public repositories. This can mean
many more network connections than expected and recipes may be reparsed at every build.
Source mirrors will also be bypassed as the upstream repository is the only source
of truth to resolve the revision accurately. For these reasons, whilst the fetcher
can support tags, we recommend being specific about revisions in recipes.
.. _gitsm-fetcher: .. _gitsm-fetcher:
@@ -696,43 +688,6 @@ Here is an example URL::
It can also be used when setting mirrors definitions using the :term:`PREMIRRORS` variable. It can also be used when setting mirrors definitions using the :term:`PREMIRRORS` variable.
.. _gcp-fetcher:
GCP Fetcher (``gs://``)
--------------------------
This submodule fetches data from a
`Google Cloud Storage Bucket <https://cloud.google.com/storage/docs/buckets>`__.
It uses the `Google Cloud Storage Python Client <https://cloud.google.com/python/docs/reference/storage/latest>`__
to check the status of objects in the bucket and download them.
The use of the Python client makes it substantially faster than using command
line tools such as gsutil.
The fetcher requires the Google Cloud Storage Python Client to be installed, along
with the gsutil tool.
The fetcher requires that the machine has valid credentials for accessing the
chosen bucket. Instructions for authentication can be found in the
`Google Cloud documentation <https://cloud.google.com/docs/authentication/provide-credentials-adc#local-dev>`__.
If it used from the OpenEmbedded build system, the fetcher can be used for
fetching sstate artifacts from a GCS bucket by specifying the
``SSTATE_MIRRORS`` variable as shown below::
SSTATE_MIRRORS ?= "\
file://.* gs://<bucket name>/PATH \
"
The fetcher can also be used in recipes::
SRC_URI = "gs://<bucket name>/<foo_container>/<bar_file>"
However, the checksum of the file should be also be provided::
SRC_URI[sha256sum] = "<sha256 string>"
.. _crate-fetcher:
Crate Fetcher (``crate://``) Crate Fetcher (``crate://``)
---------------------------- ----------------------------
@@ -749,80 +704,6 @@ Here is an example URL::
SRC_URI = "crate://crates.io/glob/0.2.11" SRC_URI = "crate://crates.io/glob/0.2.11"
.. _npm-fetcher:
NPM Fetcher (``npm://``)
------------------------
This submodule fetches source code from an
`NPM <https://en.wikipedia.org/wiki/Npm_(software)>`__
Javascript package registry.
The format for the :term:`SRC_URI` setting must be::
SRC_URI = "npm://some.registry.url;ParameterA=xxx;ParameterB=xxx;..."
This fetcher supports the following parameters:
- *"package":* The NPM package name. This is a mandatory parameter.
- *"version":* The NPM package version. This is a mandatory parameter.
- *"downloadfilename":* Specifies the filename used when storing the downloaded file.
- *"destsuffix":* Specifies the directory to use to unpack the package (default: ``npm``).
Note that NPM fetcher only fetches the package source itself. The dependencies
can be fetched through the `npmsw-fetcher`_.
Here is an example URL with both fetchers::
SRC_URI = " \
npm://registry.npmjs.org/;package=cute-files;version=${PV} \
npmsw://${THISDIR}/${BPN}/npm-shrinkwrap.json \
"
See :yocto_docs:`Creating Node Package Manager (NPM) Packages
</dev-manual/packages.html#creating-node-package-manager-npm-packages>`
in the Yocto Project manual for details about using
:yocto_docs:`devtool <https://docs.yoctoproject.org/ref-manual/devtool-reference.html>`
to automatically create a recipe from an NPM URL.
.. _npmsw-fetcher:
NPM shrinkwrap Fetcher (``npmsw://``)
-------------------------------------
This submodule fetches source code from an
`NPM shrinkwrap <https://docs.npmjs.com/cli/v8/commands/npm-shrinkwrap>`__
description file, which lists the dependencies
of an NPM package while locking their versions.
The format for the :term:`SRC_URI` setting must be::
SRC_URI = "npmsw://some.registry.url;ParameterA=xxx;ParameterB=xxx;..."
This fetcher supports the following parameters:
- *"dev":* Set this parameter to ``1`` to install "devDependencies".
- *"destsuffix":* Specifies the directory to use to unpack the dependencies
(``${S}`` by default).
Note that the shrinkwrap file can also be provided by the recipe for
the package which has such dependencies, for example::
SRC_URI = " \
npm://registry.npmjs.org/;package=cute-files;version=${PV} \
npmsw://${THISDIR}/${BPN}/npm-shrinkwrap.json \
"
Such a file can automatically be generated using
:yocto_docs:`devtool <https://docs.yoctoproject.org/ref-manual/devtool-reference.html>`
as described in the :yocto_docs:`Creating Node Package Manager (NPM) Packages
</dev-manual/packages.html#creating-node-package-manager-npm-packages>`
section of the Yocto Project.
Other Fetchers Other Fetchers
-------------- --------------
@@ -832,9 +713,9 @@ Fetch submodules also exist for the following:
- Mercurial (``hg://``) - Mercurial (``hg://``)
- OSC (``osc://``) - npm (``npm://``)
- S3 (``s3://``) - OSC (``osc://``)
- Secure FTP (``sftp://``) - Secure FTP (``sftp://``)

View File

@@ -18,32 +18,28 @@ it.
Obtaining BitBake Obtaining BitBake
================= =================
See the :ref:`bitbake-user-manual/bitbake-user-manual-intro:obtaining bitbake` section for See the :ref:`bitbake-user-manual/bitbake-user-manual-hello:obtaining bitbake` section for
information on how to obtain BitBake. Once you have the source code on information on how to obtain BitBake. Once you have the source code on
your machine, the BitBake directory appears as follows:: your machine, the BitBake directory appears as follows::
$ ls -al $ ls -al
total 108 total 100
drwxr-xr-x 9 fawkh 10000 4096 feb 24 12:10 . drwxrwxr-x. 9 wmat wmat 4096 Jan 31 13:44 .
drwx------ 36 fawkh 10000 4096 mar 2 17:00 .. drwxrwxr-x. 3 wmat wmat 4096 Feb 4 10:45 ..
-rw-r--r-- 1 fawkh 10000 365 feb 24 12:10 AUTHORS -rw-rw-r--. 1 wmat wmat 365 Nov 26 04:55 AUTHORS
drwxr-xr-x 2 fawkh 10000 4096 feb 24 12:10 bin drwxrwxr-x. 2 wmat wmat 4096 Nov 26 04:55 bin
-rw-r--r-- 1 fawkh 10000 16501 feb 24 12:10 ChangeLog drwxrwxr-x. 4 wmat wmat 4096 Jan 31 13:44 build
drwxr-xr-x 2 fawkh 10000 4096 feb 24 12:10 classes -rw-rw-r--. 1 wmat wmat 16501 Nov 26 04:55 ChangeLog
drwxr-xr-x 2 fawkh 10000 4096 feb 24 12:10 conf drwxrwxr-x. 2 wmat wmat 4096 Nov 26 04:55 classes
drwxr-xr-x 5 fawkh 10000 4096 feb 24 12:10 contrib drwxrwxr-x. 2 wmat wmat 4096 Nov 26 04:55 conf
drwxr-xr-x 6 fawkh 10000 4096 feb 24 12:10 doc drwxrwxr-x. 3 wmat wmat 4096 Nov 26 04:55 contrib
drwxr-xr-x 8 fawkh 10000 4096 mar 2 16:26 .git -rw-rw-r--. 1 wmat wmat 17987 Nov 26 04:55 COPYING
-rw-r--r-- 1 fawkh 10000 31 feb 24 12:10 .gitattributes drwxrwxr-x. 3 wmat wmat 4096 Nov 26 04:55 doc
-rw-r--r-- 1 fawkh 10000 392 feb 24 12:10 .gitignore -rw-rw-r--. 1 wmat wmat 69 Nov 26 04:55 .gitignore
drwxr-xr-x 13 fawkh 10000 4096 feb 24 12:11 lib -rw-rw-r--. 1 wmat wmat 849 Nov 26 04:55 HEADER
-rw-r--r-- 1 fawkh 10000 1224 feb 24 12:10 LICENSE drwxrwxr-x. 5 wmat wmat 4096 Jan 31 13:44 lib
-rw-r--r-- 1 fawkh 10000 15394 feb 24 12:10 LICENSE.GPL-2.0-only -rw-rw-r--. 1 wmat wmat 195 Nov 26 04:55 MANIFEST.in
-rw-r--r-- 1 fawkh 10000 1286 feb 24 12:10 LICENSE.MIT -rw-rw-r--. 1 wmat wmat 2887 Nov 26 04:55 TODO
-rw-r--r-- 1 fawkh 10000 229 feb 24 12:10 MANIFEST.in
-rw-r--r-- 1 fawkh 10000 2413 feb 24 12:10 README
-rw-r--r-- 1 fawkh 10000 43 feb 24 12:10 toaster-requirements.txt
-rw-r--r-- 1 fawkh 10000 2887 feb 24 12:10 TODO
At this point, you should have BitBake cloned to a directory that At this point, you should have BitBake cloned to a directory that
matches the previous listing except for dates and user names. matches the previous listing except for dates and user names.
@@ -56,7 +52,7 @@ directory to where your local BitBake files are and run the following
command:: command::
$ ./bin/bitbake --version $ ./bin/bitbake --version
BitBake Build Tool Core version 2.3.1 BitBake Build Tool Core version 1.23.0, bitbake version 1.23.0
The console output tells you what version The console output tells you what version
you are running. you are running.
@@ -134,8 +130,23 @@ Following is the complete "Hello World" example.
directory. Run the ``bitbake`` command and see what it does:: directory. Run the ``bitbake`` command and see what it does::
$ bitbake $ bitbake
ERROR: The BBPATH variable is not set and bitbake did not find a conf/bblayers.conf file in the expected location. The BBPATH variable is not set and bitbake did not
find a conf/bblayers.conf file in the expected location.
Maybe you accidentally invoked bitbake from the wrong directory? Maybe you accidentally invoked bitbake from the wrong directory?
DEBUG: Removed the following variables from the environment:
GNOME_DESKTOP_SESSION_ID, XDG_CURRENT_DESKTOP,
GNOME_KEYRING_CONTROL, DISPLAY, SSH_AGENT_PID, LANG, no_proxy,
XDG_SESSION_PATH, XAUTHORITY, SESSION_MANAGER, SHLVL,
MANDATORY_PATH, COMPIZ_CONFIG_PROFILE, WINDOWID, EDITOR,
GPG_AGENT_INFO, SSH_AUTH_SOCK, GDMSESSION, GNOME_KEYRING_PID,
XDG_SEAT_PATH, XDG_CONFIG_DIRS, LESSOPEN, DBUS_SESSION_BUS_ADDRESS,
_, XDG_SESSION_COOKIE, DESKTOP_SESSION, LESSCLOSE, DEFAULTS_PATH,
UBUNTU_MENUPROXY, OLDPWD, XDG_DATA_DIRS, COLORTERM, LS_COLORS
The majority of this output is specific to environment variables that
are not directly relevant to BitBake. However, the very first
message regarding the :term:`BBPATH` variable and the
``conf/bblayers.conf`` file is relevant.
When you run BitBake, it begins looking for metadata files. The When you run BitBake, it begins looking for metadata files. The
:term:`BBPATH` variable is what tells BitBake where :term:`BBPATH` variable is what tells BitBake where
@@ -168,14 +179,20 @@ Following is the complete "Hello World" example.
``bitbake`` command again:: ``bitbake`` command again::
$ bitbake $ bitbake
ERROR: Unable to parse /home/scott-lenovo/bitbake/lib/bb/parse/__init__.py ERROR: Traceback (most recent call last):
Traceback (most recent call last): File "/home/scott-lenovo/bitbake/lib/bb/cookerdata.py", line 163, in wrapped
File "/home/scott-lenovo/bitbake/lib/bb/parse/__init__.py", line 127, in resolve_file(fn='conf/bitbake.conf', d=<bb.data_smart.DataSmart object at 0x7f22919a3df0>): return func(fn, *args)
if not newfn: File "/home/scott-lenovo/bitbake/lib/bb/cookerdata.py", line 173, in parse_config_file
> raise IOError(errno.ENOENT, "file %s not found in %s" % (fn, bbpath)) return bb.parse.handle(fn, data, include)
fn = newfn File "/home/scott-lenovo/bitbake/lib/bb/parse/__init__.py", line 99, in handle
FileNotFoundError: [Errno 2] file conf/bitbake.conf not found in <projectdirectory> return h['handle'](fn, data, include)
File "/home/scott-lenovo/bitbake/lib/bb/parse/parse_py/ConfHandler.py", line 120, in handle
abs_fn = resolve_file(fn, data)
File "/home/scott-lenovo/bitbake/lib/bb/parse/__init__.py", line 117, in resolve_file
raise IOError("file %s not found in %s" % (fn, bbpath))
IOError: file conf/bitbake.conf not found in /home/scott-lenovo/hello
ERROR: Unable to parse conf/bitbake.conf: file conf/bitbake.conf not found in /home/scott-lenovo/hello
This sample output shows that BitBake could not find the This sample output shows that BitBake could not find the
``conf/bitbake.conf`` file in the project directory. This file is ``conf/bitbake.conf`` file in the project directory. This file is
@@ -209,12 +226,12 @@ Following is the complete "Hello World" example.
.. note:: .. note::
Without a value for :term:`PN`, the variables :term:`STAMP`, :term:`T`, and :term:`B`, prevent more Without a value for PN , the variables STAMP , T , and B , prevent more
than one recipe from working. You can fix this by either setting :term:`PN` to than one recipe from working. You can fix this by either setting PN to
have a value similar to what OpenEmbedded and BitBake use in the default have a value similar to what OpenEmbedded and BitBake use in the default
``bitbake.conf`` file (see previous example). Or, by manually updating each bitbake.conf file (see previous example). Or, by manually updating each
recipe to set :term:`PN`. You will also need to include :term:`PN` as part of the :term:`STAMP`, recipe to set PN . You will also need to include PN as part of the STAMP
:term:`T`, and :term:`B` variable definitions in the ``local.conf`` file. , T , and B variable definitions in the local.conf file.
The ``TMPDIR`` variable establishes a directory that BitBake uses The ``TMPDIR`` variable establishes a directory that BitBake uses
for build output and intermediate files other than the cached for build output and intermediate files other than the cached
@@ -237,14 +254,18 @@ Following is the complete "Hello World" example.
exists, you can run the ``bitbake`` command again:: exists, you can run the ``bitbake`` command again::
$ bitbake $ bitbake
ERROR: Unable to parse /home/scott-lenovo/bitbake/lib/bb/parse/parse_py/BBHandler.py ERROR: Traceback (most recent call last):
Traceback (most recent call last): File "/home/scott-lenovo/bitbake/lib/bb/cookerdata.py", line 163, in wrapped
File "/home/scott-lenovo/bitbake/lib/bb/parse/parse_py/BBHandler.py", line 67, in inherit(files=['base'], fn='configuration INHERITs', lineno=0, d=<bb.data_smart.DataSmart object at 0x7fab6815edf0>): return func(fn, *args)
if not os.path.exists(file): File "/home/scott-lenovo/bitbake/lib/bb/cookerdata.py", line 177, in _inherit
> raise ParseError("Could not inherit file %s" % (file), fn, lineno) bb.parse.BBHandler.inherit(bbclass, "configuration INHERITs", 0, data)
File "/home/scott-lenovo/bitbake/lib/bb/parse/parse_py/BBHandler.py", line 92, in inherit
bb.parse.ParseError: ParseError in configuration INHERITs: Could not inherit file classes/base.bbclass include(fn, file, lineno, d, "inherit")
File "/home/scott-lenovo/bitbake/lib/bb/parse/parse_py/ConfHandler.py", line 100, in include
raise ParseError("Could not %(error_out)s file %(fn)s" % vars(), oldfn, lineno)
ParseError: ParseError in configuration INHERITs: Could not inherit file classes/base.bbclass
ERROR: Unable to parse base: ParseError in configuration INHERITs: Could not inherit file classes/base.bbclass
In the sample output, In the sample output,
BitBake could not find the ``classes/base.bbclass`` file. You need BitBake could not find the ``classes/base.bbclass`` file. You need
@@ -263,10 +284,7 @@ Following is the complete "Hello World" example.
$ mkdir classes $ mkdir classes
Move to the ``classes`` directory and then create the Move to the ``classes`` directory and then create the
``base.bbclass`` file by inserting this single line:: ``base.bbclass`` file by inserting this single line: addtask build
addtask build
The minimal task that BitBake runs is the ``do_build`` task. This is The minimal task that BitBake runs is the ``do_build`` task. This is
all the example needs in order to build the project. Of course, the all the example needs in order to build the project. Of course, the
``base.bbclass`` can have much more depending on which build ``base.bbclass`` can have much more depending on which build
@@ -310,19 +328,10 @@ Following is the complete "Hello World" example.
BBFILES += "${LAYERDIR}/*.bb" BBFILES += "${LAYERDIR}/*.bb"
BBFILE_COLLECTIONS += "mylayer" BBFILE_COLLECTIONS += "mylayer"
BBFILE_PATTERN_mylayer := "^${LAYERDIR_RE}/" BBFILE_PATTERN_mylayer := "^${LAYERDIR_RE}/"
LAYERSERIES_CORENAMES = "hello_world_example"
LAYERSERIES_COMPAT_mylayer = "hello_world_example"
For information on these variables, click on :term:`BBFILES`, For information on these variables, click on :term:`BBFILES`,
:term:`LAYERDIR`, :term:`BBFILE_COLLECTIONS`, :term:`BBFILE_PATTERN_mylayer <BBFILE_PATTERN>` :term:`LAYERDIR`, :term:`BBFILE_COLLECTIONS` or :term:`BBFILE_PATTERN_mylayer <BBFILE_PATTERN>`
or :term:`LAYERSERIES_COMPAT` to go to the definitions in the glossary. to go to the definitions in the glossary.
.. note::
We are setting both ``LAYERSERIES_CORENAMES`` and :term:`LAYERSERIES_COMPAT` in this particular case, because we
are using bitbake without OpenEmbedded.
You should usually just use :term:`LAYERSERIES_COMPAT` to specify the OE-Core versions for which your layer
is compatible, and add the meta-openembedded layer to your project.
You need to create the recipe file next. Inside your layer at the You need to create the recipe file next. Inside your layer at the
top-level, use an editor and create a recipe file named top-level, use an editor and create a recipe file named
@@ -380,14 +389,12 @@ Following is the complete "Hello World" example.
target:: target::
$ bitbake printhello $ bitbake printhello
Loading cache: 100% |
Loaded 0 entries from dependency cache.
Parsing recipes: 100% |##################################################################################| Parsing recipes: 100% |##################################################################################|
Time: 00:00:00
Parsing of 1 .bb files complete (0 cached, 1 parsed). 1 targets, 0 skipped, 0 masked, 0 errors. Parsing of 1 .bb files complete (0 cached, 1 parsed). 1 targets, 0 skipped, 0 masked, 0 errors.
NOTE: Resolving any missing task queue dependencies NOTE: Resolving any missing task queue dependencies
Initialising tasks: 100% |###############################################################################| NOTE: Preparing RunQueue
NOTE: No setscene tasks NOTE: Executing RunQueue Tasks
NOTE: Executing Tasks
******************** ********************
* * * *
* Hello, World! * * Hello, World! *

View File

@@ -195,45 +195,22 @@ value. However, if ``A`` is not set, the variable is set to "aval".
Setting a weak default value (??=) Setting a weak default value (??=)
---------------------------------- ----------------------------------
The weak default value of a variable is the value which that variable It is possible to use a "weaker" assignment than in the previous section
will expand to if no value has been assigned to it via any of the other by using the "??=" operator. This assignment behaves identical to "?="
assignment operators. The "??=" operator takes effect immediately, replacing except that the assignment is made at the end of the parsing process
any previously defined weak default value. Here is an example:: rather than immediately. Consequently, when multiple "??=" assignments
exist, the last one is used. Also, any "=" or "?=" assignment will
override the value set with "??=". Here is an example::
W ??= "x" A ??= "somevalue"
A := "${W}" # Immediate variable expansion A ??= "someothervalue"
W ??= "y"
B := "${W}" # Immediate variable expansion
W ??= "z"
C = "${W}"
W ?= "i"
After parsing we will have:: If ``A`` is set before the above statements are
parsed, the variable retains its value. If ``A`` is not set, the
variable is set to "someothervalue".
A = "x" Again, this assignment is a "lazy" or "weak" assignment because it does
B = "y" not occur until the end of the parsing process.
C = "i"
W = "i"
Appending and prepending non-override style will not substitute the weak
default value, which means that after parsing::
W ??= "x"
W += "y"
we will have::
W = " y"
On the other hand, override-style appends/prepends/removes are applied after
any active weak default value has been substituted::
W ??= "x"
W:append = "y"
After parsing we will have::
W = "xy"
Immediate variable expansion (:=) Immediate variable expansion (:=)
--------------------------------- ---------------------------------
@@ -319,10 +296,6 @@ The variable ``D`` becomes "dvaladditional data".
You must control all spacing when you use the override syntax. You must control all spacing when you use the override syntax.
.. note::
The overrides are applied in this order, ":append", ":prepend", ":remove".
It is also possible to append and prepend to shell functions and It is also possible to append and prepend to shell functions and
BitBake-style Python functions. See the ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:shell functions`" and ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:bitbake-style python functions`" BitBake-style Python functions. See the ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:shell functions`" and ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:bitbake-style python functions`"
sections for examples. sections for examples.
@@ -334,8 +307,7 @@ Removal (Override Style Syntax)
You can remove values from lists using the removal override style You can remove values from lists using the removal override style
syntax. Specifying a value for removal causes all occurrences of that syntax. Specifying a value for removal causes all occurrences of that
value to be removed from the variable. Unlike ":append" and ":prepend", value to be removed from the variable.
there is no need to add a leading or trailing space to the value.
When you use this syntax, BitBake expects one or more strings. When you use this syntax, BitBake expects one or more strings.
Surrounding spaces and spacing are preserved. Here is an example:: Surrounding spaces and spacing are preserved. Here is an example::
@@ -356,28 +328,6 @@ The variable ``FOO`` becomes
Like ":append" and ":prepend", ":remove" is applied at variable Like ":append" and ":prepend", ":remove" is applied at variable
expansion time. expansion time.
.. note::
The overrides are applied in this order, ":append", ":prepend", ":remove".
This implies it is not possible to re-append previously removed strings.
However, one can undo a ":remove" by using an intermediate variable whose
content is passed to the ":remove" so that modifying the intermediate
variable equals to keeping the string in::
FOOREMOVE = "123 456 789"
FOO:remove = "${FOOREMOVE}"
...
FOOREMOVE = "123 789"
This expands to ``FOO:remove = "123 789"``.
.. note::
Override application order may not match variable parse history, i.e.
the output of ``bitbake -e`` may contain ":remove" before ":append",
but the result will be removed string, because ":remove" is handled
last.
Override Style Operation Advantages Override Style Operation Advantages
----------------------------------- -----------------------------------
@@ -448,12 +398,6 @@ documentation to a BitBake variable as follows::
CACHE[doc] = "The directory holding the cache of the metadata." CACHE[doc] = "The directory holding the cache of the metadata."
.. note::
Variable flag names starting with an underscore (``_``) character
are allowed but are ignored by ``d.getVarFlags("VAR")``
in Python code. Such flag names are used internally by BitBake.
Inline Python Variable Expansion Inline Python Variable Expansion
-------------------------------- --------------------------------
@@ -1496,35 +1440,12 @@ functionality of the task:
directory listed is used as the current working directory for the directory listed is used as the current working directory for the
task. task.
- ``[file-checksums]``: Controls the file dependencies for a task. The
baseline file list is the set of files associated with
:term:`SRC_URI`. May be used to set additional dependencies on
files not associated with :term:`SRC_URI`.
The value set to the list is a file-boolean pair where the first
value is the file name and the second is whether or not it
physically exists on the filesystem. ::
do_configure[file-checksums] += "${MY_DIRPATH}/my-file.txt:True"
It is important to record any paths which the task looked at and
which didn't exist. This means that if these do exist at a later
time, the task can be rerun with the new additional files. The
"exists" True or False value after the path allows this to be
handled.
- ``[lockfiles]``: Specifies one or more lockfiles to lock while the - ``[lockfiles]``: Specifies one or more lockfiles to lock while the
task executes. Only one task may hold a lockfile, and any task that task executes. Only one task may hold a lockfile, and any task that
attempts to lock an already locked file will block until the lock is attempts to lock an already locked file will block until the lock is
released. You can use this variable flag to accomplish mutual released. You can use this variable flag to accomplish mutual
exclusion. exclusion.
- ``[network]``: When set to "1", allows a task to access the network. By
default, only the ``do_fetch`` task is granted network access. Recipes
shouldn't access the network outside of ``do_fetch`` as it usually
undermines fetcher source mirroring, image and licence manifests, software
auditing and supply chain security.
- ``[noexec]``: When set to "1", marks the task as being empty, with - ``[noexec]``: When set to "1", marks the task as being empty, with
no execution required. You can use the ``[noexec]`` flag to set up no execution required. You can use the ``[noexec]`` flag to set up
tasks as dependency placeholders, or to disable tasks defined tasks as dependency placeholders, or to disable tasks defined
@@ -1978,33 +1899,6 @@ looking at the source code of the ``bb`` module, which is in
the commonly used functions ``bb.utils.contains()`` and the commonly used functions ``bb.utils.contains()`` and
``bb.utils.mkdirhier()``, which come with docstrings. ``bb.utils.mkdirhier()``, which come with docstrings.
Extending Python Library Code
-----------------------------
If you wish to add your own Python library code (e.g. to provide
functions/classes you can use from Python functions in the metadata)
you can do so from any layer using the ``addpylib`` directive.
This directive is typically added to your layer configuration (
``conf/layer.conf``) although it will be handled in any ``.conf`` file.
Usage is of the form::
addpylib <directory> <namespace>
Where <directory> specifies the directory to add to the library path.
The specified <namespace> is imported automatically, and if the imported
module specifies an attribute named ``BBIMPORTS``, that list of
sub-modules is iterated and imported too.
Testing and Debugging BitBake Python code
-----------------------------------------
The OpenEmbedded build system implements a convenient ``pydevshell`` target which
you can use to access the BitBake datastore and experiment with your own Python
code. See :yocto_docs:`Using a Python Development Shell
</dev-manual/python-development-shell.html#using-a-python-development-shell>` in the Yocto
Project manual for details.
Task Checksums and Setscene Task Checksums and Setscene
=========================== ===========================

View File

@@ -1,91 +0,0 @@
.. SPDX-License-Identifier: CC-BY-2.5
================
Variable Context
================
|
Variables might only have an impact or can be used in certain contexts. Some
should only be used in global files like ``.conf``, while others are intended only
for local files like ``.bb``. This chapter aims to describe some important variable
contexts.
.. _ref-varcontext-configuration:
BitBake's own configuration
===========================
Variables starting with ``BB_`` usually configure the behaviour of BitBake itself.
For example, one could configure:
- System resources, like disk space to be used (:term:`BB_DISKMON_DIRS`),
or the number of tasks to be run in parallel by BitBake (:term:`BB_NUMBER_THREADS`).
- How the fetchers shall behave, e.g., :term:`BB_FETCH_PREMIRRORONLY` is used
by BitBake to determine if BitBake's fetcher shall search only
:term:`PREMIRRORS` for files.
Those variables are usually configured globally.
BitBake configuration
=====================
There are variables:
- Like :term:`B` or :term:`T`, that are used to specify directories used by
BitBake during the build of a particular recipe. Those variables are
specified in ``bitbake.conf``. Some, like :term:`B`, are quite often
overwritten in recipes.
- Starting with ``FAKEROOT``, to configure how the ``fakeroot`` command is
handled. Those are usually set by ``bitbake.conf`` and might get adapted in a
``bbclass``.
- Detailing where BitBake will store and fetch information from, for
data reuse between build runs like :term:`CACHE`, :term:`DL_DIR` or
:term:`PERSISTENT_DIR`. Those are usually global.
Layers and files
================
Variables starting with ``LAYER`` configure how BitBake handles layers.
Additionally, variables starting with ``BB`` configure how layers and files are
handled. For example:
- :term:`LAYERDEPENDS` is used to configure on which layers a given layer
depends.
- The configured layers are contained in :term:`BBLAYERS` and files in
:term:`BBFILES`.
Those variables are often used in the files ``layer.conf`` and ``bblayers.conf``.
Recipes and packages
====================
Variables handling recipes and packages can be split into:
- :term:`PN`, :term:`PV` or :term:`PF` for example, contain information about
the name or revision of a recipe or package. Usually, the default set in
``bitbake.conf`` is used, but those are from time to time overwritten in
recipes.
- :term:`SUMMARY`, :term:`DESCRIPTION`, :term:`LICENSE` or :term:`HOMEPAGE`
contain the expected information and should be set specifically for every
recipe.
- In recipes, variables are also used to control build and runtime
dependencies between recipes/packages with other recipes/packages. The
most common should be: :term:`PROVIDES`, :term:`RPROVIDES`, :term:`DEPENDS`,
and :term:`RDEPENDS`.
- There are further variables starting with ``SRC`` that specify the sources in
a recipe like :term:`SRC_URI` or :term:`SRCDATE`. Those are also usually set
in recipes.
- Which version or provider of a recipe should be given preference when
multiple recipes would provide the same item, is controlled by variables
starting with ``PREFERRED_``. Those are normally set in the configuration
files of a ``MACHINE`` or ``DISTRO``.

View File

@@ -40,7 +40,8 @@ overview of their function and contents.
Azure Storage Shared Access Signature, when using the Azure Storage Shared Access Signature, when using the
:ref:`Azure Storage fetcher <bitbake-user-manual/bitbake-user-manual-fetching:fetchers>` :ref:`Azure Storage fetcher <bitbake-user-manual/bitbake-user-manual-fetching:fetchers>`
This variable can be defined to be used by the fetcher to authenticate This variable can be defined to be used by the fetcher to authenticate
and gain access to non-public artifacts:: and gain access to non-public artifacts.
::
AZ_SAS = ""se=2021-01-01&sp=r&sv=2018-11-09&sr=c&skoid=<skoid>&sig=<signature>"" AZ_SAS = ""se=2021-01-01&sp=r&sv=2018-11-09&sr=c&skoid=<skoid>&sig=<signature>""
@@ -99,26 +100,10 @@ overview of their function and contents.
the path of the build. BitBake's output should not (and usually does the path of the build. BitBake's output should not (and usually does
not) depend on the directory in which it was built. not) depend on the directory in which it was built.
:term:`BB_CACHEDIR`
Specifies the code parser cache directory (distinct from :term:`CACHE`
and :term:`PERSISTENT_DIR` although they can be set to the same value
if desired). The default value is "${TOPDIR}/cache".
:term:`BB_CHECK_SSL_CERTS` :term:`BB_CHECK_SSL_CERTS`
Specifies if SSL certificates should be checked when fetching. The default Specifies if SSL certificates should be checked when fetching. The default
value is ``1`` and certificates are not checked if the value is set to ``0``. value is ``1`` and certificates are not checked if the value is set to ``0``.
:term:`BB_HASH_CODEPARSER_VALS`
Specifies values for variables to use when populating the codeparser cache.
This can be used selectively to set dummy values for variables to avoid
the codeparser cache growing on every parse. Variables that would typically
be included are those where the value is not significant for where the
codeparser cache is used (i.e. when calculating variable dependencies for
code fragments.) The value is space-separated without quoting values, for
example::
BB_HASH_CODEPARSER_VALS = "T=/ WORKDIR=/ DATE=1234 TIME=1234"
:term:`BB_CONSOLELOG` :term:`BB_CONSOLELOG`
Specifies the path to a log file into which BitBake's user interface Specifies the path to a log file into which BitBake's user interface
writes output during the build. writes output during the build.
@@ -359,14 +344,6 @@ overview of their function and contents.
For example usage, see :term:`BB_GIT_SHALLOW`. For example usage, see :term:`BB_GIT_SHALLOW`.
:term:`BB_GLOBAL_PYMODULES`
Specifies the list of Python modules to place in the global namespace.
It is intended that only the core layer should set this and it is meant
to be a very small list, typically just ``os`` and ``sys``.
:term:`BB_GLOBAL_PYMODULES` is expected to be set before the first
``addpylib`` directive.
See also ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:extending python library code`".
:term:`BB_HASHCHECK_FUNCTION` :term:`BB_HASHCHECK_FUNCTION`
Specifies the name of the function to call during the "setscene" part Specifies the name of the function to call during the "setscene" part
of the task's execution in order to validate the list of task hashes. of the task's execution in order to validate the list of task hashes.
@@ -424,7 +401,7 @@ overview of their function and contents.
Example usage:: Example usage::
BB_HASHSERVE_UPSTREAM = "hashserv.yoctoproject.org:8686" BB_HASHSERVE_UPSTREAM = "typhoon.yocto.io:8687"
:term:`BB_INVALIDCONF` :term:`BB_INVALIDCONF`
Used in combination with the ``ConfigParsed`` event to trigger Used in combination with the ``ConfigParsed`` event to trigger
@@ -432,15 +409,6 @@ overview of their function and contents.
``ConfigParsed`` event can set the variable to trigger the re-parse. ``ConfigParsed`` event can set the variable to trigger the re-parse.
You must be careful to avoid recursive loops with this functionality. You must be careful to avoid recursive loops with this functionality.
:term:`BB_LOADFACTOR_MAX`
Setting this to a value will cause BitBake to check the system load
average before executing new tasks. If the load average is above the
the number of CPUs multipled by this factor, no new task will be started
unless there is no task executing. A value of "1.5" has been found to
work reasonably. This is helpful for systems which don't have pressure
regulation enabled, which is more granular. Pressure values take
precedence over loadfactor.
:term:`BB_LOGCONFIG` :term:`BB_LOGCONFIG`
Specifies the name of a config file that contains the user logging Specifies the name of a config file that contains the user logging
configuration. See configuration. See
@@ -515,64 +483,13 @@ overview of their function and contents.
You must set this variable in the external environment in order You must set this variable in the external environment in order
for it to work. for it to work.
:term:`BB_PRESSURE_MAX_CPU`
Specifies a maximum CPU pressure threshold, above which BitBake's
scheduler will not start new tasks (providing there is at least
one active task). If no value is set, CPU pressure is not
monitored when starting tasks.
The pressure data is calculated based upon what Linux kernels since
version 4.20 expose under ``/proc/pressure``. The threshold represents
the difference in "total" pressure from the previous second. The
minimum value is 1.0 (extremely slow builds) and the maximum is
1000000 (a pressure value unlikely to ever be reached).
This threshold can be set in ``conf/local.conf`` as::
BB_PRESSURE_MAX_CPU = "500"
:term:`BB_PRESSURE_MAX_IO`
Specifies a maximum I/O pressure threshold, above which BitBake's
scheduler will not start new tasks (providing there is at least
one active task). If no value is set, I/O pressure is not
monitored when starting tasks.
The pressure data is calculated based upon what Linux kernels since
version 4.20 expose under ``/proc/pressure``. The threshold represents
the difference in "total" pressure from the previous second. The
minimum value is 1.0 (extremely slow builds) and the maximum is
1000000 (a pressure value unlikely to ever be reached).
At this point in time, experiments show that IO pressure tends to
be short-lived and regulating just the CPU with
:term:`BB_PRESSURE_MAX_CPU` can help to reduce it.
:term:`BB_PRESSURE_MAX_MEMORY`
Specifies a maximum memory pressure threshold, above which BitBake's
scheduler will not start new tasks (providing there is at least
one active task). If no value is set, memory pressure is not
monitored when starting tasks.
The pressure data is calculated based upon what Linux kernels since
version 4.20 expose under ``/proc/pressure``. The threshold represents
the difference in "total" pressure from the previous second. The
minimum value is 1.0 (extremely slow builds) and the maximum is
1000000 (a pressure value unlikely to ever be reached).
Memory pressure is experienced when time is spent swapping,
refaulting pages from the page cache or performing direct reclaim.
This is why memory pressure is rarely seen, but setting this variable
might be useful as a last resort to prevent OOM errors if they are
occurring during builds.
:term:`BB_RUNFMT` :term:`BB_RUNFMT`
Specifies the name of the executable script files (i.e. run files) Specifies the name of the executable script files (i.e. run files)
saved into ``${``\ :term:`T`\ ``}``. By default, the saved into ``${``\ :term:`T`\ ``}``. By default, the
:term:`BB_RUNFMT` variable is undefined and the run filenames get :term:`BB_RUNFMT` variable is undefined and the run filenames get
created using the following form:: created using the following form::
run.{func}.{pid} run.{task}.{pid}
If you want to force run files to take a specific name, you can set this If you want to force run files to take a specific name, you can set this
variable in a configuration file. variable in a configuration file.
@@ -929,9 +846,9 @@ overview of their function and contents.
section. section.
:term:`BBPATH` :term:`BBPATH`
A colon-separated list used by BitBake to locate class (``.bbclass``) Used by BitBake to locate class (``.bbclass``) and configuration
and configuration (``.conf``) files. This variable is analogous to the (``.conf``) files. This variable is analogous to the ``PATH``
``PATH`` variable. variable.
If you run BitBake from a directory outside of the build directory, If you run BitBake from a directory outside of the build directory,
you must be sure to set :term:`BBPATH` to point to the build directory. you must be sure to set :term:`BBPATH` to point to the build directory.
@@ -1023,7 +940,7 @@ overview of their function and contents.
``bblayers.conf`` configuration file. ``bblayers.conf`` configuration file.
To exclude a recipe from a world build using this variable, set the To exclude a recipe from a world build using this variable, set the
variable to "1" in the recipe. Set it to "0" to add it back to world build. variable to "1" in the recipe.
.. note:: .. note::
@@ -1081,11 +998,6 @@ overview of their function and contents.
environment variable. The value is a colon-separated list of environment variable. The value is a colon-separated list of
directories that are searched left-to-right in order. directories that are searched left-to-right in order.
:term:`FILE_LAYERNAME`
During parsing and task execution, this is set to the name of the
layer containing the recipe file. Code can use this to identify which
layer a recipe is from.
:term:`GITDIR` :term:`GITDIR`
The directory in which a local copy of a Git repository is stored The directory in which a local copy of a Git repository is stored
when it is cloned. when it is cloned.
@@ -1134,29 +1046,6 @@ overview of their function and contents.
variable is not available outside of ``layer.conf`` and references variable is not available outside of ``layer.conf`` and references
are expanded immediately when parsing of the file completes. are expanded immediately when parsing of the file completes.
:term:`LAYERSERIES_COMPAT`
Lists the versions of the OpenEmbedded-Core (OE-Core) for which
a layer is compatible. Using the :term:`LAYERSERIES_COMPAT` variable
allows the layer maintainer to indicate which combinations of the
layer and OE-Core can be expected to work. The variable gives the
system a way to detect when a layer has not been tested with new
releases of OE-Core (e.g. the layer is not maintained).
To specify the OE-Core versions for which a layer is compatible, use
this variable in your layer's ``conf/layer.conf`` configuration file.
For the list, use the Yocto Project release name (e.g. "kirkstone",
"mickledore"). To specify multiple OE-Core versions for the layer, use
a space-separated list::
LAYERSERIES_COMPAT_layer_root_name = "kirkstone mickledore"
.. note::
Setting :term:`LAYERSERIES_COMPAT` is required by the Yocto Project
Compatible version 2 standard.
The OpenEmbedded build system produces a warning if the variable
is not set for any given layer.
:term:`LAYERVERSION` :term:`LAYERVERSION`
Optionally specifies the version of a layer as a single number. You Optionally specifies the version of a layer as a single number. You
can use this variable within can use this variable within
@@ -1179,8 +1068,8 @@ overview of their function and contents.
order. order.
:term:`OVERRIDES` :term:`OVERRIDES`
A colon-separated list that BitBake uses to control what variables are BitBake uses :term:`OVERRIDES` to control what variables are overridden
overridden after BitBake parses recipes and configuration files. after BitBake parses recipes and configuration files.
Following is a simple example that uses an overrides list based on Following is a simple example that uses an overrides list based on
machine architectures: OVERRIDES = "arm:x86:mips:powerpc" You can machine architectures: OVERRIDES = "arm:x86:mips:powerpc" You can

View File

@@ -13,7 +13,6 @@ BitBake User Manual
bitbake-user-manual/bitbake-user-manual-intro bitbake-user-manual/bitbake-user-manual-intro
bitbake-user-manual/bitbake-user-manual-execution bitbake-user-manual/bitbake-user-manual-execution
bitbake-user-manual/bitbake-user-manual-metadata bitbake-user-manual/bitbake-user-manual-metadata
bitbake-user-manual/bitbake-user-manual-ref-variables-context
bitbake-user-manual/bitbake-user-manual-fetching bitbake-user-manual/bitbake-user-manual-fetching
bitbake-user-manual/bitbake-user-manual-ref-variables bitbake-user-manual/bitbake-user-manual-ref-variables
bitbake-user-manual/bitbake-user-manual-hello bitbake-user-manual/bitbake-user-manual-hello

View File

@@ -1,63 +1,61 @@
.. SPDX-License-Identifier: CC-BY-2.5 .. SPDX-License-Identifier: CC-BY-2.5
================================= ===========================
BitBake Supported Release Manuals Supported Release Manuals
================================= ===========================
*******************************
Release Series 4.2 (mickledore)
*******************************
- :yocto_docs:`BitBake 2.4 User Manual </bitbake/2.4/>`
******************************
Release Series 4.0 (kirkstone)
******************************
- :yocto_docs:`BitBake 2.0 User Manual </bitbake/2.0/>`
****************************
Release Series 3.1 (dunfell)
****************************
- :yocto_docs:`BitBake 1.46 User Manual </bitbake/1.46/>`
================================
BitBake Outdated Release Manuals
================================
*****************************
Release Series 4.1 (langdale)
*****************************
- :yocto_docs:`BitBake 2.2 User Manual </bitbake/2.2/>`
****************************** ******************************
Release Series 3.4 (honister) Release Series 3.4 (honister)
****************************** ******************************
- :yocto_docs:`BitBake 1.52 User Manual </bitbake/1.52/>` - :yocto_docs:`3.4 BitBake User Manual </3.4/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.4.1 BitBake User Manual </3.4.1/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.4.2 BitBake User Manual </3.4.2/bitbake-user-manual/bitbake-user-manual.html>`
****************************** ******************************
Release Series 3.3 (hardknott) Release Series 3.3 (hardknott)
****************************** ******************************
- :yocto_docs:`BitBake 1.50 User Manual </bitbake/1.50/>` - :yocto_docs:`3.3 BitBake User Manual </3.3/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.3.1 BitBake User Manual </3.3.1/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.3.2 BitBake User Manual </3.3.2/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.3.3 BitBake User Manual </3.3.3/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.3.4 BitBake User Manual </3.3.4/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.3.5 BitBake User Manual </3.3.5/bitbake-user-manual/bitbake-user-manual.html>`
******************************* ****************************
Release Series 3.2 (gatesgarth) Release Series 3.1 (dunfell)
******************************* ****************************
- :yocto_docs:`BitBake 1.48 User Manual </bitbake/1.48/>`
*******************************************
Release Series 3.1 (dunfell first versions)
*******************************************
- :yocto_docs:`3.1 BitBake User Manual </3.1/bitbake-user-manual/bitbake-user-manual.html>` - :yocto_docs:`3.1 BitBake User Manual </3.1/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.1 BitBake User Manual </3.1.1/bitbake-user-manual/bitbake-user-manual.html>` - :yocto_docs:`3.1.1 BitBake User Manual </3.1.1/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.2 BitBake User Manual </3.1.2/bitbake-user-manual/bitbake-user-manual.html>` - :yocto_docs:`3.1.2 BitBake User Manual </3.1.2/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.3 BitBake User Manual </3.1.3/bitbake-user-manual/bitbake-user-manual.html>` - :yocto_docs:`3.1.3 BitBake User Manual </3.1.3/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.4 BitBake User Manual </3.1.4/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.5 BitBake User Manual </3.1.5/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.6 BitBake User Manual </3.1.6/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.7 BitBake User Manual </3.1.7/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.8 BitBake User Manual </3.1.8/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.9 BitBake User Manual </3.1.9/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.10 BitBake User Manual </3.1.10/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.11 BitBake User Manual </3.1.11/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.12 BitBake User Manual </3.1.12/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.13 BitBake User Manual </3.1.13/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.1.14 BitBake User Manual </3.1.14/bitbake-user-manual/bitbake-user-manual.html>`
==========================
Outdated Release Manuals
==========================
*******************************
Release Series 3.2 (gatesgarth)
*******************************
- :yocto_docs:`3.2 BitBake User Manual </3.2/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.2.1 BitBake User Manual </3.2.1/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.2.2 BitBake User Manual </3.2.2/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.2.3 BitBake User Manual </3.2.3/bitbake-user-manual/bitbake-user-manual.html>`
- :yocto_docs:`3.2.4 BitBake User Manual </3.2.4/bitbake-user-manual/bitbake-user-manual.html>`
************************* *************************
Release Series 3.0 (zeus) Release Series 3.0 (zeus)

View File

@@ -3,8 +3,6 @@
# #
# Copyright (C) 2006 Tim Ansell # Copyright (C) 2006 Tim Ansell
# #
# SPDX-License-Identifier: GPL-2.0-only
#
# Please Note: # Please Note:
# Be careful when using mutable types (ie Dict and Lists) - operations involving these are SLOW. # Be careful when using mutable types (ie Dict and Lists) - operations involving these are SLOW.
# Assign a file to __warn__ to get warnings about slow operations. # Assign a file to __warn__ to get warnings about slow operations.
@@ -36,9 +34,8 @@ class COWDictMeta(COWMeta):
__marker__ = tuple() __marker__ = tuple()
def __str__(cls): def __str__(cls):
ignored_keys = set(["__count__", "__doc__", "__module__", "__firstlineno__", "__static_attributes__"]) # FIXME: I have magic numbers!
keys = set(cls.__dict__.keys()) - ignored_keys return "<COWDict Level: %i Current Keys: %i>" % (cls.__count__, len(cls.__dict__) - 3)
return "<COWDict Level: %i Current Keys: %i>" % (cls.__count__, len(keys))
__repr__ = __str__ __repr__ = __str__
@@ -162,9 +159,8 @@ class COWDictMeta(COWMeta):
class COWSetMeta(COWDictMeta): class COWSetMeta(COWDictMeta):
def __str__(cls): def __str__(cls):
ignored_keys = set(["__count__", "__doc__", "__module__", "__firstlineno__", "__static_attributes__"]) # FIXME: I have magic numbers!
keys = set(cls.__dict__.keys()) - ignored_keys return "<COWSet Level: %i Current Keys: %i>" % (cls.__count__, len(cls.__dict__) - 3)
return "<COWSet Level: %i Current Keys: %i>" % (cls.__count__, len(keys))
__repr__ = __str__ __repr__ = __str__

View File

@@ -9,19 +9,12 @@
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
__version__ = "2.8.1" __version__ = "2.0.0"
import sys import sys
if sys.version_info < (3, 8, 0): if sys.version_info < (3, 6, 0):
raise RuntimeError("Sorry, python 3.8.0 or later is required for this version of bitbake") raise RuntimeError("Sorry, python 3.6.0 or later is required for this version of bitbake")
if sys.version_info < (3, 10, 0):
# With python 3.8 and 3.9, we see errors of "libgcc_s.so.1 must be installed for pthread_cancel to work"
# https://stackoverflow.com/questions/64797838/libgcc-s-so-1-must-be-installed-for-pthread-cancel-to-work
# https://bugs.ams1.psf.io/issue42888
# so ensure libgcc_s is loaded early on
import ctypes
libgcc_s = ctypes.CDLL('libgcc_s.so.1')
class BBHandledException(Exception): class BBHandledException(Exception):
""" """
@@ -36,35 +29,6 @@ class BBHandledException(Exception):
import os import os
import logging import logging
from collections import namedtuple
import multiprocessing as mp
# Python 3.14 changes the default multiprocessing context from "fork" to
# "forkserver". However, bitbake heavily relies on "fork" behavior to
# efficiently pass data to the child processes. Places that need this should do:
# from bb import multiprocessing
# in place of
# import multiprocessing
class MultiprocessingContext(object):
"""
Multiprocessing proxy object that uses the "fork" context for a property if
available, otherwise goes to the main multiprocessing module. This allows
it to be a drop-in replacement for the multiprocessing module, but use the
fork context
"""
def __init__(self):
super().__setattr__("_ctx", mp.get_context("fork"))
def __getattr__(self, name):
if hasattr(self._ctx, name):
return getattr(self._ctx, name)
return getattr(mp, name)
def __setattr__(self, name, value):
raise AttributeError(f"Unable to set attribute {name}")
multiprocessing = MultiprocessingContext()
class NullHandler(logging.Handler): class NullHandler(logging.Handler):
@@ -96,10 +60,6 @@ class BBLoggerMixin(object):
return return
if loglevel < bb.msg.loggerDefaultLogLevel: if loglevel < bb.msg.loggerDefaultLogLevel:
return return
if not isinstance(level, int) or not isinstance(msg, str):
mainlogger.warning("Invalid arguments in bbdebug: %s" % repr((level, msg,) + args))
return self.log(loglevel, msg, *args, **kwargs) return self.log(loglevel, msg, *args, **kwargs)
def plain(self, msg, *args, **kwargs): def plain(self, msg, *args, **kwargs):
@@ -256,14 +216,3 @@ def deprecate_import(current, modulename, fromlist, renames = None):
setattr(sys.modules[current], newname, newobj) setattr(sys.modules[current], newname, newobj)
TaskData = namedtuple("TaskData", [
"pn",
"taskname",
"fn",
"deps",
"provides",
"taskhash",
"unihash",
"hashfn",
"taskhash_deps",
])

View File

@@ -1,215 +0,0 @@
#! /usr/bin/env python3
#
# Copyright 2023 by Garmin Ltd. or its subsidiaries
#
# SPDX-License-Identifier: MIT
import sys
import ctypes
import os
import errno
import pwd
import grp
libacl = ctypes.CDLL("libacl.so.1", use_errno=True)
ACL_TYPE_ACCESS = 0x8000
ACL_TYPE_DEFAULT = 0x4000
ACL_FIRST_ENTRY = 0
ACL_NEXT_ENTRY = 1
ACL_UNDEFINED_TAG = 0x00
ACL_USER_OBJ = 0x01
ACL_USER = 0x02
ACL_GROUP_OBJ = 0x04
ACL_GROUP = 0x08
ACL_MASK = 0x10
ACL_OTHER = 0x20
ACL_READ = 0x04
ACL_WRITE = 0x02
ACL_EXECUTE = 0x01
acl_t = ctypes.c_void_p
acl_entry_t = ctypes.c_void_p
acl_permset_t = ctypes.c_void_p
acl_perm_t = ctypes.c_uint
acl_tag_t = ctypes.c_int
libacl.acl_free.argtypes = [acl_t]
def acl_free(acl):
libacl.acl_free(acl)
libacl.acl_get_file.restype = acl_t
libacl.acl_get_file.argtypes = [ctypes.c_char_p, ctypes.c_uint]
def acl_get_file(path, typ):
acl = libacl.acl_get_file(os.fsencode(path), typ)
if acl is None:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err), str(path))
return acl
libacl.acl_get_entry.argtypes = [acl_t, ctypes.c_int, ctypes.c_void_p]
def acl_get_entry(acl, entry_id):
entry = acl_entry_t()
ret = libacl.acl_get_entry(acl, entry_id, ctypes.byref(entry))
if ret < 0:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err))
if ret == 0:
return None
return entry
libacl.acl_get_tag_type.argtypes = [acl_entry_t, ctypes.c_void_p]
def acl_get_tag_type(entry_d):
tag = acl_tag_t()
ret = libacl.acl_get_tag_type(entry_d, ctypes.byref(tag))
if ret < 0:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err))
return tag.value
libacl.acl_get_qualifier.restype = ctypes.c_void_p
libacl.acl_get_qualifier.argtypes = [acl_entry_t]
def acl_get_qualifier(entry_d):
ret = libacl.acl_get_qualifier(entry_d)
if ret is None:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err))
return ctypes.c_void_p(ret)
libacl.acl_get_permset.argtypes = [acl_entry_t, ctypes.c_void_p]
def acl_get_permset(entry_d):
permset = acl_permset_t()
ret = libacl.acl_get_permset(entry_d, ctypes.byref(permset))
if ret < 0:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err))
return permset
libacl.acl_get_perm.argtypes = [acl_permset_t, acl_perm_t]
def acl_get_perm(permset_d, perm):
ret = libacl.acl_get_perm(permset_d, perm)
if ret < 0:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err))
return bool(ret)
class Entry(object):
def __init__(self, tag, qualifier, mode):
self.tag = tag
self.qualifier = qualifier
self.mode = mode
def __str__(self):
typ = ""
qual = ""
if self.tag == ACL_USER:
typ = "user"
qual = pwd.getpwuid(self.qualifier).pw_name
elif self.tag == ACL_GROUP:
typ = "group"
qual = grp.getgrgid(self.qualifier).gr_name
elif self.tag == ACL_USER_OBJ:
typ = "user"
elif self.tag == ACL_GROUP_OBJ:
typ = "group"
elif self.tag == ACL_MASK:
typ = "mask"
elif self.tag == ACL_OTHER:
typ = "other"
r = "r" if self.mode & ACL_READ else "-"
w = "w" if self.mode & ACL_WRITE else "-"
x = "x" if self.mode & ACL_EXECUTE else "-"
return f"{typ}:{qual}:{r}{w}{x}"
class ACL(object):
def __init__(self, acl):
self.acl = acl
def __del__(self):
acl_free(self.acl)
def entries(self):
entry_id = ACL_FIRST_ENTRY
while True:
entry = acl_get_entry(self.acl, entry_id)
if entry is None:
break
permset = acl_get_permset(entry)
mode = 0
for m in (ACL_READ, ACL_WRITE, ACL_EXECUTE):
if acl_get_perm(permset, m):
mode |= m
qualifier = None
tag = acl_get_tag_type(entry)
if tag == ACL_USER or tag == ACL_GROUP:
qual = acl_get_qualifier(entry)
qualifier = ctypes.cast(qual, ctypes.POINTER(ctypes.c_int))[0]
yield Entry(tag, qualifier, mode)
entry_id = ACL_NEXT_ENTRY
@classmethod
def from_path(cls, path, typ):
acl = acl_get_file(path, typ)
return cls(acl)
def main():
import argparse
import pwd
import grp
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("path", help="File Path", type=Path)
args = parser.parse_args()
acl = ACL.from_path(args.path, ACL_TYPE_ACCESS)
for entry in acl.entries():
print(str(entry))
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -1,16 +1,31 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
import itertools
import json
from .client import AsyncClient, Client, ClientPool # The Python async server defaults to a 64K receive buffer, so we hardcode our
from .serv import AsyncServer, AsyncServerConnection # maximum chunk size. It would be better if the client and server reported to
from .connection import DEFAULT_MAX_CHUNK # each other what the maximum chunk sizes were, but that will slow down the
from .exceptions import ( # connection setup with a round trip delay so I'd rather not do that unless it
ClientError, # is necessary
ServerError, DEFAULT_MAX_CHUNK = 32 * 1024
ConnectionClosedError,
InvokeError,
) def chunkify(msg, max_chunk):
if len(msg) < max_chunk - 1:
yield ''.join((msg, "\n"))
else:
yield ''.join((json.dumps({
'chunk-stream': None
}), "\n"))
args = [iter(msg)] * (max_chunk - 1)
for m in map(''.join, itertools.zip_longest(*args, fillvalue='')):
yield ''.join(itertools.chain(m, "\n"))
yield "\n"
from .client import AsyncClient, Client
from .serv import AsyncServer, AsyncServerConnection, ClientError, ServerError

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
@@ -10,130 +8,47 @@ import json
import os import os
import socket import socket
import sys import sys
import re from . import chunkify, DEFAULT_MAX_CHUNK
import contextlib
from threading import Thread
from .connection import StreamConnection, WebsocketConnection, DEFAULT_MAX_CHUNK
from .exceptions import ConnectionClosedError, InvokeError
UNIX_PREFIX = "unix://"
WS_PREFIX = "ws://"
WSS_PREFIX = "wss://"
ADDR_TYPE_UNIX = 0
ADDR_TYPE_TCP = 1
ADDR_TYPE_WS = 2
def parse_address(addr):
if addr.startswith(UNIX_PREFIX):
return (ADDR_TYPE_UNIX, (addr[len(UNIX_PREFIX) :],))
elif addr.startswith(WS_PREFIX) or addr.startswith(WSS_PREFIX):
return (ADDR_TYPE_WS, (addr,))
else:
m = re.match(r"\[(?P<host>[^\]]*)\]:(?P<port>\d+)$", addr)
if m is not None:
host = m.group("host")
port = m.group("port")
else:
host, port = addr.split(":")
return (ADDR_TYPE_TCP, (host, int(port)))
class AsyncClient(object): class AsyncClient(object):
def __init__( def __init__(self, proto_name, proto_version, logger, timeout=30):
self, self.reader = None
proto_name, self.writer = None
proto_version,
logger,
timeout=30,
server_headers=False,
headers={},
):
self.socket = None
self.max_chunk = DEFAULT_MAX_CHUNK self.max_chunk = DEFAULT_MAX_CHUNK
self.proto_name = proto_name self.proto_name = proto_name
self.proto_version = proto_version self.proto_version = proto_version
self.logger = logger self.logger = logger
self.timeout = timeout self.timeout = timeout
self.needs_server_headers = server_headers
self.server_headers = {}
self.headers = headers
async def connect_tcp(self, address, port): async def connect_tcp(self, address, port):
async def connect_sock(): async def connect_sock():
reader, writer = await asyncio.open_connection(address, port) return await asyncio.open_connection(address, port)
return StreamConnection(reader, writer, self.timeout, self.max_chunk)
self._connect_sock = connect_sock self._connect_sock = connect_sock
async def connect_unix(self, path): async def connect_unix(self, path):
async def connect_sock(): async def connect_sock():
# AF_UNIX has path length issues so chdir here to workaround return await asyncio.open_unix_connection(path)
cwd = os.getcwd()
try:
os.chdir(os.path.dirname(path))
# The socket must be opened synchronously so that CWD doesn't get
# changed out from underneath us so we pass as a sock into asyncio
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
sock.connect(os.path.basename(path))
finally:
os.chdir(cwd)
reader, writer = await asyncio.open_unix_connection(sock=sock)
return StreamConnection(reader, writer, self.timeout, self.max_chunk)
self._connect_sock = connect_sock
async def connect_websocket(self, uri):
import websockets
async def connect_sock():
websocket = await websockets.connect(
uri,
ping_interval=None,
open_timeout=self.timeout,
)
return WebsocketConnection(websocket, self.timeout)
self._connect_sock = connect_sock self._connect_sock = connect_sock
async def setup_connection(self): async def setup_connection(self):
# Send headers s = '%s %s\n\n' % (self.proto_name, self.proto_version)
await self.socket.send("%s %s" % (self.proto_name, self.proto_version)) self.writer.write(s.encode("utf-8"))
await self.socket.send( await self.writer.drain()
"needs-headers: %s" % ("true" if self.needs_server_headers else "false")
)
for k, v in self.headers.items():
await self.socket.send("%s: %s" % (k, v))
# End of headers
await self.socket.send("")
self.server_headers = {}
if self.needs_server_headers:
while True:
line = await self.socket.recv()
if not line:
# End headers
break
tag, value = line.split(":", 1)
self.server_headers[tag.lower()] = value.strip()
async def get_header(self, tag, default):
await self.connect()
return self.server_headers.get(tag, default)
async def connect(self): async def connect(self):
if self.socket is None: if self.reader is None or self.writer is None:
self.socket = await self._connect_sock() (self.reader, self.writer) = await self._connect_sock()
await self.setup_connection() await self.setup_connection()
async def disconnect(self):
if self.socket is not None:
await self.socket.close()
self.socket = None
async def close(self): async def close(self):
await self.disconnect() self.reader = None
if self.writer is not None:
self.writer.close()
self.writer = None
async def _send_wrapper(self, proc): async def _send_wrapper(self, proc):
count = 0 count = 0
@@ -144,7 +59,6 @@ class AsyncClient(object):
except ( except (
OSError, OSError,
ConnectionError, ConnectionError,
ConnectionClosedError,
json.JSONDecodeError, json.JSONDecodeError,
UnicodeDecodeError, UnicodeDecodeError,
) as e: ) as e:
@@ -156,27 +70,49 @@ class AsyncClient(object):
await self.close() await self.close()
count += 1 count += 1
def check_invoke_error(self, msg): async def send_message(self, msg):
if isinstance(msg, dict) and "invoke-error" in msg: async def get_line():
raise InvokeError(msg["invoke-error"]["message"]) try:
line = await asyncio.wait_for(self.reader.readline(), self.timeout)
except asyncio.TimeoutError:
raise ConnectionError("Timed out waiting for server")
if not line:
raise ConnectionError("Connection closed")
line = line.decode("utf-8")
if not line.endswith("\n"):
raise ConnectionError("Bad message %r" % (line))
return line
async def invoke(self, msg):
async def proc(): async def proc():
await self.socket.send_message(msg) for c in chunkify(json.dumps(msg), self.max_chunk):
return await self.socket.recv_message() self.writer.write(c.encode("utf-8"))
await self.writer.drain()
result = await self._send_wrapper(proc) l = await get_line()
self.check_invoke_error(result)
return result m = json.loads(l)
if m and "chunk-stream" in m:
lines = []
while True:
l = (await get_line()).rstrip("\n")
if not l:
break
lines.append(l)
m = json.loads("".join(lines))
return m
return await self._send_wrapper(proc)
async def ping(self): async def ping(self):
return await self.invoke({"ping": {}}) return await self.send_message(
{'ping': {}}
async def __aenter__(self): )
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await self.close()
class Client(object): class Client(object):
@@ -194,7 +130,7 @@ class Client(object):
# required (but harmless) with it. # required (but harmless) with it.
asyncio.set_event_loop(self.loop) asyncio.set_event_loop(self.loop)
self._add_methods("connect_tcp", "ping") self._add_methods('connect_tcp', 'ping')
@abc.abstractmethod @abc.abstractmethod
def _get_async_client(self): def _get_async_client(self):
@@ -212,8 +148,14 @@ class Client(object):
setattr(self, m, self._get_downcall_wrapper(downcall)) setattr(self, m, self._get_downcall_wrapper(downcall))
def connect_unix(self, path): def connect_unix(self, path):
self.loop.run_until_complete(self.client.connect_unix(path)) # AF_UNIX has path length issues so chdir here to workaround
cwd = os.getcwd()
try:
os.chdir(os.path.dirname(path))
self.loop.run_until_complete(self.client.connect_unix(os.path.basename(path)))
self.loop.run_until_complete(self.client.connect()) self.loop.run_until_complete(self.client.connect())
finally:
os.chdir(cwd)
@property @property
def max_chunk(self): def max_chunk(self):
@@ -223,95 +165,8 @@ class Client(object):
def max_chunk(self, value): def max_chunk(self, value):
self.client.max_chunk = value self.client.max_chunk = value
def disconnect(self):
self.loop.run_until_complete(self.client.close())
def close(self): def close(self):
if self.loop:
self.loop.run_until_complete(self.client.close()) self.loop.run_until_complete(self.client.close())
if sys.version_info >= (3, 6): if sys.version_info >= (3, 6):
self.loop.run_until_complete(self.loop.shutdown_asyncgens()) self.loop.run_until_complete(self.loop.shutdown_asyncgens())
self.loop.close() self.loop.close()
self.loop = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
return False
class ClientPool(object):
def __init__(self, max_clients):
self.avail_clients = []
self.num_clients = 0
self.max_clients = max_clients
self.loop = None
self.client_condition = None
@abc.abstractmethod
async def _new_client(self):
raise NotImplementedError("Must be implemented in derived class")
def close(self):
if self.client_condition:
self.client_condition = None
if self.loop:
self.loop.run_until_complete(self.__close_clients())
self.loop.run_until_complete(self.loop.shutdown_asyncgens())
self.loop.close()
self.loop = None
def run_tasks(self, tasks):
if not self.loop:
self.loop = asyncio.new_event_loop()
thread = Thread(target=self.__thread_main, args=(tasks,))
thread.start()
thread.join()
@contextlib.asynccontextmanager
async def get_client(self):
async with self.client_condition:
if self.avail_clients:
client = self.avail_clients.pop()
elif self.num_clients < self.max_clients:
self.num_clients += 1
client = await self._new_client()
else:
while not self.avail_clients:
await self.client_condition.wait()
client = self.avail_clients.pop()
try:
yield client
finally:
async with self.client_condition:
self.avail_clients.append(client)
self.client_condition.notify()
def __thread_main(self, tasks):
async def process_task(task):
async with self.get_client() as client:
await task(client)
asyncio.set_event_loop(self.loop)
if not self.client_condition:
self.client_condition = asyncio.Condition()
tasks = [process_task(t) for t in tasks]
self.loop.run_until_complete(asyncio.gather(*tasks))
async def __close_clients(self):
for c in self.avail_clients:
await c.close()
self.avail_clients = []
self.num_clients = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
return False

View File

@@ -1,146 +0,0 @@
#
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only
#
import asyncio
import itertools
import json
from datetime import datetime
from .exceptions import ClientError, ConnectionClosedError
# The Python async server defaults to a 64K receive buffer, so we hardcode our
# maximum chunk size. It would be better if the client and server reported to
# each other what the maximum chunk sizes were, but that will slow down the
# connection setup with a round trip delay so I'd rather not do that unless it
# is necessary
DEFAULT_MAX_CHUNK = 32 * 1024
def chunkify(msg, max_chunk):
if len(msg) < max_chunk - 1:
yield "".join((msg, "\n"))
else:
yield "".join((json.dumps({"chunk-stream": None}), "\n"))
args = [iter(msg)] * (max_chunk - 1)
for m in map("".join, itertools.zip_longest(*args, fillvalue="")):
yield "".join(itertools.chain(m, "\n"))
yield "\n"
def json_serialize(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError("Type %s not serializeable" % type(obj))
class StreamConnection(object):
def __init__(self, reader, writer, timeout, max_chunk=DEFAULT_MAX_CHUNK):
self.reader = reader
self.writer = writer
self.timeout = timeout
self.max_chunk = max_chunk
@property
def address(self):
return self.writer.get_extra_info("peername")
async def send_message(self, msg):
for c in chunkify(json.dumps(msg, default=json_serialize), self.max_chunk):
self.writer.write(c.encode("utf-8"))
await self.writer.drain()
async def recv_message(self):
l = await self.recv()
m = json.loads(l)
if not m:
return m
if "chunk-stream" in m:
lines = []
while True:
l = await self.recv()
if not l:
break
lines.append(l)
m = json.loads("".join(lines))
return m
async def send(self, msg):
self.writer.write(("%s\n" % msg).encode("utf-8"))
await self.writer.drain()
async def recv(self):
if self.timeout < 0:
line = await self.reader.readline()
else:
try:
line = await asyncio.wait_for(self.reader.readline(), self.timeout)
except asyncio.TimeoutError:
raise ConnectionError("Timed out waiting for data")
if not line:
raise ConnectionClosedError("Connection closed")
line = line.decode("utf-8")
if not line.endswith("\n"):
raise ConnectionError("Bad message %r" % (line))
return line.rstrip()
async def close(self):
self.reader = None
if self.writer is not None:
self.writer.close()
self.writer = None
class WebsocketConnection(object):
def __init__(self, socket, timeout):
self.socket = socket
self.timeout = timeout
@property
def address(self):
return ":".join(str(s) for s in self.socket.remote_address)
async def send_message(self, msg):
await self.send(json.dumps(msg, default=json_serialize))
async def recv_message(self):
m = await self.recv()
return json.loads(m)
async def send(self, msg):
import websockets.exceptions
try:
await self.socket.send(msg)
except websockets.exceptions.ConnectionClosed:
raise ConnectionClosedError("Connection closed")
async def recv(self):
import websockets.exceptions
try:
if self.timeout < 0:
return await self.socket.recv()
try:
return await asyncio.wait_for(self.socket.recv(), self.timeout)
except asyncio.TimeoutError:
raise ConnectionError("Timed out waiting for data")
except websockets.exceptions.ConnectionClosed:
raise ConnectionClosedError("Connection closed")
async def close(self):
if self.socket is not None:
await self.socket.close()
self.socket = None

View File

@@ -1,21 +0,0 @@
#
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only
#
class ClientError(Exception):
pass
class InvokeError(Exception):
pass
class ServerError(Exception):
pass
class ConnectionClosedError(Exception):
pass

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
@@ -11,334 +9,235 @@ import os
import signal import signal
import socket import socket
import sys import sys
from bb import multiprocessing import multiprocessing
import logging from . import chunkify, DEFAULT_MAX_CHUNK
from .connection import StreamConnection, WebsocketConnection
from .exceptions import ClientError, ServerError, ConnectionClosedError, InvokeError
class ClientLoggerAdapter(logging.LoggerAdapter): class ClientError(Exception):
def process(self, msg, kwargs): pass
return f"[Client {self.extra['address']}] {msg}", kwargs
class ServerError(Exception):
pass
class AsyncServerConnection(object): class AsyncServerConnection(object):
# If a handler returns this object (e.g. `return self.NO_RESPONSE`), no def __init__(self, reader, writer, proto_name, logger):
# return message will be automatically be sent back to the client self.reader = reader
NO_RESPONSE = object() self.writer = writer
def __init__(self, socket, proto_name, logger):
self.socket = socket
self.proto_name = proto_name self.proto_name = proto_name
self.max_chunk = DEFAULT_MAX_CHUNK
self.handlers = { self.handlers = {
"ping": self.handle_ping, 'chunk-stream': self.handle_chunk,
'ping': self.handle_ping,
} }
self.logger = ClientLoggerAdapter( self.logger = logger
logger,
{
"address": socket.address,
},
)
self.client_headers = {}
async def close(self):
await self.socket.close()
async def handle_headers(self, headers):
return {}
async def process_requests(self): async def process_requests(self):
try: try:
self.logger.info("Client %r connected" % (self.socket.address,)) self.addr = self.writer.get_extra_info('peername')
self.logger.debug('Client %r connected' % (self.addr,))
# Read protocol and version # Read protocol and version
client_protocol = await self.socket.recv() client_protocol = await self.reader.readline()
if not client_protocol: if client_protocol is None:
return return
(client_proto_name, client_proto_version) = client_protocol.split() (client_proto_name, client_proto_version) = client_protocol.decode('utf-8').rstrip().split()
if client_proto_name != self.proto_name: if client_proto_name != self.proto_name:
self.logger.debug("Rejecting invalid protocol %s" % (self.proto_name)) self.logger.debug('Rejecting invalid protocol %s' % (self.proto_name))
return return
self.proto_version = tuple(int(v) for v in client_proto_version.split(".")) self.proto_version = tuple(int(v) for v in client_proto_version.split('.'))
if not self.validate_proto_version(): if not self.validate_proto_version():
self.logger.debug( self.logger.debug('Rejecting invalid protocol version %s' % (client_proto_version))
"Rejecting invalid protocol version %s" % (client_proto_version)
)
return return
# Read headers # Read headers. Currently, no headers are implemented, so look for
self.client_headers = {} # an empty line to signal the end of the headers
while True: while True:
header = await self.socket.recv() line = await self.reader.readline()
if not header: if line is None:
# Empty line. End of headers return
break
tag, value = header.split(":", 1)
self.client_headers[tag.lower()] = value.strip()
if self.client_headers.get("needs-headers", "false") == "true": line = line.decode('utf-8').rstrip()
for k, v in (await self.handle_headers(self.client_headers)).items(): if not line:
await self.socket.send("%s: %s" % (k, v)) break
await self.socket.send("")
# Handle messages # Handle messages
while True: while True:
d = await self.socket.recv_message() d = await self.read_message()
if d is None: if d is None:
break break
try: await self.dispatch_message(d)
response = await self.dispatch_message(d) await self.writer.drain()
except InvokeError as e: except ClientError as e:
await self.socket.send_message(
{"invoke-error": {"message": str(e)}}
)
break
if response is not self.NO_RESPONSE:
await self.socket.send_message(response)
except ConnectionClosedError as e:
self.logger.info(str(e))
except (ClientError, ConnectionError) as e:
self.logger.error(str(e)) self.logger.error(str(e))
finally: finally:
await self.close() self.writer.close()
async def dispatch_message(self, msg): async def dispatch_message(self, msg):
for k in self.handlers.keys(): for k in self.handlers.keys():
if k in msg: if k in msg:
self.logger.debug("Handling %s" % k) self.logger.debug('Handling %s' % k)
return await self.handlers[k](msg[k]) await self.handlers[k](msg[k])
return
raise ClientError("Unrecognized command %r" % msg) raise ClientError("Unrecognized command %r" % msg)
def write_message(self, msg):
for c in chunkify(json.dumps(msg), self.max_chunk):
self.writer.write(c.encode('utf-8'))
async def read_message(self):
l = await self.reader.readline()
if not l:
return None
try:
message = l.decode('utf-8')
if not message.endswith('\n'):
return None
return json.loads(message)
except (json.JSONDecodeError, UnicodeDecodeError) as e:
self.logger.error('Bad message from client: %r' % message)
raise e
async def handle_chunk(self, request):
lines = []
try:
while True:
l = await self.reader.readline()
l = l.rstrip(b"\n").decode("utf-8")
if not l:
break
lines.append(l)
msg = json.loads(''.join(lines))
except (json.JSONDecodeError, UnicodeDecodeError) as e:
self.logger.error('Bad message from client: %r' % lines)
raise e
if 'chunk-stream' in msg:
raise ClientError("Nested chunks are not allowed")
await self.dispatch_message(msg)
async def handle_ping(self, request): async def handle_ping(self, request):
return {"alive": True} response = {'alive': True}
self.write_message(response)
class StreamServer(object): class AsyncServer(object):
def __init__(self, handler, logger): def __init__(self, logger):
self.handler = handler self._cleanup_socket = None
self.logger = logger self.logger = logger
self.closed = False self.start = None
self.address = None
self.loop = None
async def handle_stream_client(self, reader, writer): def start_tcp_server(self, host, port):
# writer.transport.set_write_buffer_limits(0) def start_tcp():
socket = StreamConnection(reader, writer, -1) self.server = self.loop.run_until_complete(
if self.closed: asyncio.start_server(self.handle_client, host, port)
await socket.close()
return
await self.handler(socket)
async def stop(self):
self.closed = True
class TCPStreamServer(StreamServer):
def __init__(self, host, port, handler, logger):
super().__init__(handler, logger)
self.host = host
self.port = port
def start(self, loop):
self.server = loop.run_until_complete(
asyncio.start_server(self.handle_stream_client, self.host, self.port)
) )
for s in self.server.sockets: for s in self.server.sockets:
self.logger.debug("Listening on %r" % (s.getsockname(),)) self.logger.debug('Listening on %r' % (s.getsockname(),))
# Newer python does this automatically. Do it manually here for # Newer python does this automatically. Do it manually here for
# maximum compatibility # maximum compatibility
s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
s.setsockopt(socket.SOL_TCP, socket.TCP_QUICKACK, 1) s.setsockopt(socket.SOL_TCP, socket.TCP_QUICKACK, 1)
# Enable keep alives. This prevents broken client connections
# from persisting on the server for long periods of time.
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 30)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 15)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 4)
name = self.server.sockets[0].getsockname() name = self.server.sockets[0].getsockname()
if self.server.sockets[0].family == socket.AF_INET6: if self.server.sockets[0].family == socket.AF_INET6:
self.address = "[%s]:%d" % (name[0], name[1]) self.address = "[%s]:%d" % (name[0], name[1])
else: else:
self.address = "%s:%d" % (name[0], name[1]) self.address = "%s:%d" % (name[0], name[1])
return [self.server.wait_closed()] self.start = start_tcp
async def stop(self): def start_unix_server(self, path):
await super().stop() def cleanup():
self.server.close() os.unlink(path)
def cleanup(self): def start_unix():
pass
class UnixStreamServer(StreamServer):
def __init__(self, path, handler, logger):
super().__init__(handler, logger)
self.path = path
def start(self, loop):
cwd = os.getcwd() cwd = os.getcwd()
try: try:
# Work around path length limits in AF_UNIX # Work around path length limits in AF_UNIX
os.chdir(os.path.dirname(self.path)) os.chdir(os.path.dirname(path))
self.server = loop.run_until_complete( self.server = self.loop.run_until_complete(
asyncio.start_unix_server( asyncio.start_unix_server(self.handle_client, os.path.basename(path))
self.handle_stream_client, os.path.basename(self.path)
)
) )
finally: finally:
os.chdir(cwd) os.chdir(cwd)
self.logger.debug("Listening on %r" % self.path) self.logger.debug('Listening on %r' % path)
self.address = "unix://%s" % os.path.abspath(self.path)
return [self.server.wait_closed()]
async def stop(self): self._cleanup_socket = cleanup
await super().stop() self.address = "unix://%s" % os.path.abspath(path)
self.server.close()
def cleanup(self): self.start = start_unix
os.unlink(self.path)
@abc.abstractmethod
class WebsocketsServer(object): def accept_client(self, reader, writer):
def __init__(self, host, port, handler, logger):
self.host = host
self.port = port
self.handler = handler
self.logger = logger
def start(self, loop):
import websockets.server
self.server = loop.run_until_complete(
websockets.server.serve(
self.client_handler,
self.host,
self.port,
ping_interval=None,
)
)
for s in self.server.sockets:
self.logger.debug("Listening on %r" % (s.getsockname(),))
# Enable keep alives. This prevents broken client connections
# from persisting on the server for long periods of time.
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 30)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 15)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 4)
name = self.server.sockets[0].getsockname()
if self.server.sockets[0].family == socket.AF_INET6:
self.address = "ws://[%s]:%d" % (name[0], name[1])
else:
self.address = "ws://%s:%d" % (name[0], name[1])
return [self.server.wait_closed()]
async def stop(self):
self.server.close()
def cleanup(self):
pass pass
async def client_handler(self, websocket): async def handle_client(self, reader, writer):
socket = WebsocketConnection(websocket, -1) # writer.transport.set_write_buffer_limits(0)
await self.handler(socket)
class AsyncServer(object):
def __init__(self, logger):
self.logger = logger
self.loop = None
self.run_tasks = []
def start_tcp_server(self, host, port):
self.server = TCPStreamServer(host, port, self._client_handler, self.logger)
def start_unix_server(self, path):
self.server = UnixStreamServer(path, self._client_handler, self.logger)
def start_websocket_server(self, host, port):
self.server = WebsocketsServer(host, port, self._client_handler, self.logger)
async def _client_handler(self, socket):
address = socket.address
try: try:
client = self.accept_client(socket) client = self.accept_client(reader, writer)
await client.process_requests() await client.process_requests()
except Exception as e: except Exception as e:
import traceback import traceback
self.logger.error('Error from client: %s' % str(e), exc_info=True)
self.logger.error(
"Error from client %s: %s" % (address, str(e)), exc_info=True
)
traceback.print_exc() traceback.print_exc()
finally: writer.close()
self.logger.debug("Client %s disconnected", address) self.logger.debug('Client disconnected')
await socket.close()
@abc.abstractmethod def run_loop_forever(self):
def accept_client(self, socket): try:
self.loop.run_forever()
except KeyboardInterrupt:
pass pass
async def stop(self):
self.logger.debug("Stopping server")
await self.server.stop()
def start(self):
tasks = self.server.start(self.loop)
self.address = self.server.address
return tasks
def signal_handler(self): def signal_handler(self):
self.logger.debug("Got exit signal") self.logger.debug("Got exit signal")
self.loop.create_task(self.stop()) self.loop.stop()
def _serve_forever(self, tasks): def _serve_forever(self):
try: try:
self.loop.add_signal_handler(signal.SIGTERM, self.signal_handler) self.loop.add_signal_handler(signal.SIGTERM, self.signal_handler)
self.loop.add_signal_handler(signal.SIGINT, self.signal_handler)
self.loop.add_signal_handler(signal.SIGQUIT, self.signal_handler)
signal.pthread_sigmask(signal.SIG_UNBLOCK, [signal.SIGTERM]) signal.pthread_sigmask(signal.SIG_UNBLOCK, [signal.SIGTERM])
self.loop.run_until_complete(asyncio.gather(*tasks)) self.run_loop_forever()
self.server.close()
self.logger.debug("Server shutting down") self.loop.run_until_complete(self.server.wait_closed())
self.logger.debug('Server shutting down')
finally: finally:
self.server.cleanup() if self._cleanup_socket is not None:
self._cleanup_socket()
def serve_forever(self): def serve_forever(self):
""" """
Serve requests in the current process Serve requests in the current process
""" """
self._create_loop()
tasks = self.start()
self._serve_forever(tasks)
self.loop.close()
def _create_loop(self):
# Create loop and override any loop that may have existed in # Create loop and override any loop that may have existed in
# a parent process. It is possible that the usecases of # a parent process. It is possible that the usecases of
# serve_forever might be constrained enough to allow using # serve_forever might be constrained enough to allow using
# get_event_loop here, but better safe than sorry for now. # get_event_loop here, but better safe than sorry for now.
self.loop = asyncio.new_event_loop() self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop) asyncio.set_event_loop(self.loop)
self.start()
self._serve_forever()
def serve_as_process(self, *, prefunc=None, args=(), log_level=None): def serve_as_process(self, *, prefunc=None, args=()):
""" """
Serve requests in a child process Serve requests in a child process
""" """
def run(queue): def run(queue):
# Create loop and override any loop that may have existed # Create loop and override any loop that may have existed
# in a parent process. Without doing this and instead # in a parent process. Without doing this and instead
@@ -351,22 +250,18 @@ class AsyncServer(object):
# more general, though, as any potential use of asyncio in # more general, though, as any potential use of asyncio in
# Cooker could create a loop that needs to replaced in this # Cooker could create a loop that needs to replaced in this
# new process. # new process.
self._create_loop() self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
try: try:
self.address = None self.start()
tasks = self.start()
finally: finally:
# Always put the server address to wake up the parent task
queue.put(self.address) queue.put(self.address)
queue.close() queue.close()
if prefunc is not None: if prefunc is not None:
prefunc(self, *args) prefunc(self, *args)
if log_level is not None: self._serve_forever()
self.logger.setLevel(log_level)
self._serve_forever(tasks)
if sys.version_info >= (3, 6): if sys.version_info >= (3, 6):
self.loop.run_until_complete(self.loop.shutdown_asyncgens()) self.loop.run_until_complete(self.loop.shutdown_asyncgens())

View File

@@ -20,12 +20,10 @@ import itertools
import time import time
import re import re
import stat import stat
import datetime
import bb import bb
import bb.msg import bb.msg
import bb.process import bb.process
import bb.progress import bb.progress
from io import StringIO
from bb import data, event, utils from bb import data, event, utils
bblogger = logging.getLogger('BitBake') bblogger = logging.getLogger('BitBake')
@@ -178,9 +176,7 @@ class StdoutNoopContextManager:
@property @property
def name(self): def name(self):
if "name" in dir(sys.stdout):
return sys.stdout.name return sys.stdout.name
return "<mem>"
def exec_func(func, d, dirs = None): def exec_func(func, d, dirs = None):
@@ -299,21 +295,9 @@ def exec_func_python(func, d, runfile, cwd=None):
lineno = int(d.getVarFlag(func, "lineno", False)) lineno = int(d.getVarFlag(func, "lineno", False))
bb.methodpool.insert_method(func, text, fn, lineno - 1) bb.methodpool.insert_method(func, text, fn, lineno - 1)
if verboseStdoutLogging:
sys.stdout.flush()
sys.stderr.flush()
currout = sys.stdout
currerr = sys.stderr
sys.stderr = sys.stdout = execio = StringIO()
comp = utils.better_compile(code, func, "exec_func_python() autogenerated") comp = utils.better_compile(code, func, "exec_func_python() autogenerated")
utils.better_exec(comp, {"d": d}, code, "exec_func_python() autogenerated") utils.better_exec(comp, {"d": d}, code, "exec_func_python() autogenerated")
finally: finally:
if verboseStdoutLogging:
execio.flush()
logger.plain("%s" % execio.getvalue())
sys.stdout = currout
sys.stderr = currerr
execio.close()
# We want any stdout/stderr to be printed before any other log messages to make debugging # We want any stdout/stderr to be printed before any other log messages to make debugging
# more accurate. In some cases we seem to lose stdout/stderr entirely in logging tests without this. # more accurate. In some cases we seem to lose stdout/stderr entirely in logging tests without this.
sys.stdout.flush() sys.stdout.flush()
@@ -456,11 +440,7 @@ exit $ret
if fakerootcmd: if fakerootcmd:
cmd = [fakerootcmd, runfile] cmd = [fakerootcmd, runfile]
# We only want to output to logger via LogTee if stdout is sys.__stdout__ (which will either if verboseStdoutLogging:
# be real stdout or subprocess PIPE or similar). In other cases we are being run "recursively",
# ie. inside another function, in which case stdout is already being captured so we don't
# want to Tee here as output would be printed twice, and out of order.
if verboseStdoutLogging and sys.stdout == sys.__stdout__:
logfile = LogTee(logger, StdoutNoopContextManager()) logfile = LogTee(logger, StdoutNoopContextManager())
else: else:
logfile = StdoutNoopContextManager() logfile = StdoutNoopContextManager()
@@ -591,6 +571,7 @@ def _task_data(fn, task, d):
localdata.setVar('BB_FILENAME', fn) localdata.setVar('BB_FILENAME', fn)
localdata.setVar('OVERRIDES', 'task-%s:%s' % localdata.setVar('OVERRIDES', 'task-%s:%s' %
(task[3:].replace('_', '-'), d.getVar('OVERRIDES', False))) (task[3:].replace('_', '-'), d.getVar('OVERRIDES', False)))
localdata.finalize()
bb.data.expandKeys(localdata) bb.data.expandKeys(localdata)
return localdata return localdata
@@ -637,8 +618,7 @@ def _exec_task(fn, task, d, quieterr):
logorder = os.path.join(tempdir, 'log.task_order') logorder = os.path.join(tempdir, 'log.task_order')
try: try:
with open(logorder, 'a') as logorderfile: with open(logorder, 'a') as logorderfile:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S.%f") logorderfile.write('{0} ({1}): {2}\n'.format(task, os.getpid(), logbase))
logorderfile.write('{0} {1} ({2}): {3}\n'.format(timestamp, task, os.getpid(), logbase))
except OSError: except OSError:
logger.exception("Opening log file '%s'", logorder) logger.exception("Opening log file '%s'", logorder)
pass pass
@@ -791,7 +771,44 @@ def exec_task(fn, task, d, profile = False):
event.fire(failedevent, d) event.fire(failedevent, d)
return 1 return 1
def _get_cleanmask(taskname, mcfn): def stamp_internal(taskname, d, file_name, baseonly=False, noextra=False):
"""
Internal stamp helper function
Makes sure the stamp directory exists
Returns the stamp path+filename
In the bitbake core, d can be a CacheData and file_name will be set.
When called in task context, d will be a data store, file_name will not be set
"""
taskflagname = taskname
if taskname.endswith("_setscene") and taskname != "do_setscene":
taskflagname = taskname.replace("_setscene", "")
if file_name:
stamp = d.stamp[file_name]
extrainfo = d.stamp_extrainfo[file_name].get(taskflagname) or ""
else:
stamp = d.getVar('STAMP')
file_name = d.getVar('BB_FILENAME')
extrainfo = d.getVarFlag(taskflagname, 'stamp-extra-info') or ""
if baseonly:
return stamp
if noextra:
extrainfo = ""
if not stamp:
return
stamp = bb.parse.siggen.stampfile(stamp, file_name, taskname, extrainfo)
stampdir = os.path.dirname(stamp)
if cached_mtime_noerror(stampdir) == 0:
bb.utils.mkdirhier(stampdir)
return stamp
def stamp_cleanmask_internal(taskname, d, file_name):
""" """
Internal stamp helper function to generate stamp cleaning mask Internal stamp helper function to generate stamp cleaning mask
Returns the stamp path+filename Returns the stamp path+filename
@@ -799,14 +816,31 @@ def _get_cleanmask(taskname, mcfn):
In the bitbake core, d can be a CacheData and file_name will be set. In the bitbake core, d can be a CacheData and file_name will be set.
When called in task context, d will be a data store, file_name will not be set When called in task context, d will be a data store, file_name will not be set
""" """
cleanmask = bb.parse.siggen.stampcleanmask_mcfn(taskname, mcfn) taskflagname = taskname
if taskname.endswith("_setscene") and taskname != "do_setscene":
taskflagname = taskname.replace("_setscene", "") taskflagname = taskname.replace("_setscene", "")
if cleanmask:
return [cleanmask, cleanmask.replace(taskflagname, taskflagname + "_setscene")] if file_name:
stamp = d.stampclean[file_name]
extrainfo = d.stamp_extrainfo[file_name].get(taskflagname) or ""
else:
stamp = d.getVar('STAMPCLEAN')
file_name = d.getVar('BB_FILENAME')
extrainfo = d.getVarFlag(taskflagname, 'stamp-extra-info') or ""
if not stamp:
return [] return []
def clean_stamp_mcfn(task, mcfn): cleanmask = bb.parse.siggen.stampcleanmask(stamp, file_name, taskname, extrainfo)
cleanmask = _get_cleanmask(task, mcfn)
return [cleanmask, cleanmask.replace(taskflagname, taskflagname + "_setscene")]
def make_stamp(task, d, file_name = None):
"""
Creates/updates a stamp for a given task
(d can be a data dict or dataCache)
"""
cleanmask = stamp_cleanmask_internal(task, d, file_name)
for mask in cleanmask: for mask in cleanmask:
for name in glob.glob(mask): for name in glob.glob(mask):
# Preserve sigdata files in the stamps directory # Preserve sigdata files in the stamps directory
@@ -817,45 +851,24 @@ def clean_stamp_mcfn(task, mcfn):
continue continue
os.unlink(name) os.unlink(name)
def clean_stamp(task, d): stamp = stamp_internal(task, d, file_name)
mcfn = d.getVar('BB_FILENAME')
clean_stamp_mcfn(task, mcfn)
def make_stamp_mcfn(task, mcfn):
basestamp = bb.parse.siggen.stampfile_mcfn(task, mcfn)
stampdir = os.path.dirname(basestamp)
if cached_mtime_noerror(stampdir) == 0:
bb.utils.mkdirhier(stampdir)
clean_stamp_mcfn(task, mcfn)
# Remove the file and recreate to force timestamp # Remove the file and recreate to force timestamp
# change on broken NFS filesystems # change on broken NFS filesystems
if basestamp: if stamp:
bb.utils.remove(basestamp) bb.utils.remove(stamp)
open(basestamp, "w").close() open(stamp, "w").close()
def make_stamp(task, d):
"""
Creates/updates a stamp for a given task
"""
mcfn = d.getVar('BB_FILENAME')
make_stamp_mcfn(task, mcfn)
# If we're in task context, write out a signature file for each task # If we're in task context, write out a signature file for each task
# as it completes # as it completes
if not task.endswith("_setscene"): if not task.endswith("_setscene") and task != "do_setscene" and not file_name:
stampbase = bb.parse.siggen.stampfile_base(mcfn) stampbase = stamp_internal(task, d, None, True)
bb.parse.siggen.dump_sigtask(mcfn, task, stampbase, True) file_name = d.getVar('BB_FILENAME')
bb.parse.siggen.dump_sigtask(file_name, task, stampbase, True)
def find_stale_stamps(task, d, file_name=None):
def find_stale_stamps(task, mcfn): current = stamp_internal(task, d, file_name)
current = bb.parse.siggen.stampfile_mcfn(task, mcfn) current2 = stamp_internal(task + "_setscene", d, file_name)
current2 = bb.parse.siggen.stampfile_mcfn(task + "_setscene", mcfn) cleanmask = stamp_cleanmask_internal(task, d, file_name)
cleanmask = _get_cleanmask(task, mcfn)
found = [] found = []
for mask in cleanmask: for mask in cleanmask:
for name in glob.glob(mask): for name in glob.glob(mask):
@@ -869,14 +882,38 @@ def find_stale_stamps(task, mcfn):
found.append(name) found.append(name)
return found return found
def write_taint(task, d): def del_stamp(task, d, file_name = None):
"""
Removes a stamp for a given task
(d can be a data dict or dataCache)
"""
stamp = stamp_internal(task, d, file_name)
bb.utils.remove(stamp)
def write_taint(task, d, file_name = None):
""" """
Creates a "taint" file which will force the specified task and its Creates a "taint" file which will force the specified task and its
dependents to be re-run the next time by influencing the value of its dependents to be re-run the next time by influencing the value of its
taskhash. taskhash.
(d can be a data dict or dataCache)
""" """
mcfn = d.getVar('BB_FILENAME') import uuid
bb.parse.siggen.invalidate_task(task, mcfn) if file_name:
taintfn = d.stamp[file_name] + '.' + task + '.taint'
else:
taintfn = d.getVar('STAMP') + '.' + task + '.taint'
bb.utils.mkdirhier(os.path.dirname(taintfn))
# The specific content of the taint file is not really important,
# we just need it to be random, so a random UUID is used
with open(taintfn, 'w') as taintf:
taintf.write(str(uuid.uuid4()))
def stampfile(taskname, d, file_name = None, noextra=False):
"""
Return the stamp for a given task
(d can be a data dict or dataCache)
"""
return stamp_internal(taskname, d, file_name, noextra=noextra)
def add_tasks(tasklist, d): def add_tasks(tasklist, d):
task_deps = d.getVar('_task_deps', False) task_deps = d.getVar('_task_deps', False)

View File

@@ -24,11 +24,10 @@ from collections.abc import Mapping
import bb.utils import bb.utils
from bb import PrefixLoggerAdapter from bb import PrefixLoggerAdapter
import re import re
import shutil
logger = logging.getLogger("BitBake.Cache") logger = logging.getLogger("BitBake.Cache")
__cache_version__ = "155" __cache_version__ = "154"
def getCacheFile(path, filename, mc, data_hash): def getCacheFile(path, filename, mc, data_hash):
mcspec = '' mcspec = ''
@@ -105,7 +104,7 @@ class CoreRecipeInfo(RecipeInfoCommon):
self.tasks = metadata.getVar('__BBTASKS', False) self.tasks = metadata.getVar('__BBTASKS', False)
self.basetaskhashes = metadata.getVar('__siggen_basehashes', False) or {} self.basetaskhashes = self.taskvar('BB_BASEHASH', self.tasks, metadata)
self.hashfilename = self.getvar('BB_HASHFILENAME', metadata) self.hashfilename = self.getvar('BB_HASHFILENAME', metadata)
self.task_deps = metadata.getVar('_task_deps', False) or {'tasks': [], 'parents': {}} self.task_deps = metadata.getVar('_task_deps', False) or {'tasks': [], 'parents': {}}
@@ -216,7 +215,7 @@ class CoreRecipeInfo(RecipeInfoCommon):
# Collect files we may need for possible world-dep # Collect files we may need for possible world-dep
# calculations # calculations
if not bb.utils.to_boolean(self.not_world): if not self.not_world:
cachedata.possible_world.append(fn) cachedata.possible_world.append(fn)
#else: #else:
# logger.debug2("EXCLUDE FROM WORLD: %s", fn) # logger.debug2("EXCLUDE FROM WORLD: %s", fn)
@@ -238,113 +237,15 @@ class CoreRecipeInfo(RecipeInfoCommon):
cachedata.fakerootlogs[fn] = self.fakerootlogs cachedata.fakerootlogs[fn] = self.fakerootlogs
cachedata.extradepsfunc[fn] = self.extradepsfunc cachedata.extradepsfunc[fn] = self.extradepsfunc
class SiggenRecipeInfo(RecipeInfoCommon):
__slots__ = ()
classname = "SiggenRecipeInfo"
cachefile = "bb_cache_" + classname +".dat"
# we don't want to show this information in graph files so don't set cachefields
#cachefields = []
def __init__(self, filename, metadata):
self.siggen_gendeps = metadata.getVar("__siggen_gendeps", False)
self.siggen_varvals = metadata.getVar("__siggen_varvals", False)
self.siggen_taskdeps = metadata.getVar("__siggen_taskdeps", False)
@classmethod
def init_cacheData(cls, cachedata):
cachedata.siggen_taskdeps = {}
cachedata.siggen_gendeps = {}
cachedata.siggen_varvals = {}
def add_cacheData(self, cachedata, fn):
cachedata.siggen_gendeps[fn] = self.siggen_gendeps
cachedata.siggen_varvals[fn] = self.siggen_varvals
cachedata.siggen_taskdeps[fn] = self.siggen_taskdeps
# The siggen variable data is large and impacts:
# - bitbake's overall memory usage
# - the amount of data sent over IPC between parsing processes and the server
# - the size of the cache files on disk
# - the size of "sigdata" hash information files on disk
# The data consists of strings (some large) or frozenset lists of variables
# As such, we a) deplicate the data here and b) pass references to the object at second
# access (e.g. over IPC or saving into pickle).
store = {}
save_map = {}
save_count = 1
restore_map = {}
restore_count = {}
@classmethod
def reset(cls):
# Needs to be called before starting new streamed data in a given process
# (e.g. writing out the cache again)
cls.save_map = {}
cls.save_count = 1
cls.restore_map = {}
@classmethod
def _save(cls, deps):
ret = []
if not deps:
return deps
for dep in deps:
fs = deps[dep]
if fs is None:
ret.append((dep, None, None))
elif fs in cls.save_map:
ret.append((dep, None, cls.save_map[fs]))
else:
cls.save_map[fs] = cls.save_count
ret.append((dep, fs, cls.save_count))
cls.save_count = cls.save_count + 1
return ret
@classmethod
def _restore(cls, deps, pid):
ret = {}
if not deps:
return deps
if pid not in cls.restore_map:
cls.restore_map[pid] = {}
map = cls.restore_map[pid]
for dep, fs, mapnum in deps:
if fs is None and mapnum is None:
ret[dep] = None
elif fs is None:
ret[dep] = map[mapnum]
else:
try:
fs = cls.store[fs]
except KeyError:
cls.store[fs] = fs
map[mapnum] = fs
ret[dep] = fs
return ret
def __getstate__(self):
ret = {}
for key in ["siggen_gendeps", "siggen_taskdeps", "siggen_varvals"]:
ret[key] = self._save(self.__dict__[key])
ret['pid'] = os.getpid()
return ret
def __setstate__(self, state):
pid = state['pid']
for key in ["siggen_gendeps", "siggen_taskdeps", "siggen_varvals"]:
setattr(self, key, self._restore(state[key], pid))
def virtualfn2realfn(virtualfn): def virtualfn2realfn(virtualfn):
""" """
Convert a virtual file name to a real one + the associated subclass keyword Convert a virtual file name to a real one + the associated subclass keyword
""" """
mc = "" mc = ""
if virtualfn.startswith('mc:') and virtualfn.count(':') >= 2: if virtualfn.startswith('mc:') and virtualfn.count(':') >= 2:
(_, mc, virtualfn) = virtualfn.split(':', 2) elems = virtualfn.split(':')
mc = elems[1]
virtualfn = ":".join(elems[2:])
fn = virtualfn fn = virtualfn
cls = "" cls = ""
@@ -367,7 +268,7 @@ def realfn2virtual(realfn, cls, mc):
def variant2virtual(realfn, variant): def variant2virtual(realfn, variant):
""" """
Convert a real filename + a variant to a virtual filename Convert a real filename + the associated subclass keyword to a virtual filename
""" """
if variant == "": if variant == "":
return realfn return realfn
@@ -378,18 +279,75 @@ def variant2virtual(realfn, variant):
return "mc:" + elems[1] + ":" + realfn return "mc:" + elems[1] + ":" + realfn
return "virtual:" + variant + ":" + realfn return "virtual:" + variant + ":" + realfn
# def parse_recipe(bb_data, bbfile, appends, mc=''):
# Cooker calls cacheValid on its recipe list, then either calls loadCached """
# from it's main thread or parse from separate processes to generate an up to Parse a recipe
# date cache """
#
class Cache(object): bb_data.setVar("__BBMULTICONFIG", mc)
bbfile_loc = os.path.abspath(os.path.dirname(bbfile))
bb.parse.cached_mtime_noerror(bbfile_loc)
if appends:
bb_data.setVar('__BBAPPEND', " ".join(appends))
bb_data = bb.parse.handle(bbfile, bb_data)
return bb_data
class NoCache(object):
def __init__(self, databuilder):
self.databuilder = databuilder
self.data = databuilder.data
def loadDataFull(self, virtualfn, appends):
"""
Return a complete set of data for fn.
To do this, we need to parse the file.
"""
logger.debug("Parsing %s (full)" % virtualfn)
(fn, virtual, mc) = virtualfn2realfn(virtualfn)
bb_data = self.load_bbfile(virtualfn, appends, virtonly=True)
return bb_data[virtual]
def load_bbfile(self, bbfile, appends, virtonly = False, mc=None):
"""
Load and parse one .bb build file
Return the data and whether parsing resulted in the file being skipped
"""
if virtonly:
(bbfile, virtual, mc) = virtualfn2realfn(bbfile)
bb_data = self.databuilder.mcdata[mc].createCopy()
bb_data.setVar("__ONLYFINALISE", virtual or "default")
datastores = parse_recipe(bb_data, bbfile, appends, mc)
return datastores
if mc is not None:
bb_data = self.databuilder.mcdata[mc].createCopy()
return parse_recipe(bb_data, bbfile, appends, mc)
bb_data = self.data.createCopy()
datastores = parse_recipe(bb_data, bbfile, appends)
for mc in self.databuilder.mcdata:
if not mc:
continue
bb_data = self.databuilder.mcdata[mc].createCopy()
newstores = parse_recipe(bb_data, bbfile, appends, mc)
for ns in newstores:
datastores["mc:%s:%s" % (mc, ns)] = newstores[ns]
return datastores
class Cache(NoCache):
""" """
BitBake Cache implementation BitBake Cache implementation
""" """
def __init__(self, databuilder, mc, data_hash, caches_array): def __init__(self, databuilder, mc, data_hash, caches_array):
self.databuilder = databuilder super().__init__(databuilder)
self.data = databuilder.data data = databuilder.data
# Pass caches_array information into Cache Constructor # Pass caches_array information into Cache Constructor
# It will be used later for deciding whether we # It will be used later for deciding whether we
@@ -397,7 +355,7 @@ class Cache(object):
self.mc = mc self.mc = mc
self.logger = PrefixLoggerAdapter("Cache: %s: " % (mc if mc else "default"), logger) self.logger = PrefixLoggerAdapter("Cache: %s: " % (mc if mc else "default"), logger)
self.caches_array = caches_array self.caches_array = caches_array
self.cachedir = self.data.getVar("CACHE") self.cachedir = data.getVar("CACHE")
self.clean = set() self.clean = set()
self.checked = set() self.checked = set()
self.depends_cache = {} self.depends_cache = {}
@@ -407,12 +365,20 @@ class Cache(object):
self.filelist_regex = re.compile(r'(?:(?<=:True)|(?<=:False))\s+') self.filelist_regex = re.compile(r'(?:(?<=:True)|(?<=:False))\s+')
if self.cachedir in [None, '']: if self.cachedir in [None, '']:
bb.fatal("Please ensure CACHE is set to the cache directory for BitBake to use") self.has_cache = False
self.logger.info("Not using a cache. "
"Set CACHE = <directory> to enable.")
return
self.has_cache = True
def getCacheFile(self, cachefile): def getCacheFile(self, cachefile):
return getCacheFile(self.cachedir, cachefile, self.mc, self.data_hash) return getCacheFile(self.cachedir, cachefile, self.mc, self.data_hash)
def prepare_cache(self, progress): def prepare_cache(self, progress):
if not self.has_cache:
return 0
loaded = 0 loaded = 0
self.cachefile = self.getCacheFile("bb_cache.dat") self.cachefile = self.getCacheFile("bb_cache.dat")
@@ -451,6 +417,9 @@ class Cache(object):
return loaded return loaded
def cachesize(self): def cachesize(self):
if not self.has_cache:
return 0
cachesize = 0 cachesize = 0
for cache_class in self.caches_array: for cache_class in self.caches_array:
cachefile = self.getCacheFile(cache_class.cachefile) cachefile = self.getCacheFile(cache_class.cachefile)
@@ -512,11 +481,11 @@ class Cache(object):
return len(self.depends_cache) return len(self.depends_cache)
def parse(self, filename, appends, layername): def parse(self, filename, appends):
"""Parse the specified filename, returning the recipe information""" """Parse the specified filename, returning the recipe information"""
self.logger.debug("Parsing %s", filename) self.logger.debug("Parsing %s", filename)
infos = [] infos = []
datastores = self.databuilder.parseRecipeVariants(filename, appends, mc=self.mc, layername=layername) datastores = self.load_bbfile(filename, appends, mc=self.mc)
depends = [] depends = []
variants = [] variants = []
# Process the "real" fn last so we can store variants list # Process the "real" fn last so we can store variants list
@@ -538,19 +507,43 @@ class Cache(object):
return infos return infos
def loadCached(self, filename, appends): def load(self, filename, appends):
"""Obtain the recipe information for the specified filename, """Obtain the recipe information for the specified filename,
using cached values. using cached values if available, otherwise parsing.
"""
Note that if it does parse to obtain the info, it will not
automatically add the information to the cache or to your
CacheData. Use the add or add_info method to do so after
running this, or use loadData instead."""
cached = self.cacheValid(filename, appends)
if cached:
infos = [] infos = []
# info_array item is a list of [CoreRecipeInfo, XXXRecipeInfo] # info_array item is a list of [CoreRecipeInfo, XXXRecipeInfo]
info_array = self.depends_cache[filename] info_array = self.depends_cache[filename]
for variant in info_array[0].variants: for variant in info_array[0].variants:
virtualfn = variant2virtual(filename, variant) virtualfn = variant2virtual(filename, variant)
infos.append((virtualfn, self.depends_cache[virtualfn])) infos.append((virtualfn, self.depends_cache[virtualfn]))
else:
return self.parse(filename, appends, configdata, self.caches_array)
return infos return cached, infos
def loadData(self, fn, appends, cacheData):
"""Load the recipe info for the specified filename,
parsing and adding to the cache if necessary, and adding
the recipe information to the supplied CacheData instance."""
skipped, virtuals = 0, 0
cached, infos = self.load(fn, appends)
for virtualfn, info_array in infos:
if info_array[0].skipped:
self.logger.debug("Skipping %s: %s", virtualfn, info_array[0].skipreason)
skipped += 1
else:
self.add_info(virtualfn, info_array, cacheData, not cached)
virtuals += 1
return cached, skipped, virtuals
def cacheValid(self, fn, appends): def cacheValid(self, fn, appends):
""" """
@@ -559,6 +552,10 @@ class Cache(object):
""" """
if fn not in self.checked: if fn not in self.checked:
self.cacheValidUpdate(fn, appends) self.cacheValidUpdate(fn, appends)
# Is cache enabled?
if not self.has_cache:
return False
if fn in self.clean: if fn in self.clean:
return True return True
return False return False
@@ -568,6 +565,10 @@ class Cache(object):
Is the cache valid for fn? Is the cache valid for fn?
Make thorough (slower) checks including timestamps. Make thorough (slower) checks including timestamps.
""" """
# Is cache enabled?
if not self.has_cache:
return False
self.checked.add(fn) self.checked.add(fn)
# File isn't in depends_cache # File isn't in depends_cache
@@ -618,7 +619,7 @@ class Cache(object):
for f in flist: for f in flist:
if not f: if not f:
continue continue
f, exist = f.rsplit(":", 1) f, exist = f.split(":")
if (exist == "True" and not os.path.exists(f)) or (exist == "False" and os.path.exists(f)): if (exist == "True" and not os.path.exists(f)) or (exist == "False" and os.path.exists(f)):
self.logger.debug2("%s's file checksum list file %s changed", self.logger.debug2("%s's file checksum list file %s changed",
fn, f) fn, f)
@@ -674,6 +675,10 @@ class Cache(object):
Save the cache Save the cache
Called from the parser when complete (or exiting) Called from the parser when complete (or exiting)
""" """
if not self.has_cache:
return
if self.cacheclean: if self.cacheclean:
self.logger.debug2("Cache is clean, not saving.") self.logger.debug2("Cache is clean, not saving.")
return return
@@ -694,7 +699,6 @@ class Cache(object):
p.dump(info) p.dump(info)
del self.depends_cache del self.depends_cache
SiggenRecipeInfo.reset()
@staticmethod @staticmethod
def mtime(cachefile): def mtime(cachefile):
@@ -717,11 +721,26 @@ class Cache(object):
if watcher: if watcher:
watcher(info_array[0].file_depends) watcher(info_array[0].file_depends)
if not self.has_cache:
return
if (info_array[0].skipped or 'SRCREVINACTION' not in info_array[0].pv) and not info_array[0].nocache: if (info_array[0].skipped or 'SRCREVINACTION' not in info_array[0].pv) and not info_array[0].nocache:
if parsed: if parsed:
self.cacheclean = False self.cacheclean = False
self.depends_cache[filename] = info_array self.depends_cache[filename] = info_array
def add(self, file_name, data, cacheData, parsed=None):
"""
Save data we need into the cache
"""
realfn = virtualfn2realfn(file_name)[0]
info_array = []
for cache_class in self.caches_array:
info_array.append(cache_class(realfn, data))
self.add_info(file_name, info_array, cacheData, parsed)
class MulticonfigCache(Mapping): class MulticonfigCache(Mapping):
def __init__(self, databuilder, data_hash, caches_array): def __init__(self, databuilder, data_hash, caches_array):
def progress(p): def progress(p):
@@ -758,7 +777,6 @@ class MulticonfigCache(Mapping):
loaded = 0 loaded = 0
for c in self.__caches.values(): for c in self.__caches.values():
SiggenRecipeInfo.reset()
loaded += c.prepare_cache(progress) loaded += c.prepare_cache(progress)
previous_progress = current_progress previous_progress = current_progress
@@ -836,10 +854,11 @@ class MultiProcessCache(object):
self.cachedata = self.create_cachedata() self.cachedata = self.create_cachedata()
self.cachedata_extras = self.create_cachedata() self.cachedata_extras = self.create_cachedata()
def init_cache(self, cachedir, cache_file_name=None): def init_cache(self, d, cache_file_name=None):
if not cachedir: cachedir = (d.getVar("PERSISTENT_DIR") or
d.getVar("CACHE"))
if cachedir in [None, '']:
return return
bb.utils.mkdirhier(cachedir) bb.utils.mkdirhier(cachedir)
self.cachefile = os.path.join(cachedir, self.cachefile = os.path.join(cachedir,
cache_file_name or self.__class__.cache_file_name) cache_file_name or self.__class__.cache_file_name)
@@ -870,10 +889,6 @@ class MultiProcessCache(object):
if not self.cachefile: if not self.cachefile:
return return
have_data = any(self.cachedata_extras)
if not have_data:
return
glf = bb.utils.lockfile(self.cachefile + ".lock", shared=True) glf = bb.utils.lockfile(self.cachefile + ".lock", shared=True)
i = os.getpid() i = os.getpid()
@@ -908,8 +923,6 @@ class MultiProcessCache(object):
data = self.cachedata data = self.cachedata
have_data = False
for f in [y for y in os.listdir(os.path.dirname(self.cachefile)) if y.startswith(os.path.basename(self.cachefile) + '-')]: for f in [y for y in os.listdir(os.path.dirname(self.cachefile)) if y.startswith(os.path.basename(self.cachefile) + '-')]:
f = os.path.join(os.path.dirname(self.cachefile), f) f = os.path.join(os.path.dirname(self.cachefile), f)
try: try:
@@ -924,11 +937,9 @@ class MultiProcessCache(object):
os.unlink(f) os.unlink(f)
continue continue
have_data = True
self.merge_data(extradata, data) self.merge_data(extradata, data)
os.unlink(f) os.unlink(f)
if have_data:
with open(self.cachefile, "wb") as f: with open(self.cachefile, "wb") as f:
p = pickle.Pickler(f, -1) p = pickle.Pickler(f, -1)
p.dump([data, self.__class__.CACHE_VERSION]) p.dump([data, self.__class__.CACHE_VERSION])
@@ -987,11 +998,3 @@ class SimpleCache(object):
p.dump([data, self.cacheversion]) p.dump([data, self.cacheversion])
bb.utils.unlockfile(glf) bb.utils.unlockfile(glf)
def copyfile(self, target):
if not self.cachefile:
return
glf = bb.utils.lockfile(self.cachefile + ".lock")
shutil.copy(self.cachefile, target)
bb.utils.unlockfile(glf)

View File

@@ -11,13 +11,10 @@ import os
import stat import stat
import bb.utils import bb.utils
import logging import logging
import re
from bb.cache import MultiProcessCache from bb.cache import MultiProcessCache
logger = logging.getLogger("BitBake.Cache") logger = logging.getLogger("BitBake.Cache")
filelist_regex = re.compile(r'(?:(?<=:True)|(?<=:False))\s+')
# mtime cache (non-persistent) # mtime cache (non-persistent)
# based upon the assumption that files do not change during bitbake run # based upon the assumption that files do not change during bitbake run
class FileMtimeCache(object): class FileMtimeCache(object):
@@ -112,12 +109,7 @@ class FileChecksumCache(MultiProcessCache):
return dirchecksums return dirchecksums
checksums = [] checksums = []
for pth in filelist_regex.split(filelist): for pth in filelist.split():
if not pth:
continue
pth = pth.strip()
if not pth:
continue
exist = pth.split(":")[1] exist = pth.split(":")[1]
if exist == "False": if exist == "False":
continue continue

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
@@ -27,7 +25,6 @@ import ast
import sys import sys
import codegen import codegen
import logging import logging
import inspect
import bb.pysh as pysh import bb.pysh as pysh
import bb.utils, bb.data import bb.utils, bb.data
import hashlib import hashlib
@@ -59,45 +56,10 @@ def check_indent(codestr):
return codestr return codestr
modulecode_deps = {}
def add_module_functions(fn, functions, namespace):
import os
fstat = os.stat(fn)
fixedhash = fn + ":" + str(fstat.st_size) + ":" + str(fstat.st_mtime)
for f in functions:
name = "%s.%s" % (namespace, f)
parser = PythonParser(name, logger)
try:
parser.parse_python(None, filename=fn, lineno=1, fixedhash=fixedhash+f)
#bb.warn("Cached %s" % f)
except KeyError:
targetfn = inspect.getsourcefile(functions[f])
if fn != targetfn:
# Skip references to other modules outside this file
#bb.warn("Skipping %s" % name)
continue
lines, lineno = inspect.getsourcelines(functions[f])
src = "".join(lines)
parser.parse_python(src, filename=fn, lineno=lineno, fixedhash=fixedhash+f)
#bb.warn("Not cached %s" % f)
execs = parser.execs.copy()
# Expand internal module exec references
for e in parser.execs:
if e in functions:
execs.remove(e)
execs.add(namespace + "." + e)
modulecode_deps[name] = [parser.references.copy(), execs, parser.var_execs.copy(), parser.contains.copy(), parser.extra]
#bb.warn("%s: %s\nRefs:%s Execs: %s %s %s" % (name, fn, parser.references, parser.execs, parser.var_execs, parser.contains))
def update_module_dependencies(d):
for mod in modulecode_deps:
excludes = set((d.getVarFlag(mod, "vardepsexclude") or "").split())
if excludes:
modulecode_deps[mod] = [modulecode_deps[mod][0] - excludes, modulecode_deps[mod][1] - excludes, modulecode_deps[mod][2] - excludes, modulecode_deps[mod][3], modulecode_deps[mod][4]]
# A custom getstate/setstate using tuples is actually worth 15% cachesize by # A custom getstate/setstate using tuples is actually worth 15% cachesize by
# avoiding duplication of the attribute names! # avoiding duplication of the attribute names!
class SetCache(object): class SetCache(object):
def __init__(self): def __init__(self):
self.setcache = {} self.setcache = {}
@@ -117,22 +79,21 @@ class SetCache(object):
codecache = SetCache() codecache = SetCache()
class pythonCacheLine(object): class pythonCacheLine(object):
def __init__(self, refs, execs, contains, extra): def __init__(self, refs, execs, contains):
self.refs = codecache.internSet(refs) self.refs = codecache.internSet(refs)
self.execs = codecache.internSet(execs) self.execs = codecache.internSet(execs)
self.contains = {} self.contains = {}
for c in contains: for c in contains:
self.contains[c] = codecache.internSet(contains[c]) self.contains[c] = codecache.internSet(contains[c])
self.extra = extra
def __getstate__(self): def __getstate__(self):
return (self.refs, self.execs, self.contains, self.extra) return (self.refs, self.execs, self.contains)
def __setstate__(self, state): def __setstate__(self, state):
(refs, execs, contains, extra) = state (refs, execs, contains) = state
self.__init__(refs, execs, contains, extra) self.__init__(refs, execs, contains)
def __hash__(self): def __hash__(self):
l = (hash(self.refs), hash(self.execs), hash(self.extra)) l = (hash(self.refs), hash(self.execs))
for c in sorted(self.contains.keys()): for c in sorted(self.contains.keys()):
l = l + (c, hash(self.contains[c])) l = l + (c, hash(self.contains[c]))
return hash(l) return hash(l)
@@ -161,7 +122,7 @@ class CodeParserCache(MultiProcessCache):
# so that an existing cache gets invalidated. Additionally you'll need # so that an existing cache gets invalidated. Additionally you'll need
# to increment __cache_version__ in cache.py in order to ensure that old # to increment __cache_version__ in cache.py in order to ensure that old
# recipe caches don't trigger "Taskhash mismatch" errors. # recipe caches don't trigger "Taskhash mismatch" errors.
CACHE_VERSION = 12 CACHE_VERSION = 11
def __init__(self): def __init__(self):
MultiProcessCache.__init__(self) MultiProcessCache.__init__(self)
@@ -175,8 +136,8 @@ class CodeParserCache(MultiProcessCache):
self.pythoncachelines = {} self.pythoncachelines = {}
self.shellcachelines = {} self.shellcachelines = {}
def newPythonCacheLine(self, refs, execs, contains, extra): def newPythonCacheLine(self, refs, execs, contains):
cacheline = pythonCacheLine(refs, execs, contains, extra) cacheline = pythonCacheLine(refs, execs, contains)
h = hash(cacheline) h = hash(cacheline)
if h in self.pythoncachelines: if h in self.pythoncachelines:
return self.pythoncachelines[h] return self.pythoncachelines[h]
@@ -191,12 +152,12 @@ class CodeParserCache(MultiProcessCache):
self.shellcachelines[h] = cacheline self.shellcachelines[h] = cacheline
return cacheline return cacheline
def init_cache(self, cachedir): def init_cache(self, d):
# Check if we already have the caches # Check if we already have the caches
if self.pythoncache: if self.pythoncache:
return return
MultiProcessCache.init_cache(self, cachedir) MultiProcessCache.init_cache(self, d)
# cachedata gets re-assigned in the parent # cachedata gets re-assigned in the parent
self.pythoncache = self.cachedata[0] self.pythoncache = self.cachedata[0]
@@ -208,8 +169,8 @@ class CodeParserCache(MultiProcessCache):
codeparsercache = CodeParserCache() codeparsercache = CodeParserCache()
def parser_cache_init(cachedir): def parser_cache_init(d):
codeparsercache.init_cache(cachedir) codeparsercache.init_cache(d)
def parser_cache_save(): def parser_cache_save():
codeparsercache.save_extras() codeparsercache.save_extras()
@@ -262,19 +223,19 @@ class PythonParser():
def visit_Call(self, node): def visit_Call(self, node):
name = self.called_node_name(node.func) name = self.called_node_name(node.func)
if name and (name.endswith(self.getvars) or name.endswith(self.getvarflags) or name in self.containsfuncs or name in self.containsanyfuncs): if name and (name.endswith(self.getvars) or name.endswith(self.getvarflags) or name in self.containsfuncs or name in self.containsanyfuncs):
if isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str): if isinstance(node.args[0], ast.Str):
varname = node.args[0].value varname = node.args[0].s
if name in self.containsfuncs and isinstance(node.args[1], ast.Constant): if name in self.containsfuncs and isinstance(node.args[1], ast.Str):
if varname not in self.contains: if varname not in self.contains:
self.contains[varname] = set() self.contains[varname] = set()
self.contains[varname].add(node.args[1].value) self.contains[varname].add(node.args[1].s)
elif name in self.containsanyfuncs and isinstance(node.args[1], ast.Constant): elif name in self.containsanyfuncs and isinstance(node.args[1], ast.Str):
if varname not in self.contains: if varname not in self.contains:
self.contains[varname] = set() self.contains[varname] = set()
self.contains[varname].update(node.args[1].value.split()) self.contains[varname].update(node.args[1].s.split())
elif name.endswith(self.getvarflags): elif name.endswith(self.getvarflags):
if isinstance(node.args[1], ast.Constant): if isinstance(node.args[1], ast.Str):
self.references.add('%s[%s]' % (varname, node.args[1].value)) self.references.add('%s[%s]' % (varname, node.args[1].s))
else: else:
self.warn(node.func, node.args[1]) self.warn(node.func, node.args[1])
else: else:
@@ -282,8 +243,8 @@ class PythonParser():
else: else:
self.warn(node.func, node.args[0]) self.warn(node.func, node.args[0])
elif name and name.endswith(".expand"): elif name and name.endswith(".expand"):
if isinstance(node.args[0], ast.Constant): if isinstance(node.args[0], ast.Str):
value = node.args[0].value value = node.args[0].s
d = bb.data.init() d = bb.data.init()
parser = d.expandWithRefs(value, self.name) parser = d.expandWithRefs(value, self.name)
self.references |= parser.references self.references |= parser.references
@@ -293,8 +254,8 @@ class PythonParser():
self.contains[varname] = set() self.contains[varname] = set()
self.contains[varname] |= parser.contains[varname] self.contains[varname] |= parser.contains[varname]
elif name in self.execfuncs: elif name in self.execfuncs:
if isinstance(node.args[0], ast.Constant): if isinstance(node.args[0], ast.Str):
self.var_execs.add(node.args[0].value) self.var_execs.add(node.args[0].s)
else: else:
self.warn(node.func, node.args[0]) self.warn(node.func, node.args[0])
elif name and isinstance(node.func, (ast.Name, ast.Attribute)): elif name and isinstance(node.func, (ast.Name, ast.Attribute)):
@@ -326,16 +287,10 @@ class PythonParser():
self.unhandled_message = "in call of %s, argument '%s' is not a string literal" self.unhandled_message = "in call of %s, argument '%s' is not a string literal"
self.unhandled_message = "while parsing %s, %s" % (name, self.unhandled_message) self.unhandled_message = "while parsing %s, %s" % (name, self.unhandled_message)
# For the python module code it is expensive to have the function text so it is def parse_python(self, node, lineno=0, filename="<string>"):
# uses a different fixedhash to cache against. We can take the hit on obtaining the if not node or not node.strip():
# text if it isn't in the cache.
def parse_python(self, node, lineno=0, filename="<string>", fixedhash=None):
if not fixedhash and (not node or not node.strip()):
return return
if fixedhash:
h = fixedhash
else:
h = bbhash(str(node)) h = bbhash(str(node))
if h in codeparsercache.pythoncache: if h in codeparsercache.pythoncache:
@@ -344,7 +299,6 @@ class PythonParser():
self.contains = {} self.contains = {}
for i in codeparsercache.pythoncache[h].contains: for i in codeparsercache.pythoncache[h].contains:
self.contains[i] = set(codeparsercache.pythoncache[h].contains[i]) self.contains[i] = set(codeparsercache.pythoncache[h].contains[i])
self.extra = codeparsercache.pythoncache[h].extra
return return
if h in codeparsercache.pythoncacheextras: if h in codeparsercache.pythoncacheextras:
@@ -353,12 +307,8 @@ class PythonParser():
self.contains = {} self.contains = {}
for i in codeparsercache.pythoncacheextras[h].contains: for i in codeparsercache.pythoncacheextras[h].contains:
self.contains[i] = set(codeparsercache.pythoncacheextras[h].contains[i]) self.contains[i] = set(codeparsercache.pythoncacheextras[h].contains[i])
self.extra = codeparsercache.pythoncacheextras[h].extra
return return
if fixedhash and not node:
raise KeyError
# Need to parse so take the hit on the real log buffer # Need to parse so take the hit on the real log buffer
self.log = BufferedLogger('BitBake.Data.PythonParser', logging.DEBUG, self._log) self.log = BufferedLogger('BitBake.Data.PythonParser', logging.DEBUG, self._log)
@@ -372,11 +322,8 @@ class PythonParser():
self.visit_Call(n) self.visit_Call(n)
self.execs.update(self.var_execs) self.execs.update(self.var_execs)
self.extra = None
if fixedhash:
self.extra = bbhash(str(node))
codeparsercache.pythoncacheextras[h] = codeparsercache.newPythonCacheLine(self.references, self.execs, self.contains, self.extra) codeparsercache.pythoncacheextras[h] = codeparsercache.newPythonCacheLine(self.references, self.execs, self.contains)
class ShellParser(): class ShellParser():
def __init__(self, name, log): def __init__(self, name, log):

View File

@@ -51,21 +51,20 @@ class Command:
""" """
A queue of asynchronous commands for bitbake A queue of asynchronous commands for bitbake
""" """
def __init__(self, cooker, process_server): def __init__(self, cooker):
self.cooker = cooker self.cooker = cooker
self.cmds_sync = CommandsSync() self.cmds_sync = CommandsSync()
self.cmds_async = CommandsAsync() self.cmds_async = CommandsAsync()
self.remotedatastores = None self.remotedatastores = None
self.process_server = process_server # FIXME Add lock for this
# Access with locking using process_server.{get/set/clear}_async_cmd()
self.currentAsyncCommand = None self.currentAsyncCommand = None
def runCommand(self, commandline, process_server, ro_only=False): def runCommand(self, commandline, ro_only = False):
command = commandline.pop(0) command = commandline.pop(0)
# Ensure cooker is ready for commands # Ensure cooker is ready for commands
if command not in ["updateConfig", "setFeatures", "ping"]: if command != "updateConfig" and command != "setFeatures":
try: try:
self.cooker.init_configdata() self.cooker.init_configdata()
if not self.remotedatastores: if not self.remotedatastores:
@@ -85,6 +84,7 @@ class Command:
if not hasattr(command_method, 'readonly') or not getattr(command_method, 'readonly'): if not hasattr(command_method, 'readonly') or not getattr(command_method, 'readonly'):
return None, "Not able to execute not readonly commands in readonly mode" return None, "Not able to execute not readonly commands in readonly mode"
try: try:
self.cooker.process_inotify_updates()
if getattr(command_method, 'needconfig', True): if getattr(command_method, 'needconfig', True):
self.cooker.updateCacheSync() self.cooker.updateCacheSync()
result = command_method(self, commandline) result = command_method(self, commandline)
@@ -99,23 +99,24 @@ class Command:
return None, traceback.format_exc() return None, traceback.format_exc()
else: else:
return result, None return result, None
if self.currentAsyncCommand is not None:
return None, "Busy (%s in progress)" % self.currentAsyncCommand[0]
if command not in CommandsAsync.__dict__: if command not in CommandsAsync.__dict__:
return None, "No such command" return None, "No such command"
if not process_server.set_async_cmd((command, commandline)): self.currentAsyncCommand = (command, commandline)
return None, "Busy (%s in progress)" % self.process_server.get_async_cmd()[0] self.cooker.idleCallBackRegister(self.cooker.runCommands, self.cooker)
self.cooker.idleCallBackRegister(self.runAsyncCommand, process_server)
return True, None return True, None
def runAsyncCommand(self, _, process_server, halt): def runAsyncCommand(self):
try: try:
self.cooker.process_inotify_updates()
if self.cooker.state in (bb.cooker.state.error, bb.cooker.state.shutdown, bb.cooker.state.forceshutdown): if self.cooker.state in (bb.cooker.state.error, bb.cooker.state.shutdown, bb.cooker.state.forceshutdown):
# updateCache will trigger a shutdown of the parser # updateCache will trigger a shutdown of the parser
# and then raise BBHandledException triggering an exit # and then raise BBHandledException triggering an exit
self.cooker.updateCache() self.cooker.updateCache()
return bb.server.process.idleFinish("Cooker in error state") return False
cmd = process_server.get_async_cmd() if self.currentAsyncCommand is not None:
if cmd is not None: (command, options) = self.currentAsyncCommand
(command, options) = cmd
commandmethod = getattr(CommandsAsync, command) commandmethod = getattr(CommandsAsync, command)
needcache = getattr( commandmethod, "needcache" ) needcache = getattr( commandmethod, "needcache" )
if needcache and self.cooker.state != bb.cooker.state.running: if needcache and self.cooker.state != bb.cooker.state.running:
@@ -125,21 +126,24 @@ class Command:
commandmethod(self.cmds_async, self, options) commandmethod(self.cmds_async, self, options)
return False return False
else: else:
return bb.server.process.idleFinish("Nothing to do, no async command?") return False
except KeyboardInterrupt as exc: except KeyboardInterrupt as exc:
return bb.server.process.idleFinish("Interrupted") self.finishAsyncCommand("Interrupted")
return False
except SystemExit as exc: except SystemExit as exc:
arg = exc.args[0] arg = exc.args[0]
if isinstance(arg, str): if isinstance(arg, str):
return bb.server.process.idleFinish(arg) self.finishAsyncCommand(arg)
else: else:
return bb.server.process.idleFinish("Exited with %s" % arg) self.finishAsyncCommand("Exited with %s" % arg)
return False
except Exception as exc: except Exception as exc:
import traceback import traceback
if isinstance(exc, bb.BBHandledException): if isinstance(exc, bb.BBHandledException):
return bb.server.process.idleFinish("") self.finishAsyncCommand("")
else: else:
return bb.server.process.idleFinish(traceback.format_exc()) self.finishAsyncCommand(traceback.format_exc())
return False
def finishAsyncCommand(self, msg=None, code=None): def finishAsyncCommand(self, msg=None, code=None):
if msg or msg == "": if msg or msg == "":
@@ -148,8 +152,8 @@ class Command:
bb.event.fire(CommandExit(code), self.cooker.data) bb.event.fire(CommandExit(code), self.cooker.data)
else: else:
bb.event.fire(CommandCompleted(), self.cooker.data) bb.event.fire(CommandCompleted(), self.cooker.data)
self.currentAsyncCommand = None
self.cooker.finishcommand() self.cooker.finishcommand()
self.process_server.clear_async_cmd()
def reset(self): def reset(self):
if self.remotedatastores: if self.remotedatastores:
@@ -162,14 +166,6 @@ class CommandsSync:
These must not influence any running synchronous command. These must not influence any running synchronous command.
""" """
def ping(self, command, params):
"""
Allow a UI to check the server is still alive
"""
return "Still alive!"
ping.needconfig = False
ping.readonly = True
def stateShutdown(self, command, params): def stateShutdown(self, command, params):
""" """
Trigger cooker 'shutdown' mode Trigger cooker 'shutdown' mode
@@ -307,11 +303,6 @@ class CommandsSync:
return ret return ret
getLayerPriorities.readonly = True getLayerPriorities.readonly = True
def revalidateCaches(self, command, params):
"""Called by UI clients when metadata may have changed"""
command.cooker.revalidateCaches()
parseConfiguration.needconfig = False
def getRecipes(self, command, params): def getRecipes(self, command, params):
try: try:
mc = params[0] mc = params[0]
@@ -420,30 +411,15 @@ class CommandsSync:
return command.cooker.recipecaches[mc].pkg_dp return command.cooker.recipecaches[mc].pkg_dp
getDefaultPreference.readonly = True getDefaultPreference.readonly = True
def getSkippedRecipes(self, command, params): def getSkippedRecipes(self, command, params):
"""
Get the map of skipped recipes for the specified multiconfig/mc name (`params[0]`).
Invoked by `bb.tinfoil.Tinfoil.get_skipped_recipes`
:param command: Internally used parameter.
:param params: Parameter array. params[0] is multiconfig/mc name. If not given, then default mc '' is assumed.
:return: Dict whose keys are virtualfns and values are `bb.cooker.SkippedPackage`
"""
try:
mc = params[0]
except IndexError:
mc = ''
# Return list sorted by reverse priority order # Return list sorted by reverse priority order
import bb.cache import bb.cache
def sortkey(x): def sortkey(x):
vfn, _ = x vfn, _ = x
realfn, _, item_mc = bb.cache.virtualfn2realfn(vfn) realfn, _, mc = bb.cache.virtualfn2realfn(vfn)
return -command.cooker.collections[item_mc].calc_bbfile_priority(realfn)[0], vfn return (-command.cooker.collections[mc].calc_bbfile_priority(realfn)[0], vfn)
skipdict = OrderedDict(sorted(command.cooker.skiplist_by_mc[mc].items(), key=sortkey)) skipdict = OrderedDict(sorted(command.cooker.skiplist.items(), key=sortkey))
return list(skipdict.items()) return list(skipdict.items())
getSkippedRecipes.readonly = True getSkippedRecipes.readonly = True
@@ -565,8 +541,8 @@ class CommandsSync:
and return a datastore object representing the environment and return a datastore object representing the environment
for the recipe. for the recipe.
""" """
virtualfn = params[0] fn = params[0]
(fn, cls, mc) = bb.cache.virtualfn2realfn(virtualfn) mc = bb.runqueue.mc_from_tid(fn)
appends = params[1] appends = params[1]
appendlist = params[2] appendlist = params[2]
if len(params) > 3: if len(params) > 3:
@@ -581,7 +557,6 @@ class CommandsSync:
appendfiles = command.cooker.collections[mc].get_file_appends(fn) appendfiles = command.cooker.collections[mc].get_file_appends(fn)
else: else:
appendfiles = [] appendfiles = []
layername = command.cooker.collections[mc].calc_bbfile_priority(fn)[2]
# We are calling bb.cache locally here rather than on the server, # We are calling bb.cache locally here rather than on the server,
# but that's OK because it doesn't actually need anything from # but that's OK because it doesn't actually need anything from
# the server barring the global datastore (which we have a remote # the server barring the global datastore (which we have a remote
@@ -589,10 +564,11 @@ class CommandsSync:
if config_data: if config_data:
# We have to use a different function here if we're passing in a datastore # We have to use a different function here if we're passing in a datastore
# NOTE: we took a copy above, so we don't do it here again # NOTE: we took a copy above, so we don't do it here again
envdata = command.cooker.databuilder._parse_recipe(config_data, fn, appendfiles, mc, layername)[cls] envdata = bb.cache.parse_recipe(config_data, fn, appendfiles, mc)['']
else: else:
# Use the standard path # Use the standard path
envdata = command.cooker.databuilder.parseRecipe(virtualfn, appendfiles, layername) parser = bb.cache.NoCache(command.cooker.databuilder)
envdata = parser.loadDataFull(fn, appendfiles)
idx = command.remotedatastores.store(envdata) idx = command.remotedatastores.store(envdata)
return DataStoreConnectionHandle(idx) return DataStoreConnectionHandle(idx)
parseRecipeFile.readonly = True parseRecipeFile.readonly = True
@@ -765,7 +741,7 @@ class CommandsAsync:
""" """
event = params[0] event = params[0]
bb.event.fire(eval(event), command.cooker.data) bb.event.fire(eval(event), command.cooker.data)
process_server.clear_async_cmd() command.currentAsyncCommand = None
triggerEvent.needcache = False triggerEvent.needcache = False
def resetCooker(self, command, params): def resetCooker(self, command, params):
@@ -792,14 +768,7 @@ class CommandsAsync:
(mc, pn) = bb.runqueue.split_mc(params[0]) (mc, pn) = bb.runqueue.split_mc(params[0])
taskname = params[1] taskname = params[1]
sigs = params[2] sigs = params[2]
bb.siggen.check_siggen_version(bb.siggen)
res = bb.siggen.find_siginfo(pn, taskname, sigs, command.cooker.databuilder.mcdata[mc]) res = bb.siggen.find_siginfo(pn, taskname, sigs, command.cooker.databuilder.mcdata[mc])
bb.event.fire(bb.event.FindSigInfoResult(res), command.cooker.databuilder.mcdata[mc]) bb.event.fire(bb.event.FindSigInfoResult(res), command.cooker.databuilder.mcdata[mc])
command.finishAsyncCommand() command.finishAsyncCommand()
findSigInfo.needcache = False findSigInfo.needcache = False
def getTaskSignatures(self, command, params):
res = command.cooker.getTaskSignatures(params[0], params[1])
bb.event.fire(bb.event.GetTaskSignatureResult(res), command.cooker.data)
command.finishAsyncCommand()
getTaskSignatures.needcache = True

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
# Helper library to implement streaming compression and decompression using an # Helper library to implement streaming compression and decompression using an

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #

File diff suppressed because it is too large Load Diff

View File

@@ -160,7 +160,12 @@ def catch_parse_error(func):
def wrapped(fn, *args): def wrapped(fn, *args):
try: try:
return func(fn, *args) return func(fn, *args)
except Exception as exc: except IOError as exc:
import traceback
parselog.critical(traceback.format_exc())
parselog.critical("Unable to parse %s: %s" % (fn, exc))
raise bb.BBHandledException()
except bb.data_smart.ExpansionError as exc:
import traceback import traceback
bbdir = os.path.dirname(__file__) + os.sep bbdir = os.path.dirname(__file__) + os.sep
@@ -172,11 +177,14 @@ def catch_parse_error(func):
break break
parselog.critical("Unable to parse %s" % fn, exc_info=(exc_class, exc, tb)) parselog.critical("Unable to parse %s" % fn, exc_info=(exc_class, exc, tb))
raise bb.BBHandledException() raise bb.BBHandledException()
except bb.parse.ParseError as exc:
parselog.critical(str(exc))
raise bb.BBHandledException()
return wrapped return wrapped
@catch_parse_error @catch_parse_error
def parse_config_file(fn, data, include=True): def parse_config_file(fn, data, include=True):
return bb.parse.handle(fn, data, include, baseconfig=True) return bb.parse.handle(fn, data, include)
@catch_parse_error @catch_parse_error
def _inherit(bbclass, data): def _inherit(bbclass, data):
@@ -240,13 +248,12 @@ class CookerDataBuilder(object):
for k in cookercfg.env: for k in cookercfg.env:
self.savedenv.setVar(k, cookercfg.env[k]) self.savedenv.setVar(k, cookercfg.env[k])
if k in bb.data_smart.bitbake_renamed_vars: if k in bb.data_smart.bitbake_renamed_vars:
bb.error('Shell environment variable %s has been renamed to %s' % (k, bb.data_smart.bitbake_renamed_vars[k])) bb.error('Variable %s from the shell environment has been renamed to %s' % (k, bb.data_smart.bitbake_renamed_vars[k]))
bb.fatal("Exiting to allow enviroment variables to be corrected") bb.fatal("Exiting to allow enviroment variables to be corrected")
filtered_keys = bb.utils.approved_variables() filtered_keys = bb.utils.approved_variables()
bb.data.inheritFromOS(self.basedata, self.savedenv, filtered_keys) bb.data.inheritFromOS(self.basedata, self.savedenv, filtered_keys)
self.basedata.setVar("BB_ORIGENV", self.savedenv) self.basedata.setVar("BB_ORIGENV", self.savedenv)
self.basedata.setVar("__bbclasstype", "global")
if worker: if worker:
self.basedata.setVar("BB_WORKERCONTEXT", "1") self.basedata.setVar("BB_WORKERCONTEXT", "1")
@@ -255,7 +262,6 @@ class CookerDataBuilder(object):
self.mcdata = {} self.mcdata = {}
def parseBaseConfiguration(self, worker=False): def parseBaseConfiguration(self, worker=False):
mcdata = {}
data_hash = hashlib.sha256() data_hash = hashlib.sha256()
try: try:
self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles) self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
@@ -263,6 +269,7 @@ class CookerDataBuilder(object):
if self.data.getVar("BB_WORKERCONTEXT", False) is None and not worker: if self.data.getVar("BB_WORKERCONTEXT", False) is None and not worker:
bb.fetch.fetcher_init(self.data) bb.fetch.fetcher_init(self.data)
bb.parse.init_parser(self.data) bb.parse.init_parser(self.data)
bb.codeparser.parser_cache_init(self.data)
bb.event.fire(bb.event.ConfigParsed(), self.data) bb.event.fire(bb.event.ConfigParsed(), self.data)
@@ -280,25 +287,29 @@ class CookerDataBuilder(object):
bb.parse.init_parser(self.data) bb.parse.init_parser(self.data)
data_hash.update(self.data.get_hash().encode('utf-8')) data_hash.update(self.data.get_hash().encode('utf-8'))
mcdata[''] = self.data self.mcdata[''] = self.data
multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split() multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
for config in multiconfig: for config in multiconfig:
if config[0].isdigit(): if config[0].isdigit():
bb.fatal("Multiconfig name '%s' is invalid as multiconfigs cannot start with a digit" % config) bb.fatal("Multiconfig name '%s' is invalid as multiconfigs cannot start with a digit" % config)
parsed_mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config) mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
bb.event.fire(bb.event.ConfigParsed(), parsed_mcdata) bb.event.fire(bb.event.ConfigParsed(), mcdata)
mcdata[config] = parsed_mcdata self.mcdata[config] = mcdata
data_hash.update(parsed_mcdata.get_hash().encode('utf-8')) data_hash.update(mcdata.get_hash().encode('utf-8'))
if multiconfig: if multiconfig:
bb.event.fire(bb.event.MultiConfigParsed(mcdata), self.data) bb.event.fire(bb.event.MultiConfigParsed(self.mcdata), self.data)
self.data_hash = data_hash.hexdigest() self.data_hash = data_hash.hexdigest()
except (SyntaxError, bb.BBHandledException):
raise bb.BBHandledException()
except bb.data_smart.ExpansionError as e: except bb.data_smart.ExpansionError as e:
logger.error(str(e)) logger.error(str(e))
raise bb.BBHandledException() raise bb.BBHandledException()
except Exception:
logger.exception("Error parsing configuration files")
raise bb.BBHandledException()
bb.codeparser.update_module_dependencies(self.data)
# Handle obsolete variable names # Handle obsolete variable names
d = self.data d = self.data
@@ -319,23 +330,17 @@ class CookerDataBuilder(object):
if issues: if issues:
raise bb.BBHandledException() raise bb.BBHandledException()
for mc in mcdata:
mcdata[mc].renameVar("__depends", "__base_depends")
mcdata[mc].setVar("__bbclasstype", "recipe")
# Create a copy so we can reset at a later date when UIs disconnect # Create a copy so we can reset at a later date when UIs disconnect
self.mcorigdata = mcdata self.origdata = self.data
for mc in mcdata: self.data = bb.data.createCopy(self.origdata)
self.mcdata[mc] = bb.data.createCopy(mcdata[mc]) self.mcdata[''] = self.data
self.data = self.mcdata['']
def reset(self): def reset(self):
# We may not have run parseBaseConfiguration() yet # We may not have run parseBaseConfiguration() yet
if not hasattr(self, 'mcorigdata'): if not hasattr(self, 'origdata'):
return return
for mc in self.mcorigdata: self.data = bb.data.createCopy(self.origdata)
self.mcdata[mc] = bb.data.createCopy(self.mcorigdata[mc]) self.mcdata[''] = self.data
self.data = self.mcdata['']
def _findLayerConf(self, data): def _findLayerConf(self, data):
return findConfigFile("bblayers.conf", data) return findConfigFile("bblayers.conf", data)
@@ -350,17 +355,12 @@ class CookerDataBuilder(object):
layerconf = self._findLayerConf(data) layerconf = self._findLayerConf(data)
if layerconf: if layerconf:
parselog.debug2("Found bblayers.conf (%s)", layerconf) parselog.debug(2, "Found bblayers.conf (%s)", layerconf)
# By definition bblayers.conf is in conf/ of TOPDIR. # By definition bblayers.conf is in conf/ of TOPDIR.
# We may have been called with cwd somewhere else so reset TOPDIR # We may have been called with cwd somewhere else so reset TOPDIR
data.setVar("TOPDIR", os.path.dirname(os.path.dirname(layerconf))) data.setVar("TOPDIR", os.path.dirname(os.path.dirname(layerconf)))
data = parse_config_file(layerconf, data) data = parse_config_file(layerconf, data)
if not data.getVar("BB_CACHEDIR"):
data.setVar("BB_CACHEDIR", "${TOPDIR}/cache")
bb.codeparser.parser_cache_init(data.getVar("BB_CACHEDIR"))
layers = (data.getVar('BBLAYERS') or "").split() layers = (data.getVar('BBLAYERS') or "").split()
broken_layers = [] broken_layers = []
@@ -382,10 +382,8 @@ class CookerDataBuilder(object):
parselog.critical("Please check BBLAYERS in %s" % (layerconf)) parselog.critical("Please check BBLAYERS in %s" % (layerconf))
raise bb.BBHandledException() raise bb.BBHandledException()
layerseries = None
compat_entries = {}
for layer in layers: for layer in layers:
parselog.debug2("Adding layer %s", layer) parselog.debug(2, "Adding layer %s", layer)
if 'HOME' in approved and '~' in layer: if 'HOME' in approved and '~' in layer:
layer = os.path.expanduser(layer) layer = os.path.expanduser(layer)
if layer.endswith('/'): if layer.endswith('/'):
@@ -396,27 +394,8 @@ class CookerDataBuilder(object):
data.expandVarref('LAYERDIR') data.expandVarref('LAYERDIR')
data.expandVarref('LAYERDIR_RE') data.expandVarref('LAYERDIR_RE')
# Sadly we can't have nice things.
# Some layers think they're going to be 'clever' and copy the values from
# another layer, e.g. using ${LAYERSERIES_COMPAT_core}. The whole point of
# this mechanism is to make it clear which releases a layer supports and
# show when a layer master branch is bitrotting and is unmaintained.
# We therefore avoid people doing this here.
collections = (data.getVar('BBFILE_COLLECTIONS') or "").split()
for c in collections:
compat_entry = data.getVar("LAYERSERIES_COMPAT_%s" % c)
if compat_entry:
compat_entries[c] = set(compat_entry.split())
data.delVar("LAYERSERIES_COMPAT_%s" % c)
if not layerseries:
layerseries = set((data.getVar("LAYERSERIES_CORENAMES") or "").split())
if layerseries:
data.delVar("LAYERSERIES_CORENAMES")
data.delVar('LAYERDIR_RE') data.delVar('LAYERDIR_RE')
data.delVar('LAYERDIR') data.delVar('LAYERDIR')
for c in compat_entries:
data.setVar("LAYERSERIES_COMPAT_%s" % c, " ".join(sorted(compat_entries[c])))
bbfiles_dynamic = (data.getVar('BBFILES_DYNAMIC') or "").split() bbfiles_dynamic = (data.getVar('BBFILES_DYNAMIC') or "").split()
collections = (data.getVar('BBFILE_COLLECTIONS') or "").split() collections = (data.getVar('BBFILE_COLLECTIONS') or "").split()
@@ -435,15 +414,13 @@ class CookerDataBuilder(object):
if invalid: if invalid:
bb.fatal("BBFILES_DYNAMIC entries must be of the form {!}<collection name>:<filename pattern>, not:\n %s" % "\n ".join(invalid)) bb.fatal("BBFILES_DYNAMIC entries must be of the form {!}<collection name>:<filename pattern>, not:\n %s" % "\n ".join(invalid))
layerseries = set((data.getVar("LAYERSERIES_CORENAMES") or "").split())
collections_tmp = collections[:] collections_tmp = collections[:]
for c in collections: for c in collections:
collections_tmp.remove(c) collections_tmp.remove(c)
if c in collections_tmp: if c in collections_tmp:
bb.fatal("Found duplicated BBFILE_COLLECTIONS '%s', check bblayers.conf or layer.conf to fix it." % c) bb.fatal("Found duplicated BBFILE_COLLECTIONS '%s', check bblayers.conf or layer.conf to fix it." % c)
compat = set((data.getVar("LAYERSERIES_COMPAT_%s" % c) or "").split())
compat = set()
if c in compat_entries:
compat = compat_entries[c]
if compat and not layerseries: if compat and not layerseries:
bb.fatal("No core layer found to work with layer '%s'. Missing entry in bblayers.conf?" % c) bb.fatal("No core layer found to work with layer '%s'. Missing entry in bblayers.conf?" % c)
if compat and not (compat & layerseries): if compat and not (compat & layerseries):
@@ -452,21 +429,16 @@ class CookerDataBuilder(object):
elif not compat and not data.getVar("BB_WORKERCONTEXT"): elif not compat and not data.getVar("BB_WORKERCONTEXT"):
bb.warn("Layer %s should set LAYERSERIES_COMPAT_%s in its conf/layer.conf file to list the core layer names it is compatible with." % (c, c)) bb.warn("Layer %s should set LAYERSERIES_COMPAT_%s in its conf/layer.conf file to list the core layer names it is compatible with." % (c, c))
data.setVar("LAYERSERIES_CORENAMES", " ".join(sorted(layerseries)))
if not data.getVar("BBPATH"): if not data.getVar("BBPATH"):
msg = "The BBPATH variable is not set" msg = "The BBPATH variable is not set"
if not layerconf: if not layerconf:
msg += (" and bitbake did not find a conf/bblayers.conf file in" msg += (" and bitbake did not find a conf/bblayers.conf file in"
" the expected location.\nMaybe you accidentally" " the expected location.\nMaybe you accidentally"
" invoked bitbake from the wrong directory?") " invoked bitbake from the wrong directory?")
bb.fatal(msg) raise SystemExit(msg)
if not data.getVar("TOPDIR"): if not data.getVar("TOPDIR"):
data.setVar("TOPDIR", os.path.abspath(os.getcwd())) data.setVar("TOPDIR", os.path.abspath(os.getcwd()))
if not data.getVar("BB_CACHEDIR"):
data.setVar("BB_CACHEDIR", "${TOPDIR}/cache")
bb.codeparser.parser_cache_init(data.getVar("BB_CACHEDIR"))
data = parse_config_file(os.path.join("conf", "bitbake.conf"), data) data = parse_config_file(os.path.join("conf", "bitbake.conf"), data)
@@ -493,54 +465,3 @@ class CookerDataBuilder(object):
return data return data
@staticmethod
def _parse_recipe(bb_data, bbfile, appends, mc, layername):
bb_data.setVar("__BBMULTICONFIG", mc)
bb_data.setVar("FILE_LAYERNAME", layername)
bbfile_loc = os.path.abspath(os.path.dirname(bbfile))
bb.parse.cached_mtime_noerror(bbfile_loc)
if appends:
bb_data.setVar('__BBAPPEND', " ".join(appends))
return bb.parse.handle(bbfile, bb_data)
def parseRecipeVariants(self, bbfile, appends, virtonly=False, mc=None, layername=None):
"""
Load and parse one .bb build file
Return the data and whether parsing resulted in the file being skipped
"""
if virtonly:
(bbfile, virtual, mc) = bb.cache.virtualfn2realfn(bbfile)
bb_data = self.mcdata[mc].createCopy()
bb_data.setVar("__ONLYFINALISE", virtual or "default")
return self._parse_recipe(bb_data, bbfile, appends, mc, layername)
if mc is not None:
bb_data = self.mcdata[mc].createCopy()
return self._parse_recipe(bb_data, bbfile, appends, mc, layername)
bb_data = self.data.createCopy()
datastores = self._parse_recipe(bb_data, bbfile, appends, '', layername)
for mc in self.mcdata:
if not mc:
continue
bb_data = self.mcdata[mc].createCopy()
newstores = self._parse_recipe(bb_data, bbfile, appends, mc, layername)
for ns in newstores:
datastores["mc:%s:%s" % (mc, ns)] = newstores[ns]
return datastores
def parseRecipe(self, virtualfn, appends, layername):
"""
Return a complete set of data for fn.
To do this, we need to parse the file.
"""
logger.debug("Parsing %s (full)" % virtualfn)
(fn, virtual, mc) = bb.cache.virtualfn2realfn(virtualfn)
datastores = self.parseRecipeVariants(virtualfn, appends, virtonly=True, layername=layername)
return datastores[virtual]

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #

View File

@@ -4,16 +4,14 @@ BitBake 'Data' implementations
Functions for interacting with the data structure used by the Functions for interacting with the data structure used by the
BitBake build tools. BitBake build tools.
expandKeys and datastore iteration are the most expensive The expandKeys and update_data are the most expensive
operations. Updating overrides is now "on the fly" but still based operations. At night the cookie monster came by and
on the idea of the cookie monster introduced by zecke:
"At night the cookie monster came by and
suggested 'give me cookies on setting the variables and suggested 'give me cookies on setting the variables and
things will work out'. Taking this suggestion into account things will work out'. Taking this suggestion into account
applying the skills from the not yet passed 'Entwurf und applying the skills from the not yet passed 'Entwurf und
Analyse von Algorithmen' lecture and the cookie Analyse von Algorithmen' lecture and the cookie
monster seems to be right. We will track setVar more carefully monster seems to be right. We will track setVar more carefully
to have faster datastore operations." to have faster update_data and expandKeys operations.
This is a trade-off between speed and memory again but This is a trade-off between speed and memory again but
the speed is more critical here. the speed is more critical here.
@@ -28,6 +26,11 @@ the speed is more critical here.
import sys, os, re import sys, os, re
import hashlib import hashlib
if sys.argv[0][-5:] == "pydoc":
path = os.path.dirname(os.path.dirname(sys.argv[1]))
else:
path = os.path.dirname(os.path.dirname(sys.argv[0]))
sys.path.insert(0, path)
from itertools import groupby from itertools import groupby
from bb import data_smart from bb import data_smart
@@ -67,6 +70,10 @@ def keys(d):
"""Return a list of keys in d""" """Return a list of keys in d"""
return d.keys() return d.keys()
__expand_var_regexp__ = re.compile(r"\${[^{}]+}")
__expand_python_regexp__ = re.compile(r"\${@.+?}")
def expand(s, d, varname = None): def expand(s, d, varname = None):
"""Variable expansion using the data store""" """Variable expansion using the data store"""
return d.expand(s, varname) return d.expand(s, varname)
@@ -114,8 +121,8 @@ def emit_var(var, o=sys.__stdout__, d = init(), all=False):
if d.getVarFlag(var, 'python', False) and func: if d.getVarFlag(var, 'python', False) and func:
return False return False
export = bb.utils.to_boolean(d.getVarFlag(var, "export")) export = d.getVarFlag(var, "export", False)
unexport = bb.utils.to_boolean(d.getVarFlag(var, "unexport")) unexport = d.getVarFlag(var, "unexport", False)
if not all and not export and not unexport and not func: if not all and not export and not unexport and not func:
return False return False
@@ -188,8 +195,8 @@ def emit_env(o=sys.__stdout__, d = init(), all=False):
def exported_keys(d): def exported_keys(d):
return (key for key in d.keys() if not key.startswith('__') and return (key for key in d.keys() if not key.startswith('__') and
bb.utils.to_boolean(d.getVarFlag(key, 'export')) and d.getVarFlag(key, 'export', False) and
not bb.utils.to_boolean(d.getVarFlag(key, 'unexport'))) not d.getVarFlag(key, 'unexport', False))
def exported_vars(d): def exported_vars(d):
k = list(exported_keys(d)) k = list(exported_keys(d))
@@ -261,7 +268,23 @@ def emit_func_python(func, o=sys.__stdout__, d = init()):
newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split()) newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
newdeps -= seen newdeps -= seen
def build_dependencies(key, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d, codeparsedata): def update_data(d):
"""Performs final steps upon the datastore, including application of overrides"""
d.finalize(parent = True)
def build_dependencies(key, keys, shelldeps, varflagsexcl, ignored_vars, d):
deps = set()
try:
if key[-1] == ']':
vf = key[:-1].split('[')
value, parser = d.getVarFlag(vf[0], vf[1], False, retparser=True)
deps |= parser.references
deps = deps | (keys & parser.execs)
return deps, value
varflags = d.getVarFlags(key, ["vardeps", "vardepvalue", "vardepsexclude", "exports", "postfuncs", "prefuncs", "lineno", "filename"]) or {}
vardeps = varflags.get("vardeps")
exclusions = varflags.get("vardepsexclude", "").split()
def handle_contains(value, contains, exclusions, d): def handle_contains(value, contains, exclusions, d):
newvalue = [] newvalue = []
if value: if value:
@@ -285,42 +308,20 @@ def build_dependencies(key, keys, mod_funcs, shelldeps, varflagsexcl, ignored_va
value += "\n_remove of %s" % r value += "\n_remove of %s" % r
deps |= r2.references deps |= r2.references
deps = deps | (keys & r2.execs) deps = deps | (keys & r2.execs)
value = handle_contains(value, r2.contains, exclusions, d)
return value return value
deps = set()
try:
if key in mod_funcs:
exclusions = set()
moddep = bb.codeparser.modulecode_deps[key]
value = handle_contains(moddep[4], moddep[3], exclusions, d)
return frozenset((moddep[0] | keys & moddep[1]) - ignored_vars), value
if key[-1] == ']':
vf = key[:-1].split('[')
if vf[1] == "vardepvalueexclude":
return deps, ""
value, parser = d.getVarFlag(vf[0], vf[1], False, retparser=True)
deps |= parser.references
deps = deps | (keys & parser.execs)
deps -= ignored_vars
return frozenset(deps), value
varflags = d.getVarFlags(key, ["vardeps", "vardepvalue", "vardepsexclude", "exports", "postfuncs", "prefuncs", "lineno", "filename"]) or {}
vardeps = varflags.get("vardeps")
exclusions = varflags.get("vardepsexclude", "").split()
if "vardepvalue" in varflags: if "vardepvalue" in varflags:
value = varflags.get("vardepvalue") value = varflags.get("vardepvalue")
elif varflags.get("func"): elif varflags.get("func"):
if varflags.get("python"): if varflags.get("python"):
value = codeparsedata.getVarFlag(key, "_content", False) value = d.getVarFlag(key, "_content", False)
parser = bb.codeparser.PythonParser(key, logger) parser = bb.codeparser.PythonParser(key, logger)
parser.parse_python(value, filename=varflags.get("filename"), lineno=varflags.get("lineno")) parser.parse_python(value, filename=varflags.get("filename"), lineno=varflags.get("lineno"))
deps = deps | parser.references deps = deps | parser.references
deps = deps | (keys & parser.execs) deps = deps | (keys & parser.execs)
value = handle_contains(value, parser.contains, exclusions, d) value = handle_contains(value, parser.contains, exclusions, d)
else: else:
value, parsedvar = codeparsedata.getVarFlag(key, "_content", False, retparser=True) value, parsedvar = d.getVarFlag(key, "_content", False, retparser=True)
parser = bb.codeparser.ShellParser(key, logger) parser = bb.codeparser.ShellParser(key, logger)
parser.parse_shell(parsedvar.value) parser.parse_shell(parsedvar.value)
deps = deps | shelldeps deps = deps | shelldeps
@@ -362,43 +363,36 @@ def build_dependencies(key, keys, mod_funcs, shelldeps, varflagsexcl, ignored_va
deps |= set((vardeps or "").split()) deps |= set((vardeps or "").split())
deps -= set(exclusions) deps -= set(exclusions)
deps -= ignored_vars
except bb.parse.SkipRecipe: except bb.parse.SkipRecipe:
raise raise
except Exception as e: except Exception as e:
bb.warn("Exception during build_dependencies for %s" % key) bb.warn("Exception during build_dependencies for %s" % key)
raise raise
return frozenset(deps), value return deps, value
#bb.note("Variable %s references %s and calls %s" % (key, str(deps), str(execs))) #bb.note("Variable %s references %s and calls %s" % (key, str(deps), str(execs)))
#d.setVarFlag(key, "vardeps", deps) #d.setVarFlag(key, "vardeps", deps)
def generate_dependencies(d, ignored_vars): def generate_dependencies(d, ignored_vars):
mod_funcs = set(bb.codeparser.modulecode_deps.keys()) keys = set(key for key in d if not key.startswith("__"))
keys = set(key for key in d if not key.startswith("__")) | mod_funcs shelldeps = set(key for key in d.getVar("__exportlist", False) if d.getVarFlag(key, "export", False) and not d.getVarFlag(key, "unexport", False))
shelldeps = set(key for key in d.getVar("__exportlist", False) if bb.utils.to_boolean(d.getVarFlag(key, "export")) and not bb.utils.to_boolean(d.getVarFlag(key, "unexport"))) varflagsexcl = d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS')
varflagsexcl = (d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS') or "").split()
codeparserd = d.createCopy()
for forced in (d.getVar('BB_HASH_CODEPARSER_VALS') or "").split():
key, value = forced.split("=", 1)
codeparserd.setVar(key, value)
deps = {} deps = {}
values = {} values = {}
tasklist = d.getVar('__BBTASKS', False) or [] tasklist = d.getVar('__BBTASKS', False) or []
for task in tasklist: for task in tasklist:
deps[task], values[task] = build_dependencies(task, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d, codeparserd) deps[task], values[task] = build_dependencies(task, keys, shelldeps, varflagsexcl, ignored_vars, d)
newdeps = deps[task] newdeps = deps[task]
seen = set() seen = set()
while newdeps: while newdeps:
nextdeps = newdeps nextdeps = newdeps - ignored_vars
seen |= nextdeps seen |= nextdeps
newdeps = set() newdeps = set()
for dep in nextdeps: for dep in nextdeps:
if dep not in deps: if dep not in deps:
deps[dep], values[dep] = build_dependencies(dep, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d, codeparserd) deps[dep], values[dep] = build_dependencies(dep, keys, shelldeps, varflagsexcl, ignored_vars, d)
newdeps |= deps[dep] newdeps |= deps[dep]
newdeps -= seen newdeps -= seen
#print "For %s: %s" % (task, str(deps[task])) #print "For %s: %s" % (task, str(deps[task]))
@@ -417,6 +411,7 @@ def generate_dependency_hash(tasklist, gendeps, lookupcache, ignored_vars, fn):
else: else:
data = [data] data = [data]
gendeps[task] -= ignored_vars
newdeps = gendeps[task] newdeps = gendeps[task]
seen = set() seen = set()
while newdeps: while newdeps:
@@ -424,6 +419,9 @@ def generate_dependency_hash(tasklist, gendeps, lookupcache, ignored_vars, fn):
seen |= nextdeps seen |= nextdeps
newdeps = set() newdeps = set()
for dep in nextdeps: for dep in nextdeps:
if dep in ignored_vars:
continue
gendeps[dep] -= ignored_vars
newdeps |= gendeps[dep] newdeps |= gendeps[dep]
newdeps -= seen newdeps -= seen
@@ -435,13 +433,13 @@ def generate_dependency_hash(tasklist, gendeps, lookupcache, ignored_vars, fn):
data.append(str(var)) data.append(str(var))
k = fn + ":" + task k = fn + ":" + task
basehash[k] = hashlib.sha256("".join(data).encode("utf-8")).hexdigest() basehash[k] = hashlib.sha256("".join(data).encode("utf-8")).hexdigest()
taskdeps[task] = frozenset(seen) taskdeps[task] = alldeps
return taskdeps, basehash return taskdeps, basehash
def inherits_class(klass, d): def inherits_class(klass, d):
val = d.getVar('__inherit_cache', False) or [] val = d.getVar('__inherit_cache', False) or []
needle = '/%s.bbclass' % klass needle = os.path.join('classes', '%s.bbclass' % klass)
for v in val: for v in val:
if v.endswith(needle): if v.endswith(needle):
return True return True

View File

@@ -16,10 +16,7 @@ BitBake build tools.
# #
# Based on functions from the base bb module, Copyright 2003 Holger Schurig # Based on functions from the base bb module, Copyright 2003 Holger Schurig
import builtins import copy, re, sys, traceback
import copy
import re
import sys
from collections.abc import MutableMapping from collections.abc import MutableMapping
import logging import logging
import hashlib import hashlib
@@ -31,8 +28,8 @@ logger = logging.getLogger("BitBake.Data")
__setvar_keyword__ = [":append", ":prepend", ":remove"] __setvar_keyword__ = [":append", ":prepend", ":remove"]
__setvar_regexp__ = re.compile(r'(?P<base>.*?)(?P<keyword>:append|:prepend|:remove)(:(?P<add>[^A-Z]*))?$') __setvar_regexp__ = re.compile(r'(?P<base>.*?)(?P<keyword>:append|:prepend|:remove)(:(?P<add>[^A-Z]*))?$')
__expand_var_regexp__ = re.compile(r"\${[a-zA-Z0-9\-_+./~:]+}") __expand_var_regexp__ = re.compile(r"\${[a-zA-Z0-9\-_+./~:]+?}")
__expand_python_regexp__ = re.compile(r"\${@(?:{.*?}|.)+?}") __expand_python_regexp__ = re.compile(r"\${@.+?}")
__whitespace_split__ = re.compile(r'(\s)') __whitespace_split__ = re.compile(r'(\s)')
__override_regexp__ = re.compile(r'[a-z0-9]+') __override_regexp__ = re.compile(r'[a-z0-9]+')
@@ -95,11 +92,10 @@ def infer_caller_details(loginfo, parent = False, varval = True):
loginfo['func'] = func loginfo['func'] = func
class VariableParse: class VariableParse:
def __init__(self, varname, d, unexpanded_value = None, val = None): def __init__(self, varname, d, val = None):
self.varname = varname self.varname = varname
self.d = d self.d = d
self.value = val self.value = val
self.unexpanded_value = unexpanded_value
self.references = set() self.references = set()
self.execs = set() self.execs = set()
@@ -123,11 +119,6 @@ class VariableParse:
else: else:
code = match.group()[3:-1] code = match.group()[3:-1]
# Do not run code that contains one or more unexpanded variables
# instead return the code with the characters we removed put back
if __expand_var_regexp__.findall(code):
return "${@" + code + "}"
if self.varname: if self.varname:
varname = 'Var <%s>' % self.varname varname = 'Var <%s>' % self.varname
else: else:
@@ -153,21 +144,19 @@ class VariableParse:
value = utils.better_eval(codeobj, DataContext(self.d), {'d' : self.d}) value = utils.better_eval(codeobj, DataContext(self.d), {'d' : self.d})
return str(value) return str(value)
class DataContext(dict):
excluded = set([i for i in dir(builtins) if not i.startswith('_')] + ['oe'])
class DataContext(dict):
def __init__(self, metadata, **kwargs): def __init__(self, metadata, **kwargs):
self.metadata = metadata self.metadata = metadata
dict.__init__(self, **kwargs) dict.__init__(self, **kwargs)
self['d'] = metadata self['d'] = metadata
self.context = set(bb.utils.get_context())
def __missing__(self, key): def __missing__(self, key):
if key in self.excluded or key in self.context: # Skip commonly accessed invalid variables
if key in ['bb', 'oe', 'int', 'bool', 'time', 'str', 'os']:
raise KeyError(key) raise KeyError(key)
value = self.metadata.getVar(key) value = self.metadata.getVar(key)
if value is None: if value is None or self.metadata.getVarFlag(key, 'func', False):
raise KeyError(key) raise KeyError(key)
else: else:
return value return value
@@ -272,9 +261,12 @@ class VariableHistory(object):
return return
if 'op' not in loginfo or not loginfo['op']: if 'op' not in loginfo or not loginfo['op']:
loginfo['op'] = 'set' loginfo['op'] = 'set'
if 'detail' in loginfo:
loginfo['detail'] = str(loginfo['detail'])
if 'variable' not in loginfo or 'file' not in loginfo: if 'variable' not in loginfo or 'file' not in loginfo:
raise ValueError("record() missing variable or file.") raise ValueError("record() missing variable or file.")
var = loginfo['variable'] var = loginfo['variable']
if var not in self.variables: if var not in self.variables:
self.variables[var] = [] self.variables[var] = []
if not isinstance(self.variables[var], list): if not isinstance(self.variables[var], list):
@@ -333,8 +325,7 @@ class VariableHistory(object):
flag = '[%s] ' % (event['flag']) flag = '[%s] ' % (event['flag'])
else: else:
flag = '' flag = ''
o.write("# %s %s:%s%s\n# %s\"%s\"\n" % \ o.write("# %s %s:%s%s\n# %s\"%s\"\n" % (event['op'], event['file'], event['line'], display_func, flag, re.sub('\n', '\n# ', event['detail'])))
(event['op'], event['file'], event['line'], display_func, flag, re.sub('\n', '\n# ', str(event['detail']))))
if len(history) > 1: if len(history) > 1:
o.write("# pre-expansion value:\n") o.write("# pre-expansion value:\n")
o.write('# "%s"\n' % (commentVal)) o.write('# "%s"\n' % (commentVal))
@@ -388,7 +379,7 @@ class VariableHistory(object):
if isset and event['op'] == 'set?': if isset and event['op'] == 'set?':
continue continue
isset = True isset = True
items = d.expand(str(event['detail'])).split() items = d.expand(event['detail']).split()
for item in items: for item in items:
# This is a little crude but is belt-and-braces to avoid us # This is a little crude but is belt-and-braces to avoid us
# having to handle every possible operation type specifically # having to handle every possible operation type specifically
@@ -451,9 +442,9 @@ class DataSmart(MutableMapping):
def expandWithRefs(self, s, varname): def expandWithRefs(self, s, varname):
if not isinstance(s, str): # sanity check if not isinstance(s, str): # sanity check
return VariableParse(varname, self, s, s) return VariableParse(varname, self, s)
varparse = VariableParse(varname, self, s) varparse = VariableParse(varname, self)
while s.find('${') != -1: while s.find('${') != -1:
olds = s olds = s
@@ -485,19 +476,24 @@ class DataSmart(MutableMapping):
def expand(self, s, varname = None): def expand(self, s, varname = None):
return self.expandWithRefs(s, varname).value return self.expandWithRefs(s, varname).value
def finalize(self, parent = False):
return
def internal_finalize(self, parent = False):
"""Performs final steps upon the datastore, including application of overrides"""
self.overrides = None
def need_overrides(self): def need_overrides(self):
if self.overrides is not None: if self.overrides is not None:
return return
if self.inoverride: if self.inoverride:
return return
overrride_stack = []
for count in range(5): for count in range(5):
self.inoverride = True self.inoverride = True
# Can end up here recursively so setup dummy values # Can end up here recursively so setup dummy values
self.overrides = [] self.overrides = []
self.overridesset = set() self.overridesset = set()
self.overrides = (self.getVar("OVERRIDES") or "").split(":") or [] self.overrides = (self.getVar("OVERRIDES") or "").split(":") or []
overrride_stack.append(self.overrides)
self.overridesset = set(self.overrides) self.overridesset = set(self.overrides)
self.inoverride = False self.inoverride = False
self.expand_cache = {} self.expand_cache = {}
@@ -507,7 +503,7 @@ class DataSmart(MutableMapping):
self.overrides = newoverrides self.overrides = newoverrides
self.overridesset = set(self.overrides) self.overridesset = set(self.overrides)
else: else:
bb.fatal("Overrides could not be expanded into a stable state after 5 iterations, overrides must be being referenced by other overridden variables in some recursive fashion. Please provide your configuration to bitbake-devel so we can laugh, er, I mean try and understand how to make it work. The list of failing override expansions: %s" % "\n".join(str(s) for s in overrride_stack)) bb.fatal("Overrides could not be expanded into a stable state after 5 iterations, overrides must be being referenced by other overridden variables in some recursive fashion. Please provide your configuration to bitbake-devel so we can laugh, er, I mean try and understand how to make it work.")
def initVar(self, var): def initVar(self, var):
self.expand_cache = {} self.expand_cache = {}
@@ -518,18 +514,18 @@ class DataSmart(MutableMapping):
dest = self.dict dest = self.dict
while dest: while dest:
if var in dest: if var in dest:
return dest[var] return dest[var], self.overridedata.get(var, None)
if "_data" not in dest: if "_data" not in dest:
break break
dest = dest["_data"] dest = dest["_data"]
return None return None, self.overridedata.get(var, None)
def _makeShadowCopy(self, var): def _makeShadowCopy(self, var):
if var in self.dict: if var in self.dict:
return return
local_var = self._findVar(var) local_var, _ = self._findVar(var)
if local_var: if local_var:
self.dict[var] = copy.copy(local_var) self.dict[var] = copy.copy(local_var)
@@ -580,8 +576,11 @@ class DataSmart(MutableMapping):
else: else:
loginfo['op'] = keyword loginfo['op'] = keyword
self.varhistory.record(**loginfo) self.varhistory.record(**loginfo)
# todo make sure keyword is not __doc__ or __module__
# pay the cookie monster
# more cookies for the cookie monster # more cookies for the cookie monster
if ':' in var:
self._setvar_update_overrides(base, **loginfo) self._setvar_update_overrides(base, **loginfo)
if base in self.overridevars: if base in self.overridevars:
@@ -634,8 +633,7 @@ class DataSmart(MutableMapping):
nextnew.update(vardata.references) nextnew.update(vardata.references)
nextnew.update(vardata.contains.keys()) nextnew.update(vardata.contains.keys())
new = nextnew new = nextnew
self.overrides = None self.internal_finalize(True)
self.expand_cache = {}
def _setvar_update_overrides(self, var, **loginfo): def _setvar_update_overrides(self, var, **loginfo):
# aka pay the cookie monster # aka pay the cookie monster
@@ -722,7 +720,7 @@ class DataSmart(MutableMapping):
if ':' in var: if ':' in var:
override = var[var.rfind(':')+1:] override = var[var.rfind(':')+1:]
shortvar = var[:var.rfind(':')] shortvar = var[:var.rfind(':')]
while override and __override_regexp__.match(override): while override and override.islower():
try: try:
if shortvar in self.overridedata: if shortvar in self.overridedata:
# Force CoW by recreating the list first # Force CoW by recreating the list first
@@ -777,18 +775,13 @@ class DataSmart(MutableMapping):
return None return None
cachename = var + "[" + flag + "]" cachename = var + "[" + flag + "]"
if not expand and retparser and cachename in self.expand_cache:
return self.expand_cache[cachename].unexpanded_value, self.expand_cache[cachename]
if expand and cachename in self.expand_cache: if expand and cachename in self.expand_cache:
return self.expand_cache[cachename].value return self.expand_cache[cachename].value
local_var = self._findVar(var) local_var, overridedata = self._findVar(var)
value = None value = None
removes = set() removes = set()
if flag == "_content" and not parsing: if flag == "_content" and overridedata is not None and not parsing:
overridedata = self.overridedata.get(var, None)
if flag == "_content" and not parsing and overridedata is not None:
match = False match = False
active = {} active = {}
self.need_overrides() self.need_overrides()
@@ -903,7 +896,7 @@ class DataSmart(MutableMapping):
def delVarFlag(self, var, flag, **loginfo): def delVarFlag(self, var, flag, **loginfo):
self.expand_cache = {} self.expand_cache = {}
local_var = self._findVar(var) local_var, _ = self._findVar(var)
if not local_var: if not local_var:
return return
if not var in self.dict: if not var in self.dict:
@@ -946,7 +939,7 @@ class DataSmart(MutableMapping):
self.dict[var][i] = flags[i] self.dict[var][i] = flags[i]
def getVarFlags(self, var, expand = False, internalflags=False): def getVarFlags(self, var, expand = False, internalflags=False):
local_var = self._findVar(var) local_var, _ = self._findVar(var)
flags = {} flags = {}
if local_var: if local_var:

View File

@@ -19,6 +19,7 @@ import sys
import threading import threading
import traceback import traceback
import bb.exceptions
import bb.utils import bb.utils
# This is the pid for which we should generate the event. This is set when # This is the pid for which we should generate the event. This is set when
@@ -67,39 +68,29 @@ _catchall_handlers = {}
_eventfilter = None _eventfilter = None
_uiready = False _uiready = False
_thread_lock = threading.Lock() _thread_lock = threading.Lock()
_heartbeat_enabled = False _thread_lock_enabled = False
_should_exit = threading.Event()
if hasattr(__builtins__, '__setitem__'):
builtins = __builtins__
else:
builtins = __builtins__.__dict__
def enable_threadlock(): def enable_threadlock():
# Always needed now global _thread_lock_enabled
return _thread_lock_enabled = True
def disable_threadlock(): def disable_threadlock():
# Always needed now global _thread_lock_enabled
return _thread_lock_enabled = False
def enable_heartbeat():
global _heartbeat_enabled
_heartbeat_enabled = True
def disable_heartbeat():
global _heartbeat_enabled
_heartbeat_enabled = False
#
# In long running code, this function should be called periodically
# to check if we should exit due to an interuption (.e.g Ctrl+C from the UI)
#
def check_for_interrupts(d):
global _should_exit
if _should_exit.is_set():
bb.warn("Exiting due to interrupt.")
raise bb.BBHandledException()
def execute_handler(name, handler, event, d): def execute_handler(name, handler, event, d):
event.data = d event.data = d
addedd = False
if 'd' not in builtins:
builtins['d'] = d
addedd = True
try: try:
ret = handler(event, d) ret = handler(event)
except (bb.parse.SkipRecipe, bb.BBHandledException): except (bb.parse.SkipRecipe, bb.BBHandledException):
raise raise
except Exception: except Exception:
@@ -113,7 +104,8 @@ def execute_handler(name, handler, event, d):
raise raise
finally: finally:
del event.data del event.data
if addedd:
del builtins['d']
def fire_class_handlers(event, d): def fire_class_handlers(event, d):
if isinstance(event, logging.LogRecord): if isinstance(event, logging.LogRecord):
@@ -140,14 +132,8 @@ def print_ui_queue():
if not _uiready: if not _uiready:
from bb.msg import BBLogFormatter from bb.msg import BBLogFormatter
# Flush any existing buffered content # Flush any existing buffered content
try:
sys.stdout.flush() sys.stdout.flush()
except:
pass
try:
sys.stderr.flush() sys.stderr.flush()
except:
pass
stdout = logging.StreamHandler(sys.stdout) stdout = logging.StreamHandler(sys.stdout)
stderr = logging.StreamHandler(sys.stderr) stderr = logging.StreamHandler(sys.stderr)
formatter = BBLogFormatter("%(levelname)s: %(message)s") formatter = BBLogFormatter("%(levelname)s: %(message)s")
@@ -188,17 +174,15 @@ def print_ui_queue():
def fire_ui_handlers(event, d): def fire_ui_handlers(event, d):
global _thread_lock global _thread_lock
global _thread_lock_enabled
if not _uiready: if not _uiready:
# No UI handlers registered yet, queue up the messages # No UI handlers registered yet, queue up the messages
ui_queue.append(event) ui_queue.append(event)
return return
with bb.utils.lock_timeout_nocheck(_thread_lock) as lock: if _thread_lock_enabled:
if not lock: _thread_lock.acquire()
# If we can't get the lock, we may be recursively called, queue and return
ui_queue.append(event)
return
errors = [] errors = []
for h in _ui_handlers: for h in _ui_handlers:
@@ -218,8 +202,8 @@ def fire_ui_handlers(event, d):
for h in errors: for h in errors:
del _ui_handlers[h] del _ui_handlers[h]
while ui_queue: if _thread_lock_enabled:
fire_ui_handlers(ui_queue.pop(), d) _thread_lock.release()
def fire(event, d): def fire(event, d):
"""Fire off an Event""" """Fire off an Event"""
@@ -263,16 +247,15 @@ def register(name, handler, mask=None, filename=None, lineno=None, data=None):
if handler is not None: if handler is not None:
# handle string containing python code # handle string containing python code
if isinstance(handler, str): if isinstance(handler, str):
tmp = "def %s(e, d):\n%s" % (name, handler) tmp = "def %s(e):\n%s" % (name, handler)
# Inject empty lines to make code match lineno in filename
if lineno is not None:
tmp = "\n" * (lineno-1) + tmp
try: try:
code = bb.methodpool.compile_cache(tmp) code = bb.methodpool.compile_cache(tmp)
if not code: if not code:
if filename is None: if filename is None:
filename = "%s(e, d)" % name filename = "%s(e)" % name
code = compile(tmp, filename, "exec", ast.PyCF_ONLY_AST) code = compile(tmp, filename, "exec", ast.PyCF_ONLY_AST)
if lineno is not None:
ast.increment_lineno(code, lineno-1)
code = compile(code, filename, "exec") code = compile(code, filename, "exec")
bb.methodpool.compile_cache_add(tmp, code) bb.methodpool.compile_cache_add(tmp, code)
except SyntaxError: except SyntaxError:
@@ -334,7 +317,6 @@ def set_eventfilter(func):
_eventfilter = func _eventfilter = func
def register_UIHhandler(handler, mainui=False): def register_UIHhandler(handler, mainui=False):
with bb.utils.lock_timeout(_thread_lock):
bb.event._ui_handler_seq = bb.event._ui_handler_seq + 1 bb.event._ui_handler_seq = bb.event._ui_handler_seq + 1
_ui_handlers[_ui_handler_seq] = handler _ui_handlers[_ui_handler_seq] = handler
level, debug_domains = bb.msg.constructLogOptions() level, debug_domains = bb.msg.constructLogOptions()
@@ -348,7 +330,6 @@ def unregister_UIHhandler(handlerNum, mainui=False):
if mainui: if mainui:
global _uiready global _uiready
_uiready = False _uiready = False
with bb.utils.lock_timeout(_thread_lock):
if handlerNum in _ui_handlers: if handlerNum in _ui_handlers:
del _ui_handlers[handlerNum] del _ui_handlers[handlerNum]
return return
@@ -766,7 +747,13 @@ class LogHandler(logging.Handler):
def emit(self, record): def emit(self, record):
if record.exc_info: if record.exc_info:
record.bb_exc_formatted = traceback.format_exception(*record.exc_info) etype, value, tb = record.exc_info
if hasattr(tb, 'tb_next'):
tb = list(bb.exceptions.extract_traceback(tb, context=3))
# Need to turn the value into something the logging system can pickle
record.bb_exc_info = (etype, value, tb)
record.bb_exc_formatted = bb.exceptions.format_exception(etype, value, tb, limit=5)
value = str(value)
record.exc_info = None record.exc_info = None
fire(record, None) fire(record, None)
@@ -858,19 +845,3 @@ class FindSigInfoResult(Event):
def __init__(self, result): def __init__(self, result):
Event.__init__(self) Event.__init__(self)
self.result = result self.result = result
class GetTaskSignatureResult(Event):
"""
Event to return results from GetTaskSignatures command
"""
def __init__(self, sig):
Event.__init__(self)
self.sig = sig
class ParseError(Event):
"""
Event to indicate parse failed
"""
def __init__(self, msg):
super().__init__()
self._msg = msg

View File

@@ -0,0 +1,94 @@
#
# SPDX-License-Identifier: GPL-2.0-only
#
import inspect
import traceback
import bb.namedtuple_with_abc
from collections import namedtuple
class TracebackEntry(namedtuple.abc):
"""Pickleable representation of a traceback entry"""
_fields = 'filename lineno function args code_context index'
_header = ' File "{0.filename}", line {0.lineno}, in {0.function}{0.args}'
def format(self, formatter=None):
if not self.code_context:
return self._header.format(self) + '\n'
formatted = [self._header.format(self) + ':\n']
for lineindex, line in enumerate(self.code_context):
if formatter:
line = formatter(line)
if lineindex == self.index:
formatted.append(' >%s' % line)
else:
formatted.append(' %s' % line)
return formatted
def __str__(self):
return ''.join(self.format())
def _get_frame_args(frame):
"""Get the formatted arguments and class (if available) for a frame"""
arginfo = inspect.getargvalues(frame)
try:
if not arginfo.args:
return '', None
# There have been reports from the field of python 2.6 which doesn't
# return a namedtuple here but simply a tuple so fallback gracefully if
# args isn't present.
except AttributeError:
return '', None
firstarg = arginfo.args[0]
if firstarg == 'self':
self = arginfo.locals['self']
cls = self.__class__.__name__
arginfo.args.pop(0)
del arginfo.locals['self']
else:
cls = None
formatted = inspect.formatargvalues(*arginfo)
return formatted, cls
def extract_traceback(tb, context=1):
frames = inspect.getinnerframes(tb, context)
for frame, filename, lineno, function, code_context, index in frames:
formatted_args, cls = _get_frame_args(frame)
if cls:
function = '%s.%s' % (cls, function)
yield TracebackEntry(filename, lineno, function, formatted_args,
code_context, index)
def format_extracted(extracted, formatter=None, limit=None):
if limit:
extracted = extracted[-limit:]
formatted = []
for tracebackinfo in extracted:
formatted.extend(tracebackinfo.format(formatter))
return formatted
def format_exception(etype, value, tb, context=1, limit=None, formatter=None):
formatted = ['Traceback (most recent call last):\n']
if hasattr(tb, 'tb_next'):
tb = extract_traceback(tb, context)
formatted.extend(format_extracted(tb, formatter, limit))
formatted.extend(traceback.format_exception_only(etype, value))
return formatted
def to_string(exc):
if isinstance(exc, SystemExit):
if not isinstance(exc.code, str):
return 'Exited with "%d"' % exc.code
return str(exc)

View File

@@ -23,7 +23,6 @@ import collections
import subprocess import subprocess
import pickle import pickle
import errno import errno
import shlex
import bb.persist_data, bb.utils import bb.persist_data, bb.utils
import bb.checksum import bb.checksum
import bb.process import bb.process
@@ -238,7 +237,7 @@ class URI(object):
# to RFC compliant URL format. E.g.: # to RFC compliant URL format. E.g.:
# file://foo.diff -> file:foo.diff # file://foo.diff -> file:foo.diff
if urlp.scheme in self._netloc_forbidden: if urlp.scheme in self._netloc_forbidden:
uri = re.sub(r"(?<=:)//(?!/)", "", uri, count=1) uri = re.sub("(?<=:)//(?!/)", "", uri, 1)
reparse = 1 reparse = 1
if reparse: if reparse:
@@ -291,12 +290,12 @@ class URI(object):
def _param_str_split(self, string, elmdelim, kvdelim="="): def _param_str_split(self, string, elmdelim, kvdelim="="):
ret = collections.OrderedDict() ret = collections.OrderedDict()
for k, v in [x.split(kvdelim, 1) if kvdelim in x else (x, None) for x in string.split(elmdelim) if x]: for k, v in [x.split(kvdelim, 1) for x in string.split(elmdelim) if x]:
ret[k] = v ret[k] = v
return ret return ret
def _param_str_join(self, dict_, elmdelim, kvdelim="="): def _param_str_join(self, dict_, elmdelim, kvdelim="="):
return elmdelim.join([kvdelim.join([k, v]) if v else k for k, v in dict_.items()]) return elmdelim.join([kvdelim.join([k, v]) for k, v in dict_.items()])
@property @property
def hostport(self): def hostport(self):
@@ -389,7 +388,7 @@ def decodeurl(url):
if s: if s:
if not '=' in s: if not '=' in s:
raise MalformedUrl(url, "The URL: '%s' is invalid: parameter %s does not specify a value (missing '=')" % (url, s)) raise MalformedUrl(url, "The URL: '%s' is invalid: parameter %s does not specify a value (missing '=')" % (url, s))
s1, s2 = s.split('=', 1) s1, s2 = s.split('=')
p[s1] = s2 p[s1] = s2
return type, host, urllib.parse.unquote(path), user, pswd, p return type, host, urllib.parse.unquote(path), user, pswd, p
@@ -461,7 +460,7 @@ def uri_replace(ud, uri_find, uri_replace, replacements, d, mirrortarball=None):
for k in replacements: for k in replacements:
uri_replace_decoded[loc] = uri_replace_decoded[loc].replace(k, replacements[k]) uri_replace_decoded[loc] = uri_replace_decoded[loc].replace(k, replacements[k])
#bb.note("%s %s %s" % (regexp, uri_replace_decoded[loc], uri_decoded[loc])) #bb.note("%s %s %s" % (regexp, uri_replace_decoded[loc], uri_decoded[loc]))
result_decoded[loc] = re.sub(regexp, uri_replace_decoded[loc], uri_decoded[loc], count=1) result_decoded[loc] = re.sub(regexp, uri_replace_decoded[loc], uri_decoded[loc], 1)
if loc == 2: if loc == 2:
# Handle path manipulations # Handle path manipulations
basename = None basename = None
@@ -470,7 +469,6 @@ def uri_replace(ud, uri_find, uri_replace, replacements, d, mirrortarball=None):
basename = os.path.basename(mirrortarball) basename = os.path.basename(mirrortarball)
# Kill parameters, they make no sense for mirror tarballs # Kill parameters, they make no sense for mirror tarballs
uri_decoded[5] = {} uri_decoded[5] = {}
uri_find_decoded[5] = {}
elif ud.localpath and ud.method.supports_checksum(ud): elif ud.localpath and ud.method.supports_checksum(ud):
basename = os.path.basename(ud.localpath) basename = os.path.basename(ud.localpath)
if basename: if basename:
@@ -500,7 +498,7 @@ def fetcher_init(d):
Calls before this must not hit the cache. Calls before this must not hit the cache.
""" """
with bb.persist_data.persist('BB_URI_HEADREVS', d) as revs: revs = bb.persist_data.persist('BB_URI_HEADREVS', d)
try: try:
# fetcher_init is called multiple times, so make sure we only save the # fetcher_init is called multiple times, so make sure we only save the
# revs the first time it is called. # revs the first time it is called.
@@ -519,7 +517,7 @@ def fetcher_init(d):
else: else:
raise FetchError("Invalid SRCREV cache policy of: %s" % srcrev_policy) raise FetchError("Invalid SRCREV cache policy of: %s" % srcrev_policy)
_checksum_cache.init_cache(d.getVar("BB_CACHEDIR")) _checksum_cache.init_cache(d)
for m in methods: for m in methods:
if hasattr(m, "init"): if hasattr(m, "init"):
@@ -537,7 +535,7 @@ def fetcher_compare_revisions(d):
when bitbake was started and return true if they have changed. when bitbake was started and return true if they have changed.
""" """
with dict(bb.persist_data.persist('BB_URI_HEADREVS', d)) as headrevs: headrevs = dict(bb.persist_data.persist('BB_URI_HEADREVS', d))
return headrevs != bb.fetch2.saved_headrevs return headrevs != bb.fetch2.saved_headrevs
def mirror_from_string(data): def mirror_from_string(data):
@@ -547,7 +545,7 @@ def mirror_from_string(data):
bb.warn('Invalid mirror data %s, should have paired members.' % data) bb.warn('Invalid mirror data %s, should have paired members.' % data)
return list(zip(*[iter(mirrors)]*2)) return list(zip(*[iter(mirrors)]*2))
def verify_checksum(ud, d, precomputed={}, localpath=None, fatal_nochecksum=True): def verify_checksum(ud, d, precomputed={}):
""" """
verify the MD5 and SHA256 checksum for downloaded src verify the MD5 and SHA256 checksum for downloaded src
@@ -561,19 +559,17 @@ def verify_checksum(ud, d, precomputed={}, localpath=None, fatal_nochecksum=True
file against those in the recipe each time, rather than only after file against those in the recipe each time, rather than only after
downloading. See https://bugzilla.yoctoproject.org/show_bug.cgi?id=5571. downloading. See https://bugzilla.yoctoproject.org/show_bug.cgi?id=5571.
""" """
if ud.ignore_checksums or not ud.method.supports_checksum(ud): if ud.ignore_checksums or not ud.method.supports_checksum(ud):
return {} return {}
if localpath is None:
localpath = ud.localpath
def compute_checksum_info(checksum_id): def compute_checksum_info(checksum_id):
checksum_name = getattr(ud, "%s_name" % checksum_id) checksum_name = getattr(ud, "%s_name" % checksum_id)
if checksum_id in precomputed: if checksum_id in precomputed:
checksum_data = precomputed[checksum_id] checksum_data = precomputed[checksum_id]
else: else:
checksum_data = getattr(bb.utils, "%s_file" % checksum_id)(localpath) checksum_data = getattr(bb.utils, "%s_file" % checksum_id)(ud.localpath)
checksum_expected = getattr(ud, "%s_expected" % checksum_id) checksum_expected = getattr(ud, "%s_expected" % checksum_id)
@@ -599,13 +595,17 @@ def verify_checksum(ud, d, precomputed={}, localpath=None, fatal_nochecksum=True
checksum_lines = ["SRC_URI[%s] = \"%s\"" % (ci["name"], ci["data"])] checksum_lines = ["SRC_URI[%s] = \"%s\"" % (ci["name"], ci["data"])]
# If no checksum has been provided # If no checksum has been provided
if fatal_nochecksum and ud.method.recommends_checksum(ud) and all(ci["expected"] is None for ci in checksum_infos): if ud.method.recommends_checksum(ud) and all(ci["expected"] is None for ci in checksum_infos):
messages = [] messages = []
strict = d.getVar("BB_STRICT_CHECKSUM") or "0" strict = d.getVar("BB_STRICT_CHECKSUM") or "0"
# If strict checking enabled and neither sum defined, raise error # If strict checking enabled and neither sum defined, raise error
if strict == "1": if strict == "1":
raise NoChecksumError("\n".join(checksum_lines)) messages.append("No checksum specified for '%s', please add at " \
"least one to the recipe:" % ud.localpath)
messages.extend(checksum_lines)
logger.error("\n".join(messages))
raise NoChecksumError("Missing SRC_URI checksum", ud.url)
bb.event.fire(MissingChecksumEvent(ud.url, **checksum_event), d) bb.event.fire(MissingChecksumEvent(ud.url, **checksum_event), d)
@@ -627,7 +627,7 @@ def verify_checksum(ud, d, precomputed={}, localpath=None, fatal_nochecksum=True
for ci in checksum_infos: for ci in checksum_infos:
if ci["expected"] and ci["expected"] != ci["data"]: if ci["expected"] and ci["expected"] != ci["data"]:
messages.append("File: '%s' has %s checksum '%s' when '%s' was " \ messages.append("File: '%s' has %s checksum '%s' when '%s' was " \
"expected" % (localpath, ci["id"], ci["data"], ci["expected"])) "expected" % (ud.localpath, ci["id"], ci["data"], ci["expected"]))
bad_checksum = ci["data"] bad_checksum = ci["data"]
if bad_checksum: if bad_checksum:
@@ -745,16 +745,13 @@ def subprocess_setup():
# SIGPIPE errors are known issues with gzip/bash # SIGPIPE errors are known issues with gzip/bash
signal.signal(signal.SIGPIPE, signal.SIG_DFL) signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def mark_recipe_nocache(d): def get_autorev(d):
# only not cache src rev in autorev case
if d.getVar('BB_SRCREV_POLICY') != "cache": if d.getVar('BB_SRCREV_POLICY') != "cache":
d.setVar('BB_DONT_CACHE', '1') d.setVar('BB_DONT_CACHE', '1')
def get_autorev(d):
mark_recipe_nocache(d)
d.setVar("__BBAUTOREV_SEEN", True)
return "AUTOINC" return "AUTOINC"
def _get_srcrev(d, method_name='sortable_revision'): def get_srcrev(d, method_name='sortable_revision'):
""" """
Return the revision string, usually for use in the version string (PV) of the current package Return the revision string, usually for use in the version string (PV) of the current package
Most packages usually only have one SCM so we just pass on the call. Most packages usually only have one SCM so we just pass on the call.
@@ -768,14 +765,13 @@ def _get_srcrev(d, method_name='sortable_revision'):
that fetcher provides a method with the given name and the same signature as sortable_revision. that fetcher provides a method with the given name and the same signature as sortable_revision.
""" """
d.setVar("__BBSRCREV_SEEN", "1") d.setVar("__BBSEENSRCREV", "1")
recursion = d.getVar("__BBINSRCREV") recursion = d.getVar("__BBINSRCREV")
if recursion: if recursion:
raise FetchError("There are recursive references in fetcher variables, likely through SRC_URI") raise FetchError("There are recursive references in fetcher variables, likely through SRC_URI")
d.setVar("__BBINSRCREV", True) d.setVar("__BBINSRCREV", True)
scms = [] scms = []
revs = []
fetcher = Fetch(d.getVar('SRC_URI').split(), d) fetcher = Fetch(d.getVar('SRC_URI').split(), d)
urldata = fetcher.ud urldata = fetcher.ud
for u in urldata: for u in urldata:
@@ -783,19 +779,16 @@ def _get_srcrev(d, method_name='sortable_revision'):
scms.append(u) scms.append(u)
if not scms: if not scms:
d.delVar("__BBINSRCREV") raise FetchError("SRCREV was used yet no valid SCM was found in SRC_URI")
return "", revs
if len(scms) == 1 and len(urldata[scms[0]].names) == 1: if len(scms) == 1 and len(urldata[scms[0]].names) == 1:
autoinc, rev = getattr(urldata[scms[0]].method, method_name)(urldata[scms[0]], d, urldata[scms[0]].names[0]) autoinc, rev = getattr(urldata[scms[0]].method, method_name)(urldata[scms[0]], d, urldata[scms[0]].names[0])
revs.append(rev)
if len(rev) > 10: if len(rev) > 10:
rev = rev[:10] rev = rev[:10]
d.delVar("__BBINSRCREV") d.delVar("__BBINSRCREV")
if autoinc: if autoinc:
return "AUTOINC+" + rev, revs return "AUTOINC+" + rev
return rev, revs return rev
# #
# Mutiple SCMs are in SRC_URI so we resort to SRCREV_FORMAT # Mutiple SCMs are in SRC_URI so we resort to SRCREV_FORMAT
@@ -811,7 +804,6 @@ def _get_srcrev(d, method_name='sortable_revision'):
ud = urldata[scm] ud = urldata[scm]
for name in ud.names: for name in ud.names:
autoinc, rev = getattr(ud.method, method_name)(ud, d, name) autoinc, rev = getattr(ud.method, method_name)(ud, d, name)
revs.append(rev)
seenautoinc = seenautoinc or autoinc seenautoinc = seenautoinc or autoinc
if len(rev) > 10: if len(rev) > 10:
rev = rev[:10] rev = rev[:10]
@@ -829,21 +821,7 @@ def _get_srcrev(d, method_name='sortable_revision'):
format = "AUTOINC+" + format format = "AUTOINC+" + format
d.delVar("__BBINSRCREV") d.delVar("__BBINSRCREV")
return format, revs return format
def get_hashvalue(d, method_name='sortable_revision'):
pkgv, revs = _get_srcrev(d, method_name=method_name)
return " ".join(revs)
def get_pkgv_string(d, method_name='sortable_revision'):
pkgv, revs = _get_srcrev(d, method_name=method_name)
return pkgv
def get_srcrev(d, method_name='sortable_revision'):
pkgv, revs = _get_srcrev(d, method_name=method_name)
if not pkgv:
raise FetchError("SRCREV was used yet no valid SCM was found in SRC_URI")
return pkgv
def localpath(url, d): def localpath(url, d):
fetcher = bb.fetch2.Fetch([url], d) fetcher = bb.fetch2.Fetch([url], d)
@@ -861,7 +839,6 @@ FETCH_EXPORT_VARS = ['HOME', 'PATH',
'ALL_PROXY', 'all_proxy', 'ALL_PROXY', 'all_proxy',
'GIT_PROXY_COMMAND', 'GIT_PROXY_COMMAND',
'GIT_SSH', 'GIT_SSH',
'GIT_SSH_COMMAND',
'GIT_SSL_CAINFO', 'GIT_SSL_CAINFO',
'GIT_SMART_HTTP', 'GIT_SMART_HTTP',
'SSH_AUTH_SOCK', 'SSH_AGENT_PID', 'SSH_AUTH_SOCK', 'SSH_AGENT_PID',
@@ -869,17 +846,10 @@ FETCH_EXPORT_VARS = ['HOME', 'PATH',
'DBUS_SESSION_BUS_ADDRESS', 'DBUS_SESSION_BUS_ADDRESS',
'P4CONFIG', 'P4CONFIG',
'SSL_CERT_FILE', 'SSL_CERT_FILE',
'NODE_EXTRA_CA_CERTS',
'AWS_PROFILE', 'AWS_PROFILE',
'AWS_ACCESS_KEY_ID', 'AWS_ACCESS_KEY_ID',
'AWS_SECRET_ACCESS_KEY', 'AWS_SECRET_ACCESS_KEY',
'AWS_ROLE_ARN', 'AWS_DEFAULT_REGION']
'AWS_WEB_IDENTITY_TOKEN_FILE',
'AWS_DEFAULT_REGION',
'AWS_SESSION_TOKEN',
'GIT_CACHE_PATH',
'REMOTE_CONTAINERS_IPC',
'SSL_CERT_DIR']
def get_fetcher_environment(d): def get_fetcher_environment(d):
newenv = {} newenv = {}
@@ -943,9 +913,6 @@ def runfetchcmd(cmd, d, quiet=False, cleanup=None, log=None, workdir=None):
output = "output:\n%s\n%s" % (e.stdout, e.stderr) output = "output:\n%s\n%s" % (e.stdout, e.stderr)
elif e.stderr: elif e.stderr:
output = "output:\n%s" % e.stderr output = "output:\n%s" % e.stderr
else:
if log:
output = "see logfile for output"
else: else:
output = "no output" output = "no output"
error_message = "Fetch command %s failed with exit code %s, %s" % (e.command, e.exitcode, output) error_message = "Fetch command %s failed with exit code %s, %s" % (e.command, e.exitcode, output)
@@ -1009,7 +976,6 @@ def build_mirroruris(origud, mirrors, ld):
try: try:
newud = FetchData(newuri, ld) newud = FetchData(newuri, ld)
newud.ignore_checksums = True
newud.setup_localpath(ld) newud.setup_localpath(ld)
except bb.fetch2.BBFetchException as e: except bb.fetch2.BBFetchException as e:
logger.debug("Mirror fetch failure for url %s (original url: %s)" % (newuri, origud.url)) logger.debug("Mirror fetch failure for url %s (original url: %s)" % (newuri, origud.url))
@@ -1119,7 +1085,6 @@ def try_mirror_url(fetch, origud, ud, ld, check = False):
logger.debug("Mirror fetch failure for url %s (original url: %s)" % (ud.url, origud.url)) logger.debug("Mirror fetch failure for url %s (original url: %s)" % (ud.url, origud.url))
logger.debug(str(e)) logger.debug(str(e))
try: try:
if ud.method.cleanup_upon_failure():
ud.method.clean(ud, ld) ud.method.clean(ud, ld)
except UnboundLocalError: except UnboundLocalError:
pass pass
@@ -1131,8 +1096,6 @@ def try_mirror_url(fetch, origud, ud, ld, check = False):
def ensure_symlink(target, link_name): def ensure_symlink(target, link_name):
if not os.path.exists(link_name): if not os.path.exists(link_name):
dirname = os.path.dirname(link_name)
bb.utils.mkdirhier(dirname)
if os.path.islink(link_name): if os.path.islink(link_name):
# Broken symbolic link # Broken symbolic link
os.unlink(link_name) os.unlink(link_name)
@@ -1245,7 +1208,6 @@ def srcrev_internal_helper(ud, d, name):
if srcrev == "INVALID" or not srcrev: if srcrev == "INVALID" or not srcrev:
raise FetchError("Please set a valid SRCREV for url %s (possible key names are %s, or use a ;rev=X URL parameter)" % (str(attempts), ud.url), ud.url) raise FetchError("Please set a valid SRCREV for url %s (possible key names are %s, or use a ;rev=X URL parameter)" % (str(attempts), ud.url), ud.url)
if srcrev == "AUTOINC": if srcrev == "AUTOINC":
d.setVar("__BBAUTOREV_ACTED_UPON", True)
srcrev = ud.method.latest_revision(ud, d, name) srcrev = ud.method.latest_revision(ud, d, name)
return srcrev return srcrev
@@ -1257,21 +1219,23 @@ def get_checksum_file_list(d):
SRC_URI as a space-separated string SRC_URI as a space-separated string
""" """
fetch = Fetch([], d, cache = False, localonly = True) fetch = Fetch([], d, cache = False, localonly = True)
dl_dir = d.getVar('DL_DIR')
filelist = [] filelist = []
for u in fetch.urls: for u in fetch.urls:
ud = fetch.ud[u] ud = fetch.ud[u]
if ud and isinstance(ud.method, local.Local): if ud and isinstance(ud.method, local.Local):
found = False paths = ud.method.localpaths(ud, d)
paths = ud.method.localfile_searchpaths(ud, d)
for f in paths: for f in paths:
pth = ud.decodedurl pth = ud.decodedurl
if f.startswith(dl_dir):
# The local fetcher's behaviour is to return a path under DL_DIR if it couldn't find the file anywhere else
if os.path.exists(f): if os.path.exists(f):
found = True bb.warn("Getting checksum for %s SRC_URI entry %s: file not found except in DL_DIR" % (d.getVar('PN'), os.path.basename(f)))
else:
bb.warn("Unable to get checksum for %s SRC_URI entry %s: file could not be found" % (d.getVar('PN'), os.path.basename(f)))
filelist.append(f + ":" + str(os.path.exists(f))) filelist.append(f + ":" + str(os.path.exists(f)))
if not found:
bb.fatal(("Unable to get checksum for %s SRC_URI entry %s: file could not be found"
"\nThe following paths were searched:"
"\n%s") % (d.getVar('PN'), os.path.basename(f), '\n'.join(paths)))
return " ".join(filelist) return " ".join(filelist)
@@ -1318,13 +1282,18 @@ class FetchData(object):
if checksum_name in self.parm: if checksum_name in self.parm:
checksum_expected = self.parm[checksum_name] checksum_expected = self.parm[checksum_name]
elif self.type not in ["http", "https", "ftp", "ftps", "sftp", "s3", "az", "crate", "gs"]: elif self.type not in ["http", "https", "ftp", "ftps", "sftp", "s3", "az"]:
checksum_expected = None checksum_expected = None
else: else:
checksum_expected = d.getVarFlag("SRC_URI", checksum_name) checksum_expected = d.getVarFlag("SRC_URI", checksum_name)
setattr(self, "%s_expected" % checksum_id, checksum_expected) setattr(self, "%s_expected" % checksum_id, checksum_expected)
for checksum_id in CHECKSUM_LIST:
configure_checksum(checksum_id)
self.ignore_checksums = False
self.names = self.parm.get("name",'default').split(',') self.names = self.parm.get("name",'default').split(',')
self.method = None self.method = None
@@ -1346,11 +1315,6 @@ class FetchData(object):
if hasattr(self.method, "urldata_init"): if hasattr(self.method, "urldata_init"):
self.method.urldata_init(self, d) self.method.urldata_init(self, d)
for checksum_id in CHECKSUM_LIST:
configure_checksum(checksum_id)
self.ignore_checksums = False
if "localpath" in self.parm: if "localpath" in self.parm:
# if user sets localpath for file, use it instead. # if user sets localpath for file, use it instead.
self.localpath = self.parm["localpath"] self.localpath = self.parm["localpath"]
@@ -1430,9 +1394,6 @@ class FetchMethod(object):
Is localpath something that can be represented by a checksum? Is localpath something that can be represented by a checksum?
""" """
# We cannot compute checksums for None
if urldata.localpath is None:
return False
# We cannot compute checksums for directories # We cannot compute checksums for directories
if os.path.isdir(urldata.localpath): if os.path.isdir(urldata.localpath):
return False return False
@@ -1445,12 +1406,6 @@ class FetchMethod(object):
""" """
return False return False
def cleanup_upon_failure(self):
"""
When a fetch fails, should clean() be called?
"""
return True
def verify_donestamp(self, ud, d): def verify_donestamp(self, ud, d):
""" """
Verify the donestamp file Verify the donestamp file
@@ -1520,10 +1475,7 @@ class FetchMethod(object):
if unpack: if unpack:
tar_cmd = 'tar --extract --no-same-owner' tar_cmd = 'tar --extract --no-same-owner'
if 'striplevel' in urldata.parm: if 'striplevel' in urldata.parm:
striplevel = urldata.parm['striplevel'] tar_cmd += ' --strip-components=%s' % urldata.parm['striplevel']
if not striplevel.isdigit():
raise UnpackError("Invalid striplevel parameter: %s" % striplevel, urldata.url)
tar_cmd += ' --strip-components=%s' % striplevel
if file.endswith('.tar'): if file.endswith('.tar'):
cmd = '%s -f %s' % (tar_cmd, file) cmd = '%s -f %s' % (tar_cmd, file)
elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'): elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
@@ -1563,27 +1515,24 @@ class FetchMethod(object):
elif file.endswith('.rpm') or file.endswith('.srpm'): elif file.endswith('.rpm') or file.endswith('.srpm'):
if 'extract' in urldata.parm: if 'extract' in urldata.parm:
unpack_file = urldata.parm.get('extract') unpack_file = urldata.parm.get('extract')
cmd = 'rpm2cpio.sh %s | cpio --no-absolute-filenames -id %s' % (file, unpack_file) cmd = 'rpm2cpio.sh %s | cpio -id %s' % (file, unpack_file)
iterate = True iterate = True
iterate_file = unpack_file iterate_file = unpack_file
else: else:
cmd = 'rpm2cpio.sh %s | cpio --no-absolute-filenames -id' % (file) cmd = 'rpm2cpio.sh %s | cpio -id' % (file)
elif file.endswith('.deb') or file.endswith('.ipk'): elif file.endswith('.deb') or file.endswith('.ipk'):
output = subprocess.check_output(['ar', '-t', file], preexec_fn=subprocess_setup) output = subprocess.check_output(['ar', '-t', file], preexec_fn=subprocess_setup)
datafile = None datafile = None
valid_datafiles = ('data.tar', 'data.tar.gz', 'data.tar.xz',
'data.tar.zst', 'data.tar.bz2', 'data.tar.lzma')
if output: if output:
for line in output.decode().splitlines(): for line in output.decode().splitlines():
if line in valid_datafiles: if line.startswith('data.tar.'):
datafile = line datafile = line
break break
else: else:
raise UnpackError("Unable to unpack deb/ipk package - does not contain supported data.tar* file", urldata.url) raise UnpackError("Unable to unpack deb/ipk package - does not contain data.tar.* file", urldata.url)
else: else:
raise UnpackError("Unable to unpack deb/ipk package - could not list contents", urldata.url) raise UnpackError("Unable to unpack deb/ipk package - could not list contents", urldata.url)
quoted_datafile = shlex.quote(datafile) cmd = 'ar x %s %s && %s -p -f %s && rm %s' % (file, datafile, tar_cmd, datafile, datafile)
cmd = 'ar x %s %s && %s -p -f %s && rm %s' % (shlex.quote(file), quoted_datafile, tar_cmd, quoted_datafile, quoted_datafile)
# If 'subdir' param exists, create a dir and use it as destination for unpack cmd # If 'subdir' param exists, create a dir and use it as destination for unpack cmd
if 'subdir' in urldata.parm: if 'subdir' in urldata.parm:
@@ -1599,7 +1548,6 @@ class FetchMethod(object):
unpackdir = rootdir unpackdir = rootdir
if not unpack or not cmd: if not unpack or not cmd:
urldata.unpack_tracer.unpack("file-copy", unpackdir)
# If file == dest, then avoid any copies, as we already put the file into dest! # If file == dest, then avoid any copies, as we already put the file into dest!
dest = os.path.join(unpackdir, os.path.basename(file)) dest = os.path.join(unpackdir, os.path.basename(file))
if file != dest and not (os.path.exists(dest) and os.path.samefile(file, dest)): if file != dest and not (os.path.exists(dest) and os.path.samefile(file, dest)):
@@ -1613,9 +1561,7 @@ class FetchMethod(object):
if urlpath.find("/") != -1: if urlpath.find("/") != -1:
destdir = urlpath.rsplit("/", 1)[0] + '/' destdir = urlpath.rsplit("/", 1)[0] + '/'
bb.utils.mkdirhier("%s/%s" % (unpackdir, destdir)) bb.utils.mkdirhier("%s/%s" % (unpackdir, destdir))
cmd = 'cp --force --preserve=timestamps --no-dereference --recursive -H "%s" "%s"' % (file, destdir) cmd = 'cp -fpPRH "%s" "%s"' % (file, destdir)
else:
urldata.unpack_tracer.unpack("archive-extract", unpackdir)
if not cmd: if not cmd:
return return
@@ -1669,7 +1615,7 @@ class FetchMethod(object):
if not hasattr(self, "_latest_revision"): if not hasattr(self, "_latest_revision"):
raise ParameterError("The fetcher for this URL does not support _latest_revision", ud.url) raise ParameterError("The fetcher for this URL does not support _latest_revision", ud.url)
with bb.persist_data.persist('BB_URI_HEADREVS', d) as revs: revs = bb.persist_data.persist('BB_URI_HEADREVS', d)
key = self.generate_revision_key(ud, d, name) key = self.generate_revision_key(ud, d, name)
try: try:
return revs[key] return revs[key]
@@ -1707,55 +1653,6 @@ class FetchMethod(object):
""" """
return [] return []
class DummyUnpackTracer(object):
"""
Abstract API definition for a class that traces unpacked source files back
to their respective upstream SRC_URI entries, for software composition
analysis, license compliance and detailed SBOM generation purposes.
User may load their own unpack tracer class (instead of the dummy
one) by setting the BB_UNPACK_TRACER_CLASS config parameter.
"""
def start(self, unpackdir, urldata_dict, d):
"""
Start tracing the core Fetch.unpack process, using an index to map
unpacked files to each SRC_URI entry.
This method is called by Fetch.unpack and it may receive nested calls by
gitsm and npmsw fetchers, that expand SRC_URI entries by adding implicit
URLs and by recursively calling Fetch.unpack from new (nested) Fetch
instances.
"""
return
def start_url(self, url):
"""Start tracing url unpack process.
This method is called by Fetch.unpack before the fetcher-specific unpack
method starts, and it may receive nested calls by gitsm and npmsw
fetchers.
"""
return
def unpack(self, unpack_type, destdir):
"""
Set unpack_type and destdir for current url.
This method is called by the fetcher-specific unpack method after url
tracing started.
"""
return
def finish_url(self, url):
"""Finish tracing url unpack process and update the file index.
This method is called by Fetch.unpack after the fetcher-specific unpack
method finished its job, and it may receive nested calls by gitsm
and npmsw fetchers.
"""
return
def complete(self):
"""
Finish tracing the Fetch.unpack process, and check if all nested
Fecth.unpack calls (if any) have been completed; if so, save collected
metadata.
"""
return
class Fetch(object): class Fetch(object):
def __init__(self, urls, d, cache = True, localonly = False, connection_cache = None): def __init__(self, urls, d, cache = True, localonly = False, connection_cache = None):
if localonly and cache: if localonly and cache:
@@ -1776,30 +1673,10 @@ class Fetch(object):
if key in urldata_cache: if key in urldata_cache:
self.ud = urldata_cache[key] self.ud = urldata_cache[key]
# the unpack_tracer object needs to be made available to possible nested
# Fetch instances (when those are created by gitsm and npmsw fetchers)
# so we set it as a global variable
global unpack_tracer
try:
unpack_tracer
except NameError:
class_path = d.getVar("BB_UNPACK_TRACER_CLASS")
if class_path:
# use user-defined unpack tracer class
import importlib
module_name, _, class_name = class_path.rpartition(".")
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)
unpack_tracer = class_()
else:
# fall back to the dummy/abstract class
unpack_tracer = DummyUnpackTracer()
for url in urls: for url in urls:
if url not in self.ud: if url not in self.ud:
try: try:
self.ud[url] = FetchData(url, d, localonly) self.ud[url] = FetchData(url, d, localonly)
self.ud[url].unpack_tracer = unpack_tracer
except NonLocalMethod: except NonLocalMethod:
if localonly: if localonly:
self.ud[url] = None self.ud[url] = None
@@ -1838,7 +1715,6 @@ class Fetch(object):
network = self.d.getVar("BB_NO_NETWORK") network = self.d.getVar("BB_NO_NETWORK")
premirroronly = bb.utils.to_boolean(self.d.getVar("BB_FETCH_PREMIRRORONLY")) premirroronly = bb.utils.to_boolean(self.d.getVar("BB_FETCH_PREMIRRORONLY"))
checksum_missing_messages = []
for u in urls: for u in urls:
ud = self.ud[u] ud = self.ud[u]
ud.setup_localpath(self.d) ud.setup_localpath(self.d)
@@ -1850,6 +1726,7 @@ class Fetch(object):
try: try:
self.d.setVar("BB_NO_NETWORK", network) self.d.setVar("BB_NO_NETWORK", network)
if m.verify_donestamp(ud, self.d) and not m.need_update(ud, self.d): if m.verify_donestamp(ud, self.d) and not m.need_update(ud, self.d):
done = True done = True
elif m.try_premirror(ud, self.d): elif m.try_premirror(ud, self.d):
@@ -1902,7 +1779,7 @@ class Fetch(object):
logger.debug(str(e)) logger.debug(str(e))
firsterr = e firsterr = e
# Remove any incomplete fetch # Remove any incomplete fetch
if not verified_stamp and m.cleanup_upon_failure(): if not verified_stamp:
m.clean(ud, self.d) m.clean(ud, self.d)
logger.debug("Trying MIRRORS") logger.debug("Trying MIRRORS")
mirrors = mirror_from_string(self.d.getVar('MIRRORS')) mirrors = mirror_from_string(self.d.getVar('MIRRORS'))
@@ -1921,20 +1798,13 @@ class Fetch(object):
raise ChecksumError("Stale Error Detected") raise ChecksumError("Stale Error Detected")
except BBFetchException as e: except BBFetchException as e:
if isinstance(e, NoChecksumError): if isinstance(e, ChecksumError):
(message, _) = e.args
checksum_missing_messages.append(message)
continue
elif isinstance(e, ChecksumError):
logger.error("Checksum failure fetching %s" % u) logger.error("Checksum failure fetching %s" % u)
raise raise
finally: finally:
if ud.lockfile: if ud.lockfile:
bb.utils.unlockfile(lf) bb.utils.unlockfile(lf)
if checksum_missing_messages:
logger.error("Missing SRC_URI checksum, please add those to the recipe: \n%s", "\n".join(checksum_missing_messages))
raise BBFetchException("There was some missing checksums in the recipe")
def checkstatus(self, urls=None): def checkstatus(self, urls=None):
""" """
@@ -1965,7 +1835,7 @@ class Fetch(object):
ret = m.try_mirrors(self, ud, self.d, mirrors, True) ret = m.try_mirrors(self, ud, self.d, mirrors, True)
if not ret: if not ret:
raise FetchError("URL doesn't work", u) raise FetchError("URL %s doesn't work" % u, u)
def unpack(self, root, urls=None): def unpack(self, root, urls=None):
""" """
@@ -1975,8 +1845,6 @@ class Fetch(object):
if not urls: if not urls:
urls = self.urls urls = self.urls
unpack_tracer.start(root, self.ud, self.d)
for u in urls: for u in urls:
ud = self.ud[u] ud = self.ud[u]
ud.setup_localpath(self.d) ud.setup_localpath(self.d)
@@ -1984,15 +1852,11 @@ class Fetch(object):
if ud.lockfile: if ud.lockfile:
lf = bb.utils.lockfile(ud.lockfile) lf = bb.utils.lockfile(ud.lockfile)
unpack_tracer.start_url(u)
ud.method.unpack(ud, root, self.d) ud.method.unpack(ud, root, self.d)
unpack_tracer.finish_url(u)
if ud.lockfile: if ud.lockfile:
bb.utils.unlockfile(lf) bb.utils.unlockfile(lf)
unpack_tracer.complete()
def clean(self, urls=None): def clean(self, urls=None):
""" """
Clean files that the fetcher gets or places Clean files that the fetcher gets or places
@@ -2094,7 +1958,6 @@ from . import npm
from . import npmsw from . import npmsw
from . import az from . import az
from . import crate from . import crate
from . import gcp
methods.append(local.Local()) methods.append(local.Local())
methods.append(wget.Wget()) methods.append(wget.Wget())
@@ -2116,4 +1979,3 @@ methods.append(npm.Npm())
methods.append(npmsw.NpmShrinkWrap()) methods.append(npmsw.NpmShrinkWrap())
methods.append(az.Az()) methods.append(az.Az())
methods.append(crate.Crate()) methods.append(crate.Crate())
methods.append(gcp.GCP())

View File

@@ -13,6 +13,7 @@ BitBake 'Fetch' implementation for crates.io
import hashlib import hashlib
import json import json
import os import os
import shutil
import subprocess import subprocess
import bb import bb
from bb.fetch2 import logger, subprocess_setup, UnpackError from bb.fetch2 import logger, subprocess_setup, UnpackError
@@ -33,7 +34,7 @@ class Crate(Wget):
return ud.type in ['crate'] return ud.type in ['crate']
def recommends_checksum(self, urldata): def recommends_checksum(self, urldata):
return True return False
def urldata_init(self, ud, d): def urldata_init(self, ud, d):
""" """
@@ -56,28 +57,22 @@ class Crate(Wget):
if len(parts) < 5: if len(parts) < 5:
raise bb.fetch2.ParameterError("Invalid URL: Must be crate://HOST/NAME/VERSION", ud.url) raise bb.fetch2.ParameterError("Invalid URL: Must be crate://HOST/NAME/VERSION", ud.url)
# version is expected to be the last token # last field is version
# but ignore possible url parameters which will be used version = parts[len(parts) - 1]
# by the top fetcher class
version = parts[-1].split(";")[0]
# second to last field is name # second to last field is name
name = parts[-2] name = parts[len(parts) - 2]
# host (this is to allow custom crate registries to be specified # host (this is to allow custom crate registries to be specified
host = '/'.join(parts[2:-2]) host = '/'.join(parts[2:len(parts) - 2])
# if using upstream just fix it up nicely # if using upstream just fix it up nicely
if host == 'crates.io': if host == 'crates.io':
host = 'crates.io/api/v1/crates' host = 'crates.io/api/v1/crates'
cdn_host = 'static.crates.io/crates'
else:
cdn_host = host
ud.url = "https://%s/%s/%s/download" % (cdn_host, name, version) ud.url = "https://%s/%s/%s/download" % (host, name, version)
ud.parm['downloadfilename'] = "%s-%s.crate" % (name, version) ud.parm['downloadfilename'] = "%s-%s.crate" % (name, version)
if 'name' not in ud.parm: ud.parm['name'] = name
ud.parm['name'] = '%s-%s' % (name, version)
logger.debug2("Fetching %s to %s" % (ud.url, ud.parm['downloadfilename'])) logger.debug(2, "Fetching %s to %s" % (ud.url, ud.parm['downloadfilename']))
def unpack(self, ud, rootdir, d): def unpack(self, ud, rootdir, d):
""" """
@@ -101,13 +96,11 @@ class Crate(Wget):
save_cwd = os.getcwd() save_cwd = os.getcwd()
os.chdir(rootdir) os.chdir(rootdir)
bp = d.getVar('BP') pn = d.getVar('BPN')
if bp == ud.parm.get('name'): if pn == ud.parm.get('name'):
cmd = "tar -xz --no-same-owner -f %s" % thefile cmd = "tar -xz --no-same-owner -f %s" % thefile
ud.unpack_tracer.unpack("crate-extract", rootdir)
else: else:
cargo_bitbake = self._cargo_bitbake_path(rootdir) cargo_bitbake = self._cargo_bitbake_path(rootdir)
ud.unpack_tracer.unpack("cargo-extract", cargo_bitbake)
cmd = "tar -xz --no-same-owner -f %s -C %s" % (thefile, cargo_bitbake) cmd = "tar -xz --no-same-owner -f %s -C %s" % (thefile, cargo_bitbake)

View File

@@ -1,102 +0,0 @@
"""
BitBake 'Fetch' implementation for Google Cloup Platform Storage.
Class for fetching files from Google Cloud Storage using the
Google Cloud Storage Python Client. The GCS Python Client must
be correctly installed, configured and authenticated prior to use.
Additionally, gsutil must also be installed.
"""
# Copyright (C) 2023, Snap Inc.
#
# Based in part on bb.fetch2.s3:
# Copyright (C) 2017 Andre McCurdy
#
# SPDX-License-Identifier: GPL-2.0-only
#
# Based on functions from the base bb module, Copyright 2003 Holger Schurig
import os
import bb
import urllib.parse, urllib.error
from bb.fetch2 import FetchMethod
from bb.fetch2 import FetchError
from bb.fetch2 import logger
class GCP(FetchMethod):
"""
Class to fetch urls via GCP's Python API.
"""
def __init__(self):
self.gcp_client = None
def supports(self, ud, d):
"""
Check to see if a given url can be fetched with GCP.
"""
return ud.type in ['gs']
def recommends_checksum(self, urldata):
return True
def urldata_init(self, ud, d):
if 'downloadfilename' in ud.parm:
ud.basename = ud.parm['downloadfilename']
else:
ud.basename = os.path.basename(ud.path)
ud.localfile = d.expand(urllib.parse.unquote(ud.basename))
def get_gcp_client(self):
from google.cloud import storage
self.gcp_client = storage.Client(project=None)
def download(self, ud, d):
"""
Fetch urls using the GCP API.
Assumes localpath was called first.
"""
from google.api_core.exceptions import NotFound
logger.debug2(f"Trying to download gs://{ud.host}{ud.path} to {ud.localpath}")
if self.gcp_client is None:
self.get_gcp_client()
bb.fetch2.check_network_access(d, "blob.download_to_filename", f"gs://{ud.host}{ud.path}")
# Path sometimes has leading slash, so strip it
path = ud.path.lstrip("/")
blob = self.gcp_client.bucket(ud.host).blob(path)
try:
blob.download_to_filename(ud.localpath)
except NotFound:
raise FetchError("The GCP API threw a NotFound exception")
# Additional sanity checks copied from the wget class (although there
# are no known issues which mean these are required, treat the GCP API
# tool with a little healthy suspicion).
if not os.path.exists(ud.localpath):
raise FetchError(f"The GCP API returned success for gs://{ud.host}{ud.path} but {ud.localpath} doesn't exist?!")
if os.path.getsize(ud.localpath) == 0:
os.remove(ud.localpath)
raise FetchError(f"The downloaded file for gs://{ud.host}{ud.path} resulted in a zero size file?! Deleting and failing since this isn't right.")
return True
def checkstatus(self, fetch, ud, d):
"""
Check the status of a URL.
"""
logger.debug2(f"Checking status of gs://{ud.host}{ud.path}")
if self.gcp_client is None:
self.get_gcp_client()
bb.fetch2.check_network_access(d, "gcp_client.bucket(ud.host).blob(path).exists()", f"gs://{ud.host}{ud.path}")
# Path sometimes has leading slash, so strip it
path = ud.path.lstrip("/")
if self.gcp_client.bucket(ud.host).blob(path).exists() == False:
raise FetchError(f"The GCP API reported that gs://{ud.host}{ud.path} does not exist")
else:
return True

View File

@@ -44,27 +44,13 @@ Supported SRC_URI options are:
- nobranch - nobranch
Don't check the SHA validation for branch. set this option for the recipe Don't check the SHA validation for branch. set this option for the recipe
referring to commit which is valid in any namespace (branch, tag, ...) referring to commit which is valid in tag instead of branch.
instead of branch.
The default is "0", set nobranch=1 if needed. The default is "0", set nobranch=1 if needed.
- subpath
Limit the checkout to a specific subpath of the tree.
By default, checkout the whole tree, set subpath=<path> if needed
- destsuffix
The name of the path in which to place the checkout.
By default, the path is git/, set destsuffix=<suffix> if needed
- usehead - usehead
For local git:// urls to use the current branch HEAD as the revision for use with For local git:// urls to use the current branch HEAD as the revision for use with
AUTOREV. Implies nobranch. AUTOREV. Implies nobranch.
- lfs
Enable the checkout to use LFS for large files. This will download all LFS files
in the download step, as the unpack step does not have network access.
The default is "1", set lfs=0 to skip.
""" """
# Copyright (C) 2005 Richard Purdie # Copyright (C) 2005 Richard Purdie
@@ -78,7 +64,6 @@ import fnmatch
import os import os
import re import re
import shlex import shlex
import shutil
import subprocess import subprocess
import tempfile import tempfile
import bb import bb
@@ -87,12 +72,8 @@ from contextlib import contextmanager
from bb.fetch2 import FetchMethod from bb.fetch2 import FetchMethod
from bb.fetch2 import runfetchcmd from bb.fetch2 import runfetchcmd
from bb.fetch2 import logger from bb.fetch2 import logger
from bb.fetch2 import trusted_network
sha1_re = re.compile(r'^[0-9a-f]{40}$')
slash_re = re.compile(r"/+")
class GitProgressHandler(bb.progress.LineFilterProgressHandler): class GitProgressHandler(bb.progress.LineFilterProgressHandler):
"""Extract progress information from git output""" """Extract progress information from git output"""
def __init__(self, d): def __init__(self, d):
@@ -150,9 +131,6 @@ class Git(FetchMethod):
def supports_checksum(self, urldata): def supports_checksum(self, urldata):
return False return False
def cleanup_upon_failure(self):
return False
def urldata_init(self, ud, d): def urldata_init(self, ud, d):
""" """
init git specific variable within url data init git specific variable within url data
@@ -262,7 +240,7 @@ class Git(FetchMethod):
for name in ud.names: for name in ud.names:
ud.unresolvedrev[name] = 'HEAD' ud.unresolvedrev[name] = 'HEAD'
ud.basecmd = d.getVar("FETCHCMD_git") or "git -c gc.autoDetach=false -c core.pager=cat -c safe.bareRepository=all" ud.basecmd = d.getVar("FETCHCMD_git") or "git -c core.fsyncobjectfiles=0 -c gc.autoDetach=false"
write_tarballs = d.getVar("BB_GENERATE_MIRROR_TARBALLS") or "0" write_tarballs = d.getVar("BB_GENERATE_MIRROR_TARBALLS") or "0"
ud.write_tarballs = write_tarballs != "0" or ud.rebaseable ud.write_tarballs = write_tarballs != "0" or ud.rebaseable
@@ -271,20 +249,20 @@ class Git(FetchMethod):
ud.setup_revisions(d) ud.setup_revisions(d)
for name in ud.names: for name in ud.names:
# Ensure any revision that doesn't look like a SHA-1 is translated into one # Ensure anything that doesn't look like a sha256 checksum/revision is translated into one
if not sha1_re.match(ud.revisions[name] or ''): if not ud.revisions[name] or len(ud.revisions[name]) != 40 or (False in [c in "abcdef0123456789" for c in ud.revisions[name]]):
if ud.revisions[name]: if ud.revisions[name]:
ud.unresolvedrev[name] = ud.revisions[name] ud.unresolvedrev[name] = ud.revisions[name]
ud.revisions[name] = self.latest_revision(ud, d, name) ud.revisions[name] = self.latest_revision(ud, d, name)
gitsrcname = '%s%s' % (ud.host.replace(':', '.'), ud.path.replace('/', '.').replace('*', '.').replace(' ','_').replace('(', '_').replace(')', '_')) gitsrcname = '%s%s' % (ud.host.replace(':', '.'), ud.path.replace('/', '.').replace('*', '.').replace(' ','_'))
if gitsrcname.startswith('.'): if gitsrcname.startswith('.'):
gitsrcname = gitsrcname[1:] gitsrcname = gitsrcname[1:]
# For a rebaseable git repo, it is necessary to keep a mirror tar ball # for rebaseable git repo, it is necessary to keep mirror tar ball
# per revision, so that even if the revision disappears from the # per revision, so that even the revision disappears from the
# upstream repo in the future, the mirror will remain intact and still # upstream repo in the future, the mirror will remain intact and still
# contain the revision # contains the revision
if ud.rebaseable: if ud.rebaseable:
for name in ud.names: for name in ud.names:
gitsrcname = gitsrcname + '_' + ud.revisions[name] gitsrcname = gitsrcname + '_' + ud.revisions[name]
@@ -328,10 +306,7 @@ class Git(FetchMethod):
return ud.clonedir return ud.clonedir
def need_update(self, ud, d): def need_update(self, ud, d):
return self.clonedir_need_update(ud, d) \ return self.clonedir_need_update(ud, d) or self.shallow_tarball_need_update(ud) or self.tarball_need_update(ud)
or self.shallow_tarball_need_update(ud) \
or self.tarball_need_update(ud) \
or self.lfs_need_update(ud, d)
def clonedir_need_update(self, ud, d): def clonedir_need_update(self, ud, d):
if not os.path.exists(ud.clonedir): if not os.path.exists(ud.clonedir):
@@ -343,15 +318,6 @@ class Git(FetchMethod):
return True return True
return False return False
def lfs_need_update(self, ud, d):
if self.clonedir_need_update(ud, d):
return True
for name in ud.names:
if not self._lfs_objects_downloaded(ud, d, name, ud.clonedir):
return True
return False
def clonedir_need_shallow_revs(self, ud, d): def clonedir_need_shallow_revs(self, ud, d):
for rev in ud.shallow_revs: for rev in ud.shallow_revs:
try: try:
@@ -371,16 +337,6 @@ class Git(FetchMethod):
# is not possible # is not possible
if bb.utils.to_boolean(d.getVar("BB_FETCH_PREMIRRORONLY")): if bb.utils.to_boolean(d.getVar("BB_FETCH_PREMIRRORONLY")):
return True return True
# If the url is not in trusted network, that is, BB_NO_NETWORK is set to 0
# and BB_ALLOWED_NETWORKS does not contain the host that ud.url uses, then
# we need to try premirrors first as using upstream is destined to fail.
if not trusted_network(d, ud.url):
return True
# the following check is to ensure incremental fetch in downloads, this is
# because the premirror might be old and does not contain the new rev required,
# and this will cause a total removal and new clone. So if we can reach to
# network, we prefer upstream over premirror, though the premirror might contain
# the new rev.
if os.path.exists(ud.clonedir): if os.path.exists(ud.clonedir):
return False return False
return True return True
@@ -394,54 +350,17 @@ class Git(FetchMethod):
if ud.shallow and os.path.exists(ud.fullshallow) and self.need_update(ud, d): if ud.shallow and os.path.exists(ud.fullshallow) and self.need_update(ud, d):
ud.localpath = ud.fullshallow ud.localpath = ud.fullshallow
return return
elif os.path.exists(ud.fullmirror) and self.need_update(ud, d): elif os.path.exists(ud.fullmirror) and not os.path.exists(ud.clonedir):
if not os.path.exists(ud.clonedir):
bb.utils.mkdirhier(ud.clonedir) bb.utils.mkdirhier(ud.clonedir)
runfetchcmd("tar -xzf %s" % ud.fullmirror, d, workdir=ud.clonedir) runfetchcmd("tar -xzf %s" % ud.fullmirror, d, workdir=ud.clonedir)
else:
with tempfile.TemporaryDirectory(dir=d.getVar('DL_DIR')) as tmpdir:
runfetchcmd("tar -xzf %s" % ud.fullmirror, d, workdir=tmpdir)
output = runfetchcmd("%s remote" % ud.basecmd, d, quiet=True, workdir=ud.clonedir)
if 'mirror' in output:
runfetchcmd("%s remote rm mirror" % ud.basecmd, d, workdir=ud.clonedir)
runfetchcmd("%s remote add --mirror=fetch mirror %s" % (ud.basecmd, tmpdir), d, workdir=ud.clonedir)
fetch_cmd = "LANG=C %s fetch -f --update-head-ok --progress mirror " % (ud.basecmd)
runfetchcmd(fetch_cmd, d, workdir=ud.clonedir)
repourl = self._get_repo_url(ud) repourl = self._get_repo_url(ud)
needs_clone = False
if os.path.exists(ud.clonedir):
# The directory may exist, but not be the top level of a bare git
# repository in which case it needs to be deleted and re-cloned.
try:
# Since clones can be bare, use --absolute-git-dir instead of --show-toplevel
output = runfetchcmd("LANG=C %s rev-parse --absolute-git-dir" % ud.basecmd, d, workdir=ud.clonedir)
toplevel = output.rstrip()
if not bb.utils.path_is_descendant(toplevel, ud.clonedir):
logger.warning("Top level directory '%s' is not a descendant of '%s'. Re-cloning", toplevel, ud.clonedir)
needs_clone = True
except bb.fetch2.FetchError as e:
logger.warning("Unable to get top level for %s (not a git directory?): %s", ud.clonedir, e)
needs_clone = True
except FileNotFoundError as e:
logger.warning("%s", e)
needs_clone = True
if needs_clone:
shutil.rmtree(ud.clonedir)
else:
needs_clone = True
# If the repo still doesn't exist, fallback to cloning it # If the repo still doesn't exist, fallback to cloning it
if needs_clone: if not os.path.exists(ud.clonedir):
# We do this since git will use a "-l" option automatically for local urls where possible, # We do this since git will use a "-l" option automatically for local urls where possible
# but it doesn't work when git/objects is a symlink, only works when it is a directory.
if repourl.startswith("file://"): if repourl.startswith("file://"):
repourl_path = repourl[7:] repourl = repourl[7:]
objects = os.path.join(repourl_path, 'objects')
if os.path.isdir(objects) and not os.path.islink(objects):
repourl = repourl_path
clone_cmd = "LANG=C %s clone --bare --mirror %s %s --progress" % (ud.basecmd, shlex.quote(repourl), ud.clonedir) clone_cmd = "LANG=C %s clone --bare --mirror %s %s --progress" % (ud.basecmd, shlex.quote(repourl), ud.clonedir)
if ud.proto.lower() != 'file': if ud.proto.lower() != 'file':
bb.fetch2.check_network_access(d, clone_cmd, ud.url) bb.fetch2.check_network_access(d, clone_cmd, ud.url)
@@ -455,11 +374,7 @@ class Git(FetchMethod):
runfetchcmd("%s remote rm origin" % ud.basecmd, d, workdir=ud.clonedir) runfetchcmd("%s remote rm origin" % ud.basecmd, d, workdir=ud.clonedir)
runfetchcmd("%s remote add --mirror=fetch origin %s" % (ud.basecmd, shlex.quote(repourl)), d, workdir=ud.clonedir) runfetchcmd("%s remote add --mirror=fetch origin %s" % (ud.basecmd, shlex.quote(repourl)), d, workdir=ud.clonedir)
if ud.nobranch:
fetch_cmd = "LANG=C %s fetch -f --progress %s refs/*:refs/*" % (ud.basecmd, shlex.quote(repourl)) fetch_cmd = "LANG=C %s fetch -f --progress %s refs/*:refs/*" % (ud.basecmd, shlex.quote(repourl))
else:
fetch_cmd = "LANG=C %s fetch -f --progress %s refs/heads/*:refs/heads/* refs/tags/*:refs/tags/*" % (ud.basecmd, shlex.quote(repourl))
if ud.proto.lower() != 'file': if ud.proto.lower() != 'file':
bb.fetch2.check_network_access(d, fetch_cmd, ud.url) bb.fetch2.check_network_access(d, fetch_cmd, ud.url)
progresshandler = GitProgressHandler(d) progresshandler = GitProgressHandler(d)
@@ -482,14 +397,15 @@ class Git(FetchMethod):
if missing_rev: if missing_rev:
raise bb.fetch2.FetchError("Unable to find revision %s even from upstream" % missing_rev) raise bb.fetch2.FetchError("Unable to find revision %s even from upstream" % missing_rev)
if self.lfs_need_update(ud, d): if self._contains_lfs(ud, d, ud.clonedir) and self._need_lfs(ud):
# Unpack temporary working copy, use it to run 'git checkout' to force pre-fetching # Unpack temporary working copy, use it to run 'git checkout' to force pre-fetching
# of all LFS blobs needed at the srcrev. # of all LFS blobs needed at the srcrev.
# #
# It would be nice to just do this inline here by running 'git-lfs fetch' # It would be nice to just do this inline here by running 'git-lfs fetch'
# on the bare clonedir, but that operation requires a working copy on some # on the bare clonedir, but that operation requires a working copy on some
# releases of Git LFS. # releases of Git LFS.
with tempfile.TemporaryDirectory(dir=d.getVar('DL_DIR')) as tmpdir: tmpdir = tempfile.mkdtemp(dir=d.getVar('DL_DIR'))
try:
# Do the checkout. This implicitly involves a Git LFS fetch. # Do the checkout. This implicitly involves a Git LFS fetch.
Git.unpack(self, ud, tmpdir, d) Git.unpack(self, ud, tmpdir, d)
@@ -505,8 +421,10 @@ class Git(FetchMethod):
# Only do this if the unpack resulted in a .git/lfs directory being # Only do this if the unpack resulted in a .git/lfs directory being
# created; this only happens if at least one blob needed to be # created; this only happens if at least one blob needed to be
# downloaded. # downloaded.
if os.path.exists(os.path.join(ud.destdir, ".git", "lfs")): if os.path.exists(os.path.join(tmpdir, "git", ".git", "lfs")):
runfetchcmd("tar -cf - lfs | tar -xf - -C %s" % ud.clonedir, d, workdir="%s/.git" % ud.destdir) runfetchcmd("tar -cf - lfs | tar -xf - -C %s" % ud.clonedir, d, workdir="%s/git/.git" % tmpdir)
finally:
bb.utils.remove(tmpdir, recurse=True)
def build_mirror_data(self, ud, d): def build_mirror_data(self, ud, d):
@@ -544,9 +462,9 @@ class Git(FetchMethod):
logger.info("Creating tarball of git repository") logger.info("Creating tarball of git repository")
with create_atomic(ud.fullmirror) as tfile: with create_atomic(ud.fullmirror) as tfile:
mtime = runfetchcmd("{} log --all -1 --format=%cD".format(ud.basecmd), d, mtime = runfetchcmd("git log --all -1 --format=%cD", d,
quiet=True, workdir=ud.clonedir) quiet=True, workdir=ud.clonedir)
runfetchcmd("tar -czf %s --owner oe:0 --group oe:0 --mtime \"%s\" ." runfetchcmd("tar -czf %s --owner pokybuild --group users --mtime \"%s\" ."
% (tfile, mtime), d, workdir=ud.clonedir) % (tfile, mtime), d, workdir=ud.clonedir)
runfetchcmd("touch %s.done" % ud.fullmirror, d) runfetchcmd("touch %s.done" % ud.fullmirror, d)
@@ -602,7 +520,7 @@ class Git(FetchMethod):
shallow_cmd = [self.make_shallow_path, '-s'] shallow_cmd = [self.make_shallow_path, '-s']
for b in shallow_branches: for b in shallow_branches:
shallow_cmd.append('-r') shallow_cmd.append('-r')
shallow_cmd.append(shlex.quote(b)) shallow_cmd.append(b)
shallow_cmd.extend(shallow_revisions) shallow_cmd.extend(shallow_revisions)
runfetchcmd(subprocess.list2cmdline(shallow_cmd), d, workdir=dest) runfetchcmd(subprocess.list2cmdline(shallow_cmd), d, workdir=dest)
@@ -632,8 +550,6 @@ class Git(FetchMethod):
destdir = ud.destdir = os.path.join(destdir, destsuffix) destdir = ud.destdir = os.path.join(destdir, destsuffix)
if os.path.exists(destdir): if os.path.exists(destdir):
bb.utils.prunedir(destdir) bb.utils.prunedir(destdir)
if not ud.bareclone:
ud.unpack_tracer.unpack("git", destdir)
need_lfs = self._need_lfs(ud) need_lfs = self._need_lfs(ud)
@@ -643,6 +559,7 @@ class Git(FetchMethod):
source_found = False source_found = False
source_error = [] source_error = []
if not source_found:
clonedir_is_up_to_date = not self.clonedir_need_update(ud, d) clonedir_is_up_to_date = not self.clonedir_need_update(ud, d)
if clonedir_is_up_to_date: if clonedir_is_up_to_date:
runfetchcmd("%s clone %s %s/ %s" % (ud.basecmd, ud.cloneflags, ud.clonedir, destdir), d) runfetchcmd("%s clone %s %s/ %s" % (ud.basecmd, ud.cloneflags, ud.clonedir, destdir), d)
@@ -672,8 +589,6 @@ class Git(FetchMethod):
raise bb.fetch2.FetchError("Repository %s has LFS content, install git-lfs on host to download (or set lfs=0 to ignore it)" % (repourl)) raise bb.fetch2.FetchError("Repository %s has LFS content, install git-lfs on host to download (or set lfs=0 to ignore it)" % (repourl))
elif not need_lfs: elif not need_lfs:
bb.note("Repository %s has LFS content but it is not being fetched" % (repourl)) bb.note("Repository %s has LFS content but it is not being fetched" % (repourl))
else:
runfetchcmd("%s lfs install --local" % ud.basecmd, d, workdir=destdir)
if not ud.nocheckout: if not ud.nocheckout:
if subpath: if subpath:
@@ -725,35 +640,6 @@ class Git(FetchMethod):
raise bb.fetch2.FetchError("The command '%s' gave output with more then 1 line unexpectedly, output: '%s'" % (cmd, output)) raise bb.fetch2.FetchError("The command '%s' gave output with more then 1 line unexpectedly, output: '%s'" % (cmd, output))
return output.split()[0] != "0" return output.split()[0] != "0"
def _lfs_objects_downloaded(self, ud, d, name, wd):
"""
Verifies whether the LFS objects for requested revisions have already been downloaded
"""
# Bail out early if this repository doesn't use LFS
if not self._need_lfs(ud) or not self._contains_lfs(ud, d, wd):
return True
# The Git LFS specification specifies ([1]) the LFS folder layout so it should be safe to check for file
# existence.
# [1] https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md#intercepting-git
cmd = "%s lfs ls-files -l %s" \
% (ud.basecmd, ud.revisions[name])
output = runfetchcmd(cmd, d, quiet=True, workdir=wd).rstrip()
# Do not do any further matching if no objects are managed by LFS
if not output:
return True
# Match all lines beginning with the hexadecimal OID
oid_regex = re.compile("^(([a-fA-F0-9]{2})([a-fA-F0-9]{2})[A-Fa-f0-9]+)")
for line in output.split("\n"):
oid = re.search(oid_regex, line)
if not oid:
bb.warn("git lfs ls-files output '%s' did not match expected format." % line)
if not os.path.exists(os.path.join(wd, "lfs", "objects", oid.group(2), oid.group(3), oid.group(1))):
return False
return True
def _need_lfs(self, ud): def _need_lfs(self, ud):
return ud.parm.get("lfs", "1") == "1" return ud.parm.get("lfs", "1") == "1"
@@ -762,11 +648,13 @@ class Git(FetchMethod):
Check if the repository has 'lfs' (large file) content Check if the repository has 'lfs' (large file) content
""" """
if ud.nobranch: if not ud.nobranch:
# If no branch is specified, use the current git commit branchname = ud.branches[ud.names[0]]
refname = self._build_revision(ud, d, ud.names[0]) else:
elif wd == ud.clonedir: branchname = "master"
# The bare clonedir doesn't use the remote names; it has the branch immediately. # The bare clonedir doesn't use the remote names; it has the branch immediately.
if wd == ud.clonedir:
refname = ud.branches[ud.names[0]] refname = ud.branches[ud.names[0]]
else: else:
refname = "origin/%s" % ud.branches[ud.names[0]] refname = "origin/%s" % ud.branches[ud.names[0]]
@@ -809,6 +697,7 @@ class Git(FetchMethod):
Return a unique key for the url Return a unique key for the url
""" """
# Collapse adjacent slashes # Collapse adjacent slashes
slash_re = re.compile(r"/+")
return "git:" + ud.host + slash_re.sub(".", ud.path) + ud.unresolvedrev[name] return "git:" + ud.host + slash_re.sub(".", ud.path) + ud.unresolvedrev[name]
def _lsremote(self, ud, d, search): def _lsremote(self, ud, d, search):
@@ -841,11 +730,11 @@ class Git(FetchMethod):
""" """
Compute the HEAD revision for the url Compute the HEAD revision for the url
""" """
if not d.getVar("__BBSRCREV_SEEN"): if not d.getVar("__BBSEENSRCREV"):
raise bb.fetch2.FetchError("Recipe uses a floating tag/branch '%s' for repo '%s' without a fixed SRCREV yet doesn't call bb.fetch2.get_srcrev() (use SRCPV in PV for OE)." % (ud.unresolvedrev[name], ud.host+ud.path)) raise bb.fetch2.FetchError("Recipe uses a floating tag/branch without a fixed SRCREV yet doesn't call bb.fetch2.get_srcrev() (use SRCPV in PV for OE).")
# Ensure we mark as not cached # Ensure we mark as not cached
bb.fetch2.mark_recipe_nocache(d) bb.fetch2.get_autorev(d)
output = self._lsremote(ud, d, "") output = self._lsremote(ud, d, "")
# Tags of the form ^{} may not work, need to fallback to other form # Tags of the form ^{} may not work, need to fallback to other form
@@ -871,42 +760,38 @@ class Git(FetchMethod):
""" """
pupver = ('', '') pupver = ('', '')
tagregex = re.compile(d.getVar('UPSTREAM_CHECK_GITTAGREGEX') or r"(?P<pver>([0-9][\.|_]?)+)")
try: try:
output = self._lsremote(ud, d, "refs/tags/*") output = self._lsremote(ud, d, "refs/tags/*")
except (bb.fetch2.FetchError, bb.fetch2.NetworkAccess) as e: except (bb.fetch2.FetchError, bb.fetch2.NetworkAccess) as e:
bb.note("Could not list remote: %s" % str(e)) bb.note("Could not list remote: %s" % str(e))
return pupver return pupver
rev_tag_re = re.compile(r"([0-9a-f]{40})\s+refs/tags/(.*)")
pver_re = re.compile(d.getVar('UPSTREAM_CHECK_GITTAGREGEX') or r"(?P<pver>([0-9][\.|_]?)+)")
nonrel_re = re.compile(r"(alpha|beta|rc|final)+")
verstring = "" verstring = ""
revision = ""
for line in output.split("\n"): for line in output.split("\n"):
if not line: if not line:
break break
m = rev_tag_re.match(line) tag_head = line.split("/")[-1]
if not m:
continue
(revision, tag) = m.groups()
# Ignore non-released branches # Ignore non-released branches
if nonrel_re.search(tag): m = re.search(r"(alpha|beta|rc|final)+", tag_head)
if m:
continue continue
# search for version in the line # search for version in the line
m = pver_re.search(tag) tag = tagregex.search(tag_head)
if not m: if tag is None:
continue continue
pver = m.group('pver').replace("_", ".") tag = tag.group('pver')
tag = tag.replace("_", ".")
if verstring and bb.utils.vercmp(("0", pver, ""), ("0", verstring, "")) < 0: if verstring and bb.utils.vercmp(("0", tag, ""), ("0", verstring, "")) < 0:
continue continue
verstring = pver verstring = tag
revision = line.split()[0]
pupver = (verstring, revision) pupver = (verstring, revision)
return pupver return pupver
@@ -926,8 +811,9 @@ class Git(FetchMethod):
commits = None commits = None
else: else:
if not os.path.exists(rev_file) or not os.path.getsize(rev_file): if not os.path.exists(rev_file) or not os.path.getsize(rev_file):
from pipes import quote
commits = bb.fetch2.runfetchcmd( commits = bb.fetch2.runfetchcmd(
"git rev-list %s -- | wc -l" % shlex.quote(rev), "git rev-list %s -- | wc -l" % quote(rev),
d, quiet=True).strip().lstrip('0') d, quiet=True).strip().lstrip('0')
if commits: if commits:
open(rev_file, "w").write("%d\n" % int(commits)) open(rev_file, "w").write("%d\n" % int(commits))

View File

@@ -88,9 +88,9 @@ class GitSM(Git):
subrevision[m] = module_hash.split()[2] subrevision[m] = module_hash.split()[2]
# Convert relative to absolute uri based on parent uri # Convert relative to absolute uri based on parent uri
if uris[m].startswith('..') or uris[m].startswith('./'): if uris[m].startswith('..'):
newud = copy.copy(ud) newud = copy.copy(ud)
newud.path = os.path.normpath(os.path.join(newud.path, uris[m])) newud.path = os.path.realpath(os.path.join(newud.path, uris[m]))
uris[m] = Git._get_repo_url(self, newud) uris[m] = Git._get_repo_url(self, newud)
for module in submodules: for module in submodules:
@@ -115,21 +115,10 @@ class GitSM(Git):
# This has to be a file reference # This has to be a file reference
proto = "file" proto = "file"
url = "gitsm://" + uris[module] url = "gitsm://" + uris[module]
if url.endswith("{}{}".format(ud.host, ud.path)):
raise bb.fetch2.FetchError("Submodule refers to the parent repository. This will cause deadlock situation in current version of Bitbake." \
"Consider using git fetcher instead.")
url += ';protocol=%s' % proto url += ';protocol=%s' % proto
url += ";name=%s" % module url += ";name=%s" % module
url += ";subpath=%s" % module url += ";subpath=%s" % module
url += ";nobranch=1"
url += ";lfs=%s" % ("1" if self._need_lfs(ud) else "0")
# Note that adding "user=" here to give credentials to the
# submodule is not supported. Since using SRC_URI to give git://
# URL a password is not supported, one have to use one of the
# recommended way (eg. ~/.netrc or SSH config) which does specify
# the user (See comment in git.py).
# So, we will not take patches adding "user=" support here.
ld = d.createCopy() ld = d.createCopy()
# Not necessary to set SRC_URI, since we're passing the URI to # Not necessary to set SRC_URI, since we're passing the URI to
@@ -147,19 +136,6 @@ class GitSM(Git):
return submodules != [] return submodules != []
def call_process_submodules(self, ud, d, extra_check, subfunc):
# If we're using a shallow mirror tarball it needs to be
# unpacked temporarily so that we can examine the .gitmodules file
if ud.shallow and os.path.exists(ud.fullshallow) and extra_check:
tmpdir = tempfile.mkdtemp(dir=d.getVar("DL_DIR"))
try:
runfetchcmd("tar -xzf %s" % ud.fullshallow, d, workdir=tmpdir)
self.process_submodules(ud, tmpdir, subfunc, d)
finally:
shutil.rmtree(tmpdir)
else:
self.process_submodules(ud, ud.clonedir, subfunc, d)
def need_update(self, ud, d): def need_update(self, ud, d):
if Git.need_update(self, ud, d): if Git.need_update(self, ud, d):
return True return True
@@ -177,7 +153,15 @@ class GitSM(Git):
logger.error('gitsm: submodule update check failed: %s %s' % (type(e).__name__, str(e))) logger.error('gitsm: submodule update check failed: %s %s' % (type(e).__name__, str(e)))
need_update_result = True need_update_result = True
self.call_process_submodules(ud, d, not os.path.exists(ud.clonedir), need_update_submodule) # If we're using a shallow mirror tarball it needs to be unpacked
# temporarily so that we can examine the .gitmodules file
if ud.shallow and os.path.exists(ud.fullshallow) and not os.path.exists(ud.clonedir):
tmpdir = tempfile.mkdtemp(dir=d.getVar("DL_DIR"))
runfetchcmd("tar -xzf %s" % ud.fullshallow, d, workdir=tmpdir)
self.process_submodules(ud, tmpdir, need_update_submodule, d)
shutil.rmtree(tmpdir)
else:
self.process_submodules(ud, ud.clonedir, need_update_submodule, d)
if need_update_list: if need_update_list:
logger.debug('gitsm: Submodules requiring update: %s' % (' '.join(need_update_list))) logger.debug('gitsm: Submodules requiring update: %s' % (' '.join(need_update_list)))
@@ -200,7 +184,16 @@ class GitSM(Git):
raise raise
Git.download(self, ud, d) Git.download(self, ud, d)
self.call_process_submodules(ud, d, self.need_update(ud, d), download_submodule)
# If we're using a shallow mirror tarball it needs to be unpacked
# temporarily so that we can examine the .gitmodules file
if ud.shallow and os.path.exists(ud.fullshallow) and self.need_update(ud, d):
tmpdir = tempfile.mkdtemp(dir=d.getVar("DL_DIR"))
runfetchcmd("tar -xzf %s" % ud.fullshallow, d, workdir=tmpdir)
self.process_submodules(ud, tmpdir, download_submodule, d)
shutil.rmtree(tmpdir)
else:
self.process_submodules(ud, ud.clonedir, download_submodule, d)
def unpack(self, ud, destdir, d): def unpack(self, ud, destdir, d):
def unpack_submodules(ud, url, module, modpath, workdir, d): def unpack_submodules(ud, url, module, modpath, workdir, d):
@@ -214,10 +207,6 @@ class GitSM(Git):
try: try:
newfetch = Fetch([url], d, cache=False) newfetch = Fetch([url], d, cache=False)
# modpath is needed by unpack tracer to calculate submodule
# checkout dir
new_ud = newfetch.ud[url]
new_ud.modpath = modpath
newfetch.unpack(root=os.path.dirname(os.path.join(repo_conf, 'modules', module))) newfetch.unpack(root=os.path.dirname(os.path.join(repo_conf, 'modules', module)))
except Exception as e: except Exception as e:
logger.error('gitsm: submodule unpack failed: %s %s' % (type(e).__name__, str(e))) logger.error('gitsm: submodule unpack failed: %s %s' % (type(e).__name__, str(e)))
@@ -243,24 +232,10 @@ class GitSM(Git):
ret = self.process_submodules(ud, ud.destdir, unpack_submodules, d) ret = self.process_submodules(ud, ud.destdir, unpack_submodules, d)
if not ud.bareclone and ret: if not ud.bareclone and ret:
cmdprefix = "" # All submodules should already be downloaded and configured in the tree. This simply sets
# Avoid LFS smudging (replacing the LFS pointers with the actual content) when LFS shouldn't be used but git-lfs is installed. # up the configuration and checks out the files. The main project config should remain
if not self._need_lfs(ud): # unmodified, and no download from the internet should occur.
cmdprefix = "GIT_LFS_SKIP_SMUDGE=1 " runfetchcmd("%s submodule update --recursive --no-fetch" % (ud.basecmd), d, quiet=True, workdir=ud.destdir)
runfetchcmd("%s%s submodule update --recursive --no-fetch" % (cmdprefix, ud.basecmd), d, quiet=True, workdir=ud.destdir)
def clean(self, ud, d):
def clean_submodule(ud, url, module, modpath, workdir, d):
url += ";bareclone=1;nobranch=1"
try:
newfetch = Fetch([url], d, cache=False)
newfetch.clean()
except Exception as e:
logger.warning('gitsm: submodule clean failed: %s %s' % (type(e).__name__, str(e)))
self.call_process_submodules(ud, d, True, clean_submodule)
# Clean top git dir
Git.clean(self, ud, d)
def implicit_urldata(self, ud, d): def implicit_urldata(self, ud, d):
import shutil, subprocess, tempfile import shutil, subprocess, tempfile
@@ -271,6 +246,14 @@ class GitSM(Git):
newfetch = Fetch([url], d, cache=False) newfetch = Fetch([url], d, cache=False)
urldata.extend(newfetch.expanded_urldata()) urldata.extend(newfetch.expanded_urldata())
self.call_process_submodules(ud, d, ud.method.need_update(ud, d), add_submodule) # If we're using a shallow mirror tarball it needs to be unpacked
# temporarily so that we can examine the .gitmodules file
if ud.shallow and os.path.exists(ud.fullshallow) and ud.method.need_update(ud, d):
tmpdir = tempfile.mkdtemp(dir=d.getVar("DL_DIR"))
subprocess.check_call("tar -xzf %s" % ud.fullshallow, cwd=tmpdir, shell=True)
self.process_submodules(ud, tmpdir, add_submodule, d)
shutil.rmtree(tmpdir)
else:
self.process_submodules(ud, ud.clonedir, add_submodule, d)
return urldata return urldata

View File

@@ -242,7 +242,6 @@ class Hg(FetchMethod):
revflag = "-r %s" % ud.revision revflag = "-r %s" % ud.revision
subdir = ud.parm.get("destsuffix", ud.module) subdir = ud.parm.get("destsuffix", ud.module)
codir = "%s/%s" % (destdir, subdir) codir = "%s/%s" % (destdir, subdir)
ud.unpack_tracer.unpack("hg", codir)
scmdata = ud.parm.get("scmdata", "") scmdata = ud.parm.get("scmdata", "")
if scmdata != "nokeep": if scmdata != "nokeep":

View File

@@ -41,9 +41,9 @@ class Local(FetchMethod):
""" """
Return the local filename of a given url assuming a successful fetch. Return the local filename of a given url assuming a successful fetch.
""" """
return self.localfile_searchpaths(urldata, d)[-1] return self.localpaths(urldata, d)[-1]
def localfile_searchpaths(self, urldata, d): def localpaths(self, urldata, d):
""" """
Return the local filename of a given url assuming a successful fetch. Return the local filename of a given url assuming a successful fetch.
""" """
@@ -51,14 +51,18 @@ class Local(FetchMethod):
path = urldata.decodedurl path = urldata.decodedurl
newpath = path newpath = path
if path[0] == "/": if path[0] == "/":
logger.debug2("Using absolute %s" % (path))
return [path] return [path]
filespath = d.getVar('FILESPATH') filespath = d.getVar('FILESPATH')
if filespath: if filespath:
logger.debug2("Searching for %s in paths:\n %s" % (path, "\n ".join(filespath.split(":")))) logger.debug2("Searching for %s in paths:\n %s" % (path, "\n ".join(filespath.split(":"))))
newpath, hist = bb.utils.which(filespath, path, history=True) newpath, hist = bb.utils.which(filespath, path, history=True)
logger.debug2("Using %s for %s" % (newpath, path))
searched.extend(hist) searched.extend(hist)
if not os.path.exists(newpath):
dldirfile = os.path.join(d.getVar("DL_DIR"), path)
logger.debug2("Defaulting to %s for %s" % (dldirfile, path))
bb.utils.mkdirhier(os.path.dirname(dldirfile))
searched.append(dldirfile)
return searched
return searched return searched
def need_update(self, ud, d): def need_update(self, ud, d):
@@ -74,7 +78,9 @@ class Local(FetchMethod):
filespath = d.getVar('FILESPATH') filespath = d.getVar('FILESPATH')
if filespath: if filespath:
locations = filespath.split(":") locations = filespath.split(":")
msg = "Unable to find file " + urldata.url + " anywhere to download to " + urldata.localpath + ". The paths that were searched were:\n " + "\n ".join(locations) locations.append(d.getVar("DL_DIR"))
msg = "Unable to find file " + urldata.url + " anywhere. The paths that were searched were:\n " + "\n ".join(locations)
raise FetchError(msg) raise FetchError(msg)
return True return True

View File

@@ -44,12 +44,9 @@ def npm_package(package):
"""Convert the npm package name to remove unsupported character""" """Convert the npm package name to remove unsupported character"""
# Scoped package names (with the @) use the same naming convention # Scoped package names (with the @) use the same naming convention
# as the 'npm pack' command. # as the 'npm pack' command.
name = re.sub("/", "-", package) if package.startswith("@"):
name = name.lower() return re.sub("/", "-", package[1:])
name = re.sub(r"[^\-a-z0-9]", "", name) return package
name = name.strip("-")
return name
def npm_filename(package, version): def npm_filename(package, version):
"""Get the filename of a npm package""" """Get the filename of a npm package"""
@@ -106,7 +103,6 @@ class NpmEnvironment(object):
"""Run npm command in a controlled environment""" """Run npm command in a controlled environment"""
with tempfile.TemporaryDirectory() as tmpdir: with tempfile.TemporaryDirectory() as tmpdir:
d = bb.data.createCopy(self.d) d = bb.data.createCopy(self.d)
d.setVar("PATH", d.getVar("PATH")) # PATH might contain $HOME - evaluate it before patching
d.setVar("HOME", tmpdir) d.setVar("HOME", tmpdir)
if not workdir: if not workdir:
@@ -160,7 +156,7 @@ class Npm(FetchMethod):
raise ParameterError("Invalid 'version' parameter", ud.url) raise ParameterError("Invalid 'version' parameter", ud.url)
# Extract the 'registry' part of the url # Extract the 'registry' part of the url
ud.registry = re.sub(r"^npm://", "https://", ud.url.split(";")[0]) ud.registry = re.sub(r"^npm://", "http://", ud.url.split(";")[0])
# Using the 'downloadfilename' parameter as local filename # Using the 'downloadfilename' parameter as local filename
# or the npm package name. # or the npm package name.
@@ -298,7 +294,6 @@ class Npm(FetchMethod):
destsuffix = ud.parm.get("destsuffix", "npm") destsuffix = ud.parm.get("destsuffix", "npm")
destdir = os.path.join(rootdir, destsuffix) destdir = os.path.join(rootdir, destsuffix)
npm_unpack(ud.localpath, destdir, d) npm_unpack(ud.localpath, destdir, d)
ud.unpack_tracer.unpack("npm", destdir)
def clean(self, ud, d): def clean(self, ud, d):
"""Clean any existing full or partial download""" """Clean any existing full or partial download"""

View File

@@ -41,9 +41,8 @@ def foreach_dependencies(shrinkwrap, callback=None, dev=False):
with: with:
name = the package name (string) name = the package name (string)
params = the package parameters (dictionary) params = the package parameters (dictionary)
destdir = the destination of the package (string) deptree = the package dependency tree (array of strings)
""" """
# For handling old style dependencies entries in shinkwrap files
def _walk_deps(deps, deptree): def _walk_deps(deps, deptree):
for name in deps: for name in deps:
subtree = [*deptree, name] subtree = [*deptree, name]
@@ -53,21 +52,8 @@ def foreach_dependencies(shrinkwrap, callback=None, dev=False):
continue continue
elif deps[name].get("bundled", False): elif deps[name].get("bundled", False):
continue continue
destsubdirs = [os.path.join("node_modules", dep) for dep in subtree] callback(name, deps[name], subtree)
destsuffix = os.path.join(*destsubdirs)
callback(name, deps[name], destsuffix)
# packages entry means new style shrinkwrap file, else use dependencies
packages = shrinkwrap.get("packages", None)
if packages is not None:
for package in packages:
if package != "":
name = package.split('node_modules/')[-1]
package_infos = packages.get(package, {})
if dev == False and package_infos.get("dev", False):
continue
callback(name, package_infos, package)
else:
_walk_deps(shrinkwrap.get("dependencies", {}), []) _walk_deps(shrinkwrap.get("dependencies", {}), [])
class NpmShrinkWrap(FetchMethod): class NpmShrinkWrap(FetchMethod):
@@ -89,10 +75,12 @@ class NpmShrinkWrap(FetchMethod):
# Resolve the dependencies # Resolve the dependencies
ud.deps = [] ud.deps = []
def _resolve_dependency(name, params, destsuffix): def _resolve_dependency(name, params, deptree):
url = None url = None
localpath = None localpath = None
extrapaths = [] extrapaths = []
destsubdirs = [os.path.join("node_modules", dep) for dep in deptree]
destsuffix = os.path.join(*destsubdirs)
unpack = True unpack = True
integrity = params.get("integrity", None) integrity = params.get("integrity", None)
@@ -141,28 +129,10 @@ class NpmShrinkWrap(FetchMethod):
localpath = os.path.join(d.getVar("DL_DIR"), localfile) localpath = os.path.join(d.getVar("DL_DIR"), localfile)
# Handle local tarball and link sources
elif version.startswith("file"):
localpath = version[5:]
if not version.endswith(".tgz"):
unpack = False
# Handle git sources # Handle git sources
elif version.startswith(("git", "bitbucket","gist")) or ( elif version.startswith("git"):
not version.endswith((".tgz", ".tar", ".tar.gz"))
and not version.startswith((".", "@", "/"))
and "/" in version
):
if version.startswith("github:"): if version.startswith("github:"):
version = "git+https://github.com/" + version[len("github:"):] version = "git+https://github.com/" + version[len("github:"):]
elif version.startswith("gist:"):
version = "git+https://gist.github.com/" + version[len("gist:"):]
elif version.startswith("bitbucket:"):
version = "git+https://bitbucket.org/" + version[len("bitbucket:"):]
elif version.startswith("gitlab:"):
version = "git+https://gitlab.com/" + version[len("gitlab:"):]
elif not version.startswith(("git+","git:")):
version = "git+https://github.com/" + version
regex = re.compile(r""" regex = re.compile(r"""
^ ^
git\+ git\+
@@ -188,12 +158,16 @@ class NpmShrinkWrap(FetchMethod):
url = str(uri) url = str(uri)
# Handle local tarball and link sources
elif version.startswith("file"):
localpath = version[5:]
if not version.endswith(".tgz"):
unpack = False
else: else:
raise ParameterError("Unsupported dependency: %s" % name, ud.url) raise ParameterError("Unsupported dependency: %s" % name, ud.url)
# name is needed by unpack tracer for module mapping
ud.deps.append({ ud.deps.append({
"name": name,
"url": url, "url": url,
"localpath": localpath, "localpath": localpath,
"extrapaths": extrapaths, "extrapaths": extrapaths,
@@ -219,16 +193,12 @@ class NpmShrinkWrap(FetchMethod):
# This fetcher resolves multiple URIs from a shrinkwrap file and then # This fetcher resolves multiple URIs from a shrinkwrap file and then
# forwards it to a proxy fetcher. The management of the donestamp file, # forwards it to a proxy fetcher. The management of the donestamp file,
# the lockfile and the checksums are forwarded to the proxy fetcher. # the lockfile and the checksums are forwarded to the proxy fetcher.
shrinkwrap_urls = [dep["url"] for dep in ud.deps if dep["url"]] ud.proxy = Fetch([dep["url"] for dep in ud.deps if dep["url"]], data)
if shrinkwrap_urls:
ud.proxy = Fetch(shrinkwrap_urls, data)
ud.needdonestamp = False ud.needdonestamp = False
@staticmethod @staticmethod
def _foreach_proxy_method(ud, handle): def _foreach_proxy_method(ud, handle):
returns = [] returns = []
#Check if there are dependencies before try to fetch them
if len(ud.deps) > 0:
for proxy_url in ud.proxy.urls: for proxy_url in ud.proxy.urls:
proxy_ud = ud.proxy.ud[proxy_url] proxy_ud = ud.proxy.ud[proxy_url]
proxy_d = ud.proxy.d proxy_d = ud.proxy.d
@@ -272,7 +242,6 @@ class NpmShrinkWrap(FetchMethod):
destsuffix = ud.parm.get("destsuffix") destsuffix = ud.parm.get("destsuffix")
if destsuffix: if destsuffix:
destdir = os.path.join(rootdir, destsuffix) destdir = os.path.join(rootdir, destsuffix)
ud.unpack_tracer.unpack("npm-shrinkwrap", destdir)
bb.utils.mkdirhier(destdir) bb.utils.mkdirhier(destdir)
bb.utils.copyfile(ud.shrinkwrap_file, bb.utils.copyfile(ud.shrinkwrap_file,

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
""" """
@@ -11,7 +9,6 @@ Based on the svn "Fetch" implementation.
import logging import logging
import os import os
import re
import bb import bb
from bb.fetch2 import FetchMethod from bb.fetch2 import FetchMethod
from bb.fetch2 import FetchError from bb.fetch2 import FetchError
@@ -39,7 +36,6 @@ class Osc(FetchMethod):
# Create paths to osc checkouts # Create paths to osc checkouts
oscdir = d.getVar("OSCDIR") or (d.getVar("DL_DIR") + "/osc") oscdir = d.getVar("OSCDIR") or (d.getVar("DL_DIR") + "/osc")
relpath = self._strip_leading_slashes(ud.path) relpath = self._strip_leading_slashes(ud.path)
ud.oscdir = oscdir
ud.pkgdir = os.path.join(oscdir, ud.host) ud.pkgdir = os.path.join(oscdir, ud.host)
ud.moddir = os.path.join(ud.pkgdir, relpath, ud.module) ud.moddir = os.path.join(ud.pkgdir, relpath, ud.module)
@@ -47,13 +43,13 @@ class Osc(FetchMethod):
ud.revision = ud.parm['rev'] ud.revision = ud.parm['rev']
else: else:
pv = d.getVar("PV", False) pv = d.getVar("PV", False)
rev = bb.fetch2.srcrev_internal_helper(ud, d, '') rev = bb.fetch2.srcrev_internal_helper(ud, d)
if rev: if rev:
ud.revision = rev ud.revision = rev
else: else:
ud.revision = "" ud.revision = ""
ud.localfile = d.expand('%s_%s_%s.tar.gz' % (ud.module.replace('/', '.'), relpath.replace('/', '.'), ud.revision)) ud.localfile = d.expand('%s_%s_%s.tar.gz' % (ud.module.replace('/', '.'), ud.path.replace('/', '.'), ud.revision))
def _buildosccommand(self, ud, d, command): def _buildosccommand(self, ud, d, command):
""" """
@@ -63,49 +59,26 @@ class Osc(FetchMethod):
basecmd = d.getVar("FETCHCMD_osc") or "/usr/bin/env osc" basecmd = d.getVar("FETCHCMD_osc") or "/usr/bin/env osc"
proto = ud.parm.get('protocol', 'https') proto = ud.parm.get('protocol', 'ocs')
options = [] options = []
config = "-c %s" % self.generate_config(ud, d) config = "-c %s" % self.generate_config(ud, d)
if getattr(ud, 'revision', ''): if ud.revision:
options.append("-r %s" % ud.revision) options.append("-r %s" % ud.revision)
coroot = self._strip_leading_slashes(ud.path) coroot = self._strip_leading_slashes(ud.path)
if command == "fetch": if command == "fetch":
osccmd = "%s %s -A %s://%s co %s/%s %s" % (basecmd, config, proto, ud.host, coroot, ud.module, " ".join(options)) osccmd = "%s %s co %s/%s %s" % (basecmd, config, coroot, ud.module, " ".join(options))
elif command == "update": elif command == "update":
osccmd = "%s %s -A %s://%s up %s" % (basecmd, config, proto, ud.host, " ".join(options)) osccmd = "%s %s up %s" % (basecmd, config, " ".join(options))
elif command == "api_source":
osccmd = "%s %s -A %s://%s api source/%s/%s" % (basecmd, config, proto, ud.host, coroot, ud.module)
else: else:
raise FetchError("Invalid osc command %s" % command, ud.url) raise FetchError("Invalid osc command %s" % command, ud.url)
return osccmd return osccmd
def _latest_revision(self, ud, d, name):
"""
Fetch latest revision for the given package
"""
api_source_cmd = self._buildosccommand(ud, d, "api_source")
output = runfetchcmd(api_source_cmd, d)
match = re.match(r'<directory ?.* rev="(\d+)".*>', output)
if match is None:
raise FetchError("Unable to parse osc response", ud.url)
return match.groups()[0]
def _revision_key(self, ud, d, name):
"""
Return a unique key for the url
"""
# Collapse adjacent slashes
slash_re = re.compile(r"/+")
rev = getattr(ud, 'revision', "latest")
return "osc:%s%s.%s.%s" % (ud.host, slash_re.sub(".", ud.path), name, rev)
def download(self, ud, d): def download(self, ud, d):
""" """
Fetch url Fetch url
@@ -113,7 +86,7 @@ class Osc(FetchMethod):
logger.debug2("Fetch: checking for module directory '" + ud.moddir + "'") logger.debug2("Fetch: checking for module directory '" + ud.moddir + "'")
if os.access(ud.moddir, os.R_OK): if os.access(os.path.join(d.getVar('OSCDIR'), ud.path, ud.module), os.R_OK):
oscupdatecmd = self._buildosccommand(ud, d, "update") oscupdatecmd = self._buildosccommand(ud, d, "update")
logger.info("Update "+ ud.url) logger.info("Update "+ ud.url)
# update sources there # update sources there
@@ -141,23 +114,20 @@ class Osc(FetchMethod):
Generate a .oscrc to be used for this run. Generate a .oscrc to be used for this run.
""" """
config_path = os.path.join(ud.oscdir, "oscrc") config_path = os.path.join(d.getVar('OSCDIR'), "oscrc")
if not os.path.exists(ud.oscdir):
bb.utils.mkdirhier(ud.oscdir)
if (os.path.exists(config_path)): if (os.path.exists(config_path)):
os.remove(config_path) os.remove(config_path)
f = open(config_path, 'w') f = open(config_path, 'w')
proto = ud.parm.get('protocol', 'https')
f.write("[general]\n") f.write("[general]\n")
f.write("apiurl = %s://%s\n" % (proto, ud.host)) f.write("apisrv = %s\n" % ud.host)
f.write("scheme = http\n")
f.write("su-wrapper = su -c\n") f.write("su-wrapper = su -c\n")
f.write("build-root = %s\n" % d.getVar('WORKDIR')) f.write("build-root = %s\n" % d.getVar('WORKDIR'))
f.write("urllist = %s\n" % d.getVar("OSCURLLIST")) f.write("urllist = %s\n" % d.getVar("OSCURLLIST"))
f.write("extra-pkgs = gzip\n") f.write("extra-pkgs = gzip\n")
f.write("\n") f.write("\n")
f.write("[%s://%s]\n" % (proto, ud.host)) f.write("[%s]\n" % ud.host)
f.write("user = %s\n" % ud.parm["user"]) f.write("user = %s\n" % ud.parm["user"])
f.write("pass = %s\n" % ud.parm["pswd"]) f.write("pass = %s\n" % ud.parm["pswd"])
f.close() f.close()

View File

@@ -103,7 +103,7 @@ class SFTP(FetchMethod):
if path[:3] == '/~/': if path[:3] == '/~/':
path = path[3:] path = path[3:]
remote = '"%s%s:%s"' % (user, urlo.hostname, path) remote = '%s%s:%s' % (user, urlo.hostname, path)
cmd = '%s %s %s %s' % (basecmd, port, remote, lpath) cmd = '%s %s %s %s' % (basecmd, port, remote, lpath)

View File

@@ -32,7 +32,6 @@ IETF secsh internet draft:
import re, os import re, os
from bb.fetch2 import check_network_access, FetchMethod, ParameterError, runfetchcmd from bb.fetch2 import check_network_access, FetchMethod, ParameterError, runfetchcmd
import urllib
__pattern__ = re.compile(r''' __pattern__ = re.compile(r'''
@@ -71,7 +70,6 @@ class SSH(FetchMethod):
"git:// prefix with protocol=ssh", urldata.url) "git:// prefix with protocol=ssh", urldata.url)
m = __pattern__.match(urldata.url) m = __pattern__.match(urldata.url)
path = m.group('path') path = m.group('path')
path = urllib.parse.unquote(path)
host = m.group('host') host = m.group('host')
urldata.localpath = os.path.join(d.getVar('DL_DIR'), urldata.localpath = os.path.join(d.getVar('DL_DIR'),
os.path.basename(os.path.normpath(path))) os.path.basename(os.path.normpath(path)))
@@ -101,7 +99,7 @@ class SSH(FetchMethod):
if path[0] != '~': if path[0] != '~':
path = '/%s' % path path = '/%s' % path
path = urllib.parse.unquote(path) path = path.replace("%3A", ":")
fr += ':%s' % path fr += ':%s' % path
@@ -141,7 +139,7 @@ class SSH(FetchMethod):
if path[0] != '~': if path[0] != '~':
path = '/%s' % path path = '/%s' % path
path = urllib.parse.unquote(path) path = path.replace("%3A", ":")
cmd = 'ssh -o BatchMode=true %s %s [ -f %s ]' % ( cmd = 'ssh -o BatchMode=true %s %s [ -f %s ]' % (
portarg, portarg,
@@ -150,6 +148,8 @@ class SSH(FetchMethod):
) )
check_network_access(d, cmd, urldata.url) check_network_access(d, cmd, urldata.url)
runfetchcmd(cmd, d)
if runfetchcmd(cmd, d):
return True return True
return False

View File

@@ -26,6 +26,7 @@ from bb.fetch2 import FetchMethod
from bb.fetch2 import FetchError from bb.fetch2 import FetchError
from bb.fetch2 import logger from bb.fetch2 import logger
from bb.fetch2 import runfetchcmd from bb.fetch2 import runfetchcmd
from bb.utils import export_proxies
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from bs4 import SoupStrainer from bs4 import SoupStrainer
@@ -87,10 +88,7 @@ class Wget(FetchMethod):
if not ud.localfile: if not ud.localfile:
ud.localfile = d.expand(urllib.parse.unquote(ud.host + ud.path).replace("/", ".")) ud.localfile = d.expand(urllib.parse.unquote(ud.host + ud.path).replace("/", "."))
self.basecmd = d.getVar("FETCHCMD_wget") or "/usr/bin/env wget -t 2 -T 100" self.basecmd = d.getVar("FETCHCMD_wget") or "/usr/bin/env wget -t 2 -T 30 --passive-ftp"
if ud.type == 'ftp' or ud.type == 'ftps':
self.basecmd += " --passive-ftp"
if not self.check_certs(d): if not self.check_certs(d):
self.basecmd += " --no-check-certificate" self.basecmd += " --no-check-certificate"
@@ -108,8 +106,8 @@ class Wget(FetchMethod):
fetchcmd = self.basecmd fetchcmd = self.basecmd
dldir = os.path.realpath(d.getVar("DL_DIR")) if 'downloadfilename' in ud.parm:
localpath = os.path.join(dldir, ud.localfile) + ".tmp" localpath = os.path.join(d.getVar("DL_DIR"), ud.localfile)
bb.utils.mkdirhier(os.path.dirname(localpath)) bb.utils.mkdirhier(os.path.dirname(localpath))
fetchcmd += " -O %s" % shlex.quote(localpath) fetchcmd += " -O %s" % shlex.quote(localpath)
@@ -129,30 +127,21 @@ class Wget(FetchMethod):
uri = ud.url.split(";")[0] uri = ud.url.split(";")[0]
if os.path.exists(ud.localpath): if os.path.exists(ud.localpath):
# file exists, but we didnt complete it.. trying again.. # file exists, but we didnt complete it.. trying again..
fetchcmd += " -c -P " + dldir + " '" + uri + "'" fetchcmd += d.expand(" -c -P ${DL_DIR} '%s'" % uri)
else: else:
fetchcmd += " -P " + dldir + " '" + uri + "'" fetchcmd += d.expand(" -P ${DL_DIR} '%s'" % uri)
self._runwget(ud, d, fetchcmd, False) self._runwget(ud, d, fetchcmd, False)
# Sanity check since wget can pretend it succeed when it didn't # Sanity check since wget can pretend it succeed when it didn't
# Also, this used to happen if sourceforge sent us to the mirror page # Also, this used to happen if sourceforge sent us to the mirror page
if not os.path.exists(localpath): if not os.path.exists(ud.localpath):
raise FetchError("The fetch command returned success for url %s but %s doesn't exist?!" % (uri, localpath), uri) raise FetchError("The fetch command returned success for url %s but %s doesn't exist?!" % (uri, ud.localpath), uri)
if os.path.getsize(localpath) == 0: if os.path.getsize(ud.localpath) == 0:
os.remove(localpath) os.remove(ud.localpath)
raise FetchError("The fetch of %s resulted in a zero size file?! Deleting and failing since this isn't right." % (uri), uri) raise FetchError("The fetch of %s resulted in a zero size file?! Deleting and failing since this isn't right." % (uri), uri)
# Try and verify any checksum now, meaning if it isn't correct, we don't remove the
# original file, which might be a race (imagine two recipes referencing the same
# source, one with an incorrect checksum)
bb.fetch2.verify_checksum(ud, d, localpath=localpath, fatal_nochecksum=False)
# Remove the ".tmp" and move the file into position atomically
# Our lock prevents multiple writers but mirroring code may grab incomplete files
os.rename(localpath, localpath[:-4])
return True return True
def checkstatus(self, fetch, ud, d, try_again=True): def checkstatus(self, fetch, ud, d, try_again=True):
@@ -303,70 +292,15 @@ class Wget(FetchMethod):
http_error_403 = http_error_405 http_error_403 = http_error_405
def _url_origin(url):
parsed = urllib.parse.urlsplit(url)
scheme = parsed.scheme.lower()
host = parsed.hostname.lower() if parsed.hostname else ""
port = parsed.port
if port is None:
port = {"http": 80, "https": 443}.get(scheme)
return (scheme, host, port)
def _same_origin(url_a, url_b):
return _url_origin(url_a) == _url_origin(url_b)
class FixedHTTPRedirectHandler(urllib.request.HTTPRedirectHandler): class FixedHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
""" """
urllib2.HTTPRedirectHandler before 3.13 has two flaws: urllib2.HTTPRedirectHandler resets the method to GET on redirect,
when we want to follow redirects using the original method.
It resets the method to GET on redirect when we want to follow
redirects using the original method (typically HEAD). This was fixed
in 759e8e7.
It also doesn't handle 308 (Permanent Redirect). This was fixed in
c379bc5.
Until we depend on Python 3.13 onwards, copy the redirect_request
method to fix these issues.
Additionally, strip sensitive headers (Authorization, Cookie) when
redirecting to a different origin to avoid credential leaks.
""" """
def redirect_request(self, req, fp, code, msg, headers, newurl): def redirect_request(self, req, fp, code, msg, headers, newurl):
m = req.get_method() newreq = urllib.request.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, headers, newurl)
if (not (code in (301, 302, 303, 307, 308) and m in ("GET", "HEAD") newreq.get_method = req.get_method
or code in (301, 302, 303) and m == "POST")): return newreq
raise urllib.HTTPError(req.full_url, code, msg, headers, fp)
# Strictly (according to RFC 2616), 301 or 302 in response to
# a POST MUST NOT cause a redirection without confirmation
# from the user (of urllib.request, in this case). In practice,
# essentially all clients do redirect in this case, so we do
# the same.
# Be conciliant with URIs containing a space. This is mainly
# redundant with the more complete encoding done in http_error_302(),
# but it is kept for compatibility with other callers.
newurl = newurl.replace(' ', '%20')
CONTENT_HEADERS = ("content-length", "content-type")
SENSITIVE_REDIRECT_HEADERS = ("authorization", "cookie")
same_origin = _same_origin(req.get_full_url(), newurl)
newheaders = {}
for k, v in req.headers.items():
header = k.lower()
if header in CONTENT_HEADERS:
continue
if not same_origin and header in SENSITIVE_REDIRECT_HEADERS:
continue
newheaders[k] = v
return urllib.request.Request(newurl,
method="HEAD" if m == "HEAD" else "GET",
headers=newheaders,
origin_req_host=req.origin_req_host,
unverifiable=True)
http_error_308 = urllib.request.HTTPRedirectHandler.http_error_302
# We need to update the environment here as both the proxy and HTTPS # We need to update the environment here as both the proxy and HTTPS
# handlers need variables set. The proxy needs http_proxy and friends to # handlers need variables set. The proxy needs http_proxy and friends to
@@ -399,11 +333,7 @@ class Wget(FetchMethod):
opener = urllib.request.build_opener(*handlers) opener = urllib.request.build_opener(*handlers)
try: try:
parts = urllib.parse.urlparse(ud.url.split(";")[0]) uri = ud.url.split(";")[0]
if parts.query:
uri = "{}://{}{}?{}".format(parts.scheme, parts.netloc, parts.path, parts.query)
else:
uri = "{}://{}{}".format(parts.scheme, parts.netloc, parts.path)
r = urllib.request.Request(uri) r = urllib.request.Request(uri)
r.get_method = lambda: "HEAD" r.get_method = lambda: "HEAD"
# Some servers (FusionForge, as used on Alioth) require that the # Some servers (FusionForge, as used on Alioth) require that the
@@ -422,22 +352,29 @@ class Wget(FetchMethod):
try: try:
import netrc import netrc
auth_data = netrc.netrc().authenticators(urllib.parse.urlparse(uri).hostname) n = netrc.netrc()
if auth_data: login, unused, password = n.authenticators(urllib.parse.urlparse(uri).hostname)
login, _, password = auth_data
add_basic_auth("%s:%s" % (login, password), r) add_basic_auth("%s:%s" % (login, password), r)
except (FileNotFoundError, netrc.NetrcParseError): except (TypeError, ImportError, IOError, netrc.NetrcParseError):
pass pass
with opener.open(r, timeout=100) as response: with opener.open(r, timeout=30) as response:
pass pass
except (urllib.error.URLError, ConnectionResetError, TimeoutError) as e: except urllib.error.URLError as e:
if try_again: if try_again:
logger.debug2("checkstatus: trying again") logger.debug2("checkstatus: trying again")
return self.checkstatus(fetch, ud, d, False) return self.checkstatus(fetch, ud, d, False)
else: else:
# debug for now to avoid spamming the logs in e.g. remote sstate searches # debug for now to avoid spamming the logs in e.g. remote sstate searches
logger.debug2("checkstatus() urlopen failed for %s: %s" % (uri,e)) logger.debug2("checkstatus() urlopen failed: %s" % e)
return False
except ConnectionResetError as e:
if try_again:
logger.debug2("checkstatus: trying again")
return self.checkstatus(fetch, ud, d, False)
else:
# debug for now to avoid spamming the logs in e.g. remote sstate searches
logger.debug2("checkstatus() urlopen failed: %s" % e)
return False return False
return True return True
@@ -699,10 +636,10 @@ class Wget(FetchMethod):
# search for version matches on folders inside the path, like: # search for version matches on folders inside the path, like:
# "5.7" in http://download.gnome.org/sources/${PN}/5.7/${PN}-${PV}.tar.gz # "5.7" in http://download.gnome.org/sources/${PN}/5.7/${PN}-${PV}.tar.gz
dirver_regex = re.compile(r"(?P<dirver>[^/]*(\d+\.)*\d+([-_]r\d+)*)/") dirver_regex = re.compile(r"(?P<dirver>[^/]*(\d+\.)*\d+([-_]r\d+)*)/")
m = dirver_regex.findall(path) m = dirver_regex.search(path)
if m: if m:
pn = d.getVar('PN') pn = d.getVar('PN')
dirver = m[-1][0] dirver = m.group('dirver')
dirver_pn_regex = re.compile(r"%s\d?" % (re.escape(pn))) dirver_pn_regex = re.compile(r"%s\d?" % (re.escape(pn)))
if not dirver_pn_regex.search(dirver): if not dirver_pn_regex.search(dirver):

View File

@@ -12,12 +12,11 @@
import os import os
import sys import sys
import logging import logging
import argparse import optparse
import warnings import warnings
import fcntl import fcntl
import time import time
import traceback import traceback
import datetime
import bb import bb
from bb import event from bb import event
@@ -44,18 +43,18 @@ def present_options(optionlist):
else: else:
return optionlist[0] return optionlist[0]
class BitbakeHelpFormatter(argparse.HelpFormatter): class BitbakeHelpFormatter(optparse.IndentedHelpFormatter):
def _get_help_string(self, action): def format_option(self, option):
# We need to do this here rather than in the text we supply to # We need to do this here rather than in the text we supply to
# add_option() because we don't want to call list_extension_modules() # add_option() because we don't want to call list_extension_modules()
# on every execution (since it imports all of the modules) # on every execution (since it imports all of the modules)
# Note also that we modify option.help rather than the returned text # Note also that we modify option.help rather than the returned text
# - this is so that we don't have to re-format the text ourselves # - this is so that we don't have to re-format the text ourselves
if action.dest == 'ui': if option.dest == 'ui':
valid_uis = list_extension_modules(bb.ui, 'main') valid_uis = list_extension_modules(bb.ui, 'main')
return action.help.replace('@CHOICES@', present_options(valid_uis)) option.help = option.help.replace('@CHOICES@', present_options(valid_uis))
return action.help return optparse.IndentedHelpFormatter.format_option(self, option)
def list_extension_modules(pkg, checkattr): def list_extension_modules(pkg, checkattr):
""" """
@@ -115,121 +114,50 @@ def _showwarning(message, category, filename, lineno, file=None, line=None):
warnings.showwarning = _showwarning warnings.showwarning = _showwarning
def create_bitbake_parser(): def create_bitbake_parser():
parser = argparse.ArgumentParser( parser = optparse.OptionParser(
description="""\ formatter=BitbakeHelpFormatter(),
version="BitBake Build Tool Core version %s" % bb.__version__,
usage="""%prog [options] [recipename/target recipe:do_task ...]
Executes the specified task (default is 'build') for a given set of target recipes (.bb files).
It is assumed there is a conf/bblayers.conf available in cwd or in BBPATH which It is assumed there is a conf/bblayers.conf available in cwd or in BBPATH which
will provide the layer, BBFILES and other configuration information. will provide the layer, BBFILES and other configuration information.""")
""",
formatter_class=BitbakeHelpFormatter,
allow_abbrev=False,
add_help=False, # help is manually added below in a specific argument group
)
general_group = parser.add_argument_group('General options') parser.add_option("-b", "--buildfile", action="store", dest="buildfile", default=None,
task_group = parser.add_argument_group('Task control options') help="Execute tasks from a specific .bb recipe directly. WARNING: Does "
exec_group = parser.add_argument_group('Execution control options') "not handle any dependencies from other recipes.")
logging_group = parser.add_argument_group('Logging/output control options')
server_group = parser.add_argument_group('Server options')
config_group = parser.add_argument_group('Configuration options')
general_group.add_argument("targets", nargs="*", metavar="recipename/target", parser.add_option("-k", "--continue", action="store_false", dest="halt", default=True,
help="Execute the specified task (default is 'build') for these target " help="Continue as much as possible after an error. While the target that "
"recipes (.bb files).") "failed and anything depending on it cannot be built, as much as "
"possible will be built before stopping.")
general_group.add_argument("-s", "--show-versions", action="store_true", parser.add_option("-f", "--force", action="store_true", dest="force", default=False,
help="Show current and preferred versions of all recipes.")
general_group.add_argument("-e", "--environment", action="store_true",
dest="show_environment",
help="Show the global or per-recipe environment complete with information"
" about where variables were set/changed.")
general_group.add_argument("-g", "--graphviz", action="store_true", dest="dot_graph",
help="Save dependency tree information for the specified "
"targets in the dot syntax.")
# @CHOICES@ is substituted out by BitbakeHelpFormatter above
general_group.add_argument("-u", "--ui",
default=os.environ.get('BITBAKE_UI', 'knotty'),
help="The user interface to use (@CHOICES@ - default %(default)s).")
general_group.add_argument("--version", action="store_true",
help="Show programs version and exit.")
general_group.add_argument('-h', '--help', action='help',
help='Show this help message and exit.')
task_group.add_argument("-f", "--force", action="store_true",
help="Force the specified targets/task to run (invalidating any " help="Force the specified targets/task to run (invalidating any "
"existing stamp file).") "existing stamp file).")
task_group.add_argument("-c", "--cmd", parser.add_option("-c", "--cmd", action="store", dest="cmd",
help="Specify the task to execute. The exact options available " help="Specify the task to execute. The exact options available "
"depend on the metadata. Some examples might be 'compile'" "depend on the metadata. Some examples might be 'compile'"
" or 'populate_sysroot' or 'listtasks' may give a list of " " or 'populate_sysroot' or 'listtasks' may give a list of "
"the tasks available.") "the tasks available.")
task_group.add_argument("-C", "--clear-stamp", dest="invalidate_stamp", parser.add_option("-C", "--clear-stamp", action="store", dest="invalidate_stamp",
help="Invalidate the stamp for the specified task such as 'compile' " help="Invalidate the stamp for the specified task such as 'compile' "
"and then run the default task for the specified target(s).") "and then run the default task for the specified target(s).")
task_group.add_argument("--runall", action="append", default=[], parser.add_option("-r", "--read", action="append", dest="prefile", default=[],
help="Run the specified task for any recipe in the taskgraph of the " help="Read the specified file before bitbake.conf.")
"specified target (even if it wouldn't otherwise have run).")
task_group.add_argument("--runonly", action="append", parser.add_option("-R", "--postread", action="append", dest="postfile", default=[],
help="Run only the specified task within the taskgraph of the " help="Read the specified file after bitbake.conf.")
"specified targets (and any task dependencies those tasks may have).")
task_group.add_argument("--no-setscene", action="store_true", parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
dest="nosetscene", help="Enable tracing of shell tasks (with 'set -x'). "
help="Do not run any setscene tasks. sstate will be ignored and " "Also print bb.note(...) messages to stdout (in "
"everything needed, built.") "addition to writing them to ${T}/log.do_<task>).")
task_group.add_argument("--skip-setscene", action="store_true", parser.add_option("-D", "--debug", action="count", dest="debug", default=0,
dest="skipsetscene",
help="Skip setscene tasks if they would be executed. Tasks previously "
"restored from sstate will be kept, unlike --no-setscene.")
task_group.add_argument("--setscene-only", action="store_true",
dest="setsceneonly",
help="Only run setscene tasks, don't run any real tasks.")
exec_group.add_argument("-n", "--dry-run", action="store_true",
help="Don't execute, just go through the motions.")
exec_group.add_argument("-p", "--parse-only", action="store_true",
help="Quit after parsing the BB recipes.")
exec_group.add_argument("-k", "--continue", action="store_false", dest="halt",
help="Continue as much as possible after an error. While the target that "
"failed and anything depending on it cannot be built, as much as "
"possible will be built before stopping.")
exec_group.add_argument("-P", "--profile", action="store_true",
help="Profile the command and save reports.")
exec_group.add_argument("-S", "--dump-signatures", action="append",
default=[], metavar="SIGNATURE_HANDLER",
help="Dump out the signature construction information, with no task "
"execution. The SIGNATURE_HANDLER parameter is passed to the "
"handler. Two common values are none and printdiff but the handler "
"may define more/less. none means only dump the signature, printdiff"
" means recursively compare the dumped signature with the most recent"
" one in a local build or sstate cache (can be used to find out why tasks re-run"
" when that is not expected)")
exec_group.add_argument("--revisions-changed", action="store_true",
help="Set the exit code depending on whether upstream floating "
"revisions have changed or not.")
exec_group.add_argument("-b", "--buildfile",
help="Execute tasks from a specific .bb recipe directly. WARNING: Does "
"not handle any dependencies from other recipes.")
logging_group.add_argument("-D", "--debug", action="count", default=0,
help="Increase the debug level. You can specify this " help="Increase the debug level. You can specify this "
"more than once. -D sets the debug level to 1, " "more than once. -D sets the debug level to 1, "
"where only bb.debug(1, ...) messages are printed " "where only bb.debug(1, ...) messages are printed "
@@ -241,81 +169,125 @@ def create_bitbake_parser():
"to ${T}/log.do_taskname, regardless of the debug " "to ${T}/log.do_taskname, regardless of the debug "
"level.") "level.")
logging_group.add_argument("-l", "--log-domains", action="append", dest="debug_domains", parser.add_option("-q", "--quiet", action="count", dest="quiet", default=0,
default=[], help="Output less log message data to the terminal. You can specify this more than once.")
help="Show debug logging for the specified logging domains.")
logging_group.add_argument("-v", "--verbose", action="store_true", parser.add_option("-n", "--dry-run", action="store_true", dest="dry_run", default=False,
help="Enable tracing of shell tasks (with 'set -x'). " help="Don't execute, just go through the motions.")
"Also print bb.note(...) messages to stdout (in "
"addition to writing them to ${T}/log.do_<task>).")
logging_group.add_argument("-q", "--quiet", action="count", default=0, parser.add_option("-S", "--dump-signatures", action="append", dest="dump_signatures",
help="Output less log message data to the terminal. You can specify this " default=[], metavar="SIGNATURE_HANDLER",
"more than once.") help="Dump out the signature construction information, with no task "
"execution. The SIGNATURE_HANDLER parameter is passed to the "
"handler. Two common values are none and printdiff but the handler "
"may define more/less. none means only dump the signature, printdiff"
" means compare the dumped signature with the cached one.")
logging_group.add_argument("-w", "--write-log", dest="writeeventlog", parser.add_option("-p", "--parse-only", action="store_true",
default=os.environ.get("BBEVENTLOG"), dest="parse_only", default=False,
help="Writes the event log of the build to a bitbake event json file. " help="Quit after parsing the BB recipes.")
"Use '' (empty string) to assign the name automatically.")
parser.add_option("-s", "--show-versions", action="store_true",
dest="show_versions", default=False,
help="Show current and preferred versions of all recipes.")
server_group.add_argument("-B", "--bind", default=False, parser.add_option("-e", "--environment", action="store_true",
dest="show_environment", default=False,
help="Show the global or per-recipe environment complete with information"
" about where variables were set/changed.")
parser.add_option("-g", "--graphviz", action="store_true", dest="dot_graph", default=False,
help="Save dependency tree information for the specified "
"targets in the dot syntax.")
parser.add_option("-I", "--ignore-deps", action="append",
dest="extra_assume_provided", default=[],
help="Assume these dependencies don't exist and are already provided "
"(equivalent to ASSUME_PROVIDED). Useful to make dependency "
"graphs more appealing")
parser.add_option("-l", "--log-domains", action="append", dest="debug_domains", default=[],
help="Show debug logging for the specified logging domains")
parser.add_option("-P", "--profile", action="store_true", dest="profile", default=False,
help="Profile the command and save reports.")
# @CHOICES@ is substituted out by BitbakeHelpFormatter above
parser.add_option("-u", "--ui", action="store", dest="ui",
default=os.environ.get('BITBAKE_UI', 'knotty'),
help="The user interface to use (@CHOICES@ - default %default).")
parser.add_option("", "--token", action="store", dest="xmlrpctoken",
default=os.environ.get("BBTOKEN"),
help="Specify the connection token to be used when connecting "
"to a remote server.")
parser.add_option("", "--revisions-changed", action="store_true",
dest="revisions_changed", default=False,
help="Set the exit code depending on whether upstream floating "
"revisions have changed or not.")
parser.add_option("", "--server-only", action="store_true",
dest="server_only", default=False,
help="Run bitbake without a UI, only starting a server "
"(cooker) process.")
parser.add_option("-B", "--bind", action="store", dest="bind", default=False,
help="The name/address for the bitbake xmlrpc server to bind to.") help="The name/address for the bitbake xmlrpc server to bind to.")
server_group.add_argument("-T", "--idle-timeout", type=float, dest="server_timeout", parser.add_option("-T", "--idle-timeout", type=float, dest="server_timeout",
default=os.getenv("BB_SERVER_TIMEOUT"), default=os.getenv("BB_SERVER_TIMEOUT"),
help="Set timeout to unload bitbake server due to inactivity, " help="Set timeout to unload bitbake server due to inactivity, "
"set to -1 means no unload, " "set to -1 means no unload, "
"default: Environment variable BB_SERVER_TIMEOUT.") "default: Environment variable BB_SERVER_TIMEOUT.")
server_group.add_argument("--remote-server", parser.add_option("", "--no-setscene", action="store_true",
dest="nosetscene", default=False,
help="Do not run any setscene tasks. sstate will be ignored and "
"everything needed, built.")
parser.add_option("", "--skip-setscene", action="store_true",
dest="skipsetscene", default=False,
help="Skip setscene tasks if they would be executed. Tasks previously "
"restored from sstate will be kept, unlike --no-setscene")
parser.add_option("", "--setscene-only", action="store_true",
dest="setsceneonly", default=False,
help="Only run setscene tasks, don't run any real tasks.")
parser.add_option("", "--remote-server", action="store", dest="remote_server",
default=os.environ.get("BBSERVER"), default=os.environ.get("BBSERVER"),
help="Connect to the specified server.") help="Connect to the specified server.")
server_group.add_argument("-m", "--kill-server", action="store_true", parser.add_option("-m", "--kill-server", action="store_true",
dest="kill_server", default=False,
help="Terminate any running bitbake server.") help="Terminate any running bitbake server.")
server_group.add_argument("--token", dest="xmlrpctoken", parser.add_option("", "--observe-only", action="store_true",
default=os.environ.get("BBTOKEN"), dest="observe_only", default=False,
help="Specify the connection token to be used when connecting "
"to a remote server.")
server_group.add_argument("--observe-only", action="store_true",
help="Connect to a server as an observing-only client.") help="Connect to a server as an observing-only client.")
server_group.add_argument("--status-only", action="store_true", parser.add_option("", "--status-only", action="store_true",
dest="status_only", default=False,
help="Check the status of the remote bitbake server.") help="Check the status of the remote bitbake server.")
server_group.add_argument("--server-only", action="store_true", parser.add_option("-w", "--write-log", action="store", dest="writeeventlog",
help="Run bitbake without a UI, only starting a server " default=os.environ.get("BBEVENTLOG"),
"(cooker) process.") help="Writes the event log of the build to a bitbake event json file. "
"Use '' (empty string) to assign the name automatically.")
parser.add_option("", "--runall", action="append", dest="runall",
help="Run the specified task for any recipe in the taskgraph of the specified target (even if it wouldn't otherwise have run).")
config_group.add_argument("-r", "--read", action="append", dest="prefile", default=[], parser.add_option("", "--runonly", action="append", dest="runonly",
help="Read the specified file before bitbake.conf.") help="Run only the specified task within the taskgraph of the specified targets (and any task dependencies those tasks may have).")
config_group.add_argument("-R", "--postread", action="append", dest="postfile", default=[],
help="Read the specified file after bitbake.conf.")
config_group.add_argument("-I", "--ignore-deps", action="append",
dest="extra_assume_provided", default=[],
help="Assume these dependencies don't exist and are already provided "
"(equivalent to ASSUME_PROVIDED). Useful to make dependency "
"graphs more appealing.")
return parser return parser
class BitBakeConfigParameters(cookerdata.ConfigParameters): class BitBakeConfigParameters(cookerdata.ConfigParameters):
def parseCommandLine(self, argv=sys.argv): def parseCommandLine(self, argv=sys.argv):
parser = create_bitbake_parser() parser = create_bitbake_parser()
options = parser.parse_intermixed_args(argv[1:]) options, targets = parser.parse_args(argv)
if options.version:
print("BitBake Build Tool Core version %s" % bb.__version__)
sys.exit(0)
if options.quiet and options.verbose: if options.quiet and options.verbose:
parser.error("options --quiet and --verbose are mutually exclusive") parser.error("options --quiet and --verbose are mutually exclusive")
@@ -347,7 +319,7 @@ class BitBakeConfigParameters(cookerdata.ConfigParameters):
else: else:
options.xmlrpcinterface = (None, 0) options.xmlrpcinterface = (None, 0)
return options, options.targets return options, targets[1:]
def bitbake_main(configParams, configuration): def bitbake_main(configParams, configuration):
@@ -412,9 +384,6 @@ def bitbake_main(configParams, configuration):
return 1 return 1
def timestamp():
return datetime.datetime.now().strftime('%H:%M:%S.%f')
def setup_bitbake(configParams, extrafeatures=None): def setup_bitbake(configParams, extrafeatures=None):
# Ensure logging messages get sent to the UI as events # Ensure logging messages get sent to the UI as events
handler = bb.event.LogHandler() handler = bb.event.LogHandler()
@@ -422,11 +391,6 @@ def setup_bitbake(configParams, extrafeatures=None):
# In status only mode there are no logs and no UI # In status only mode there are no logs and no UI
logger.addHandler(handler) logger.addHandler(handler)
if configParams.dump_signatures:
if extrafeatures is None:
extrafeatures = []
extrafeatures.append(bb.cooker.CookerFeatures.RECIPE_SIGGEN_INFO)
if configParams.server_only: if configParams.server_only:
featureset = [] featureset = []
ui_module = None ui_module = None
@@ -454,7 +418,7 @@ def setup_bitbake(configParams, extrafeatures=None):
retries = 8 retries = 8
while retries: while retries:
try: try:
topdir, lock, lockfile = lockBitbake() topdir, lock = lockBitbake()
sockname = topdir + "/bitbake.sock" sockname = topdir + "/bitbake.sock"
if lock: if lock:
if configParams.status_only or configParams.kill_server: if configParams.status_only or configParams.kill_server:
@@ -465,22 +429,18 @@ def setup_bitbake(configParams, extrafeatures=None):
logger.info("Starting bitbake server...") logger.info("Starting bitbake server...")
# Clear the event queue since we already displayed messages # Clear the event queue since we already displayed messages
bb.event.ui_queue = [] bb.event.ui_queue = []
server = bb.server.process.BitBakeServer(lock, sockname, featureset, configParams.server_timeout, configParams.xmlrpcinterface, configParams.profile) server = bb.server.process.BitBakeServer(lock, sockname, featureset, configParams.server_timeout, configParams.xmlrpcinterface)
else: else:
logger.info("Reconnecting to bitbake server...") logger.info("Reconnecting to bitbake server...")
if not os.path.exists(sockname): if not os.path.exists(sockname):
logger.info("Previous bitbake instance shutting down?, waiting to retry... (%s)" % timestamp()) logger.info("Previous bitbake instance shutting down?, waiting to retry...")
procs = bb.server.process.get_lockfile_process_msg(lockfile)
if procs:
logger.info("Processes holding bitbake.lock (missing socket %s):\n%s" % (sockname, procs))
logger.info("Directory listing: %s" % (str(os.listdir(topdir))))
i = 0 i = 0
lock = None lock = None
# Wait for 5s or until we can get the lock # Wait for 5s or until we can get the lock
while not lock and i < 50: while not lock and i < 50:
time.sleep(0.1) time.sleep(0.1)
_, lock, _ = lockBitbake() _, lock = lockBitbake()
i += 1 i += 1
if lock: if lock:
bb.utils.unlockfile(lock) bb.utils.unlockfile(lock)
@@ -499,9 +459,9 @@ def setup_bitbake(configParams, extrafeatures=None):
retries -= 1 retries -= 1
tryno = 8 - retries tryno = 8 - retries
if isinstance(e, (bb.server.process.ProcessTimeout, BrokenPipeError, EOFError, SystemExit)): if isinstance(e, (bb.server.process.ProcessTimeout, BrokenPipeError, EOFError, SystemExit)):
logger.info("Retrying server connection (#%d)... (%s)" % (tryno, timestamp())) logger.info("Retrying server connection (#%d)..." % tryno)
else: else:
logger.info("Retrying server connection (#%d)... (%s, %s)" % (tryno, traceback.format_exc(), timestamp())) logger.info("Retrying server connection (#%d)... (%s)" % (tryno, traceback.format_exc()))
if not retries: if not retries:
bb.fatal("Unable to connect to bitbake server, or start one (server startup failures would be in bitbake-cookerdaemon.log).") bb.fatal("Unable to connect to bitbake server, or start one (server startup failures would be in bitbake-cookerdaemon.log).")
@@ -530,5 +490,5 @@ def lockBitbake():
bb.error("Unable to find conf/bblayers.conf or conf/bitbake.conf. BBPATH is unset and/or not in a build directory?") bb.error("Unable to find conf/bblayers.conf or conf/bitbake.conf. BBPATH is unset and/or not in a build directory?")
raise BBMainFatal raise BBMainFatal
lockfile = topdir + "/bitbake.lock" lockfile = topdir + "/bitbake.lock"
return topdir, bb.utils.lockfile(lockfile, False, False), lockfile return topdir, bb.utils.lockfile(lockfile, False, False)

View File

@@ -234,10 +234,9 @@ class diskMonitor:
freeInode = st.f_favail freeInode = st.f_favail
if minInode and freeInode < minInode: if minInode and freeInode < minInode:
# Some filesystems use dynamic inodes so can't run out. # Some filesystems use dynamic inodes so can't run out
# This is reported by the inode count being 0 (btrfs) or the free # (e.g. btrfs). This is reported by the inode count being 0.
# inode count being -1 (cephfs). if st.f_files == 0:
if st.f_files == 0 or st.f_favail == -1:
self.devDict[k][2] = None self.devDict[k][2] = None
continue continue
# Always show warning, the self.checked would always be False if the action is WARN # Always show warning, the self.checked would always be False if the action is WARN

View File

@@ -89,6 +89,10 @@ class BBLogFormatter(logging.Formatter):
msg = logging.Formatter.format(self, record) msg = logging.Formatter.format(self, record)
if hasattr(record, 'bb_exc_formatted'): if hasattr(record, 'bb_exc_formatted'):
msg += '\n' + ''.join(record.bb_exc_formatted) msg += '\n' + ''.join(record.bb_exc_formatted)
elif hasattr(record, 'bb_exc_info'):
etype, value, tb = record.bb_exc_info
formatted = bb.exceptions.format_exception(etype, value, tb, limit=5)
msg += '\n' + ''.join(formatted)
return msg return msg
def colorize(self, record): def colorize(self, record):
@@ -129,6 +133,7 @@ class LogFilterShowOnce(logging.Filter):
self.seen_errors = set() self.seen_errors = set()
def filter(self, record): def filter(self, record):
msg = record.msg
if record.levelno == bb.msg.BBLogFormatter.WARNONCE: if record.levelno == bb.msg.BBLogFormatter.WARNONCE:
if record.msg in self.seen_warnings: if record.msg in self.seen_warnings:
return False return False
@@ -226,7 +231,7 @@ def logger_create(name, output=sys.stderr, level=logging.INFO, preserve_handlers
console = logging.StreamHandler(output) console = logging.StreamHandler(output)
console.addFilter(bb.msg.LogFilterShowOnce()) console.addFilter(bb.msg.LogFilterShowOnce())
format = bb.msg.BBLogFormatter("%(levelname)s: %(message)s") format = bb.msg.BBLogFormatter("%(levelname)s: %(message)s")
if color == 'always' or (color == 'auto' and output.isatty() and os.environ.get('NO_COLOR', '') == ''): if color == 'always' or (color == 'auto' and output.isatty()):
format.enable_color() format.enable_color()
console.setFormatter(format) console.setFormatter(format)
if preserve_handlers: if preserve_handlers:

View File

@@ -49,32 +49,20 @@ class SkipPackage(SkipRecipe):
__mtime_cache = {} __mtime_cache = {}
def cached_mtime(f): def cached_mtime(f):
if f not in __mtime_cache: if f not in __mtime_cache:
res = os.stat(f) __mtime_cache[f] = os.stat(f)[stat.ST_MTIME]
__mtime_cache[f] = (res.st_mtime_ns, res.st_size, res.st_ino)
return __mtime_cache[f] return __mtime_cache[f]
def cached_mtime_noerror(f): def cached_mtime_noerror(f):
if f not in __mtime_cache: if f not in __mtime_cache:
try: try:
res = os.stat(f) __mtime_cache[f] = os.stat(f)[stat.ST_MTIME]
__mtime_cache[f] = (res.st_mtime_ns, res.st_size, res.st_ino)
except OSError: except OSError:
return 0 return 0
return __mtime_cache[f] return __mtime_cache[f]
def check_mtime(f, mtime):
try:
res = os.stat(f)
current_mtime = (res.st_mtime_ns, res.st_size, res.st_ino)
__mtime_cache[f] = current_mtime
except OSError:
current_mtime = 0
return current_mtime == mtime
def update_mtime(f): def update_mtime(f):
try: try:
res = os.stat(f) __mtime_cache[f] = os.stat(f)[stat.ST_MTIME]
__mtime_cache[f] = (res.st_mtime_ns, res.st_size, res.st_ino)
except OSError: except OSError:
if f in __mtime_cache: if f in __mtime_cache:
del __mtime_cache[f] del __mtime_cache[f]
@@ -111,12 +99,12 @@ def supports(fn, data):
return 1 return 1
return 0 return 0
def handle(fn, data, include=0, baseconfig=False): def handle(fn, data, include = 0):
"""Call the handler that is appropriate for this file""" """Call the handler that is appropriate for this file"""
for h in handlers: for h in handlers:
if h['supports'](fn, data): if h['supports'](fn, data):
with data.inchistory.include(fn): with data.inchistory.include(fn):
return h['handle'](fn, data, include, baseconfig) return h['handle'](fn, data, include)
raise ParseError("not a BitBake file", fn) raise ParseError("not a BitBake file", fn)
def init(fn, data): def init(fn, data):

View File

@@ -9,7 +9,6 @@
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
import sys
import bb import bb
from bb import methodpool from bb import methodpool
from bb.parse import logger from bb.parse import logger
@@ -211,12 +210,10 @@ class ExportFuncsNode(AstNode):
def eval(self, data): def eval(self, data):
sentinel = " # Export function set\n"
for func in self.n: for func in self.n:
calledfunc = self.classname + "_" + func calledfunc = self.classname + "_" + func
basevar = data.getVar(func, False) if data.getVar(func, False) and not data.getVarFlag(func, 'export_func', False):
if basevar and sentinel not in basevar:
continue continue
if data.getVar(func, False): if data.getVar(func, False):
@@ -226,18 +223,19 @@ class ExportFuncsNode(AstNode):
for flag in [ "func", "python" ]: for flag in [ "func", "python" ]:
if data.getVarFlag(calledfunc, flag, False): if data.getVarFlag(calledfunc, flag, False):
data.setVarFlag(func, flag, data.getVarFlag(calledfunc, flag, False)) data.setVarFlag(func, flag, data.getVarFlag(calledfunc, flag, False))
for flag in ["dirs", "cleandirs", "fakeroot"]: for flag in [ "dirs" ]:
if data.getVarFlag(func, flag, False): if data.getVarFlag(func, flag, False):
data.setVarFlag(calledfunc, flag, data.getVarFlag(func, flag, False)) data.setVarFlag(calledfunc, flag, data.getVarFlag(func, flag, False))
data.setVarFlag(func, "filename", "autogenerated") data.setVarFlag(func, "filename", "autogenerated")
data.setVarFlag(func, "lineno", 1) data.setVarFlag(func, "lineno", 1)
if data.getVarFlag(calledfunc, "python", False): if data.getVarFlag(calledfunc, "python", False):
data.setVar(func, sentinel + " bb.build.exec_func('" + calledfunc + "', d)\n", parsing=True) data.setVar(func, " bb.build.exec_func('" + calledfunc + "', d)\n", parsing=True)
else: else:
if "-" in self.classname: if "-" in self.classname:
bb.fatal("The classname %s contains a dash character and is calling an sh function %s using EXPORT_FUNCTIONS. Since a dash is illegal in sh function names, this cannot work, please rename the class or don't use EXPORT_FUNCTIONS." % (self.classname, calledfunc)) bb.fatal("The classname %s contains a dash character and is calling an sh function %s using EXPORT_FUNCTIONS. Since a dash is illegal in sh function names, this cannot work, please rename the class or don't use EXPORT_FUNCTIONS." % (self.classname, calledfunc))
data.setVar(func, sentinel + " " + calledfunc + "\n", parsing=True) data.setVar(func, " " + calledfunc + "\n", parsing=True)
data.setVarFlag(func, 'export_func', '1')
class AddTaskNode(AstNode): class AddTaskNode(AstNode):
def __init__(self, filename, lineno, func, before, after): def __init__(self, filename, lineno, func, before, after):
@@ -271,41 +269,6 @@ class BBHandlerNode(AstNode):
data.setVarFlag(h, "handler", 1) data.setVarFlag(h, "handler", 1)
data.setVar('__BBHANDLERS', bbhands) data.setVar('__BBHANDLERS', bbhands)
class PyLibNode(AstNode):
def __init__(self, filename, lineno, libdir, namespace):
AstNode.__init__(self, filename, lineno)
self.libdir = libdir
self.namespace = namespace
def eval(self, data):
global_mods = (data.getVar("BB_GLOBAL_PYMODULES") or "").split()
for m in global_mods:
if m not in bb.utils._context:
bb.utils._context[m] = __import__(m)
libdir = data.expand(self.libdir)
if libdir not in sys.path:
sys.path.append(libdir)
try:
bb.utils._context[self.namespace] = __import__(self.namespace)
toimport = getattr(bb.utils._context[self.namespace], "BBIMPORTS", [])
for i in toimport:
bb.utils._context[self.namespace] = __import__(self.namespace + "." + i)
mod = getattr(bb.utils._context[self.namespace], i)
fn = getattr(mod, "__file__")
funcs = {}
for f in dir(mod):
if f.startswith("_"):
continue
fcall = getattr(mod, f)
if not callable(fcall):
continue
funcs[f] = fcall
bb.codeparser.add_module_functions(fn, funcs, "%s.%s" % (self.namespace, i))
except AttributeError as e:
bb.error("Error importing OE modules: %s" % str(e))
class InheritNode(AstNode): class InheritNode(AstNode):
def __init__(self, filename, lineno, classes): def __init__(self, filename, lineno, classes):
AstNode.__init__(self, filename, lineno) AstNode.__init__(self, filename, lineno)
@@ -314,16 +277,6 @@ class InheritNode(AstNode):
def eval(self, data): def eval(self, data):
bb.parse.BBHandler.inherit(self.classes, self.filename, self.lineno, data) bb.parse.BBHandler.inherit(self.classes, self.filename, self.lineno, data)
class InheritDeferredNode(AstNode):
def __init__(self, filename, lineno, classes):
AstNode.__init__(self, filename, lineno)
self.inherit = (classes, filename, lineno)
def eval(self, data):
inherits = data.getVar('__BBDEFINHERITS', False) or []
inherits.append(self.inherit)
data.setVar('__BBDEFINHERITS', inherits)
def handleInclude(statements, filename, lineno, m, force): def handleInclude(statements, filename, lineno, m, force):
statements.append(IncludeNode(filename, lineno, m.group(1), force)) statements.append(IncludeNode(filename, lineno, m.group(1), force))
@@ -367,17 +320,10 @@ def handleDelTask(statements, filename, lineno, m):
def handleBBHandlers(statements, filename, lineno, m): def handleBBHandlers(statements, filename, lineno, m):
statements.append(BBHandlerNode(filename, lineno, m.group(1))) statements.append(BBHandlerNode(filename, lineno, m.group(1)))
def handlePyLib(statements, filename, lineno, m):
statements.append(PyLibNode(filename, lineno, m.group(1), m.group(2)))
def handleInherit(statements, filename, lineno, m): def handleInherit(statements, filename, lineno, m):
classes = m.group(1) classes = m.group(1)
statements.append(InheritNode(filename, lineno, classes)) statements.append(InheritNode(filename, lineno, classes))
def handleInheritDeferred(statements, filename, lineno, m):
classes = m.group(1)
statements.append(InheritDeferredNode(filename, lineno, classes))
def runAnonFuncs(d): def runAnonFuncs(d):
code = [] code = []
for funcname in d.getVar("__BBANONFUNCS", False) or []: for funcname in d.getVar("__BBANONFUNCS", False) or []:
@@ -391,14 +337,6 @@ def finalize(fn, d, variant = None):
if d.getVar("_FAILPARSINGERRORHANDLED", False) == True: if d.getVar("_FAILPARSINGERRORHANDLED", False) == True:
raise bb.BBHandledException() raise bb.BBHandledException()
while True:
inherits = d.getVar('__BBDEFINHERITS', False) or []
if not inherits:
break
inherit, filename, lineno = inherits.pop(0)
d.setVar('__BBDEFINHERITS', inherits)
bb.parse.BBHandler.inherit(inherit, filename, lineno, d, deferred=True)
for var in d.getVar('__BBHANDLERS', False) or []: for var in d.getVar('__BBHANDLERS', False) or []:
# try to add the handler # try to add the handler
handlerfn = d.getVarFlag(var, "filename", False) handlerfn = d.getVarFlag(var, "filename", False)
@@ -423,9 +361,6 @@ def finalize(fn, d, variant = None):
d.setVar('BBINCLUDED', bb.parse.get_file_depends(d)) d.setVar('BBINCLUDED', bb.parse.get_file_depends(d))
if d.getVar('__BBAUTOREV_SEEN') and d.getVar('__BBSRCREV_SEEN') and not d.getVar("__BBAUTOREV_ACTED_UPON"):
bb.fatal("AUTOREV/SRCPV set too late for the fetcher to work properly, please set the variables earlier in parsing. Erroring instead of later obtuse build failures.")
bb.event.fire(bb.event.RecipeParsed(fn), d) bb.event.fire(bb.event.RecipeParsed(fn), d)
finally: finally:
bb.event.set_handlers(saved_handlers) bb.event.set_handlers(saved_handlers)
@@ -487,9 +422,7 @@ def multi_finalize(fn, d):
d.setVar("BBEXTENDVARIANT", variantmap[name]) d.setVar("BBEXTENDVARIANT", variantmap[name])
else: else:
d.setVar("PN", "%s-%s" % (pn, name)) d.setVar("PN", "%s-%s" % (pn, name))
inherits = d.getVar('__BBDEFINHERITS', False) or [] bb.parse.BBHandler.inherit(extendedmap[name], fn, 0, d)
inherits.append((extendedmap[name], fn, 0))
d.setVar('__BBDEFINHERITS', inherits)
safe_d.setVar("BBCLASSEXTEND", extended) safe_d.setVar("BBCLASSEXTEND", extended)
_create_variants(datastores, extendedmap.keys(), extendfunc, onlyfinalise) _create_variants(datastores, extendedmap.keys(), extendfunc, onlyfinalise)

View File

@@ -21,7 +21,6 @@ from .ConfHandler import include, init
__func_start_regexp__ = re.compile(r"(((?P<py>python(?=(\s|\()))|(?P<fr>fakeroot(?=\s)))\s*)*(?P<func>[\w\.\-\+\{\}\$:]+)?\s*\(\s*\)\s*{$" ) __func_start_regexp__ = re.compile(r"(((?P<py>python(?=(\s|\()))|(?P<fr>fakeroot(?=\s)))\s*)*(?P<func>[\w\.\-\+\{\}\$:]+)?\s*\(\s*\)\s*{$" )
__inherit_regexp__ = re.compile(r"inherit\s+(.+)" ) __inherit_regexp__ = re.compile(r"inherit\s+(.+)" )
__inherit_def_regexp__ = re.compile(r"inherit_defer\s+(.+)" )
__export_func_regexp__ = re.compile(r"EXPORT_FUNCTIONS\s+(.+)" ) __export_func_regexp__ = re.compile(r"EXPORT_FUNCTIONS\s+(.+)" )
__addtask_regexp__ = re.compile(r"addtask\s+(?P<func>\w+)\s*((before\s*(?P<before>((.*(?=after))|(.*))))|(after\s*(?P<after>((.*(?=before))|(.*)))))*") __addtask_regexp__ = re.compile(r"addtask\s+(?P<func>\w+)\s*((before\s*(?P<before>((.*(?=after))|(.*))))|(after\s*(?P<after>((.*(?=before))|(.*)))))*")
__deltask_regexp__ = re.compile(r"deltask\s+(.+)") __deltask_regexp__ = re.compile(r"deltask\s+(.+)")
@@ -34,7 +33,6 @@ __infunc__ = []
__inpython__ = False __inpython__ = False
__body__ = [] __body__ = []
__classname__ = "" __classname__ = ""
__residue__ = []
cached_statements = {} cached_statements = {}
@@ -42,18 +40,12 @@ def supports(fn, d):
"""Return True if fn has a supported extension""" """Return True if fn has a supported extension"""
return os.path.splitext(fn)[-1] in [".bb", ".bbclass", ".inc"] return os.path.splitext(fn)[-1] in [".bb", ".bbclass", ".inc"]
def inherit(files, fn, lineno, d, deferred=False): def inherit(files, fn, lineno, d):
__inherit_cache = d.getVar('__inherit_cache', False) or [] __inherit_cache = d.getVar('__inherit_cache', False) or []
#if "${" in files and not deferred:
# bb.warn("%s:%s has non deferred conditional inherit" % (fn, lineno))
files = d.expand(files).split() files = d.expand(files).split()
for file in files: for file in files:
classtype = d.getVar("__bbclasstype", False)
origfile = file
for t in ["classes-" + classtype, "classes"]:
file = origfile
if not os.path.isabs(file) and not file.endswith(".bbclass"): if not os.path.isabs(file) and not file.endswith(".bbclass"):
file = os.path.join(t, '%s.bbclass' % file) file = os.path.join('classes', '%s.bbclass' % file)
if not os.path.isabs(file): if not os.path.isabs(file):
bbpath = d.getVar("BBPATH") bbpath = d.getVar("BBPATH")
@@ -64,24 +56,15 @@ def inherit(files, fn, lineno, d, deferred=False):
if abs_fn: if abs_fn:
file = abs_fn file = abs_fn
if os.path.exists(file):
break
if not os.path.exists(file):
raise ParseError("Could not inherit file %s" % (file), fn, lineno)
if not file in __inherit_cache: if not file in __inherit_cache:
logger.debug("Inheriting %s (from %s:%d)" % (file, fn, lineno)) logger.debug("Inheriting %s (from %s:%d)" % (file, fn, lineno))
__inherit_cache.append( file ) __inherit_cache.append( file )
d.setVar('__inherit_cache', __inherit_cache) d.setVar('__inherit_cache', __inherit_cache)
try: include(fn, file, lineno, d, "inherit")
bb.parse.handle(file, d, True)
except (IOError, OSError) as exc:
raise ParseError("Could not inherit file %s: %s" % (fn, exc.strerror), fn, lineno)
__inherit_cache = d.getVar('__inherit_cache', False) or [] __inherit_cache = d.getVar('__inherit_cache', False) or []
def get_statements(filename, absolute_filename, base_name): def get_statements(filename, absolute_filename, base_name):
global cached_statements, __residue__, __body__ global cached_statements
try: try:
return cached_statements[absolute_filename] return cached_statements[absolute_filename]
@@ -101,17 +84,12 @@ def get_statements(filename, absolute_filename, base_name):
# add a blank line to close out any python definition # add a blank line to close out any python definition
feeder(lineno, "", filename, base_name, statements, eof=True) feeder(lineno, "", filename, base_name, statements, eof=True)
if __residue__:
raise ParseError("Unparsed lines %s: %s" % (filename, str(__residue__)), filename, lineno)
if __body__:
raise ParseError("Unparsed lines from unclosed function %s: %s" % (filename, str(__body__)), filename, lineno)
if filename.endswith(".bbclass") or filename.endswith(".inc"): if filename.endswith(".bbclass") or filename.endswith(".inc"):
cached_statements[absolute_filename] = statements cached_statements[absolute_filename] = statements
return statements return statements
def handle(fn, d, include, baseconfig=False): def handle(fn, d, include):
global __infunc__, __body__, __residue__, __classname__ global __func_start_regexp__, __inherit_regexp__, __export_func_regexp__, __addtask_regexp__, __addhandler_regexp__, __infunc__, __body__, __residue__, __classname__
__body__ = [] __body__ = []
__infunc__ = [] __infunc__ = []
__classname__ = "" __classname__ = ""
@@ -163,7 +141,7 @@ def handle(fn, d, include, baseconfig=False):
return d return d
def feeder(lineno, s, fn, root, statements, eof=False): def feeder(lineno, s, fn, root, statements, eof=False):
global __inpython__, __infunc__, __body__, __residue__, __classname__ global __func_start_regexp__, __inherit_regexp__, __export_func_regexp__, __addtask_regexp__, __addhandler_regexp__, __def_regexp__, __python_func_regexp__, __inpython__, __infunc__, __body__, bb, __residue__, __classname__
# Check tabs in python functions: # Check tabs in python functions:
# - def py_funcname(): covered by __inpython__ # - def py_funcname(): covered by __inpython__
@@ -200,10 +178,10 @@ def feeder(lineno, s, fn, root, statements, eof=False):
if s and s[0] == '#': if s and s[0] == '#':
if len(__residue__) != 0 and __residue__[0][0] != "#": if len(__residue__) != 0 and __residue__[0][0] != "#":
bb.fatal("There is a comment on line %s of file %s:\n'''\n%s\n'''\nwhich is in the middle of a multiline expression. This syntax is invalid, please correct it." % (lineno, fn, s)) bb.fatal("There is a comment on line %s of file %s (%s) which is in the middle of a multiline expression.\nBitbake used to ignore these but no longer does so, please fix your metadata as errors are likely as a result of this change." % (lineno, fn, s))
if len(__residue__) != 0 and __residue__[0][0] == "#" and (not s or s[0] != "#"): if len(__residue__) != 0 and __residue__[0][0] == "#" and (not s or s[0] != "#"):
bb.fatal("There is a confusing multiline partially commented expression on line %s of file %s:\n%s\nPlease clarify whether this is all a comment or should be parsed." % (lineno - len(__residue__), fn, "\n".join(__residue__))) bb.fatal("There is a confusing multiline, partially commented expression on line %s of file %s (%s).\nPlease clarify whether this is all a comment or should be parsed." % (lineno, fn, s))
if s and s[-1] == '\\': if s and s[-1] == '\\':
__residue__.append(s[:-1]) __residue__.append(s[:-1])
@@ -274,12 +252,7 @@ def feeder(lineno, s, fn, root, statements, eof=False):
ast.handleInherit(statements, fn, lineno, m) ast.handleInherit(statements, fn, lineno, m)
return return
m = __inherit_def_regexp__.match(s) return ConfHandler.feeder(lineno, s, fn, statements)
if m:
ast.handleInheritDeferred(statements, fn, lineno, m)
return
return ConfHandler.feeder(lineno, s, fn, statements, conffile=False)
# Add us to the handlers list # Add us to the handlers list
from .. import handlers from .. import handlers

View File

@@ -21,7 +21,7 @@ __config_regexp__ = re.compile( r"""
^ ^
(?P<exp>export\s+)? (?P<exp>export\s+)?
(?P<var>[a-zA-Z0-9\-_+.${}/~:]+?) (?P<var>[a-zA-Z0-9\-_+.${}/~:]+?)
(\[(?P<flag>[a-zA-Z0-9\-_+.][a-zA-Z0-9\-_+.@]*)\])? (\[(?P<flag>[a-zA-Z0-9\-_+.]+)\])?
\s* ( \s* (
(?P<colon>:=) | (?P<colon>:=) |
@@ -45,8 +45,7 @@ __include_regexp__ = re.compile( r"include\s+(.+)" )
__require_regexp__ = re.compile( r"require\s+(.+)" ) __require_regexp__ = re.compile( r"require\s+(.+)" )
__export_regexp__ = re.compile( r"export\s+([a-zA-Z0-9\-_+.${}/~]+)$" ) __export_regexp__ = re.compile( r"export\s+([a-zA-Z0-9\-_+.${}/~]+)$" )
__unset_regexp__ = re.compile( r"unset\s+([a-zA-Z0-9\-_+.${}/~]+)$" ) __unset_regexp__ = re.compile( r"unset\s+([a-zA-Z0-9\-_+.${}/~]+)$" )
__unset_flag_regexp__ = re.compile( r"unset\s+([a-zA-Z0-9\-_+.${}/~]+)\[([a-zA-Z0-9\-_+.][a-zA-Z0-9\-_+.@]+)\]$" ) __unset_flag_regexp__ = re.compile( r"unset\s+([a-zA-Z0-9\-_+.${}/~]+)\[([a-zA-Z0-9\-_+.]+)\]$" )
__addpylib_regexp__ = re.compile(r"addpylib\s+(.+)\s+(.+)" )
def init(data): def init(data):
return return
@@ -108,7 +107,7 @@ def include_single_file(parentfn, fn, lineno, data, error_out):
# parsing. This turns out to be a hard problem to solve any other way. # parsing. This turns out to be a hard problem to solve any other way.
confFilters = [] confFilters = []
def handle(fn, data, include, baseconfig=False): def handle(fn, data, include):
init(data) init(data)
if include == 0: if include == 0:
@@ -126,26 +125,21 @@ def handle(fn, data, include, baseconfig=False):
s = f.readline() s = f.readline()
if not s: if not s:
break break
origlineno = lineno
origline = s
w = s.strip() w = s.strip()
# skip empty lines # skip empty lines
if not w: if not w:
continue continue
s = s.rstrip() s = s.rstrip()
while s[-1] == '\\': while s[-1] == '\\':
line = f.readline() s2 = f.readline().rstrip()
origline += line
s2 = line.rstrip()
lineno = lineno + 1 lineno = lineno + 1
if (not s2 or s2 and s2[0] != "#") and s[0] == "#" : if (not s2 or s2 and s2[0] != "#") and s[0] == "#" :
bb.fatal("There is a confusing multiline, partially commented expression starting on line %s of file %s:\n%s\nPlease clarify whether this is all a comment or should be parsed." % (origlineno, fn, origline)) bb.fatal("There is a confusing multiline, partially commented expression on line %s of file %s (%s).\nPlease clarify whether this is all a comment or should be parsed." % (lineno, fn, s))
s = s[:-1] + s2 s = s[:-1] + s2
# skip comments # skip comments
if s[0] == '#': if s[0] == '#':
continue continue
feeder(lineno, s, abs_fn, statements, baseconfig=baseconfig) feeder(lineno, s, abs_fn, statements)
# DONE WITH PARSING... time to evaluate # DONE WITH PARSING... time to evaluate
data.setVar('FILE', abs_fn) data.setVar('FILE', abs_fn)
@@ -153,14 +147,14 @@ def handle(fn, data, include, baseconfig=False):
if oldfile: if oldfile:
data.setVar('FILE', oldfile) data.setVar('FILE', oldfile)
f.close()
for f in confFilters: for f in confFilters:
f(fn, data) f(fn, data)
return data return data
# baseconfig is set for the bblayers/layer.conf cookerdata config parsing def feeder(lineno, s, fn, statements):
# The function is also used by BBHandler, conffile would be False
def feeder(lineno, s, fn, statements, baseconfig=False, conffile=True):
m = __config_regexp__.match(s) m = __config_regexp__.match(s)
if m: if m:
groupd = m.groupdict() groupd = m.groupdict()
@@ -192,11 +186,6 @@ def feeder(lineno, s, fn, statements, baseconfig=False, conffile=True):
ast.handleUnsetFlag(statements, fn, lineno, m) ast.handleUnsetFlag(statements, fn, lineno, m)
return return
m = __addpylib_regexp__.match(s)
if baseconfig and conffile and m:
ast.handlePyLib(statements, fn, lineno, m)
return
raise ParseError("unparsed line: '%s'" % s, fn, lineno); raise ParseError("unparsed line: '%s'" % s, fn, lineno);
# Add us to the handlers list # Add us to the handlers list

View File

@@ -154,7 +154,6 @@ class SQLTable(collections.abc.MutableMapping):
def __exit__(self, *excinfo): def __exit__(self, *excinfo):
self.connection.__exit__(*excinfo) self.connection.__exit__(*excinfo)
self.connection.close()
@_Decorators.retry() @_Decorators.retry()
@_Decorators.transaction @_Decorators.transaction
@@ -209,7 +208,7 @@ class SQLTable(collections.abc.MutableMapping):
def __lt__(self, other): def __lt__(self, other):
if not isinstance(other, Mapping): if not isinstance(other, Mapping):
raise NotImplementedError() raise NotImplemented
return len(self) < len(other) return len(self) < len(other)
@@ -250,23 +249,4 @@ def persist(domain, d):
bb.utils.mkdirhier(cachedir) bb.utils.mkdirhier(cachedir)
cachefile = os.path.join(cachedir, "bb_persist_data.sqlite3") cachefile = os.path.join(cachedir, "bb_persist_data.sqlite3")
try:
return SQLTable(cachefile, domain) return SQLTable(cachefile, domain)
except sqlite3.OperationalError:
# Sqlite fails to open database when its path is too long.
# After testing, 504 is the biggest path length that can be opened by
# sqlite.
# Note: This code is called before sanity.bbclass and its path length
# check
max_len = 504
if len(cachefile) > max_len:
logger.critical("The path of the cache file is too long "
"({0} chars > {1}) to be opened by sqlite! "
"Your cache file is \"{2}\"".format(
len(cachefile),
max_len,
cachefile))
sys.exit(1)
else:
raise

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #

View File

@@ -396,8 +396,8 @@ def getRuntimeProviders(dataCache, rdepend):
return rproviders return rproviders
# Only search dynamic packages if we can't find anything in other variables # Only search dynamic packages if we can't find anything in other variables
for pat_key in dataCache.packages_dynamic: for pattern in dataCache.packages_dynamic:
pattern = pat_key.replace(r'+', r"\+") pattern = pattern.replace(r'+', r"\+")
if pattern in regexp_cache: if pattern in regexp_cache:
regexp = regexp_cache[pattern] regexp = regexp_cache[pattern]
else: else:
@@ -408,7 +408,7 @@ def getRuntimeProviders(dataCache, rdepend):
raise raise
regexp_cache[pattern] = regexp regexp_cache[pattern] = regexp
if regexp.match(rdepend): if regexp.match(rdepend):
rproviders += dataCache.packages_dynamic[pat_key] rproviders += dataCache.packages_dynamic[pattern]
logger.debug("Assuming %s is a dynamic package, but it may not exist" % rdepend) logger.debug("Assuming %s is a dynamic package, but it may not exist" % rdepend)
return rproviders return rproviders

File diff suppressed because it is too large Load Diff

View File

@@ -13,13 +13,14 @@
import bb import bb
import bb.event import bb.event
import logging import logging
from bb import multiprocessing import multiprocessing
import threading import threading
import array import array
import os import os
import sys import sys
import time import time
import select import select
import signal
import socket import socket
import subprocess import subprocess
import errno import errno
@@ -28,7 +29,6 @@ import datetime
import pickle import pickle
import traceback import traceback
import gc import gc
import stat
import bb.server.xmlrpcserver import bb.server.xmlrpcserver
from bb import daemonize from bb import daemonize
from multiprocessing import queues from multiprocessing import queues
@@ -38,46 +38,9 @@ logger = logging.getLogger('BitBake')
class ProcessTimeout(SystemExit): class ProcessTimeout(SystemExit):
pass pass
def currenttime():
return datetime.datetime.now().strftime('%H:%M:%S.%f')
def serverlog(msg): def serverlog(msg):
print(str(os.getpid()) + " " + currenttime() + " " + msg) print(str(os.getpid()) + " " + datetime.datetime.now().strftime('%H:%M:%S.%f') + " " + msg)
#Seems a flush here triggers filesytem sync like behaviour and long hangs in the server sys.stdout.flush()
#sys.stdout.flush()
#
# When we have lockfile issues, try and find infomation about which process is
# using the lockfile
#
def get_lockfile_process_msg(lockfile):
# Some systems may not have lsof available
procs = None
try:
procs = subprocess.check_output(["lsof", '-w', lockfile], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
# File was deleted?
pass
except OSError as e:
if e.errno != errno.ENOENT:
raise
if procs is None:
# Fall back to fuser if lsof is unavailable
try:
procs = subprocess.check_output(["fuser", '-v', lockfile], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
# File was deleted?
pass
except OSError as e:
if e.errno != errno.ENOENT:
raise
if procs:
return procs.decode("utf-8")
return None
class idleFinish():
def __init__(self, msg):
self.msg = msg
class ProcessServer(): class ProcessServer():
profile_filename = "profile.log" profile_filename = "profile.log"
@@ -96,19 +59,12 @@ class ProcessServer():
self.maxuiwait = 30 self.maxuiwait = 30
self.xmlrpc = False self.xmlrpc = False
self.idle = None
# Need a lock for _idlefuns changes
self._idlefuns = {} self._idlefuns = {}
self._idlefuncsLock = threading.Lock()
self.idle_cond = threading.Condition(self._idlefuncsLock)
self.bitbake_lock = lock self.bitbake_lock = lock
self.bitbake_lock_name = lockname self.bitbake_lock_name = lockname
self.sock = sock self.sock = sock
self.sockname = sockname self.sockname = sockname
# It is possible the directory may be renamed. Cache the inode of the socket file
# so we can tell if things changed.
self.sockinode = os.stat(self.sockname)[stat.ST_INO]
self.server_timeout = server_timeout self.server_timeout = server_timeout
self.timeout = self.server_timeout self.timeout = self.server_timeout
@@ -117,9 +73,7 @@ class ProcessServer():
def register_idle_function(self, function, data): def register_idle_function(self, function, data):
"""Register a function to be called while the server is idle""" """Register a function to be called while the server is idle"""
assert hasattr(function, '__call__') assert hasattr(function, '__call__')
with bb.utils.lock_timeout(self._idlefuncsLock):
self._idlefuns[function] = data self._idlefuns[function] = data
serverlog("Registering idle function %s" % str(function))
def run(self): def run(self):
@@ -158,31 +112,6 @@ class ProcessServer():
return ret return ret
def _idle_check(self):
return len(self._idlefuns) == 0 and self.cooker.command.currentAsyncCommand is None
def wait_for_idle(self, timeout=30):
# Wait for the idle loop to have cleared
with bb.utils.lock_timeout(self._idlefuncsLock):
return self.idle_cond.wait_for(self._idle_check, timeout) is not False
def set_async_cmd(self, cmd):
with bb.utils.lock_timeout(self._idlefuncsLock):
ret = self.idle_cond.wait_for(self._idle_check, 30)
if ret is False:
return False
self.cooker.command.currentAsyncCommand = cmd
return True
def clear_async_cmd(self):
with bb.utils.lock_timeout(self._idlefuncsLock):
self.cooker.command.currentAsyncCommand = None
self.idle_cond.notify_all()
def get_async_cmd(self):
with bb.utils.lock_timeout(self._idlefuncsLock):
return self.cooker.command.currentAsyncCommand
def main(self): def main(self):
self.cooker.pre_serve() self.cooker.pre_serve()
@@ -197,19 +126,14 @@ class ProcessServer():
fds.append(self.xmlrpc) fds.append(self.xmlrpc)
seendata = False seendata = False
serverlog("Entering server connection loop") serverlog("Entering server connection loop")
serverlog("Lockfile is: %s\nSocket is %s (%s)" % (self.bitbake_lock_name, self.sockname, os.path.exists(self.sockname)))
def disconnect_client(self, fds): def disconnect_client(self, fds):
serverlog("Disconnecting Client (socket: %s)" % os.path.exists(self.sockname)) serverlog("Disconnecting Client")
if self.controllersock: if self.controllersock:
fds.remove(self.controllersock) fds.remove(self.controllersock)
self.controllersock.close() self.controllersock.close()
self.controllersock = False self.controllersock = False
if self.haveui: if self.haveui:
# Wait for the idle loop to have cleared (30s max)
if not self.wait_for_idle(30):
serverlog("Idle loop didn't finish queued commands after 30s, exiting.")
self.quit = True
fds.remove(self.command_channel) fds.remove(self.command_channel)
bb.event.unregister_UIHhandler(self.event_handle, True) bb.event.unregister_UIHhandler(self.event_handle, True)
self.command_channel_reply.writer.close() self.command_channel_reply.writer.close()
@@ -221,7 +145,7 @@ class ProcessServer():
self.cooker.clientComplete() self.cooker.clientComplete()
self.haveui = False self.haveui = False
ready = select.select(fds,[],[],0)[0] ready = select.select(fds,[],[],0)[0]
if newconnections and not self.quit: if newconnections:
serverlog("Starting new client") serverlog("Starting new client")
conn = newconnections.pop(-1) conn = newconnections.pop(-1)
fds.append(conn) fds.append(conn)
@@ -293,10 +217,8 @@ class ProcessServer():
continue continue
try: try:
serverlog("Running command %s" % command) serverlog("Running command %s" % command)
reply = self.cooker.command.runCommand(command, self) self.command_channel_reply.send(self.cooker.command.runCommand(command))
serverlog("Sending reply %s" % repr(reply)) serverlog("Command Completed")
self.command_channel_reply.send(reply)
serverlog("Command Completed (socket: %s)" % os.path.exists(self.sockname))
except Exception as e: except Exception as e:
stack = traceback.format_exc() stack = traceback.format_exc()
serverlog('Exception in server main event loop running command %s (%s)' % (command, stack)) serverlog('Exception in server main event loop running command %s (%s)' % (command, stack))
@@ -323,25 +245,16 @@ class ProcessServer():
ready = self.idle_commands(.1, fds) ready = self.idle_commands(.1, fds)
if self.idle: serverlog("Exiting")
self.idle.join()
serverlog("Exiting (socket: %s)" % os.path.exists(self.sockname))
# Remove the socket file so we don't get any more connections to avoid races # Remove the socket file so we don't get any more connections to avoid races
# The build directory could have been renamed so if the file isn't the one we created
# we shouldn't delete it.
try: try:
sockinode = os.stat(self.sockname)[stat.ST_INO]
if sockinode == self.sockinode:
os.unlink(self.sockname) os.unlink(self.sockname)
else: except:
serverlog("bitbake.sock inode mismatch (%s vs %s), not deleting." % (sockinode, self.sockinode)) pass
except Exception as err:
serverlog("Removing socket file '%s' failed (%s)" % (self.sockname, err))
self.sock.close() self.sock.close()
try: try:
self.cooker.shutdown(True, idle=False) self.cooker.shutdown(True)
self.cooker.notifier.stop() self.cooker.notifier.stop()
self.cooker.confignotifier.stop() self.cooker.confignotifier.stop()
except: except:
@@ -367,21 +280,20 @@ class ProcessServer():
except FileNotFoundError: except FileNotFoundError:
return None return None
lockcontents = get_lock_contents(lockfile)
serverlog("Original lockfile contents: " + str(lockcontents))
lock.close() lock.close()
lock = None lock = None
while not lock: while not lock:
i = 0 i = 0
lock = None lock = None
if not os.path.exists(os.path.basename(lockfile)):
serverlog("Lockfile directory gone, exiting.")
return
while not lock and i < 30: while not lock and i < 30:
lock = bb.utils.lockfile(lockfile, shared=False, retry=False, block=False) lock = bb.utils.lockfile(lockfile, shared=False, retry=False, block=False)
if not lock: if not lock:
newlockcontents = get_lock_contents(lockfile) newlockcontents = get_lock_contents(lockfile)
if not newlockcontents[0].startswith([f"{os.getpid()}\n", f"{os.getpid()} "]): if newlockcontents != lockcontents:
# A new server was started, the lockfile contents changed, we can exit # A new server was started, the lockfile contents changed, we can exit
serverlog("Lockfile now contains different contents, exiting: " + str(newlockcontents)) serverlog("Lockfile now contains different contents, exiting: " + str(newlockcontents))
return return
@@ -395,52 +307,42 @@ class ProcessServer():
return return
if not lock: if not lock:
procs = get_lockfile_process_msg(lockfile) # Some systems may not have lsof available
procs = None
try:
procs = subprocess.check_output(["lsof", '-w', lockfile], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
# File was deleted?
continue
except OSError as e:
if e.errno != errno.ENOENT:
raise
if procs is None:
# Fall back to fuser if lsof is unavailable
try:
procs = subprocess.check_output(["fuser", '-v', lockfile], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
# File was deleted?
continue
except OSError as e:
if e.errno != errno.ENOENT:
raise
msg = ["Delaying shutdown due to active processes which appear to be holding bitbake.lock"] msg = ["Delaying shutdown due to active processes which appear to be holding bitbake.lock"]
if procs: if procs:
msg.append(":\n%s" % procs) msg.append(":\n%s" % str(procs.decode("utf-8")))
serverlog("".join(msg)) serverlog("".join(msg))
def idle_thread(self): def idle_commands(self, delay, fds=None):
if self.cooker.configuration.profile: nextsleep = delay
try: if not fds:
import cProfile as profile
except:
import profile
prof = profile.Profile()
ret = profile.Profile.runcall(prof, self.idle_thread_internal)
prof.dump_stats("profile-mainloop.log")
bb.utils.process_profilelog("profile-mainloop.log")
serverlog("Raw profiling information saved to profile-mainloop.log and processed statistics to profile-mainloop.log.processed")
else:
self.idle_thread_internal()
def idle_thread_internal(self):
def remove_idle_func(function):
with bb.utils.lock_timeout(self._idlefuncsLock):
del self._idlefuns[function]
self.idle_cond.notify_all()
while not self.quit:
nextsleep = 0.1
fds = [] fds = []
with bb.utils.lock_timeout(self._idlefuncsLock): for function, data in list(self._idlefuns.items()):
items = list(self._idlefuns.items())
for function, data in items:
try: try:
retval = function(self, data, False) retval = function(self, data, False)
if isinstance(retval, idleFinish): if retval is False:
serverlog("Removing idle function %s at idleFinish" % str(function)) del self._idlefuns[function]
remove_idle_func(function)
self.cooker.command.finishAsyncCommand(retval.msg)
nextsleep = None
elif retval is False:
serverlog("Removing idle function %s" % str(function))
remove_idle_func(function)
nextsleep = None nextsleep = None
elif retval is True: elif retval is True:
nextsleep = None nextsleep = None
@@ -456,13 +358,12 @@ class ProcessServer():
except Exception as exc: except Exception as exc:
if not isinstance(exc, bb.BBHandledException): if not isinstance(exc, bb.BBHandledException):
logger.exception('Running idle function') logger.exception('Running idle function')
remove_idle_func(function) del self._idlefuns[function]
serverlog("Exception %s broke the idle_thread, exiting" % traceback.format_exc())
self.quit = True self.quit = True
# Create new heartbeat event? # Create new heartbeat event?
now = time.time() now = time.time()
if bb.event._heartbeat_enabled and now >= self.next_heartbeat: if now >= self.next_heartbeat:
# We might have missed heartbeats. Just trigger once in # We might have missed heartbeats. Just trigger once in
# that case and continue after the usual delay. # that case and continue after the usual delay.
self.next_heartbeat += self.heartbeat_seconds self.next_heartbeat += self.heartbeat_seconds
@@ -475,29 +376,12 @@ class ProcessServer():
except Exception as exc: except Exception as exc:
if not isinstance(exc, bb.BBHandledException): if not isinstance(exc, bb.BBHandledException):
logger.exception('Running heartbeat function') logger.exception('Running heartbeat function')
serverlog("Exception %s broke in idle_thread, exiting" % traceback.format_exc())
self.quit = True self.quit = True
if nextsleep and bb.event._heartbeat_enabled and now + nextsleep > self.next_heartbeat: if nextsleep and now + nextsleep > self.next_heartbeat:
# Shorten timeout so that we we wake up in time for # Shorten timeout so that we we wake up in time for
# the heartbeat. # the heartbeat.
nextsleep = self.next_heartbeat - now nextsleep = self.next_heartbeat - now
if nextsleep is not None:
select.select(fds,[],[],nextsleep)[0]
def idle_commands(self, delay, fds=None):
nextsleep = delay
if not fds:
fds = []
if not self.idle:
self.idle = threading.Thread(target=self.idle_thread)
self.idle.start()
elif self.idle and not self.idle.is_alive():
serverlog("Idle thread terminated, main thread exiting too")
bb.error("Idle thread terminated, main thread exiting too")
self.quit = True
if nextsleep is not None: if nextsleep is not None:
if self.xmlrpc: if self.xmlrpc:
nextsleep = self.xmlrpc.get_timeout(nextsleep) nextsleep = self.xmlrpc.get_timeout(nextsleep)
@@ -516,18 +400,12 @@ class ServerCommunicator():
self.recv = recv self.recv = recv
def runCommand(self, command): def runCommand(self, command):
try:
self.connection.send(command) self.connection.send(command)
except BrokenPipeError as e:
raise BrokenPipeError("bitbake-server might have died or been forcibly stopped, ie. OOM killed") from e
if not self.recv.poll(30): if not self.recv.poll(30):
logger.info("No reply from server in 30s (for command %s at %s)" % (command[0], currenttime())) logger.info("No reply from server in 30s")
if not self.recv.poll(30): if not self.recv.poll(30):
raise ProcessTimeout("Timeout while waiting for a reply from the bitbake server (60s at %s)" % currenttime()) raise ProcessTimeout("Timeout while waiting for a reply from the bitbake server (60s)")
try:
ret, exc = self.recv.get() ret, exc = self.recv.get()
except EOFError as e:
raise EOFError("bitbake-server might have died or been forcibly stopped, ie. OOM killed") from e
# Should probably turn all exceptions in exc back into exceptions? # Should probably turn all exceptions in exc back into exceptions?
# For now, at least handle BBHandledException # For now, at least handle BBHandledException
if exc and ("BBHandledException" in exc or "SystemExit" in exc): if exc and ("BBHandledException" in exc or "SystemExit" in exc):
@@ -560,7 +438,6 @@ class BitBakeProcessServerConnection(object):
self.socket_connection = sock self.socket_connection = sock
def terminate(self): def terminate(self):
self.events.close()
self.socket_connection.close() self.socket_connection.close()
self.connection.connection.close() self.connection.connection.close()
self.connection.recv.close() self.connection.recv.close()
@@ -571,14 +448,13 @@ start_log_datetime_format = '%Y-%m-%d %H:%M:%S.%f'
class BitBakeServer(object): class BitBakeServer(object):
def __init__(self, lock, sockname, featureset, server_timeout, xmlrpcinterface, profile): def __init__(self, lock, sockname, featureset, server_timeout, xmlrpcinterface):
self.server_timeout = server_timeout self.server_timeout = server_timeout
self.xmlrpcinterface = xmlrpcinterface self.xmlrpcinterface = xmlrpcinterface
self.featureset = featureset self.featureset = featureset
self.sockname = sockname self.sockname = sockname
self.bitbake_lock = lock self.bitbake_lock = lock
self.profile = profile
self.readypipe, self.readypipein = os.pipe() self.readypipe, self.readypipein = os.pipe()
# Place the log in the builddirectory alongside the lock file # Place the log in the builddirectory alongside the lock file
@@ -642,9 +518,9 @@ class BitBakeServer(object):
os.set_inheritable(self.bitbake_lock.fileno(), True) os.set_inheritable(self.bitbake_lock.fileno(), True)
os.set_inheritable(self.readypipein, True) os.set_inheritable(self.readypipein, True)
serverscript = os.path.realpath(os.path.dirname(__file__) + "/../../../bin/bitbake-server") serverscript = os.path.realpath(os.path.dirname(__file__) + "/../../../bin/bitbake-server")
os.execl(sys.executable, sys.executable, serverscript, "decafbad", str(self.bitbake_lock.fileno()), str(self.readypipein), self.logfile, self.bitbake_lock.name, self.sockname, str(self.server_timeout or 0), str(int(self.profile)), str(self.xmlrpcinterface[0]), str(self.xmlrpcinterface[1])) os.execl(sys.executable, "bitbake-server", serverscript, "decafbad", str(self.bitbake_lock.fileno()), str(self.readypipein), self.logfile, self.bitbake_lock.name, self.sockname, str(self.server_timeout or 0), str(self.xmlrpcinterface[0]), str(self.xmlrpcinterface[1]))
def execServer(lockfd, readypipeinfd, lockname, sockname, server_timeout, xmlrpcinterface, profile): def execServer(lockfd, readypipeinfd, lockname, sockname, server_timeout, xmlrpcinterface):
import bb.cookerdata import bb.cookerdata
import bb.cooker import bb.cooker
@@ -656,7 +532,6 @@ def execServer(lockfd, readypipeinfd, lockname, sockname, server_timeout, xmlrpc
# Create server control socket # Create server control socket
if os.path.exists(sockname): if os.path.exists(sockname):
serverlog("WARNING: removing existing socket file '%s'" % sockname)
os.unlink(sockname) os.unlink(sockname)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
@@ -673,8 +548,7 @@ def execServer(lockfd, readypipeinfd, lockname, sockname, server_timeout, xmlrpc
writer = ConnectionWriter(readypipeinfd) writer = ConnectionWriter(readypipeinfd)
try: try:
featureset = [] featureset = []
cooker = bb.cooker.BBCooker(featureset, server) cooker = bb.cooker.BBCooker(featureset, server.register_idle_function)
cooker.configuration.profile = profile
except bb.BBHandledException: except bb.BBHandledException:
return None return None
writer.send("r") writer.send("r")
@@ -789,18 +663,23 @@ class BBUIEventQueue:
self.reader = ConnectionReader(readfd) self.reader = ConnectionReader(readfd)
self.t = threading.Thread() self.t = threading.Thread()
self.t.daemon = True
self.t.run = self.startCallbackHandler self.t.run = self.startCallbackHandler
self.t.start() self.t.start()
def getEvent(self): def getEvent(self):
with bb.utils.lock_timeout(self.eventQueueLock): self.eventQueueLock.acquire()
if len(self.eventQueue) == 0: if len(self.eventQueue) == 0:
self.eventQueueLock.release()
return None return None
item = self.eventQueue.pop(0) item = self.eventQueue.pop(0)
if len(self.eventQueue) == 0: if len(self.eventQueue) == 0:
self.eventQueueNotify.clear() self.eventQueueNotify.clear()
self.eventQueueLock.release()
return item return item
def waitEvent(self, delay): def waitEvent(self, delay):
@@ -808,9 +687,10 @@ class BBUIEventQueue:
return self.getEvent() return self.getEvent()
def queue_event(self, event): def queue_event(self, event):
with bb.utils.lock_timeout(self.eventQueueLock): self.eventQueueLock.acquire()
self.eventQueue.append(event) self.eventQueue.append(event)
self.eventQueueNotify.set() self.eventQueueNotify.set()
self.eventQueueLock.release()
def send_event(self, event): def send_event(self, event):
self.queue_event(pickle.loads(event)) self.queue_event(pickle.loads(event))
@@ -819,17 +699,13 @@ class BBUIEventQueue:
bb.utils.set_process_name("UIEventQueue") bb.utils.set_process_name("UIEventQueue")
while True: while True:
try: try:
ready = self.reader.wait(0.25) self.reader.wait()
if ready:
event = self.reader.get() event = self.reader.get()
self.queue_event(event) self.queue_event(event)
except (EOFError, OSError, TypeError): except EOFError:
# Easiest way to exit is to close the file descriptor to cause an exit # Easiest way to exit is to close the file descriptor to cause an exit
break break
def close(self):
self.reader.close() self.reader.close()
self.t.join()
class ConnectionReader(object): class ConnectionReader(object):
@@ -844,7 +720,7 @@ class ConnectionReader(object):
return self.reader.poll(timeout) return self.reader.poll(timeout)
def get(self): def get(self):
with bb.utils.lock_timeout(self.rlock): with self.rlock:
res = self.reader.recv_bytes() res = self.reader.recv_bytes()
return multiprocessing.reduction.ForkingPickler.loads(res) return multiprocessing.reduction.ForkingPickler.loads(res)
@@ -865,7 +741,7 @@ class ConnectionWriter(object):
def _send(self, obj): def _send(self, obj):
gc.disable() gc.disable()
with bb.utils.lock_timeout(self.wlock): with self.wlock:
self.writer.send_bytes(obj) self.writer.send_bytes(obj)
gc.enable() gc.enable()
@@ -878,13 +754,11 @@ class ConnectionWriter(object):
# pthread_sigmask block/unblock would be nice but doesn't work, https://bugs.python.org/issue47139 # pthread_sigmask block/unblock would be nice but doesn't work, https://bugs.python.org/issue47139
process = multiprocessing.current_process() process = multiprocessing.current_process()
if process and hasattr(process, "queue_signals"): if process and hasattr(process, "queue_signals"):
with bb.utils.lock_timeout(process.signal_threadlock): with process.signal_threadlock:
process.queue_signals = True process.queue_signals = True
self._send(obj) self._send(obj)
process.queue_signals = False process.queue_signals = False
for sig in process.signal_received.pop():
while len(process.signal_received) > 0:
sig = process.signal_received.pop()
process.handle_sig(sig, None) process.handle_sig(sig, None)
else: else:
self._send(obj) self._send(obj)

View File

@@ -118,7 +118,7 @@ class BitBakeXMLRPCServerCommands():
""" """
Run a cooker command on the server Run a cooker command on the server
""" """
return self.server.cooker.command.runCommand(command, self.server.parent, self.server.readonly) return self.server.cooker.command.runCommand(command, self.server.readonly)
def getEventHandle(self): def getEventHandle(self):
return self.event_handle return self.event_handle

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #
@@ -14,8 +12,6 @@ import bb.data
import difflib import difflib
import simplediff import simplediff
import json import json
import types
from contextlib import contextmanager
import bb.compress.zstd import bb.compress.zstd
from bb.checksum import FileChecksumCache from bb.checksum import FileChecksumCache
from bb import runqueue from bb import runqueue
@@ -25,37 +21,15 @@ import hashserv.client
logger = logging.getLogger('BitBake.SigGen') logger = logging.getLogger('BitBake.SigGen')
hashequiv_logger = logging.getLogger('BitBake.SigGen.HashEquiv') hashequiv_logger = logging.getLogger('BitBake.SigGen.HashEquiv')
#find_siginfo and find_siginfo_version are set by the metadata siggen
# The minimum version of the find_siginfo function we need
find_siginfo_minversion = 2
HASHSERV_ENVVARS = [
"SSL_CERT_DIR",
"SSL_CERT_FILE",
"NO_PROXY",
"HTTPS_PROXY",
"HTTP_PROXY"
]
def check_siggen_version(siggen):
if not hasattr(siggen, "find_siginfo_version"):
bb.fatal("Siggen from metadata (OE-Core?) is too old, please update it (no version found)")
if siggen.find_siginfo_version < siggen.find_siginfo_minversion:
bb.fatal("Siggen from metadata (OE-Core?) is too old, please update it (%s vs %s)" % (siggen.find_siginfo_version, siggen.find_siginfo_minversion))
def check_hashserv_unihash(unihash):
if not hashserv.is_valid_unihash(unihash):
bb.fatal("Hash Equivalence Server returned invalid unihash")
class SetEncoder(json.JSONEncoder): class SetEncoder(json.JSONEncoder):
def default(self, obj): def default(self, obj):
if isinstance(obj, set) or isinstance(obj, frozenset): if isinstance(obj, set):
return dict(_set_object=list(sorted(obj))) return dict(_set_object=list(sorted(obj)))
return json.JSONEncoder.default(self, obj) return json.JSONEncoder.default(self, obj)
def SetDecoder(dct): def SetDecoder(dct):
if '_set_object' in dct: if '_set_object' in dct:
return frozenset(dct['_set_object']) return set(dct['_set_object'])
return dct return dct
def init(d): def init(d):
@@ -66,6 +40,7 @@ def init(d):
for sg in siggens: for sg in siggens:
if desired == sg.name: if desired == sg.name:
return sg(d) return sg(d)
break
else: else:
logger.error("Invalid signature generator '%s', using default 'noop'\n" logger.error("Invalid signature generator '%s', using default 'noop'\n"
"Available generators: %s", desired, "Available generators: %s", desired,
@@ -77,6 +52,11 @@ class SignatureGenerator(object):
""" """
name = "noop" name = "noop"
# If the derived class supports multiconfig datacaches, set this to True
# The default is False for backward compatibility with derived signature
# generators that do not understand multiconfig caches
supports_multiconfig_datacaches = False
def __init__(self, data): def __init__(self, data):
self.basehash = {} self.basehash = {}
self.taskhash = {} self.taskhash = {}
@@ -94,39 +74,9 @@ class SignatureGenerator(object):
def postparsing_clean_cache(self): def postparsing_clean_cache(self):
return return
def setup_datacache(self, datacaches):
self.datacaches = datacaches
def setup_datacache_from_datastore(self, mcfn, d):
# In task context we have no cache so setup internal data structures
# from the fully parsed data store provided
mc = d.getVar("__BBMULTICONFIG", False) or ""
tasks = d.getVar('__BBTASKS', False)
self.datacaches = {}
self.datacaches[mc] = types.SimpleNamespace()
setattr(self.datacaches[mc], "stamp", {})
self.datacaches[mc].stamp[mcfn] = d.getVar('STAMP')
setattr(self.datacaches[mc], "stamp_extrainfo", {})
self.datacaches[mc].stamp_extrainfo[mcfn] = {}
for t in tasks:
flag = d.getVarFlag(t, "stamp-extra-info")
if flag:
self.datacaches[mc].stamp_extrainfo[mcfn][t] = flag
def get_cached_unihash(self, tid):
return None
def get_unihash(self, tid): def get_unihash(self, tid):
unihash = self.get_cached_unihash(tid)
if unihash:
return unihash
return self.taskhash[tid] return self.taskhash[tid]
def get_unihashes(self, tids):
return {tid: self.get_unihash(tid) for tid in tids}
def prep_taskhash(self, tid, deps, dataCaches): def prep_taskhash(self, tid, deps, dataCaches):
return return
@@ -138,51 +88,17 @@ class SignatureGenerator(object):
"""Write/update the file checksum cache onto disk""" """Write/update the file checksum cache onto disk"""
return return
def stampfile_base(self, mcfn):
mc = bb.runqueue.mc_from_tid(mcfn)
return self.datacaches[mc].stamp[mcfn]
def stampfile_mcfn(self, taskname, mcfn, extrainfo=True):
mc = bb.runqueue.mc_from_tid(mcfn)
stamp = self.datacaches[mc].stamp[mcfn]
if not stamp:
return
stamp_extrainfo = ""
if extrainfo:
taskflagname = taskname
if taskname.endswith("_setscene"):
taskflagname = taskname.replace("_setscene", "")
stamp_extrainfo = self.datacaches[mc].stamp_extrainfo[mcfn].get(taskflagname) or ""
return self.stampfile(stamp, mcfn, taskname, stamp_extrainfo)
def stampfile(self, stampbase, file_name, taskname, extrainfo): def stampfile(self, stampbase, file_name, taskname, extrainfo):
return ("%s.%s.%s" % (stampbase, taskname, extrainfo)).rstrip('.') return ("%s.%s.%s" % (stampbase, taskname, extrainfo)).rstrip('.')
def stampcleanmask_mcfn(self, taskname, mcfn):
mc = bb.runqueue.mc_from_tid(mcfn)
stamp = self.datacaches[mc].stamp[mcfn]
if not stamp:
return []
taskflagname = taskname
if taskname.endswith("_setscene"):
taskflagname = taskname.replace("_setscene", "")
stamp_extrainfo = self.datacaches[mc].stamp_extrainfo[mcfn].get(taskflagname) or ""
return self.stampcleanmask(stamp, mcfn, taskname, stamp_extrainfo)
def stampcleanmask(self, stampbase, file_name, taskname, extrainfo): def stampcleanmask(self, stampbase, file_name, taskname, extrainfo):
return ("%s.%s.%s" % (stampbase, taskname, extrainfo)).rstrip('.') return ("%s.%s.%s" % (stampbase, taskname, extrainfo)).rstrip('.')
def dump_sigtask(self, mcfn, task, stampbase, runtime): def dump_sigtask(self, fn, task, stampbase, runtime):
return return
def invalidate_task(self, task, mcfn): def invalidate_task(self, task, d, fn):
mc = bb.runqueue.mc_from_tid(mcfn) bb.build.del_stamp(task, d, fn)
stamp = self.datacaches[mc].stamp[mcfn]
bb.utils.remove(stamp)
def dump_sigs(self, dataCache, options): def dump_sigs(self, dataCache, options):
return return
@@ -205,20 +121,44 @@ class SignatureGenerator(object):
def save_unitaskhashes(self): def save_unitaskhashes(self):
return return
def copy_unitaskhashes(self, targetdir):
return
def set_setscene_tasks(self, setscene_tasks): def set_setscene_tasks(self, setscene_tasks):
return return
@classmethod
def get_data_caches(cls, dataCaches, mc):
"""
This function returns the datacaches that should be passed to signature
generator functions. If the signature generator supports multiconfig
caches, the entire dictionary of data caches is sent, otherwise a
special proxy is sent that support both index access to all
multiconfigs, and also direct access for the default multiconfig.
The proxy class allows code in this class itself to always use
multiconfig aware code (to ease maintenance), but derived classes that
are unaware of multiconfig data caches can still access the default
multiconfig as expected.
Do not override this function in derived classes; it will be removed in
the future when support for multiconfig data caches is mandatory
"""
class DataCacheProxy(object):
def __init__(self):
pass
def __getitem__(self, key):
return dataCaches[key]
def __getattr__(self, name):
return getattr(dataCaches[mc], name)
if cls.supports_multiconfig_datacaches:
return dataCaches
return DataCacheProxy()
def exit(self): def exit(self):
return return
def build_pnid(mc, pn, taskname):
if mc:
return "mc:" + mc + ":" + pn + ":" + taskname
return pn + ":" + taskname
class SignatureGeneratorBasic(SignatureGenerator): class SignatureGeneratorBasic(SignatureGenerator):
""" """
""" """
@@ -228,9 +168,12 @@ class SignatureGeneratorBasic(SignatureGenerator):
self.basehash = {} self.basehash = {}
self.taskhash = {} self.taskhash = {}
self.unihash = {} self.unihash = {}
self.taskdeps = {}
self.runtaskdeps = {} self.runtaskdeps = {}
self.file_checksum_values = {} self.file_checksum_values = {}
self.taints = {} self.taints = {}
self.gendeps = {}
self.lookupcache = {}
self.setscenetasks = set() self.setscenetasks = set()
self.basehash_ignore_vars = set((data.getVar("BB_BASEHASH_IGNORE_VARS") or "").split()) self.basehash_ignore_vars = set((data.getVar("BB_BASEHASH_IGNORE_VARS") or "").split())
self.taskhash_ignore_tasks = None self.taskhash_ignore_tasks = None
@@ -254,15 +197,15 @@ class SignatureGeneratorBasic(SignatureGenerator):
else: else:
self.twl = None self.twl = None
def _build_data(self, mcfn, d): def _build_data(self, fn, d):
ignore_mismatch = ((d.getVar("BB_HASH_IGNORE_MISMATCH") or '') == '1') ignore_mismatch = ((d.getVar("BB_HASH_IGNORE_MISMATCH") or '') == '1')
tasklist, gendeps, lookupcache = bb.data.generate_dependencies(d, self.basehash_ignore_vars) tasklist, gendeps, lookupcache = bb.data.generate_dependencies(d, self.basehash_ignore_vars)
taskdeps, basehash = bb.data.generate_dependency_hash(tasklist, gendeps, lookupcache, self.basehash_ignore_vars, mcfn) taskdeps, basehash = bb.data.generate_dependency_hash(tasklist, gendeps, lookupcache, self.basehash_ignore_vars, fn)
for task in tasklist: for task in tasklist:
tid = mcfn + ":" + task tid = fn + ":" + task
if not ignore_mismatch and tid in self.basehash and self.basehash[tid] != basehash[tid]: if not ignore_mismatch and tid in self.basehash and self.basehash[tid] != basehash[tid]:
bb.error("When reparsing %s, the basehash value changed from %s to %s. The metadata is not deterministic and this needs to be fixed." % (tid, self.basehash[tid], basehash[tid])) bb.error("When reparsing %s, the basehash value changed from %s to %s. The metadata is not deterministic and this needs to be fixed." % (tid, self.basehash[tid], basehash[tid]))
bb.error("The following commands may help:") bb.error("The following commands may help:")
@@ -273,7 +216,11 @@ class SignatureGeneratorBasic(SignatureGenerator):
bb.error("%s -Sprintdiff\n" % cmd) bb.error("%s -Sprintdiff\n" % cmd)
self.basehash[tid] = basehash[tid] self.basehash[tid] = basehash[tid]
return taskdeps, gendeps, lookupcache self.taskdeps[fn] = taskdeps
self.gendeps[fn] = gendeps
self.lookupcache[fn] = lookupcache
return taskdeps
def set_setscene_tasks(self, setscene_tasks): def set_setscene_tasks(self, setscene_tasks):
self.setscenetasks = set(setscene_tasks) self.setscenetasks = set(setscene_tasks)
@@ -281,42 +228,31 @@ class SignatureGeneratorBasic(SignatureGenerator):
def finalise(self, fn, d, variant): def finalise(self, fn, d, variant):
mc = d.getVar("__BBMULTICONFIG", False) or "" mc = d.getVar("__BBMULTICONFIG", False) or ""
mcfn = fn
if variant or mc: if variant or mc:
mcfn = bb.cache.realfn2virtual(fn, variant, mc) fn = bb.cache.realfn2virtual(fn, variant, mc)
try: try:
taskdeps, gendeps, lookupcache = self._build_data(mcfn, d) taskdeps = self._build_data(fn, d)
except bb.parse.SkipRecipe: except bb.parse.SkipRecipe:
raise raise
except: except:
bb.warn("Error during finalise of %s" % mcfn) bb.warn("Error during finalise of %s" % fn)
raise raise
basehashes = {}
for task in taskdeps:
basehashes[task] = self.basehash[mcfn + ":" + task]
d.setVar("__siggen_basehashes", basehashes)
d.setVar("__siggen_gendeps", gendeps)
d.setVar("__siggen_varvals", lookupcache)
d.setVar("__siggen_taskdeps", taskdeps)
#Slow but can be useful for debugging mismatched basehashes #Slow but can be useful for debugging mismatched basehashes
#self.setup_datacache_from_datastore(mcfn, d) #for task in self.taskdeps[fn]:
#for task in taskdeps: # self.dump_sigtask(fn, task, d.getVar("STAMP"), False)
# self.dump_sigtask(mcfn, task, d.getVar("STAMP"), False)
def setup_datacache_from_datastore(self, mcfn, d): for task in taskdeps:
super().setup_datacache_from_datastore(mcfn, d) d.setVar("BB_BASEHASH:task-%s" % task, self.basehash[fn + ":" + task])
mc = bb.runqueue.mc_from_tid(mcfn) def postparsing_clean_cache(self):
for attr in ["siggen_varvals", "siggen_taskdeps", "siggen_gendeps"]: #
if not hasattr(self.datacaches[mc], attr): # After parsing we can remove some things from memory to reduce our memory footprint
setattr(self.datacaches[mc], attr, {}) #
self.datacaches[mc].siggen_varvals[mcfn] = d.getVar("__siggen_varvals") self.gendeps = {}
self.datacaches[mc].siggen_taskdeps[mcfn] = d.getVar("__siggen_taskdeps") self.lookupcache = {}
self.datacaches[mc].siggen_gendeps[mcfn] = d.getVar("__siggen_gendeps") self.taskdeps = {}
def rundep_check(self, fn, recipename, task, dep, depname, dataCaches): def rundep_check(self, fn, recipename, task, dep, depname, dataCaches):
# Return True if we should keep the dependency, False to drop it # Return True if we should keep the dependency, False to drop it
@@ -339,37 +275,38 @@ class SignatureGeneratorBasic(SignatureGenerator):
def prep_taskhash(self, tid, deps, dataCaches): def prep_taskhash(self, tid, deps, dataCaches):
(mc, _, task, mcfn) = bb.runqueue.split_tid_mcfn(tid) (mc, _, task, fn) = bb.runqueue.split_tid_mcfn(tid)
self.basehash[tid] = dataCaches[mc].basetaskhash[tid] self.basehash[tid] = dataCaches[mc].basetaskhash[tid]
self.runtaskdeps[tid] = [] self.runtaskdeps[tid] = []
self.file_checksum_values[tid] = [] self.file_checksum_values[tid] = []
recipename = dataCaches[mc].pkg_fn[mcfn] recipename = dataCaches[mc].pkg_fn[fn]
self.tidtopn[tid] = recipename self.tidtopn[tid] = recipename
# save hashfn for deps into siginfo?
for dep in deps:
(depmc, _, deptask, depmcfn) = bb.runqueue.split_tid_mcfn(dep)
dep_pn = dataCaches[depmc].pkg_fn[depmcfn]
if not self.rundep_check(mcfn, recipename, task, dep, dep_pn, dataCaches): for dep in sorted(deps, key=clean_basepath):
(depmc, _, _, depmcfn) = bb.runqueue.split_tid_mcfn(dep)
depname = dataCaches[depmc].pkg_fn[depmcfn]
if not self.supports_multiconfig_datacaches and mc != depmc:
# If the signature generator doesn't understand multiconfig
# data caches, any dependency not in the same multiconfig must
# be skipped for backward compatibility
continue
if not self.rundep_check(fn, recipename, task, dep, depname, dataCaches):
continue continue
if dep not in self.taskhash: if dep not in self.taskhash:
bb.fatal("%s is not in taskhash, caller isn't calling in dependency order?" % dep) bb.fatal("%s is not in taskhash, caller isn't calling in dependency order?" % dep)
self.runtaskdeps[tid].append(dep)
dep_pnid = build_pnid(depmc, dep_pn, deptask) if task in dataCaches[mc].file_checksums[fn]:
self.runtaskdeps[tid].append((dep_pnid, dep))
if task in dataCaches[mc].file_checksums[mcfn]:
if self.checksum_cache: if self.checksum_cache:
checksums = self.checksum_cache.get_checksums(dataCaches[mc].file_checksums[mcfn][task], recipename, self.localdirsexclude) checksums = self.checksum_cache.get_checksums(dataCaches[mc].file_checksums[fn][task], recipename, self.localdirsexclude)
else: else:
checksums = bb.fetch2.get_file_checksums(dataCaches[mc].file_checksums[mcfn][task], recipename, self.localdirsexclude) checksums = bb.fetch2.get_file_checksums(dataCaches[mc].file_checksums[fn][task], recipename, self.localdirsexclude)
for (f,cs) in checksums: for (f,cs) in checksums:
self.file_checksum_values[tid].append((f,cs)) self.file_checksum_values[tid].append((f,cs))
taskdep = dataCaches[mc].task_deps[mcfn] taskdep = dataCaches[mc].task_deps[fn]
if 'nostamp' in taskdep and task in taskdep['nostamp']: if 'nostamp' in taskdep and task in taskdep['nostamp']:
# Nostamp tasks need an implicit taint so that they force any dependent tasks to run # Nostamp tasks need an implicit taint so that they force any dependent tasks to run
if tid in self.taints and self.taints[tid].startswith("nostamp:"): if tid in self.taints and self.taints[tid].startswith("nostamp:"):
@@ -380,30 +317,30 @@ class SignatureGeneratorBasic(SignatureGenerator):
taint = str(uuid.uuid4()) taint = str(uuid.uuid4())
self.taints[tid] = "nostamp:" + taint self.taints[tid] = "nostamp:" + taint
taint = self.read_taint(mcfn, task, dataCaches[mc].stamp[mcfn]) taint = self.read_taint(fn, task, dataCaches[mc].stamp[fn])
if taint: if taint:
self.taints[tid] = taint self.taints[tid] = taint
logger.warning("%s is tainted from a forced run" % tid) logger.warning("%s is tainted from a forced run" % tid)
return set(dep for _, dep in self.runtaskdeps[tid]) return
def get_taskhash(self, tid, deps, dataCaches): def get_taskhash(self, tid, deps, dataCaches):
data = self.basehash[tid] data = self.basehash[tid]
for dep in sorted(self.runtaskdeps[tid]): for dep in self.runtaskdeps[tid]:
data += self.get_unihash(dep[1]) data = data + self.get_unihash(dep)
for (f, cs) in sorted(self.file_checksum_values[tid], key=clean_checksum_file_path): for (f, cs) in self.file_checksum_values[tid]:
if cs: if cs:
if "/./" in f: if "/./" in f:
data += "./" + f.split("/./")[1] data = data + "./" + f.split("/./")[1]
data += cs data = data + cs
if tid in self.taints: if tid in self.taints:
if self.taints[tid].startswith("nostamp:"): if self.taints[tid].startswith("nostamp:"):
data += self.taints[tid][8:] data = data + self.taints[tid][8:]
else: else:
data += self.taints[tid] data = data + self.taints[tid]
h = hashlib.sha256(data.encode("utf-8")).hexdigest() h = hashlib.sha256(data.encode("utf-8")).hexdigest()
self.taskhash[tid] = h self.taskhash[tid] = h
@@ -422,12 +359,9 @@ class SignatureGeneratorBasic(SignatureGenerator):
def save_unitaskhashes(self): def save_unitaskhashes(self):
self.unihash_cache.save(self.unitaskhashes) self.unihash_cache.save(self.unitaskhashes)
def copy_unitaskhashes(self, targetdir): def dump_sigtask(self, fn, task, stampbase, runtime):
self.unihash_cache.copyfile(targetdir)
def dump_sigtask(self, mcfn, task, stampbase, runtime): tid = fn + ":" + task
tid = mcfn + ":" + task
mc = bb.runqueue.mc_from_tid(mcfn)
referencestamp = stampbase referencestamp = stampbase
if isinstance(runtime, str) and runtime.startswith("customfile"): if isinstance(runtime, str) and runtime.startswith("customfile"):
sigfile = stampbase sigfile = stampbase
@@ -444,32 +378,32 @@ class SignatureGeneratorBasic(SignatureGenerator):
data['task'] = task data['task'] = task
data['basehash_ignore_vars'] = self.basehash_ignore_vars data['basehash_ignore_vars'] = self.basehash_ignore_vars
data['taskhash_ignore_tasks'] = self.taskhash_ignore_tasks data['taskhash_ignore_tasks'] = self.taskhash_ignore_tasks
data['taskdeps'] = self.datacaches[mc].siggen_taskdeps[mcfn][task] data['taskdeps'] = self.taskdeps[fn][task]
data['basehash'] = self.basehash[tid] data['basehash'] = self.basehash[tid]
data['gendeps'] = {} data['gendeps'] = {}
data['varvals'] = {} data['varvals'] = {}
data['varvals'][task] = self.datacaches[mc].siggen_varvals[mcfn][task] data['varvals'][task] = self.lookupcache[fn][task]
for dep in self.datacaches[mc].siggen_taskdeps[mcfn][task]: for dep in self.taskdeps[fn][task]:
if dep in self.basehash_ignore_vars: if dep in self.basehash_ignore_vars:
continue continue
data['gendeps'][dep] = self.datacaches[mc].siggen_gendeps[mcfn][dep] data['gendeps'][dep] = self.gendeps[fn][dep]
data['varvals'][dep] = self.datacaches[mc].siggen_varvals[mcfn][dep] data['varvals'][dep] = self.lookupcache[fn][dep]
if runtime and tid in self.taskhash: if runtime and tid in self.taskhash:
data['runtaskdeps'] = [dep[0] for dep in sorted(self.runtaskdeps[tid])] data['runtaskdeps'] = self.runtaskdeps[tid]
data['file_checksum_values'] = [] data['file_checksum_values'] = []
for f,cs in sorted(self.file_checksum_values[tid], key=clean_checksum_file_path): for f,cs in self.file_checksum_values[tid]:
if "/./" in f: if "/./" in f:
data['file_checksum_values'].append(("./" + f.split("/./")[1], cs)) data['file_checksum_values'].append(("./" + f.split("/./")[1], cs))
else: else:
data['file_checksum_values'].append((os.path.basename(f), cs)) data['file_checksum_values'].append((os.path.basename(f), cs))
data['runtaskhashes'] = {} data['runtaskhashes'] = {}
for dep in self.runtaskdeps[tid]: for dep in data['runtaskdeps']:
data['runtaskhashes'][dep[0]] = self.get_unihash(dep[1]) data['runtaskhashes'][dep] = self.get_unihash(dep)
data['taskhash'] = self.taskhash[tid] data['taskhash'] = self.taskhash[tid]
data['unihash'] = self.get_unihash(tid) data['unihash'] = self.get_unihash(tid)
taint = self.read_taint(mcfn, task, referencestamp) taint = self.read_taint(fn, task, referencestamp)
if taint: if taint:
data['taint'] = taint data['taint'] = taint
@@ -486,7 +420,7 @@ class SignatureGeneratorBasic(SignatureGenerator):
bb.error("Taskhash mismatch %s versus %s for %s" % (computed_taskhash, self.taskhash[tid], tid)) bb.error("Taskhash mismatch %s versus %s for %s" % (computed_taskhash, self.taskhash[tid], tid))
sigfile = sigfile.replace(self.taskhash[tid], computed_taskhash) sigfile = sigfile.replace(self.taskhash[tid], computed_taskhash)
fd, tmpfile = bb.utils.mkstemp(dir=os.path.dirname(sigfile), prefix="sigtask.") fd, tmpfile = tempfile.mkstemp(dir=os.path.dirname(sigfile), prefix="sigtask.")
try: try:
with bb.compress.zstd.open(fd, "wt", encoding="utf-8", num_threads=1) as f: with bb.compress.zstd.open(fd, "wt", encoding="utf-8", num_threads=1) as f:
json.dump(data, f, sort_keys=True, separators=(",", ":"), cls=SetEncoder) json.dump(data, f, sort_keys=True, separators=(",", ":"), cls=SetEncoder)
@@ -500,6 +434,18 @@ class SignatureGeneratorBasic(SignatureGenerator):
pass pass
raise err raise err
def dump_sigfn(self, fn, dataCaches, options):
if fn in self.taskdeps:
for task in self.taskdeps[fn]:
tid = fn + ":" + task
mc = bb.runqueue.mc_from_tid(tid)
if tid not in self.taskhash:
continue
if dataCaches[mc].basetaskhash[tid] != self.basehash[tid]:
bb.error("Bitbake's cached basehash does not match the one we just generated (%s)!" % tid)
bb.error("The mismatched hashes were %s and %s" % (dataCaches[mc].basetaskhash[tid], self.basehash[tid]))
self.dump_sigtask(fn, task, dataCaches[mc].stamp[fn], True)
class SignatureGeneratorBasicHash(SignatureGeneratorBasic): class SignatureGeneratorBasicHash(SignatureGeneratorBasic):
name = "basichash" name = "basichash"
@@ -510,11 +456,11 @@ class SignatureGeneratorBasicHash(SignatureGeneratorBasic):
# If task is not in basehash, then error # If task is not in basehash, then error
return self.basehash[tid] return self.basehash[tid]
def stampfile(self, stampbase, mcfn, taskname, extrainfo, clean=False): def stampfile(self, stampbase, fn, taskname, extrainfo, clean=False):
if taskname.endswith("_setscene"): if taskname != "do_setscene" and taskname.endswith("_setscene"):
tid = mcfn + ":" + taskname[:-9] tid = fn + ":" + taskname[:-9]
else: else:
tid = mcfn + ":" + taskname tid = fn + ":" + taskname
if clean: if clean:
h = "*" h = "*"
else: else:
@@ -522,106 +468,41 @@ class SignatureGeneratorBasicHash(SignatureGeneratorBasic):
return ("%s.%s.%s.%s" % (stampbase, taskname, h, extrainfo)).rstrip('.') return ("%s.%s.%s.%s" % (stampbase, taskname, h, extrainfo)).rstrip('.')
def stampcleanmask(self, stampbase, mcfn, taskname, extrainfo): def stampcleanmask(self, stampbase, fn, taskname, extrainfo):
return self.stampfile(stampbase, mcfn, taskname, extrainfo, clean=True) return self.stampfile(stampbase, fn, taskname, extrainfo, clean=True)
def invalidate_task(self, task, mcfn): def invalidate_task(self, task, d, fn):
bb.note("Tainting hash to force rebuild of task %s, %s" % (mcfn, task)) bb.note("Tainting hash to force rebuild of task %s, %s" % (fn, task))
bb.build.write_taint(task, d, fn)
mc = bb.runqueue.mc_from_tid(mcfn)
stamp = self.datacaches[mc].stamp[mcfn]
taintfn = stamp + '.' + task + '.taint'
import uuid
bb.utils.mkdirhier(os.path.dirname(taintfn))
# The specific content of the taint file is not really important,
# we just need it to be random, so a random UUID is used
with open(taintfn, 'w') as taintf:
taintf.write(str(uuid.uuid4()))
class SignatureGeneratorUniHashMixIn(object): class SignatureGeneratorUniHashMixIn(object):
def __init__(self, data): def __init__(self, data):
self.extramethod = {} self.extramethod = {}
# NOTE: The cache only tracks hashes that exist. Hashes that don't
# exist are always queries from the server since it is possible for
# hashes to appear over time, but much less likely for them to
# disappear
self.unihash_exists_cache = set()
self.username = None
self.password = None
self.env = {}
origenv = data.getVar("BB_ORIGENV")
for e in HASHSERV_ENVVARS:
value = data.getVar(e)
if not value and origenv:
value = origenv.getVar(e)
if value:
self.env[e] = value
super().__init__(data) super().__init__(data)
def get_taskdata(self): def get_taskdata(self):
return (self.server, self.method, self.extramethod, self.max_parallel, self.username, self.password, self.env) + super().get_taskdata() return (self.server, self.method, self.extramethod) + super().get_taskdata()
def set_taskdata(self, data): def set_taskdata(self, data):
self.server, self.method, self.extramethod, self.max_parallel, self.username, self.password, self.env = data[:7] self.server, self.method, self.extramethod = data[:3]
super().set_taskdata(data[7:]) super().set_taskdata(data[3:])
def get_hashserv_creds(self):
if self.username and self.password:
return {
"username": self.username,
"password": self.password,
}
return {}
@contextmanager
def _client_env(self):
orig_env = os.environ.copy()
try:
for k, v in self.env.items():
os.environ[k] = v
yield
finally:
for k, v in self.env.items():
if k in orig_env:
os.environ[k] = orig_env[k]
else:
del os.environ[k]
@contextmanager
def client(self): def client(self):
with self._client_env():
if getattr(self, '_client', None) is None: if getattr(self, '_client', None) is None:
self._client = hashserv.create_client(self.server, **self.get_hashserv_creds()) self._client = hashserv.create_client(self.server)
yield self._client return self._client
@contextmanager
def client_pool(self):
with self._client_env():
if getattr(self, '_client_pool', None) is None:
self._client_pool = hashserv.client.ClientPool(self.server, self.max_parallel, **self.get_hashserv_creds())
yield self._client_pool
def reset(self, data): def reset(self, data):
self.__close_clients()
return super().reset(data)
def exit(self):
self.__close_clients()
return super().exit()
def __close_clients(self):
with self._client_env():
if getattr(self, '_client', None) is not None: if getattr(self, '_client', None) is not None:
self._client.close() self._client.close()
self._client = None self._client = None
if getattr(self, '_client_pool', None) is not None: return super().reset(data)
self._client_pool.close()
self._client_pool = None def exit(self):
if getattr(self, '_client', None) is not None:
self._client.close()
self._client = None
return super().exit()
def get_stampfile_hash(self, tid): def get_stampfile_hash(self, tid):
if tid in self.taskhash: if tid in self.taskhash:
@@ -654,7 +535,7 @@ class SignatureGeneratorUniHashMixIn(object):
return None return None
return unihash return unihash
def get_cached_unihash(self, tid): def get_unihash(self, tid):
taskhash = self.taskhash[tid] taskhash = self.taskhash[tid]
# If its not a setscene task we can return # If its not a setscene task we can return
@@ -669,79 +550,6 @@ class SignatureGeneratorUniHashMixIn(object):
self.unihash[tid] = unihash self.unihash[tid] = unihash
return unihash return unihash
return None
def _get_method(self, tid):
method = self.method
if tid in self.extramethod:
method = method + self.extramethod[tid]
return method
def unihashes_exist(self, query):
if len(query) == 0:
return {}
uncached_query = {}
result = {}
for key, unihash in query.items():
if unihash in self.unihash_exists_cache:
result[key] = True
else:
uncached_query[key] = unihash
if self.max_parallel <= 1 or len(uncached_query) <= 1:
# No parallelism required. Make the query serially with the single client
with self.client() as client:
uncached_result = {
key: client.unihash_exists(value) for key, value in uncached_query.items()
}
else:
with self.client_pool() as client_pool:
uncached_result = client_pool.unihashes_exist(uncached_query)
for key, exists in uncached_result.items():
if exists:
self.unihash_exists_cache.add(query[key])
result[key] = exists
return result
def get_unihash(self, tid):
return self.get_unihashes([tid])[tid]
def get_unihashes(self, tids):
"""
For a iterable of tids, returns a dictionary that maps each tid to a
unihash
"""
result = {}
queries = {}
query_result = {}
for tid in tids:
unihash = self.get_cached_unihash(tid)
if unihash:
result[tid] = unihash
else:
queries[tid] = (self._get_method(tid), self.taskhash[tid])
if len(queries) == 0:
return result
if self.max_parallel <= 1 or len(queries) <= 1:
# No parallelism required. Make the query using a single client
with self.client() as client:
keys = list(queries.keys())
unihashes = client.get_unihash_batch(queries[k] for k in keys)
for idx, k in enumerate(keys):
query_result[k] = unihashes[idx]
else:
with self.client_pool() as client_pool:
query_result = client_pool.get_unihashes(queries)
for tid, unihash in query_result.items():
# In the absence of being able to discover a unique hash from the # In the absence of being able to discover a unique hash from the
# server, make it be equivalent to the taskhash. The unique "hash" only # server, make it be equivalent to the taskhash. The unique "hash" only
# really needs to be a unique string (not even necessarily a hash), but # really needs to be a unique string (not even necessarily a hash), but
@@ -755,33 +563,37 @@ class SignatureGeneratorUniHashMixIn(object):
# independent builders find the same taskhash, but it isn't reported # independent builders find the same taskhash, but it isn't reported
# to the server, there is a better chance that they will agree on # to the server, there is a better chance that they will agree on
# the unique hash. # the unique hash.
taskhash = self.taskhash[tid] unihash = taskhash
if unihash:
check_hashserv_unihash(unihash) try:
method = self.method
if tid in self.extramethod:
method = method + self.extramethod[tid]
data = self.client().get_unihash(method, self.taskhash[tid])
if data:
unihash = data
# A unique hash equal to the taskhash is not very interesting, # A unique hash equal to the taskhash is not very interesting,
# so it is reported it at debug level 2. If they differ, that # so it is reported it at debug level 2. If they differ, that
# is much more interesting, so it is reported at debug level 1 # is much more interesting, so it is reported at debug level 1
hashequiv_logger.bbdebug((1, 2)[unihash == taskhash], 'Found unihash %s in place of %s for %s from %s' % (unihash, taskhash, tid, self.server)) hashequiv_logger.debug((1, 2)[unihash == taskhash], 'Found unihash %s in place of %s for %s from %s' % (unihash, taskhash, tid, self.server))
else: else:
hashequiv_logger.debug2('No reported unihash for %s:%s from %s' % (tid, taskhash, self.server)) hashequiv_logger.debug2('No reported unihash for %s:%s from %s' % (tid, taskhash, self.server))
unihash = taskhash except ConnectionError as e:
bb.warn('Error contacting Hash Equivalence Server %s: %s' % (self.server, str(e)))
self.set_unihash(tid, unihash) self.set_unihash(tid, unihash)
self.unihash[tid] = unihash self.unihash[tid] = unihash
result[tid] = unihash return unihash
return result
def report_unihash(self, path, task, d): def report_unihash(self, path, task, d):
import importlib import importlib
taskhash = d.getVar('BB_TASKHASH') taskhash = d.getVar('BB_TASKHASH')
unihash = d.getVar('BB_UNIHASH', expand=False) unihash = d.getVar('BB_UNIHASH')
report_taskdata = d.getVar('SSTATE_HASHEQUIV_REPORT_TASKDATA') == '1' report_taskdata = d.getVar('SSTATE_HASHEQUIV_REPORT_TASKDATA') == '1'
tempdir = d.getVar('T') tempdir = d.getVar('T')
mcfn = d.getVar('BB_FILENAME') fn = d.getVar('BB_FILENAME')
tid = mcfn + ':do_' + task tid = fn + ':do_' + task
key = tid + ':' + taskhash key = tid + ':' + taskhash
if self.setscenetasks and tid not in self.setscenetasks: if self.setscenetasks and tid not in self.setscenetasks:
@@ -835,15 +647,12 @@ class SignatureGeneratorUniHashMixIn(object):
if tid in self.extramethod: if tid in self.extramethod:
method = method + self.extramethod[tid] method = method + self.extramethod[tid]
with self.client() as client: data = self.client().report_unihash(taskhash, method, outhash, unihash, extra_data)
data = client.report_unihash(taskhash, method, outhash, unihash, extra_data)
new_unihash = data['unihash'] new_unihash = data['unihash']
check_hashserv_unihash(new_unihash)
if new_unihash != unihash: if new_unihash != unihash:
hashequiv_logger.debug('Task %s unihash changed %s -> %s by server %s' % (taskhash, unihash, new_unihash, self.server)) hashequiv_logger.debug('Task %s unihash changed %s -> %s by server %s' % (taskhash, unihash, new_unihash, self.server))
bb.event.fire(bb.runqueue.taskUniHashUpdate(mcfn + ':do_' + task, new_unihash), d) bb.event.fire(bb.runqueue.taskUniHashUpdate(fn + ':do_' + task, new_unihash), d)
self.set_unihash(tid, new_unihash) self.set_unihash(tid, new_unihash)
d.setVar('BB_UNIHASH', new_unihash) d.setVar('BB_UNIHASH', new_unihash)
else: else:
@@ -869,9 +678,7 @@ class SignatureGeneratorUniHashMixIn(object):
if tid in self.extramethod: if tid in self.extramethod:
method = method + self.extramethod[tid] method = method + self.extramethod[tid]
with self.client() as client: data = self.client().report_unihash_equiv(taskhash, method, wanted_unihash, extra_data)
data = client.report_unihash_equiv(taskhash, method, wanted_unihash, extra_data)
hashequiv_logger.verbose('Reported task %s as unihash %s to %s (%s)' % (tid, wanted_unihash, self.server, str(data))) hashequiv_logger.verbose('Reported task %s as unihash %s to %s (%s)' % (tid, wanted_unihash, self.server, str(data)))
if data is None: if data is None:
@@ -879,7 +686,6 @@ class SignatureGeneratorUniHashMixIn(object):
return False return False
finalunihash = data['unihash'] finalunihash = data['unihash']
check_hashserv_unihash(finalunihash)
if finalunihash == current_unihash: if finalunihash == current_unihash:
hashequiv_logger.verbose('Task %s unihash %s unchanged by server' % (tid, finalunihash)) hashequiv_logger.verbose('Task %s unihash %s unchanged by server' % (tid, finalunihash))
@@ -905,20 +711,20 @@ class SignatureGeneratorTestEquivHash(SignatureGeneratorUniHashMixIn, SignatureG
super().init_rundepcheck(data) super().init_rundepcheck(data)
self.server = data.getVar('BB_HASHSERVE') self.server = data.getVar('BB_HASHSERVE')
self.method = "sstate_output_hash" self.method = "sstate_output_hash"
self.max_parallel = 1
def clean_checksum_file_path(file_checksum_tuple): #
f, cs = file_checksum_tuple # Dummy class used for bitbake-selftest
if "/./" in f: #
return "./" + f.split("/./")[1] class SignatureGeneratorTestMulticonfigDepends(SignatureGeneratorBasicHash):
return f name = "TestMulticonfigDepends"
supports_multiconfig_datacaches = True
def dump_this_task(outfile, d): def dump_this_task(outfile, d):
import bb.parse import bb.parse
mcfn = d.getVar("BB_FILENAME") fn = d.getVar("BB_FILENAME")
task = "do_" + d.getVar("BB_CURRENTTASK") task = "do_" + d.getVar("BB_CURRENTTASK")
referencestamp = bb.parse.siggen.stampfile_base(mcfn) referencestamp = bb.build.stamp_internal(task, d, None, True)
bb.parse.siggen.dump_sigtask(mcfn, task, outfile, "customfile:" + referencestamp) bb.parse.siggen.dump_sigtask(fn, task, outfile, "customfile:" + referencestamp)
def init_colors(enable_color): def init_colors(enable_color):
"""Initialise colour dict for passing to compare_sigfiles()""" """Initialise colour dict for passing to compare_sigfiles()"""
@@ -971,6 +777,39 @@ def list_inline_diff(oldlist, newlist, colors=None):
ret.append(item) ret.append(item)
return '[%s]' % (', '.join(ret)) return '[%s]' % (', '.join(ret))
def clean_basepath(basepath):
basepath, dir, recipe_task = basepath.rsplit("/", 2)
cleaned = dir + '/' + recipe_task
if basepath[0] == '/':
return cleaned
if basepath.startswith("mc:") and basepath.count(':') >= 2:
mc, mc_name, basepath = basepath.split(":", 2)
mc_suffix = ':mc:' + mc_name
else:
mc_suffix = ''
# mc stuff now removed from basepath. Whatever was next, if present will be the first
# suffix. ':/', recipe path start, marks the end of this. Something like
# 'virtual:a[:b[:c]]:/path...' (b and c being optional)
if basepath[0] != '/':
cleaned += ':' + basepath.split(':/', 1)[0]
return cleaned + mc_suffix
def clean_basepaths(a):
b = {}
for x in a:
b[clean_basepath(x)] = a[x]
return b
def clean_basepaths_list(a):
b = []
for x in a:
b.append(clean_basepath(x))
return b
# Handled renamed fields # Handled renamed fields
def handle_renames(data): def handle_renames(data):
if 'basewhitelist' in data: if 'basewhitelist' in data:
@@ -1001,18 +840,10 @@ def compare_sigfiles(a, b, recursecb=None, color=False, collapsed=False):
formatparams.update(values) formatparams.update(values)
return formatstr.format(**formatparams) return formatstr.format(**formatparams)
try:
with bb.compress.zstd.open(a, "rt", encoding="utf-8", num_threads=1) as f: with bb.compress.zstd.open(a, "rt", encoding="utf-8", num_threads=1) as f:
a_data = json.load(f, object_hook=SetDecoder) a_data = json.load(f, object_hook=SetDecoder)
except (TypeError, OSError) as err:
bb.error("Failed to open sigdata file '%s': %s" % (a, str(err)))
raise err
try:
with bb.compress.zstd.open(b, "rt", encoding="utf-8", num_threads=1) as f: with bb.compress.zstd.open(b, "rt", encoding="utf-8", num_threads=1) as f:
b_data = json.load(f, object_hook=SetDecoder) b_data = json.load(f, object_hook=SetDecoder)
except (TypeError, OSError) as err:
bb.error("Failed to open sigdata file '%s': %s" % (b, str(err)))
raise err
for data in [a_data, b_data]: for data in [a_data, b_data]:
handle_renames(data) handle_renames(data)
@@ -1147,11 +978,11 @@ def compare_sigfiles(a, b, recursecb=None, color=False, collapsed=False):
a = a_data['runtaskdeps'][idx] a = a_data['runtaskdeps'][idx]
b = b_data['runtaskdeps'][idx] b = b_data['runtaskdeps'][idx]
if a_data['runtaskhashes'][a] != b_data['runtaskhashes'][b] and not collapsed: if a_data['runtaskhashes'][a] != b_data['runtaskhashes'][b] and not collapsed:
changed.append("%s with hash %s\n changed to\n%s with hash %s" % (a, a_data['runtaskhashes'][a], b, b_data['runtaskhashes'][b])) changed.append("%s with hash %s\n changed to\n%s with hash %s" % (clean_basepath(a), a_data['runtaskhashes'][a], clean_basepath(b), b_data['runtaskhashes'][b]))
if changed: if changed:
clean_a = a_data['runtaskdeps'] clean_a = clean_basepaths_list(a_data['runtaskdeps'])
clean_b = b_data['runtaskdeps'] clean_b = clean_basepaths_list(b_data['runtaskdeps'])
if clean_a != clean_b: if clean_a != clean_b:
output.append(color_format("{color_title}runtaskdeps changed:{color_default}\n%s") % list_inline_diff(clean_a, clean_b, colors)) output.append(color_format("{color_title}runtaskdeps changed:{color_default}\n%s") % list_inline_diff(clean_a, clean_b, colors))
else: else:
@@ -1172,7 +1003,7 @@ def compare_sigfiles(a, b, recursecb=None, color=False, collapsed=False):
#output.append("Dependency on task %s was replaced by %s with same hash" % (dep, bdep)) #output.append("Dependency on task %s was replaced by %s with same hash" % (dep, bdep))
bdep_found = True bdep_found = True
if not bdep_found: if not bdep_found:
output.append(color_format("{color_title}Dependency on task %s was added{color_default} with hash %s") % (dep, b[dep])) output.append(color_format("{color_title}Dependency on task %s was added{color_default} with hash %s") % (clean_basepath(dep), b[dep]))
if removed: if removed:
for dep in sorted(removed): for dep in sorted(removed):
adep_found = False adep_found = False
@@ -1182,11 +1013,11 @@ def compare_sigfiles(a, b, recursecb=None, color=False, collapsed=False):
#output.append("Dependency on task %s was replaced by %s with same hash" % (adep, dep)) #output.append("Dependency on task %s was replaced by %s with same hash" % (adep, dep))
adep_found = True adep_found = True
if not adep_found: if not adep_found:
output.append(color_format("{color_title}Dependency on task %s was removed{color_default} with hash %s") % (dep, a[dep])) output.append(color_format("{color_title}Dependency on task %s was removed{color_default} with hash %s") % (clean_basepath(dep), a[dep]))
if changed: if changed:
for dep in sorted(changed): for dep in sorted(changed):
if not collapsed: if not collapsed:
output.append(color_format("{color_title}Hash for task dependency %s changed{color_default} from %s to %s") % (dep, a[dep], b[dep])) output.append(color_format("{color_title}Hash for task dependency %s changed{color_default} from %s to %s") % (clean_basepath(dep), a[dep], b[dep]))
if callable(recursecb): if callable(recursecb):
recout = recursecb(dep, a[dep], b[dep]) recout = recursecb(dep, a[dep], b[dep])
if recout: if recout:
@@ -1196,7 +1027,6 @@ def compare_sigfiles(a, b, recursecb=None, color=False, collapsed=False):
# If a dependent hash changed, might as well print the line above and then defer to the changes in # If a dependent hash changed, might as well print the line above and then defer to the changes in
# that hash since in all likelyhood, they're the same changes this task also saw. # that hash since in all likelyhood, they're the same changes this task also saw.
output = [output[-1]] + recout output = [output[-1]] + recout
break
a_taint = a_data.get('taint', None) a_taint = a_data.get('taint', None)
b_taint = b_data.get('taint', None) b_taint = b_data.get('taint', None)
@@ -1218,7 +1048,7 @@ def calc_basehash(sigdata):
basedata = '' basedata = ''
alldeps = sigdata['taskdeps'] alldeps = sigdata['taskdeps']
for dep in sorted(alldeps): for dep in alldeps:
basedata = basedata + dep basedata = basedata + dep
val = sigdata['varvals'][dep] val = sigdata['varvals'][dep]
if val is not None: if val is not None:
@@ -1250,12 +1080,8 @@ def calc_taskhash(sigdata):
def dump_sigfile(a): def dump_sigfile(a):
output = [] output = []
try:
with bb.compress.zstd.open(a, "rt", encoding="utf-8", num_threads=1) as f: with bb.compress.zstd.open(a, "rt", encoding="utf-8", num_threads=1) as f:
a_data = json.load(f, object_hook=SetDecoder) a_data = json.load(f, object_hook=SetDecoder)
except (TypeError, OSError) as err:
bb.error("Failed to open sigdata file '%s': %s" % (a, str(err)))
raise err
handle_renames(a_data) handle_renames(a_data)

View File

@@ -44,7 +44,6 @@ class VariableReferenceTest(ReferenceTest):
def parseExpression(self, exp): def parseExpression(self, exp):
parsedvar = self.d.expandWithRefs(exp, None) parsedvar = self.d.expandWithRefs(exp, None)
self.references = parsedvar.references self.references = parsedvar.references
self.execs = parsedvar.execs
def test_simple_reference(self): def test_simple_reference(self):
self.setEmptyVars(["FOO"]) self.setEmptyVars(["FOO"])
@@ -62,11 +61,6 @@ class VariableReferenceTest(ReferenceTest):
self.parseExpression("${@d.getVar('BAR') + 'foo'}") self.parseExpression("${@d.getVar('BAR') + 'foo'}")
self.assertReferences(set(["BAR"])) self.assertReferences(set(["BAR"]))
def test_python_exec_reference(self):
self.parseExpression("${@eval('3 * 5')}")
self.assertReferences(set())
self.assertExecs(set(["eval"]))
class ShellReferenceTest(ReferenceTest): class ShellReferenceTest(ReferenceTest):
def parseExpression(self, exp): def parseExpression(self, exp):
@@ -324,7 +318,7 @@ d.getVar(a(), False)
"filename": "example.bb", "filename": "example.bb",
}) })
deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d) deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), self.d)
self.assertEqual(deps, set(["somevar", "bar", "something", "inexpand", "test", "test2", "a"])) self.assertEqual(deps, set(["somevar", "bar", "something", "inexpand", "test", "test2", "a"]))
@@ -371,7 +365,7 @@ esac
self.d.setVarFlags("FOO", {"func": True}) self.d.setVarFlags("FOO", {"func": True})
self.setEmptyVars(execs) self.setEmptyVars(execs)
deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d) deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), self.d)
self.assertEqual(deps, set(["somevar", "inverted"] + execs)) self.assertEqual(deps, set(["somevar", "inverted"] + execs))
@@ -381,7 +375,7 @@ esac
self.d.setVar("FOO", "foo=oe_libinstall; eval $foo") self.d.setVar("FOO", "foo=oe_libinstall; eval $foo")
self.d.setVarFlag("FOO", "vardeps", "oe_libinstall") self.d.setVarFlag("FOO", "vardeps", "oe_libinstall")
deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d) deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), self.d)
self.assertEqual(deps, set(["oe_libinstall"])) self.assertEqual(deps, set(["oe_libinstall"]))
@@ -390,7 +384,7 @@ esac
self.d.setVar("FOO", "foo=oe_libinstall; eval $foo") self.d.setVar("FOO", "foo=oe_libinstall; eval $foo")
self.d.setVarFlag("FOO", "vardeps", "${@'oe_libinstall'}") self.d.setVarFlag("FOO", "vardeps", "${@'oe_libinstall'}")
deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d) deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), self.d)
self.assertEqual(deps, set(["oe_libinstall"])) self.assertEqual(deps, set(["oe_libinstall"]))
@@ -405,7 +399,7 @@ esac
# Check dependencies # Check dependencies
self.d.setVar('ANOTHERVAR', expr) self.d.setVar('ANOTHERVAR', expr)
self.d.setVar('TESTVAR', 'anothervalue testval testval2') self.d.setVar('TESTVAR', 'anothervalue testval testval2')
deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d) deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), self.d)
self.assertEqual(sorted(values.splitlines()), self.assertEqual(sorted(values.splitlines()),
sorted([expr, sorted([expr,
'TESTVAR{anothervalue} = Set', 'TESTVAR{anothervalue} = Set',
@@ -424,49 +418,23 @@ esac
self.d.setVar('ANOTHERVAR', varval) self.d.setVar('ANOTHERVAR', varval)
self.d.setVar('TESTVAR', 'anothervalue testval testval2') self.d.setVar('TESTVAR', 'anothervalue testval testval2')
self.d.setVar('TESTVAR2', 'testval3') self.d.setVar('TESTVAR2', 'testval3')
deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), set(["TESTVAR"]), self.d, self.d) deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(["TESTVAR"]), self.d)
self.assertEqual(sorted(values.splitlines()), sorted([varval])) self.assertEqual(sorted(values.splitlines()), sorted([varval]))
self.assertEqual(deps, set(["TESTVAR2"])) self.assertEqual(deps, set(["TESTVAR2"]))
self.assertEqual(self.d.getVar('ANOTHERVAR').split(), ['testval3', 'anothervalue']) self.assertEqual(self.d.getVar('ANOTHERVAR').split(), ['testval3', 'anothervalue'])
# Check the vardepsexclude flag is handled by contains functionality # Check the vardepsexclude flag is handled by contains functionality
self.d.setVarFlag('ANOTHERVAR', 'vardepsexclude', 'TESTVAR') self.d.setVarFlag('ANOTHERVAR', 'vardepsexclude', 'TESTVAR')
deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d) deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), self.d)
self.assertEqual(sorted(values.splitlines()), sorted([varval])) self.assertEqual(sorted(values.splitlines()), sorted([varval]))
self.assertEqual(deps, set(["TESTVAR2"])) self.assertEqual(deps, set(["TESTVAR2"]))
self.assertEqual(self.d.getVar('ANOTHERVAR').split(), ['testval3', 'anothervalue']) self.assertEqual(self.d.getVar('ANOTHERVAR').split(), ['testval3', 'anothervalue'])
def test_contains_vardeps_override_operators(self):
# Check override operators handle dependencies correctly with the contains functionality
expr_plain = 'testval'
expr_prepend = '${@bb.utils.filter("TESTVAR1", "testval1", d)} '
expr_append = ' ${@bb.utils.filter("TESTVAR2", "testval2", d)}'
expr_remove = '${@bb.utils.contains("TESTVAR3", "no-testval", "testval", "", d)}'
# Check dependencies
self.d.setVar('ANOTHERVAR', expr_plain)
self.d.prependVar('ANOTHERVAR', expr_prepend)
self.d.appendVar('ANOTHERVAR', expr_append)
self.d.setVar('ANOTHERVAR:remove', expr_remove)
self.d.setVar('TESTVAR1', 'blah')
self.d.setVar('TESTVAR2', 'testval2')
self.d.setVar('TESTVAR3', 'no-testval')
deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d)
self.assertEqual(sorted(values.splitlines()),
sorted([
expr_prepend + expr_plain + expr_append,
'_remove of ' + expr_remove,
'TESTVAR1{testval1} = Unset',
'TESTVAR2{testval2} = Set',
'TESTVAR3{no-testval} = Set',
]))
# Check final value
self.assertEqual(self.d.getVar('ANOTHERVAR').split(), ['testval2'])
#Currently no wildcard support #Currently no wildcard support
#def test_vardeps_wildcards(self): #def test_vardeps_wildcards(self):
# self.d.setVar("oe_libinstall", "echo test") # self.d.setVar("oe_libinstall", "echo test")
# self.d.setVar("FOO", "foo=oe_libinstall; eval $foo") # self.d.setVar("FOO", "foo=oe_libinstall; eval $foo")
# self.d.setVarFlag("FOO", "vardeps", "oe_*") # self.d.setVarFlag("FOO", "vardeps", "oe_*")
# self.assertEqual(deps, set(["oe_libinstall"])) # self.assertEquals(deps, set(["oe_libinstall"]))

View File

@@ -20,7 +20,7 @@ class ProgressWatcher:
def __init__(self): def __init__(self):
self._reports = [] self._reports = []
def handle_event(self, event, d): def handle_event(self, event):
self._reports.append((event.progress, event.rate)) self._reports.append((event.progress, event.rate))
def reports(self): def reports(self):

View File

@@ -1,6 +1,4 @@
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #

View File

@@ -1,8 +1,6 @@
# #
# BitBake Tests for cooker.py # BitBake Tests for cooker.py
# #
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only # SPDX-License-Identifier: GPL-2.0-only
# #

View File

@@ -60,15 +60,6 @@ class DataExpansions(unittest.TestCase):
val = self.d.expand("${@5*12}") val = self.d.expand("${@5*12}")
self.assertEqual(str(val), "60") self.assertEqual(str(val), "60")
def test_python_snippet_w_dict(self):
val = self.d.expand("${@{ 'green': 1, 'blue': 2 }['green']}")
self.assertEqual(str(val), "1")
def test_python_unexpanded_multi(self):
self.d.setVar("bar", "${unsetvar}")
val = self.d.expand("${@2*2},${foo},${@d.getVar('foo') + ' ${bar}'},${foo}")
self.assertEqual(str(val), "4,value_of_foo,${@d.getVar('foo') + ' ${unsetvar}'},value_of_foo")
def test_expand_in_python_snippet(self): def test_expand_in_python_snippet(self):
val = self.d.expand("${@'boo ' + '${foo}'}") val = self.d.expand("${@'boo ' + '${foo}'}")
self.assertEqual(str(val), "boo value_of_foo") self.assertEqual(str(val), "boo value_of_foo")
@@ -77,18 +68,6 @@ class DataExpansions(unittest.TestCase):
val = self.d.expand("${@d.getVar('foo') + ' ${bar}'}") val = self.d.expand("${@d.getVar('foo') + ' ${bar}'}")
self.assertEqual(str(val), "value_of_foo value_of_bar") self.assertEqual(str(val), "value_of_foo value_of_bar")
def test_python_snippet_function_reference(self):
self.d.setVar("TESTVAL", "testvalue")
self.d.setVar("testfunc", 'd.getVar("TESTVAL")')
context = bb.utils.get_context()
context["testfunc"] = lambda d: d.getVar("TESTVAL")
val = self.d.expand("${@testfunc(d)}")
self.assertEqual(str(val), "testvalue")
def test_python_snippet_builtin_metadata(self):
self.d.setVar("eval", "INVALID")
self.d.expand("${@eval('3')}")
def test_python_unexpanded(self): def test_python_unexpanded(self):
self.d.setVar("bar", "${unsetvar}") self.d.setVar("bar", "${unsetvar}")
val = self.d.expand("${@d.getVar('foo') + ' ${bar}'}") val = self.d.expand("${@d.getVar('foo') + ' ${bar}'}")
@@ -395,16 +374,6 @@ class TestOverrides(unittest.TestCase):
self.d.setVar("OVERRIDES", "foo:bar:some_val") self.d.setVar("OVERRIDES", "foo:bar:some_val")
self.assertEqual(self.d.getVar("TEST"), "testvalue3") self.assertEqual(self.d.getVar("TEST"), "testvalue3")
# Test an override with _<numeric> in it based on a real world OE issue
def test_underscore_override_2(self):
self.d.setVar("TARGET_ARCH", "x86_64")
self.d.setVar("PN", "test-${TARGET_ARCH}")
self.d.setVar("VERSION", "1")
self.d.setVar("VERSION:pn-test-${TARGET_ARCH}", "2")
self.d.setVar("OVERRIDES", "pn-${PN}")
bb.data.expandKeys(self.d)
self.assertEqual(self.d.getVar("VERSION"), "2")
def test_remove_with_override(self): def test_remove_with_override(self):
self.d.setVar("TEST:bar", "testvalue2") self.d.setVar("TEST:bar", "testvalue2")
self.d.setVar("TEST:some_val", "testvalue3 testvalue5") self.d.setVar("TEST:some_val", "testvalue3 testvalue5")
@@ -426,6 +395,16 @@ class TestOverrides(unittest.TestCase):
self.d.setVar("TEST:bar:append", "testvalue2") self.d.setVar("TEST:bar:append", "testvalue2")
self.assertEqual(self.d.getVar("TEST"), "testvalue2") self.assertEqual(self.d.getVar("TEST"), "testvalue2")
# Test an override with _<numeric> in it based on a real world OE issue
def test_underscore_override(self):
self.d.setVar("TARGET_ARCH", "x86_64")
self.d.setVar("PN", "test-${TARGET_ARCH}")
self.d.setVar("VERSION", "1")
self.d.setVar("VERSION:pn-test-${TARGET_ARCH}", "2")
self.d.setVar("OVERRIDES", "pn-${PN}")
bb.data.expandKeys(self.d)
self.assertEqual(self.d.getVar("VERSION"), "2")
def test_append_and_unused_override(self): def test_append_and_unused_override(self):
# Had a bug where an unused override append could return "" instead of None # Had a bug where an unused override append could return "" instead of None
self.d.setVar("BAR:append:unusedoverride", "testvalue2") self.d.setVar("BAR:append:unusedoverride", "testvalue2")

View File

@@ -13,7 +13,6 @@ import pickle
import threading import threading
import time import time
import unittest import unittest
import tempfile
from unittest.mock import Mock from unittest.mock import Mock
from unittest.mock import call from unittest.mock import call
@@ -158,7 +157,7 @@ class EventHandlingTest(unittest.TestCase):
self._test_process.event_handler, self._test_process.event_handler,
event, event,
None) None)
self._test_process.event_handler.assert_called_once_with(event, None) self._test_process.event_handler.assert_called_once_with(event)
def test_fire_class_handlers(self): def test_fire_class_handlers(self):
""" Test fire_class_handlers method """ """ Test fire_class_handlers method """
@@ -176,10 +175,10 @@ class EventHandlingTest(unittest.TestCase):
bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event1, None)
bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None)
bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None)
expected_event_handler1 = [call(event1, None)] expected_event_handler1 = [call(event1)]
expected_event_handler2 = [call(event1, None), expected_event_handler2 = [call(event1),
call(event2, None), call(event2),
call(event2, None)] call(event2)]
self.assertEqual(self._test_process.event_handler1.call_args_list, self.assertEqual(self._test_process.event_handler1.call_args_list,
expected_event_handler1) expected_event_handler1)
self.assertEqual(self._test_process.event_handler2.call_args_list, self.assertEqual(self._test_process.event_handler2.call_args_list,
@@ -206,7 +205,7 @@ class EventHandlingTest(unittest.TestCase):
bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None)
bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None)
expected_event_handler1 = [] expected_event_handler1 = []
expected_event_handler2 = [call(event1, None)] expected_event_handler2 = [call(event1)]
self.assertEqual(self._test_process.event_handler1.call_args_list, self.assertEqual(self._test_process.event_handler1.call_args_list,
expected_event_handler1) expected_event_handler1)
self.assertEqual(self._test_process.event_handler2.call_args_list, self.assertEqual(self._test_process.event_handler2.call_args_list,
@@ -224,7 +223,7 @@ class EventHandlingTest(unittest.TestCase):
self.assertEqual(result, bb.event.Registered) self.assertEqual(result, bb.event.Registered)
bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event1, None)
bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None)
expected = [call(event1, None), call(event2, None)] expected = [call(event1), call(event2)]
self.assertEqual(self._test_process.event_handler1.call_args_list, self.assertEqual(self._test_process.event_handler1.call_args_list,
expected) expected)
@@ -238,7 +237,7 @@ class EventHandlingTest(unittest.TestCase):
self.assertEqual(result, bb.event.Registered) self.assertEqual(result, bb.event.Registered)
bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event1, None)
bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None)
expected = [call(event1, None), call(event2, None), call(event1, None)] expected = [call(event1), call(event2), call(event1)]
self.assertEqual(self._test_process.event_handler1.call_args_list, self.assertEqual(self._test_process.event_handler1.call_args_list,
expected) expected)
@@ -252,7 +251,7 @@ class EventHandlingTest(unittest.TestCase):
self.assertEqual(result, bb.event.Registered) self.assertEqual(result, bb.event.Registered)
bb.event.fire_class_handlers(event1, None) bb.event.fire_class_handlers(event1, None)
bb.event.fire_class_handlers(event2, None) bb.event.fire_class_handlers(event2, None)
expected = [call(event1,None), call(event2, None), call(event1, None), call(event2, None)] expected = [call(event1), call(event2), call(event1), call(event2)]
self.assertEqual(self._test_process.event_handler1.call_args_list, self.assertEqual(self._test_process.event_handler1.call_args_list,
expected) expected)
@@ -360,10 +359,9 @@ class EventHandlingTest(unittest.TestCase):
event1 = bb.event.ConfigParsed() event1 = bb.event.ConfigParsed()
bb.event.fire(event1, None) bb.event.fire(event1, None)
expected = [call(event1, None)] expected = [call(event1)]
self.assertEqual(self._test_process.event_handler1.call_args_list, self.assertEqual(self._test_process.event_handler1.call_args_list,
expected) expected)
expected = [call(event1)]
self.assertEqual(self._test_ui1.event.send.call_args_list, self.assertEqual(self._test_ui1.event.send.call_args_list,
expected) expected)
@@ -452,9 +450,10 @@ class EventHandlingTest(unittest.TestCase):
and disable threadlocks tests """ and disable threadlocks tests """
bb.event.fire(bb.event.OperationStarted(), None) bb.event.fire(bb.event.OperationStarted(), None)
def test_event_threadlock(self): def test_enable_threadlock(self):
""" Test enable_threadlock method """ """ Test enable_threadlock method """
self._set_threadlock_test_mockups() self._set_threadlock_test_mockups()
bb.event.enable_threadlock()
self._set_and_run_threadlock_test_workers() self._set_and_run_threadlock_test_workers()
# Calls to UI handlers should be in order as all the registered # Calls to UI handlers should be in order as all the registered
# handlers for the event coming from the first worker should be # handlers for the event coming from the first worker should be
@@ -462,6 +461,20 @@ class EventHandlingTest(unittest.TestCase):
self.assertEqual(self._threadlock_test_calls, self.assertEqual(self._threadlock_test_calls,
["w1_ui1", "w1_ui2", "w2_ui1", "w2_ui2"]) ["w1_ui1", "w1_ui2", "w2_ui1", "w2_ui2"])
def test_disable_threadlock(self):
""" Test disable_threadlock method """
self._set_threadlock_test_mockups()
bb.event.disable_threadlock()
self._set_and_run_threadlock_test_workers()
# Calls to UI handlers should be intertwined together. Thanks to the
# delay in the registered handlers for the event coming from the first
# worker, the event coming from the second worker starts being
# processed before finishing handling the first worker event.
self.assertEqual(self._threadlock_test_calls,
["w1_ui1", "w2_ui1", "w1_ui2", "w2_ui2"])
class EventClassesTest(unittest.TestCase): class EventClassesTest(unittest.TestCase):
""" Event classes test class """ """ Event classes test class """
@@ -469,8 +482,6 @@ class EventClassesTest(unittest.TestCase):
def setUp(self): def setUp(self):
bb.event.worker_pid = EventClassesTest._worker_pid bb.event.worker_pid = EventClassesTest._worker_pid
self.d = bb.data.init()
bb.parse.siggen = bb.siggen.init(self.d)
def test_Event(self): def test_Event(self):
""" Test the Event base class """ """ Test the Event base class """
@@ -953,24 +964,3 @@ class EventClassesTest(unittest.TestCase):
event = bb.event.FindSigInfoResult(result) event = bb.event.FindSigInfoResult(result)
self.assertEqual(event.result, result) self.assertEqual(event.result, result)
self.assertEqual(event.pid, EventClassesTest._worker_pid) self.assertEqual(event.pid, EventClassesTest._worker_pid)
def test_lineno_in_eventhandler(self):
# The error lineno is 5, not 4 since the first line is '\n'
error_line = """
# Comment line1
# Comment line2
python test_lineno_in_eventhandler() {
This is an error line
}
addhandler test_lineno_in_eventhandler
test_lineno_in_eventhandler[eventmask] = "bb.event.ConfigParsed"
"""
with self.assertLogs() as logs:
f = tempfile.NamedTemporaryFile(suffix = '.bb')
f.write(bytes(error_line, "utf-8"))
f.flush()
d = bb.parse.handle(f.name, self.d)['']
output = "".join(logs.output)
self.assertTrue(" line 5\n" in output)

View File

@@ -1,20 +0,0 @@
<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width"><style type="text/css">body,html {background:#fff;font-family:"Bitstream Vera Sans","Lucida Grande","Lucida Sans Unicode",Lucidux,Verdana,Lucida,sans-serif;}tr:nth-child(even) {background:#f4f4f4;}th,td {padding:0.1em 0.5em;}th {text-align:left;font-weight:bold;background:#eee;border-bottom:1px solid #aaa;}#list {border:1px solid #aaa;width:100%;}a {color:#a33;}a:hover {color:#e33;}</style>
<title>Index of /sources/libxml2/2.10/</title>
</head><body><h1>Index of /sources/libxml2/2.10/</h1>
<table id="list"><thead><tr><th style="width:55%"><a href="?C=N&amp;O=A">File Name</a>&nbsp;<a href="?C=N&amp;O=D">&nbsp;&darr;&nbsp;</a></th><th style="width:20%"><a href="?C=S&amp;O=A">File Size</a>&nbsp;<a href="?C=S&amp;O=D">&nbsp;&darr;&nbsp;</a></th><th style="width:25%"><a href="?C=M&amp;O=A">Date</a>&nbsp;<a href="?C=M&amp;O=D">&nbsp;&darr;&nbsp;</a></th></tr></thead>
<tbody><tr><td class="link"><a href="../">Parent directory/</a></td><td class="size">-</td><td class="date">-</td></tr>
<tr><td class="link"><a href="LATEST-IS-2.10.3" title="LATEST-IS-2.10.3">LATEST-IS-2.10.3</a></td><td class="size">2.5 MiB</td><td class="date">2022-Oct-14 12:55</td></tr>
<tr><td class="link"><a href="libxml2-2.10.0.news" title="libxml2-2.10.0.news">libxml2-2.10.0.news</a></td><td class="size">7.1 KiB</td><td class="date">2022-Aug-17 11:55</td></tr>
<tr><td class="link"><a href="libxml2-2.10.0.sha256sum" title="libxml2-2.10.0.sha256sum">libxml2-2.10.0.sha256sum</a></td><td class="size">174 B</td><td class="date">2022-Aug-17 11:55</td></tr>
<tr><td class="link"><a href="libxml2-2.10.0.tar.xz" title="libxml2-2.10.0.tar.xz">libxml2-2.10.0.tar.xz</a></td><td class="size">2.6 MiB</td><td class="date">2022-Aug-17 11:55</td></tr>
<tr><td class="link"><a href="libxml2-2.10.1.news" title="libxml2-2.10.1.news">libxml2-2.10.1.news</a></td><td class="size">455 B</td><td class="date">2022-Aug-25 11:33</td></tr>
<tr><td class="link"><a href="libxml2-2.10.1.sha256sum" title="libxml2-2.10.1.sha256sum">libxml2-2.10.1.sha256sum</a></td><td class="size">174 B</td><td class="date">2022-Aug-25 11:33</td></tr>
<tr><td class="link"><a href="libxml2-2.10.1.tar.xz" title="libxml2-2.10.1.tar.xz">libxml2-2.10.1.tar.xz</a></td><td class="size">2.6 MiB</td><td class="date">2022-Aug-25 11:33</td></tr>
<tr><td class="link"><a href="libxml2-2.10.2.news" title="libxml2-2.10.2.news">libxml2-2.10.2.news</a></td><td class="size">309 B</td><td class="date">2022-Aug-29 14:56</td></tr>
<tr><td class="link"><a href="libxml2-2.10.2.sha256sum" title="libxml2-2.10.2.sha256sum">libxml2-2.10.2.sha256sum</a></td><td class="size">174 B</td><td class="date">2022-Aug-29 14:56</td></tr>
<tr><td class="link"><a href="libxml2-2.10.2.tar.xz" title="libxml2-2.10.2.tar.xz">libxml2-2.10.2.tar.xz</a></td><td class="size">2.5 MiB</td><td class="date">2022-Aug-29 14:56</td></tr>
<tr><td class="link"><a href="libxml2-2.10.3.news" title="libxml2-2.10.3.news">libxml2-2.10.3.news</a></td><td class="size">294 B</td><td class="date">2022-Oct-14 12:55</td></tr>
<tr><td class="link"><a href="libxml2-2.10.3.sha256sum" title="libxml2-2.10.3.sha256sum">libxml2-2.10.3.sha256sum</a></td><td class="size">174 B</td><td class="date">2022-Oct-14 12:55</td></tr>
<tr><td class="link"><a href="libxml2-2.10.3.tar.xz" title="libxml2-2.10.3.tar.xz">libxml2-2.10.3.tar.xz</a></td><td class="size">2.5 MiB</td><td class="date">2022-Oct-14 12:55</td></tr>
</tbody></table></body></html>

View File

@@ -1,40 +0,0 @@
<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width"><style type="text/css">body,html {background:#fff;font-family:"Bitstream Vera Sans","Lucida Grande","Lucida Sans Unicode",Lucidux,Verdana,Lucida,sans-serif;}tr:nth-child(even) {background:#f4f4f4;}th,td {padding:0.1em 0.5em;}th {text-align:left;font-weight:bold;background:#eee;border-bottom:1px solid #aaa;}#list {border:1px solid #aaa;width:100%;}a {color:#a33;}a:hover {color:#e33;}</style>
<title>Index of /sources/libxml2/2.9/</title>
</head><body><h1>Index of /sources/libxml2/2.9/</h1>
<table id="list"><thead><tr><th style="width:55%"><a href="?C=N&amp;O=A">File Name</a>&nbsp;<a href="?C=N&amp;O=D">&nbsp;&darr;&nbsp;</a></th><th style="width:20%"><a href="?C=S&amp;O=A">File Size</a>&nbsp;<a href="?C=S&amp;O=D">&nbsp;&darr;&nbsp;</a></th><th style="width:25%"><a href="?C=M&amp;O=A">Date</a>&nbsp;<a href="?C=M&amp;O=D">&nbsp;&darr;&nbsp;</a></th></tr></thead>
<tbody><tr><td class="link"><a href="../">Parent directory/</a></td><td class="size">-</td><td class="date">-</td></tr>
<tr><td class="link"><a href="LATEST-IS-2.9.14" title="LATEST-IS-2.9.14">LATEST-IS-2.9.14</a></td><td class="size">3.0 MiB</td><td class="date">2022-May-02 12:03</td></tr>
<tr><td class="link"><a href="libxml2-2.9.0.sha256sum" title="libxml2-2.9.0.sha256sum">libxml2-2.9.0.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:27</td></tr>
<tr><td class="link"><a href="libxml2-2.9.0.tar.xz" title="libxml2-2.9.0.tar.xz">libxml2-2.9.0.tar.xz</a></td><td class="size">3.0 MiB</td><td class="date">2022-Feb-14 18:27</td></tr>
<tr><td class="link"><a href="libxml2-2.9.1.sha256sum" title="libxml2-2.9.1.sha256sum">libxml2-2.9.1.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:28</td></tr>
<tr><td class="link"><a href="libxml2-2.9.1.tar.xz" title="libxml2-2.9.1.tar.xz">libxml2-2.9.1.tar.xz</a></td><td class="size">3.0 MiB</td><td class="date">2022-Feb-14 18:28</td></tr>
<tr><td class="link"><a href="libxml2-2.9.10.sha256sum" title="libxml2-2.9.10.sha256sum">libxml2-2.9.10.sha256sum</a></td><td class="size">88 B</td><td class="date">2022-Feb-14 18:42</td></tr>
<tr><td class="link"><a href="libxml2-2.9.10.tar.xz" title="libxml2-2.9.10.tar.xz">libxml2-2.9.10.tar.xz</a></td><td class="size">3.2 MiB</td><td class="date">2022-Feb-14 18:42</td></tr>
<tr><td class="link"><a href="libxml2-2.9.11.sha256sum" title="libxml2-2.9.11.sha256sum">libxml2-2.9.11.sha256sum</a></td><td class="size">88 B</td><td class="date">2022-Feb-14 18:43</td></tr>
<tr><td class="link"><a href="libxml2-2.9.11.tar.xz" title="libxml2-2.9.11.tar.xz">libxml2-2.9.11.tar.xz</a></td><td class="size">3.2 MiB</td><td class="date">2022-Feb-14 18:43</td></tr>
<tr><td class="link"><a href="libxml2-2.9.12.sha256sum" title="libxml2-2.9.12.sha256sum">libxml2-2.9.12.sha256sum</a></td><td class="size">88 B</td><td class="date">2022-Feb-14 18:45</td></tr>
<tr><td class="link"><a href="libxml2-2.9.12.tar.xz" title="libxml2-2.9.12.tar.xz">libxml2-2.9.12.tar.xz</a></td><td class="size">3.2 MiB</td><td class="date">2022-Feb-14 18:45</td></tr>
<tr><td class="link"><a href="libxml2-2.9.13.news" title="libxml2-2.9.13.news">libxml2-2.9.13.news</a></td><td class="size">26.6 KiB</td><td class="date">2022-Feb-20 12:42</td></tr>
<tr><td class="link"><a href="libxml2-2.9.13.sha256sum" title="libxml2-2.9.13.sha256sum">libxml2-2.9.13.sha256sum</a></td><td class="size">174 B</td><td class="date">2022-Feb-20 12:42</td></tr>
<tr><td class="link"><a href="libxml2-2.9.13.tar.xz" title="libxml2-2.9.13.tar.xz">libxml2-2.9.13.tar.xz</a></td><td class="size">3.1 MiB</td><td class="date">2022-Feb-20 12:42</td></tr>
<tr><td class="link"><a href="libxml2-2.9.14.news" title="libxml2-2.9.14.news">libxml2-2.9.14.news</a></td><td class="size">1.0 KiB</td><td class="date">2022-May-02 12:03</td></tr>
<tr><td class="link"><a href="libxml2-2.9.14.sha256sum" title="libxml2-2.9.14.sha256sum">libxml2-2.9.14.sha256sum</a></td><td class="size">174 B</td><td class="date">2022-May-02 12:03</td></tr>
<tr><td class="link"><a href="libxml2-2.9.14.tar.xz" title="libxml2-2.9.14.tar.xz">libxml2-2.9.14.tar.xz</a></td><td class="size">3.0 MiB</td><td class="date">2022-May-02 12:03</td></tr>
<tr><td class="link"><a href="libxml2-2.9.2.sha256sum" title="libxml2-2.9.2.sha256sum">libxml2-2.9.2.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:30</td></tr>
<tr><td class="link"><a href="libxml2-2.9.2.tar.xz" title="libxml2-2.9.2.tar.xz">libxml2-2.9.2.tar.xz</a></td><td class="size">3.2 MiB</td><td class="date">2022-Feb-14 18:30</td></tr>
<tr><td class="link"><a href="libxml2-2.9.3.sha256sum" title="libxml2-2.9.3.sha256sum">libxml2-2.9.3.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:31</td></tr>
<tr><td class="link"><a href="libxml2-2.9.3.tar.xz" title="libxml2-2.9.3.tar.xz">libxml2-2.9.3.tar.xz</a></td><td class="size">3.2 MiB</td><td class="date">2022-Feb-14 18:31</td></tr>
<tr><td class="link"><a href="libxml2-2.9.4.sha256sum" title="libxml2-2.9.4.sha256sum">libxml2-2.9.4.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:33</td></tr>
<tr><td class="link"><a href="libxml2-2.9.4.tar.xz" title="libxml2-2.9.4.tar.xz">libxml2-2.9.4.tar.xz</a></td><td class="size">2.9 MiB</td><td class="date">2022-Feb-14 18:33</td></tr>
<tr><td class="link"><a href="libxml2-2.9.5.sha256sum" title="libxml2-2.9.5.sha256sum">libxml2-2.9.5.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:35</td></tr>
<tr><td class="link"><a href="libxml2-2.9.5.tar.xz" title="libxml2-2.9.5.tar.xz">libxml2-2.9.5.tar.xz</a></td><td class="size">3.0 MiB</td><td class="date">2022-Feb-14 18:35</td></tr>
<tr><td class="link"><a href="libxml2-2.9.6.sha256sum" title="libxml2-2.9.6.sha256sum">libxml2-2.9.6.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:36</td></tr>
<tr><td class="link"><a href="libxml2-2.9.6.tar.xz" title="libxml2-2.9.6.tar.xz">libxml2-2.9.6.tar.xz</a></td><td class="size">3.0 MiB</td><td class="date">2022-Feb-14 18:36</td></tr>
<tr><td class="link"><a href="libxml2-2.9.7.sha256sum" title="libxml2-2.9.7.sha256sum">libxml2-2.9.7.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:37</td></tr>
<tr><td class="link"><a href="libxml2-2.9.7.tar.xz" title="libxml2-2.9.7.tar.xz">libxml2-2.9.7.tar.xz</a></td><td class="size">3.0 MiB</td><td class="date">2022-Feb-14 18:37</td></tr>
<tr><td class="link"><a href="libxml2-2.9.8.sha256sum" title="libxml2-2.9.8.sha256sum">libxml2-2.9.8.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:39</td></tr>
<tr><td class="link"><a href="libxml2-2.9.8.tar.xz" title="libxml2-2.9.8.tar.xz">libxml2-2.9.8.tar.xz</a></td><td class="size">3.0 MiB</td><td class="date">2022-Feb-14 18:39</td></tr>
<tr><td class="link"><a href="libxml2-2.9.9.sha256sum" title="libxml2-2.9.9.sha256sum">libxml2-2.9.9.sha256sum</a></td><td class="size">87 B</td><td class="date">2022-Feb-14 18:40</td></tr>
<tr><td class="link"><a href="libxml2-2.9.9.tar.xz" title="libxml2-2.9.9.tar.xz">libxml2-2.9.9.tar.xz</a></td><td class="size">3.0 MiB</td><td class="date">2022-Feb-14 18:40</td></tr>
</tbody></table></body></html>

View File

@@ -1,19 +0,0 @@
<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width"><style type="text/css">body,html {background:#fff;font-family:"Bitstream Vera Sans","Lucida Grande","Lucida Sans Unicode",Lucidux,Verdana,Lucida,sans-serif;}tr:nth-child(even) {background:#f4f4f4;}th,td {padding:0.1em 0.5em;}th {text-align:left;font-weight:bold;background:#eee;border-bottom:1px solid #aaa;}#list {border:1px solid #aaa;width:100%;}a {color:#a33;}a:hover {color:#e33;}</style>
<title>Index of /sources/libxml2/</title>
</head><body><h1>Index of /sources/libxml2/</h1>
<table id="list"><thead><tr><th style="width:55%"><a href="?C=N&amp;O=A">File Name</a>&nbsp;<a href="?C=N&amp;O=D">&nbsp;&darr;&nbsp;</a></th><th style="width:20%"><a href="?C=S&amp;O=A">File Size</a>&nbsp;<a href="?C=S&amp;O=D">&nbsp;&darr;&nbsp;</a></th><th style="width:25%"><a href="?C=M&amp;O=A">Date</a>&nbsp;<a href="?C=M&amp;O=D">&nbsp;&darr;&nbsp;</a></th></tr></thead>
<tbody><tr><td class="link"><a href="../">Parent directory/</a></td><td class="size">-</td><td class="date">-</td></tr>
<tr><td class="link"><a href="2.0/" title="2.0">2.0/</a></td><td class="size">-</td><td class="date">2009-Jul-14 13:04</td></tr>
<tr><td class="link"><a href="2.1/" title="2.1">2.1/</a></td><td class="size">-</td><td class="date">2009-Jul-14 13:04</td></tr>
<tr><td class="link"><a href="2.10/" title="2.10">2.10/</a></td><td class="size">-</td><td class="date">2022-Oct-14 12:55</td></tr>
<tr><td class="link"><a href="2.2/" title="2.2">2.2/</a></td><td class="size">-</td><td class="date">2009-Jul-14 13:04</td></tr>
<tr><td class="link"><a href="2.3/" title="2.3">2.3/</a></td><td class="size">-</td><td class="date">2009-Jul-14 13:05</td></tr>
<tr><td class="link"><a href="2.4/" title="2.4">2.4/</a></td><td class="size">-</td><td class="date">2009-Jul-14 13:05</td></tr>
<tr><td class="link"><a href="2.5/" title="2.5">2.5/</a></td><td class="size">-</td><td class="date">2009-Jul-14 13:05</td></tr>
<tr><td class="link"><a href="2.6/" title="2.6">2.6/</a></td><td class="size">-</td><td class="date">2009-Jul-14 13:05</td></tr>
<tr><td class="link"><a href="2.7/" title="2.7">2.7/</a></td><td class="size">-</td><td class="date">2022-Feb-14 18:24</td></tr>
<tr><td class="link"><a href="2.8/" title="2.8">2.8/</a></td><td class="size">-</td><td class="date">2022-Feb-14 18:26</td></tr>
<tr><td class="link"><a href="2.9/" title="2.9">2.9/</a></td><td class="size">-</td><td class="date">2022-May-02 12:04</td></tr>
<tr><td class="link"><a href="cache.json" title="cache.json">cache.json</a></td><td class="size">22.8 KiB</td><td class="date">2022-Oct-14 12:55</td></tr>
</tbody></table></body></html>

File diff suppressed because it is too large Load Diff

View File

@@ -119,7 +119,7 @@ EXTRA_OECONF:class-target = "b"
EXTRA_OECONF:append = " c" EXTRA_OECONF:append = " c"
""" """
def test_parse_overrides2(self): def test_parse_overrides(self):
f = self.parsehelper(self.overridetest2) f = self.parsehelper(self.overridetest2)
d = bb.parse.handle(f.name, self.d)[''] d = bb.parse.handle(f.name, self.d)['']
d.appendVar("EXTRA_OECONF", " d") d.appendVar("EXTRA_OECONF", " d")
@@ -164,7 +164,6 @@ python () {
# become unset/disappear. # become unset/disappear.
# #
def test_parse_classextend_contamination(self): def test_parse_classextend_contamination(self):
self.d.setVar("__bbclasstype", "recipe")
cls = self.parsehelper(self.classextend_bbclass, suffix=".bbclass") cls = self.parsehelper(self.classextend_bbclass, suffix=".bbclass")
#clsname = os.path.basename(cls.name).replace(".bbclass", "") #clsname = os.path.basename(cls.name).replace(".bbclass", "")
self.classextend = self.classextend.replace("###CLASS###", cls.name) self.classextend = self.classextend.replace("###CLASS###", cls.name)
@@ -186,158 +185,12 @@ deltask ${EMPTYVAR}
""" """
def test_parse_addtask_deltask(self): def test_parse_addtask_deltask(self):
import sys import sys
with self.assertLogs() as logs:
f = self.parsehelper(self.addtask_deltask) f = self.parsehelper(self.addtask_deltask)
d = bb.parse.handle(f.name, self.d)[''] d = bb.parse.handle(f.name, self.d)['']
output = "".join(logs.output) stdout = sys.stdout.getvalue()
self.assertTrue("addtask contained multiple 'before' keywords" in output) self.assertTrue("addtask contained multiple 'before' keywords" in stdout)
self.assertTrue("addtask contained multiple 'after' keywords" in output) self.assertTrue("addtask contained multiple 'after' keywords" in stdout)
self.assertTrue('addtask ignored: " do_patch"' in output) self.assertTrue('addtask ignored: " do_patch"' in stdout)
#self.assertTrue('dependent task do_foo for do_patch does not exist' in output) #self.assertTrue('dependent task do_foo for do_patch does not exist' in stdout)
broken_multiline_comment = """
# First line of comment \\
# Second line of comment \\
"""
def test_parse_broken_multiline_comment(self):
f = self.parsehelper(self.broken_multiline_comment)
with self.assertRaises(bb.BBHandledException):
d = bb.parse.handle(f.name, self.d)['']
comment_in_var = """
VAR = " \\
SOMEVAL \\
# some comment \\
SOMEOTHERVAL \\
"
"""
def test_parse_comment_in_var(self):
f = self.parsehelper(self.comment_in_var)
with self.assertRaises(bb.BBHandledException):
d = bb.parse.handle(f.name, self.d)['']
at_sign_in_var_flag = """
A[flag@.service] = "nonet"
B[flag@.target] = "ntb"
C[f] = "flag"
unset A[flag@.service]
"""
def test_parse_at_sign_in_var_flag(self):
f = self.parsehelper(self.at_sign_in_var_flag)
d = bb.parse.handle(f.name, self.d)['']
self.assertEqual(d.getVar("A"), None)
self.assertEqual(d.getVar("B"), None)
self.assertEqual(d.getVarFlag("A","flag@.service"), None)
self.assertEqual(d.getVarFlag("B","flag@.target"), "ntb")
self.assertEqual(d.getVarFlag("C","f"), "flag")
def test_parse_invalid_at_sign_in_var_flag(self):
invalid_at_sign = self.at_sign_in_var_flag.replace("B[f", "B[@f")
f = self.parsehelper(invalid_at_sign)
with self.assertRaises(bb.parse.ParseError):
d = bb.parse.handle(f.name, self.d)['']
export_function_recipe = """
inherit someclass
"""
export_function_recipe2 = """
inherit someclass
do_compile () {
false
}
python do_compilepython () {
bb.note("Something else")
}
"""
export_function_class = """
someclass_do_compile() {
true
}
python someclass_do_compilepython () {
bb.note("Something")
}
EXPORT_FUNCTIONS do_compile do_compilepython
"""
export_function_class2 = """
secondclass_do_compile() {
true
}
python secondclass_do_compilepython () {
bb.note("Something")
}
EXPORT_FUNCTIONS do_compile do_compilepython
"""
def test_parse_export_functions(self):
def check_function_flags(d):
self.assertEqual(d.getVarFlag("do_compile", "func"), 1)
self.assertEqual(d.getVarFlag("do_compilepython", "func"), 1)
self.assertEqual(d.getVarFlag("do_compile", "python"), None)
self.assertEqual(d.getVarFlag("do_compilepython", "python"), "1")
with tempfile.TemporaryDirectory() as tempdir:
self.d.setVar("__bbclasstype", "recipe")
recipename = tempdir + "/recipe.bb"
os.makedirs(tempdir + "/classes")
with open(tempdir + "/classes/someclass.bbclass", "w") as f:
f.write(self.export_function_class)
f.flush()
with open(tempdir + "/classes/secondclass.bbclass", "w") as f:
f.write(self.export_function_class2)
f.flush()
with open(recipename, "w") as f:
f.write(self.export_function_recipe)
f.flush()
os.chdir(tempdir)
d = bb.parse.handle(recipename, bb.data.createCopy(self.d))['']
self.assertIn("someclass_do_compile", d.getVar("do_compile"))
self.assertIn("someclass_do_compilepython", d.getVar("do_compilepython"))
check_function_flags(d)
recipename2 = tempdir + "/recipe2.bb"
with open(recipename2, "w") as f:
f.write(self.export_function_recipe2)
f.flush()
d = bb.parse.handle(recipename2, bb.data.createCopy(self.d))['']
self.assertNotIn("someclass_do_compile", d.getVar("do_compile"))
self.assertNotIn("someclass_do_compilepython", d.getVar("do_compilepython"))
self.assertIn("false", d.getVar("do_compile"))
self.assertIn("else", d.getVar("do_compilepython"))
check_function_flags(d)
with open(recipename, "a+") as f:
f.write("\ninherit secondclass\n")
f.flush()
with open(recipename2, "a+") as f:
f.write("\ninherit secondclass\n")
f.flush()
d = bb.parse.handle(recipename, bb.data.createCopy(self.d))['']
self.assertIn("secondclass_do_compile", d.getVar("do_compile"))
self.assertIn("secondclass_do_compilepython", d.getVar("do_compilepython"))
check_function_flags(d)
d = bb.parse.handle(recipename2, bb.data.createCopy(self.d))['']
self.assertNotIn("someclass_do_compile", d.getVar("do_compile"))
self.assertNotIn("someclass_do_compilepython", d.getVar("do_compilepython"))
self.assertIn("false", d.getVar("do_compile"))
self.assertIn("else", d.getVar("do_compilepython"))
check_function_flags(d)

View File

@@ -1,2 +0,0 @@
do_build[mcdepends] = "mc::mc-1:h1:do_invalid"

View File

@@ -26,7 +26,7 @@ class RunQueueTests(unittest.TestCase):
a1_sstatevalid = "a1:do_package a1:do_package_qa a1:do_packagedata a1:do_package_write_ipk a1:do_package_write_rpm a1:do_populate_lic a1:do_populate_sysroot" a1_sstatevalid = "a1:do_package a1:do_package_qa a1:do_packagedata a1:do_package_write_ipk a1:do_package_write_rpm a1:do_populate_lic a1:do_populate_sysroot"
b1_sstatevalid = "b1:do_package b1:do_package_qa b1:do_packagedata b1:do_package_write_ipk b1:do_package_write_rpm b1:do_populate_lic b1:do_populate_sysroot" b1_sstatevalid = "b1:do_package b1:do_package_qa b1:do_packagedata b1:do_package_write_ipk b1:do_package_write_rpm b1:do_populate_lic b1:do_populate_sysroot"
def run_bitbakecmd(self, cmd, builddir, sstatevalid="", slowtasks="", extraenv=None, cleanup=False, allowfailure=False): def run_bitbakecmd(self, cmd, builddir, sstatevalid="", slowtasks="", extraenv=None, cleanup=False):
env = os.environ.copy() env = os.environ.copy()
env["BBPATH"] = os.path.realpath(os.path.join(os.path.dirname(__file__), "runqueue-tests")) env["BBPATH"] = os.path.realpath(os.path.join(os.path.dirname(__file__), "runqueue-tests"))
env["BB_ENV_PASSTHROUGH_ADDITIONS"] = "SSTATEVALID SLOWTASKS TOPDIR" env["BB_ENV_PASSTHROUGH_ADDITIONS"] = "SSTATEVALID SLOWTASKS TOPDIR"
@@ -41,8 +41,6 @@ class RunQueueTests(unittest.TestCase):
output = subprocess.check_output(cmd, env=env, stderr=subprocess.STDOUT,universal_newlines=True, cwd=builddir) output = subprocess.check_output(cmd, env=env, stderr=subprocess.STDOUT,universal_newlines=True, cwd=builddir)
print(output) print(output)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
if allowfailure:
return e.output
self.fail("Command %s failed with %s" % (cmd, e.output)) self.fail("Command %s failed with %s" % (cmd, e.output))
tasks = [] tasks = []
tasklog = builddir + "/task.log" tasklog = builddir + "/task.log"
@@ -290,7 +288,7 @@ class RunQueueTests(unittest.TestCase):
with tempfile.TemporaryDirectory(prefix="runqueuetest") as tempdir: with tempfile.TemporaryDirectory(prefix="runqueuetest") as tempdir:
extraenv = { extraenv = {
"BBMULTICONFIG" : "mc-1 mc_2", "BBMULTICONFIG" : "mc-1 mc_2",
"BB_SIGNATURE_HANDLER" : "basichash", "BB_SIGNATURE_HANDLER" : "TestMulticonfigDepends",
"EXTRA_BBFILES": "${COREBASE}/recipes/fails-mc/*.bb", "EXTRA_BBFILES": "${COREBASE}/recipes/fails-mc/*.bb",
} }
tasks = self.run_bitbakecmd(["bitbake", "mc:mc-1:f1"], tempdir, "", extraenv=extraenv, cleanup=True) tasks = self.run_bitbakecmd(["bitbake", "mc:mc-1:f1"], tempdir, "", extraenv=extraenv, cleanup=True)
@@ -316,13 +314,6 @@ class RunQueueTests(unittest.TestCase):
["mc_2:a1:%s" % t for t in rerun_tasks] ["mc_2:a1:%s" % t for t in rerun_tasks]
self.assertEqual(set(tasks), set(expected)) self.assertEqual(set(tasks), set(expected))
# Check that a multiconfig that doesn't exist rasies a correct error message
error_output = self.run_bitbakecmd(["bitbake", "g1"], tempdir, "", extraenv=extraenv, cleanup=True, allowfailure=True)
self.assertIn("non-existent task", error_output)
# If the word 'Traceback' or 'KeyError' is in the output we've regressed
self.assertNotIn("Traceback", error_output)
self.assertNotIn("KeyError", error_output)
self.shutdown(tempdir) self.shutdown(tempdir)
def test_hashserv_single(self): def test_hashserv_single(self):

View File

@@ -9,9 +9,7 @@
import unittest import unittest
import logging import logging
import bb import bb
import bb.data
import time import time
from contextlib import contextmanager
logger = logging.getLogger('BitBake.TestSiggen') logger = logging.getLogger('BitBake.TestSiggen')
@@ -19,58 +17,75 @@ import bb.siggen
class SiggenTest(unittest.TestCase): class SiggenTest(unittest.TestCase):
def test_build_pnid(self): def test_clean_basepath_simple_target_basepath(self):
tests = { basepath = '/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask'
('', 'helloworld', 'do_sometask') : 'helloworld:do_sometask', expected_cleaned = 'helloworld/helloworld_1.2.3.bb:do_sometask'
('XX', 'helloworld', 'do_sometask') : 'mc:XX:helloworld:do_sometask',
}
for t in tests: actual_cleaned = bb.siggen.clean_basepath(basepath)
self.assertEqual(bb.siggen.build_pnid(*t), tests[t])
def test_get_unihashes_rejects_invalid_hashserv_unihash(self): self.assertEqual(actual_cleaned, expected_cleaned)
class TestClient:
def get_unihash_batch(self, query):
list(query)
return ["${@os.system('true')}"]
class TestSiggen(bb.siggen.SignatureGeneratorUniHashMixIn): def test_clean_basepath_basic_virtual_basepath(self):
def __init__(self): basepath = 'virtual:something:/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask'
self.server = "test-server" expected_cleaned = 'helloworld/helloworld_1.2.3.bb:do_sometask:virtual:something'
self.method = "test-method"
self.extramethod = {}
self.taskhash = {"test.bb:do_compile": "a" * 64}
self.unihash = {}
self.unitaskhashes = {}
self.tidtopn = {}
self.setscenetasks = set()
self.max_parallel = 1
@contextmanager actual_cleaned = bb.siggen.clean_basepath(basepath)
def client(self):
yield TestClient()
siggen = TestSiggen() self.assertEqual(actual_cleaned, expected_cleaned)
with self.assertRaises(bb.BBHandledException): def test_clean_basepath_mc_basepath(self):
siggen.get_unihashes(["test.bb:do_compile"]) basepath = 'mc:somemachine:/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask'
expected_cleaned = 'helloworld/helloworld_1.2.3.bb:do_sometask:mc:somemachine'
self.assertEqual(siggen.unihash, {}) actual_cleaned = bb.siggen.clean_basepath(basepath)
self.assertEqual(siggen.unitaskhashes, {})
def test_report_unihash_reads_bb_unihash_without_expansion(self): self.assertEqual(actual_cleaned, expected_cleaned)
class TestSiggen(bb.siggen.SignatureGeneratorUniHashMixIn):
def __init__(self):
self.setscenetasks = set()
self.taskhash = {"test.bb:do_compile": "b" * 64}
d = bb.data.init() def test_clean_basepath_virtual_long_prefix_basepath(self):
d.setVar("BB_TASKHASH", "a" * 64) basepath = 'virtual:something:A:B:C:/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask'
d.setVar("BB_UNIHASH", "${@d.setVar('EXPANDED_UNIHASH', '1') or 'bad'}") expected_cleaned = 'helloworld/helloworld_1.2.3.bb:do_sometask:virtual:something:A:B:C'
d.setVar("SSTATE_HASHEQUIV_REPORT_TASKDATA", "0")
d.setVar("T", "/tmp")
d.setVar("BB_FILENAME", "test.bb")
TestSiggen().report_unihash(".", "compile", d) actual_cleaned = bb.siggen.clean_basepath(basepath)
self.assertIsNone(d.getVar("EXPANDED_UNIHASH")) self.assertEqual(actual_cleaned, expected_cleaned)
def test_clean_basepath_mc_virtual_basepath(self):
basepath = 'mc:somemachine:virtual:something:/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask'
expected_cleaned = 'helloworld/helloworld_1.2.3.bb:do_sometask:virtual:something:mc:somemachine'
actual_cleaned = bb.siggen.clean_basepath(basepath)
self.assertEqual(actual_cleaned, expected_cleaned)
def test_clean_basepath_mc_virtual_long_prefix_basepath(self):
basepath = 'mc:X:virtual:something:C:B:A:/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask'
expected_cleaned = 'helloworld/helloworld_1.2.3.bb:do_sometask:virtual:something:C:B:A:mc:X'
actual_cleaned = bb.siggen.clean_basepath(basepath)
self.assertEqual(actual_cleaned, expected_cleaned)
# def test_clean_basepath_performance(self):
# input_basepaths = [
# 'mc:X:/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask',
# 'mc:X:virtual:something:C:B:A:/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask',
# 'virtual:something:C:B:A:/different/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask',
# 'virtual:something:A:/full/path/to/poky/meta/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask',
# '/this/is/most/common/input/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask',
# '/and/should/be/tested/with/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask',
# '/more/weight/recipes-whatever/helloworld/helloworld_1.2.3.bb:do_sometask',
# ]
# time_start = time.time()
# i = 2000000
# while i >= 0:
# for basepath in input_basepaths:
# bb.siggen.clean_basepath(basepath)
# i -= 1
# elapsed = time.time() - time_start
# print('{} ({}s)'.format(self.id(), round(elapsed, 3)))
# self.assertTrue(False)

View File

@@ -3,7 +3,7 @@
# #
import http.server import http.server
from bb import multiprocessing import multiprocessing
import os import os
import traceback import traceback
import signal import signal

View File

@@ -10,7 +10,6 @@
import logging import logging
import os import os
import sys import sys
import time
import atexit import atexit
import re import re
from collections import OrderedDict, defaultdict from collections import OrderedDict, defaultdict
@@ -188,19 +187,11 @@ class TinfoilCookerAdapter:
self._cache[name] = attrvalue self._cache[name] = attrvalue
return attrvalue return attrvalue
class TinfoilSkiplistByMcAdapter:
def __init__(self, tinfoil):
self.tinfoil = tinfoil
def __getitem__(self, mc):
return self.tinfoil.get_skipped_recipes(mc)
def __init__(self, tinfoil): def __init__(self, tinfoil):
self.tinfoil = tinfoil self.tinfoil = tinfoil
self.multiconfigs = [''] + (tinfoil.config_data.getVar('BBMULTICONFIG') or '').split() self.multiconfigs = [''] + (tinfoil.config_data.getVar('BBMULTICONFIG') or '').split()
self.collections = {} self.collections = {}
self.recipecaches = {} self.recipecaches = {}
self.skiplist_by_mc = self.TinfoilSkiplistByMcAdapter(tinfoil)
for mc in self.multiconfigs: for mc in self.multiconfigs:
self.collections[mc] = self.TinfoilCookerCollectionAdapter(tinfoil, mc) self.collections[mc] = self.TinfoilCookerCollectionAdapter(tinfoil, mc)
self.recipecaches[mc] = self.TinfoilRecipeCacheAdapter(tinfoil, mc) self.recipecaches[mc] = self.TinfoilRecipeCacheAdapter(tinfoil, mc)
@@ -209,6 +200,8 @@ class TinfoilCookerAdapter:
# Grab these only when they are requested since they aren't always used # Grab these only when they are requested since they aren't always used
if name in self._cache: if name in self._cache:
return self._cache[name] return self._cache[name]
elif name == 'skiplist':
attrvalue = self.tinfoil.get_skipped_recipes()
elif name == 'bbfile_config_priorities': elif name == 'bbfile_config_priorities':
ret = self.tinfoil.run_command('getLayerPriorities') ret = self.tinfoil.run_command('getLayerPriorities')
bbfile_config_priorities = [] bbfile_config_priorities = []
@@ -331,11 +324,11 @@ class Tinfoil:
self.recipes_parsed = False self.recipes_parsed = False
self.quiet = 0 self.quiet = 0
self.oldhandlers = self.logger.handlers[:] self.oldhandlers = self.logger.handlers[:]
self.localhandlers = []
if setup_logging: if setup_logging:
# This is the *client-side* logger, nothing to do with # This is the *client-side* logger, nothing to do with
# logging messages from the server # logging messages from the server
bb.msg.logger_create('BitBake', output) bb.msg.logger_create('BitBake', output)
self.localhandlers = []
for handler in self.logger.handlers: for handler in self.logger.handlers:
if handler not in self.oldhandlers: if handler not in self.oldhandlers:
self.localhandlers.append(handler) self.localhandlers.append(handler)
@@ -455,12 +448,6 @@ class Tinfoil:
self.run_actions(config_params) self.run_actions(config_params)
self.recipes_parsed = True self.recipes_parsed = True
def modified_files(self):
"""
Notify the server it needs to revalidate it's caches since the client has modified files
"""
self.run_command("revalidateCaches")
def run_command(self, command, *params, handle_events=True): def run_command(self, command, *params, handle_events=True):
""" """
Run a command on the server (as implemented in bb.command). Run a command on the server (as implemented in bb.command).
@@ -520,12 +507,12 @@ class Tinfoil:
""" """
return defaultdict(list, self.run_command('getOverlayedRecipes', mc)) return defaultdict(list, self.run_command('getOverlayedRecipes', mc))
def get_skipped_recipes(self, mc=''): def get_skipped_recipes(self):
""" """
Find recipes which were skipped (i.e. SkipRecipe was raised Find recipes which were skipped (i.e. SkipRecipe was raised
during parsing). during parsing).
""" """
return OrderedDict(self.run_command('getSkippedRecipes', mc)) return OrderedDict(self.run_command('getSkippedRecipes'))
def get_all_providers(self, mc=''): def get_all_providers(self, mc=''):
return defaultdict(list, self.run_command('allProviders', mc)) return defaultdict(list, self.run_command('allProviders', mc))
@@ -539,7 +526,6 @@ class Tinfoil:
def get_runtime_providers(self, rdep): def get_runtime_providers(self, rdep):
return self.run_command('getRuntimeProviders', rdep) return self.run_command('getRuntimeProviders', rdep)
# TODO: teach this method about mc
def get_recipe_file(self, pn): def get_recipe_file(self, pn):
""" """
Get the file name for the specified recipe/target. Raises Get the file name for the specified recipe/target. Raises
@@ -548,7 +534,6 @@ class Tinfoil:
""" """
best = self.find_best_provider(pn) best = self.find_best_provider(pn)
if not best or (len(best) > 3 and not best[3]): if not best or (len(best) > 3 and not best[3]):
# TODO: pass down mc
skiplist = self.get_skipped_recipes() skiplist = self.get_skipped_recipes()
taskdata = bb.taskdata.TaskData(None, skiplist=skiplist) taskdata = bb.taskdata.TaskData(None, skiplist=skiplist)
skipreasons = taskdata.get_reasons(pn) skipreasons = taskdata.get_reasons(pn)
@@ -744,7 +729,6 @@ class Tinfoil:
ret = self.run_command('buildTargets', targets, task) ret = self.run_command('buildTargets', targets, task)
if handle_events: if handle_events:
lastevent = time.time()
result = False result = False
# Borrowed from knotty, instead somewhat hackily we use the helper # Borrowed from knotty, instead somewhat hackily we use the helper
# as the object to store "shutdown" on # as the object to store "shutdown" on
@@ -757,7 +741,6 @@ class Tinfoil:
try: try:
event = self.wait_event(0.25) event = self.wait_event(0.25)
if event: if event:
lastevent = time.time()
if event_callback and event_callback(event): if event_callback and event_callback(event):
continue continue
if helper.eventHandler(event): if helper.eventHandler(event):
@@ -790,7 +773,7 @@ class Tinfoil:
if isinstance(event, bb.command.CommandCompleted): if isinstance(event, bb.command.CommandCompleted):
result = True result = True
break break
if isinstance(event, (bb.command.CommandFailed, bb.command.CommandExit)): if isinstance(event, bb.command.CommandFailed):
self.logger.error(str(event)) self.logger.error(str(event))
result = False result = False
break break
@@ -802,13 +785,10 @@ class Tinfoil:
self.logger.error(str(event)) self.logger.error(str(event))
result = False result = False
break break
elif helper.shutdown > 1: elif helper.shutdown > 1:
break break
termfilter.updateFooter() termfilter.updateFooter()
if time.time() > (lastevent + (3*60)):
if not self.run_command('ping', handle_events=False):
print("\nUnable to ping server and no events, closing down...\n")
return False
except KeyboardInterrupt: except KeyboardInterrupt:
termfilter.clearFooter() termfilter.clearFooter()
if helper.shutdown == 1: if helper.shutdown == 1:

View File

@@ -45,7 +45,7 @@ from pprint import pformat
import logging import logging
from datetime import datetime, timedelta from datetime import datetime, timedelta
from django.db import transaction from django.db import transaction, connection
# pylint: disable=invalid-name # pylint: disable=invalid-name
@@ -496,7 +496,7 @@ class ORMWrapper(object):
if not parent_path: if not parent_path:
parent_path = "/" parent_path = "/"
parent_obj = self._cached_get(Target_File, target = target_obj, path = parent_path, inodetype = Target_File.ITYPE_DIRECTORY) parent_obj = self._cached_get(Target_File, target = target_obj, path = parent_path, inodetype = Target_File.ITYPE_DIRECTORY)
Target_File.objects.create( tf_obj = Target_File.objects.create(
target = target_obj, target = target_obj,
path = path, path = path,
size = size, size = size,
@@ -561,7 +561,7 @@ class ORMWrapper(object):
parent_obj = Target_File.objects.get(target = target_obj, path = parent_path, inodetype = Target_File.ITYPE_DIRECTORY) parent_obj = Target_File.objects.get(target = target_obj, path = parent_path, inodetype = Target_File.ITYPE_DIRECTORY)
Target_File.objects.create( tf_obj = Target_File.objects.create(
target = target_obj, target = target_obj,
path = path, path = path,
size = size, size = size,
@@ -1062,6 +1062,27 @@ class BuildInfoHelper(object):
return recipe_info return recipe_info
def _get_path_information(self, task_object):
self._ensure_build()
assert isinstance(task_object, Task)
build_stats_format = "{tmpdir}/buildstats/{buildname}/{package}/"
build_stats_path = []
for t in self.internal_state['targets']:
buildname = self.internal_state['build'].build_name
pe, pv = task_object.recipe.version.split(":",1)
if pe:
package = task_object.recipe.name + "-" + pe + "_" + pv
else:
package = task_object.recipe.name + "-" + pv
build_stats_path.append(build_stats_format.format(tmpdir=self.tmp_dir,
buildname=buildname,
package=package))
return build_stats_path
################################ ################################
## external available methods to store information ## external available methods to store information
@@ -1746,6 +1767,7 @@ class BuildInfoHelper(object):
buildname = self.server.runCommand(['getVariable', 'BUILDNAME'])[0] buildname = self.server.runCommand(['getVariable', 'BUILDNAME'])[0]
machine = self.server.runCommand(['getVariable', 'MACHINE'])[0] machine = self.server.runCommand(['getVariable', 'MACHINE'])[0]
image_name = self.server.runCommand(['getVariable', 'IMAGE_NAME'])[0]
# location of the manifest files for this build; # location of the manifest files for this build;
# note that this file is only produced if an image is produced # note that this file is only produced if an image is produced
@@ -1766,18 +1788,6 @@ class BuildInfoHelper(object):
# filter out anything which isn't an image target # filter out anything which isn't an image target
image_targets = [target for target in targets if target.is_image] image_targets = [target for target in targets if target.is_image]
if len(image_targets) > 0:
#if there are image targets retrieve image_name
image_name = self.server.runCommand(['getVariable', 'IMAGE_NAME'])[0]
if not image_name:
#When build target is an image and image_name is not found as an environment variable
logger.info("IMAGE_NAME not found, extracting from bitbake command")
cmd = self.server.runCommand(['getVariable','BB_CMDLINE'])[0]
#filter out tokens that are command line options
cmd = [token for token in cmd if not token.startswith('-')]
image_name = cmd[1].split(':', 1)[0] # remove everything after : in image name
logger.info("IMAGE_NAME found as : %s " % image_name)
for image_target in image_targets: for image_target in image_targets:
# this is set to True if we find at least one file relating to # this is set to True if we find at least one file relating to
# this target; if this remains False after the scan, we copy the # this target; if this remains False after the scan, we copy the

Some files were not shown because too many files have changed in this diff Show More