parse: Add support for addpylib conf file directive
RFC PATCH 1/2 parse: Add support for addpylib conf file directive
For many years OE-Core has injected it's own python modules into the python namespace using an immediate expansion of a variable in base.bbclass.
We really need this to become a first class citizen of the langauge, this new addpylib directive allows that. Usage is of the form:
addpylib <directory> <namespace>
The namespace is imported and if there is an attribute BBIMPORT, that list of names is iterated and imported too.
This mirrors what OE-Core has done for a long time with one difference in implmentation, sys.path is only appended to. This means later imported namespaces can't overwrite an earlier one and can't overwrite the main python module space. In practice we've never done that and it isn't something we should encourage or support.
--- lib/bb/parse/ast.py | 22 ++++++++++++++++++++++ lib/bb/parse/parse_py/ConfHandler.py | 6 ++++++ 2 files changed, 28 insertions(+)
lib/bb/parse/ast.py +22 -0
@@ -9,6 +9,7 @@ # SPDX-License-Identifier: GPL-2.0-only # +import sys import bb from bb import methodpool from bb.parse import logger
@@ -269,6 +270,24 @@ class BBHandlerNode(AstNode): data.setVarFlag(h, "handler", 1) 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): + 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[i.split(".", 1)[0]] = __import__(i) + except AttributeError as e: + bb.error("Error importing OE modules: %s" % str(e)) + class InheritNode(AstNode): def __init__(self, filename, lineno, classes): AstNode.__init__(self, filename, lineno)
@@ -320,6 +339,9 @@ def handleDelTask(statements, filename, lineno, m): def handleBBHandlers(statements, filename, lineno, m): 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): classes = m.group(1) statements.append(InheritNode(filename, lineno, classes))
lib/bb/parse/parse_py/ConfHandler.py +6 -0
@@ -46,6 +46,7 @@ __require_regexp__ = re.compile( r"require\s+(.+)" ) __export_regexp__ = re.compile( r"export\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\-_+.]+)\]$" ) +__addpylib_regexp__ = re.compile(r"addpylib\s+(.+)\s+(.+)" ) def init(data): return
@@ -189,6 +190,11 @@ def feeder(lineno, s, fn, statements): ast.handleUnsetFlag(statements, fn, lineno, m) return + m = __addpylib_regexp__.match(s) + if m: + ast.handlePyLib(statements, fn, lineno, m) + return + raise ParseError("unparsed line: '%s'" % s, fn, lineno); # Add us to the handlers list
Signature · 1 line
2.34.1
RFC PATCH 2/2 ast/data: Add dependencies from python module functions
Moving code into python modules is a very effective way to reduce parsing time and overhead in recipes. The downside has always been that any dependency information on which variables those functions access is lost and the hashes can therefore become less reliable.
This patch adds parsing of the imported module functions and that dependency information is them injected back into the hash dependency information.
Intermodule function references are resolved to the full function call names in our module namespace to ensure interfunction dependencies are correctly handled too.
--- lib/bb/codeparser.py | 2 ++ lib/bb/data.py | 40 +++++++++++++++++++++++----------------- lib/bb/parse/ast.py | 40 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 64 insertions(+), 18 deletions(-)
lib/bb/codeparser.py +2 -0
@@ -36,6 +36,8 @@ from bb.cache import MultiProcessCache logger = logging.getLogger('BitBake.CodeParser') +modulecode_deps = {} + def bbhash(s): return hashlib.sha256(s.encode("utf-8")).hexdigest()
lib/bb/data.py +23 -17
@@ -261,22 +261,9 @@ def emit_func_python(func, o=sys.__stdout__, d = init()): newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split()) newdeps -= seen -def build_dependencies(key, keys, shelldeps, varflagsexcl, ignored_vars, d): +def build_dependencies(key, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d): deps = set() try: - 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() - def handle_contains(value, contains, exclusions, d): newvalue = [] if value:
@@ -294,6 +281,24 @@ def build_dependencies(key, keys, shelldeps, varflagsexcl, ignored_vars, d): newvalue.append("\n%s{%s} = Set" % (k, item)) return "".join(newvalue) + if key in mod_funcs: + exclusions = set() + moddep = bb.codeparser.modulecode_deps[key] + value = handle_contains("", moddep[3], exclusions, d) + return frozenset(moddep[0] - 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() + def handle_remove(value, deps, removes, d): for r in sorted(removes): r2 = d.expandWithRefs(r, None)
@@ -367,7 +372,8 @@ def build_dependencies(key, keys, shelldeps, varflagsexcl, ignored_vars, d): def generate_dependencies(d, ignored_vars): - keys = set(key for key in d if not key.startswith("__")) + mod_funcs = set(bb.codeparser.modulecode_deps.keys()) + 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)) varflagsexcl = d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS')
@@ -376,7 +382,7 @@ def generate_dependencies(d, ignored_vars): tasklist = d.getVar('__BBTASKS', False) or [] for task in tasklist: - deps[task], values[task] = build_dependencies(task, keys, shelldeps, varflagsexcl, ignored_vars, d) + deps[task], values[task] = build_dependencies(task, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d) newdeps = deps[task] seen = set() while newdeps:
@@ -385,7 +391,7 @@ def generate_dependencies(d, ignored_vars): newdeps = set() for dep in nextdeps: if dep not in deps: - deps[dep], values[dep] = build_dependencies(dep, keys, shelldeps, varflagsexcl, ignored_vars, d) + deps[dep], values[dep] = build_dependencies(dep, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d) newdeps |= deps[dep] newdeps -= seen #print "For %s: %s" % (task, str(deps[task]))
lib/bb/parse/ast.py +39 -1
@@ -10,6 +10,7 @@ # import sys +import inspect import bb from bb import methodpool from bb.parse import logger
@@ -284,7 +285,44 @@ class PyLibNode(AstNode): bb.utils._context[self.namespace] = __import__(self.namespace) toimport = getattr(bb.utils._context[self.namespace], "BBIMPORTS", []) for i in toimport: - bb.utils._context[i.split(".", 1)[0]] = __import__(i) + base = i.split(".", 1)[0] + bb.utils._context[base] = __import__(i) + if "." in i: + mod = getattr(bb.utils._context[base], i.split(".", 1)[1]) + funcs = dir(mod) + for f in funcs: + if f.startswith("_"): + continue + fcall = getattr(mod, f) + if not callable(fcall): + continue + src = inspect.getsource(fcall) + name = "%s.%s" % (i, f) + parser = bb.codeparser.PythonParser(name, logger) + parser.parse_python(src, filename=inspect.getfile(fcall), lineno=1) + execs = parser.execs + # Expand internal module exec references + for e in parser.execs: + if e in funcs: + execs.remove(e) + execs.add(i + "." + e) + bb.codeparser.modulecode_deps[name] = [parser.references.copy(), execs, parser.var_execs.copy(), parser.contains.copy()] + #bb.warn("%s: %s\nRefs:%s Execs: %s %s %s" % (name, src, parser.references, parser.execs, parser.var_execs, parser.contains)) + + # Resolve intermodule references now, stack dependencies + found = True + while found: + found = False + funcs = set(bb.codeparser.modulecode_deps.keys()) + for entry in bb.codeparser.modulecode_deps: + for dup in (bb.codeparser.modulecode_deps[entry][1] & funcs): + found = True + bb.codeparser.modulecode_deps[entry][1].remove(dup) + bb.codeparser.modulecode_deps[entry][0] |= bb.codeparser.modulecode_deps[dup][0] + bb.codeparser.modulecode_deps[entry][1] |= bb.codeparser.modulecode_deps[dup][1] + bb.codeparser.modulecode_deps[entry][2] |= bb.codeparser.modulecode_deps[dup][2] + bb.codeparser.modulecode_deps[entry][3] |= bb.codeparser.modulecode_deps[dup][3] + except AttributeError as e: bb.error("Error importing OE modules: %s" % str(e))
Signature · 1 line
2.34.1
Re: [bitbake-devel] [PATCH RFC 2/2] ast/data: Add dependencies from python module functions
Quoted 133 lines · Richard Purdie
Moving code into python modules is a very effective way to reduce parsing time and overhead in recipes. The downside has always been that any dependency information on which variables those functions access is lost and the hashes can therefore become less reliable.
This patch adds parsing of the imported module functions and that dependency information is them injected back into the hash dependency information.
Intermodule function references are resolved to the full function call names in our module namespace to ensure interfunction dependencies are correctly handled too.
Signed-off-by Richard Purdie <[email protected]>--- lib/bb/codeparser.py | 2 ++ lib/bb/data.py | 40 +++++++++++++++++++++++----------------- lib/bb/parse/ast.py | 40 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 64 insertions(+), 18 deletions(-)lib/bb/codeparser.py +2
-0@@ -36,6 +36,8 @@ from bb.cache import MultiProcessCache logger = logging.getLogger('BitBake.CodeParser') +modulecode_deps = {} + def bbhash(s): return hashlib.sha256(s.encode("utf-8")).hexdigest()lib/bb/data.py +23
-17@@ -261,22 +261,9 @@ def emit_func_python(func, o=sys.__stdout__, d = init()): newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split()) newdeps -= seen -def build_dependencies(key, keys, shelldeps, varflagsexcl, ignored_vars, d): +def build_dependencies(key, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d): deps = set() try: - 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() - def handle_contains(value, contains, exclusions, d): newvalue = [] if value:@@ -294,6 +281,24 @@ def build_dependencies(key, keys, shelldeps, varflagsexcl, ignored_vars, d): newvalue.append("\n%s{%s} = Set" % (k, item)) return "".join(newvalue) + if key in mod_funcs: + exclusions = set() + moddep = bb.codeparser.modulecode_deps[key] + value = handle_contains("", moddep[3], exclusions, d) + return frozenset(moddep[0] - 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() + def handle_remove(value, deps, removes, d): for r in sorted(removes): r2 = d.expandWithRefs(r, None)@@ -367,7 +372,8 @@ def build_dependencies(key, keys, shelldeps, varflagsexcl, ignored_vars, d): def generate_dependencies(d, ignored_vars): - keys = set(key for key in d if not key.startswith("__")) + mod_funcs = set(bb.codeparser.modulecode_deps.keys()) + 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)) varflagsexcl = d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS')@@ -376,7 +382,7 @@ def generate_dependencies(d, ignored_vars): tasklist = d.getVar('__BBTASKS', False) or [] for task in tasklist: - deps[task], values[task] = build_dependencies(task, keys, shelldeps, varflagsexcl, ignored_vars, d) + deps[task], values[task] = build_dependencies(task, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d) newdeps = deps[task] seen = set() while newdeps:@@ -385,7 +391,7 @@ def generate_dependencies(d, ignored_vars): newdeps = set() for dep in nextdeps: if dep not in deps: - deps[dep], values[dep] = build_dependencies(dep, keys, shelldeps, varflagsexcl, ignored_vars, d) + deps[dep], values[dep] = build_dependencies(dep, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d) newdeps |= deps[dep] newdeps -= seen #print "For %s: %s" % (task, str(deps[task]))lib/bb/parse/ast.py +3
-1@@ -10,6 +10,7 @@ # import sys +import inspect import bb from bb import methodpool from bb.parse import logger@@ -284,7 +285,44 @@ class PyLibNode(AstNode): bb.utils._context[self.namespace] = __import__(self.namespace) toimport = getattr(bb.utils._context[self.namespace], "BBIMPORTS", []) for i in toimport: - bb.utils._context[i.split(".", 1)[0]] = __import__(i) + base = i.split(".", 1)[0] + bb.utils._context[base] = __import__(i)
lib/bb/parse/ast.py class PyLibNode(AstNode): · line 299
Quoted 10 lines
lib/bb/parse/ast.py +10
-0+ if "." in i: + mod = getattr(bb.utils._context[base], i.split(".", 1)[1]) + funcs = dir(mod) + for f in funcs: + if f.startswith("_"): + continue + fcall = getattr(mod, f) + if not callable(fcall): + continue + src = inspect.getsource(fcall)
While the text of a module should always be present, making python go back to it is probably inefficient when it's already gone through the effort of converting it to byte code (I beleive it has to go find the corresponding .py file for the .pyc file it already loaded into memory). Perhaps we can split out the part of PythonParser that deals with the compiled AST to a new function and call that with inspect?
Maybe something like:
bytecode = inspect.getmembers_static(fcall, "__code__")[0][1] parser.parse_python_ast(bytecode)
lib/bb/parse/ast.py class PyLibNode(AstNode): · line 307
Quoted 8 lines
lib/bb/parse/ast.py +8
-0+ name = "%s.%s" % (i, f) + parser = bb.codeparser.PythonParser(name, logger) + parser.parse_python(src, filename=inspect.getfile(fcall), lineno=1) + execs = parser.execs + # Expand internal module exec references + for e in parser.execs: + if e in funcs: + execs.remove(e)
You are modifying parser.execs in place which will ruin your iteration. I think you probably want:
execs = {f"{i}.{e}" if e in funcs else e for e in parser.execs}
Or if you don't want list comprehension:
execs = []
for e in parse.execs:
if e in funcs:
execs.add(f"{i}.{e}") else:
execs.add(e)
Quoted 33 lines
lib/bb/parse/ast.py +18
-1+ execs.add(i + "." + e) + bb.codeparser.modulecode_deps[name] = [parser.references.copy(), execs, parser.var_execs.copy(), parser.contains.copy()] + #bb.warn("%s: %s\nRefs:%s Execs: %s %s %s" % (name, src, parser.references, parser.execs, parser.var_execs, parser.contains)) + + # Resolve intermodule references now, stack dependencies + found = True + while found: + found = False + funcs = set(bb.codeparser.modulecode_deps.keys()) + for entry in bb.codeparser.modulecode_deps: + for dup in (bb.codeparser.modulecode_deps[entry][1] & funcs): + found = True + bb.codeparser.modulecode_deps[entry][1].remove(dup) + bb.codeparser.modulecode_deps[entry][0] |= bb.codeparser.modulecode_deps[dup][0] + bb.codeparser.modulecode_deps[entry][1] |= bb.codeparser.modulecode_deps[dup][1] + bb.codeparser.modulecode_deps[entry][2] |= bb.codeparser.modulecode_deps[dup][2] + bb.codeparser.modulecode_deps[entry][3] |= bb.codeparser.modulecode_deps[dup][3] + except AttributeError as e: bb.error("Error importing OE modules: %s" % str(e)) --2.34.1
-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#14116): https://lists.openembedded.org/g/bitbake-devel/message/14116
Mute This Topic: https://lists.openembedded.org/mt/95297764/3616693
Group Owner: [email protected]
Unsubscribe: https://lists.openembedded.org/g/bitbake-devel/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-
Re: [bitbake-devel] [PATCH RFC 2/2] ast/data: Add dependencies from python module functions
Quoted 37 lines · Joshua Watt
Quoted 17 lines · Richard Purdie
lib/bb/parse/ast.py +3
-1@@ -10,6 +10,7 @@ # import sys +import inspect import bb from bb import methodpool from bb.parse import logger@@ -284,7 +285,44 @@ class PyLibNode(AstNode): bb.utils._context[self.namespace] = __import__(self.namespace) toimport = getattr(bb.utils._context[self.namespace], "BBIMPORTS", []) for i in toimport: - bb.utils._context[i.split(".", 1)[0]] = __import__(i) + base = i.split(".", 1)[0] + bb.utils._context[base] = __import__(i)lib/bb/parse/ast.py class PyLibNode(AstNode): · line 299
Quoted 10 lines
lib/bb/parse/ast.py +10
-0+ if "." in i: + mod = getattr(bb.utils._context[base], i.split(".", 1)[1]) + funcs = dir(mod) + for f in funcs: + if f.startswith("_"): + continue + fcall = getattr(mod, f) + if not callable(fcall): + continue + src = inspect.getsource(fcall)While the text of a module should always be present, making python go back to it is probably inefficient when it's already gone through the effort of converting it to byte code (I beleive it has to go find the corresponding .py file for the .pyc file it already loaded into memory). Perhaps we can split out the part of PythonParser that deals with the compiled AST to a new function and call that with inspect?
Quoted 4 lines
Maybe something like:
bytecode =
inspect.getmembers_static(fcall, "__code__")[0][1]parser.parse_python_ast(bytecode)
Sadly we need the text since PythonParser has it's own optimisations and hash lookups based upon that :/. I agree this is probably not as efficient as it should be though. We also still don't currently get the lineno information we need either.
Quoted 10 lines
lib/bb/parse/ast.py class PyLibNode(AstNode): · line 307
Quoted 9 lines
lib/bb/parse/ast.py +8
-0+ name = "%s.%s" % (i, f) + parser = bb.codeparser.PythonParser(name, logger) + parser.parse_python(src, filename=inspect.getfile(fcall), lineno=1) + execs = parser.execs + # Expand internal module exec references + for e in parser.execs: + if e in funcs: + execs.remove(e)
Quoted 2 lines
You are modifying parser.execs in place which will ruin your iteration.
Well spotted. It was meant to be execs = parser.execs.copy() (see the other copy()'s of the other bits later.
Quoted 4 lines
I think you probably want:
execs = {f"{i}.{e}" if e in funcs else e for e in parser.execs}
Quoted 8 lines
Or if you don't want list comprehension:
execs = []
for e in parse.execs:
if e in funcs:execs.add(f"{i}.{e}")else:
execs.add(e)
Cheers,
Richard