Skip to contentSkip to conversation

bitbake-layers: ensure tinfoil.shutdown() gets executed when tinfoil.prepare() fails

PATCH In review Alexander Kanavin 3 participants 13 messages Nov 18, 2024 – Dec 5, 2024

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/4 bitbake-layers: ensure tinfoil.shutdown() gets executed when tinfoil.prepare() fails

From: Alexander Kanavin <[email protected]>

https://git.yoctoproject.org/poky/commit/bitbake/bin/bitbake-layers?id=f6de2b033d32c0f92f19f5a4a8c4c8874a00a8f7
erroneously moved tinfoil.prepare() out of try..finally block, where 'finally' contains a tinfoil.shutdown() call.

Without the shutdown, if there is an error in tinfoil.prepare() (such as parsing errors), the tool locks up, as seen here:
https://valkyrie.yoctoproject.org/#/builders/71/builds/431

---
 bin/bitbake-layers | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
bin/bitbake-layers +7 -7
index aebb5100c2c..613e675cb0d 100755
@@ -59,13 +59,13 @@ def main():
     plugins = []
     tinfoil = bb.tinfoil.Tinfoil(tracking=True)
     tinfoil.logger.setLevel(logger.getEffectiveLevel())
-    if global_args.force > 1:
-        bbpaths = []
-    else:
-        tinfoil.prepare(True)
-        bbpaths = tinfoil.config_data.getVar('BBPATH').split(':')
-    
-    try: 
+    try:
+        if global_args.force > 1:
+            bbpaths = []
+        else:
+            tinfoil.prepare(True)
+            bbpaths = tinfoil.config_data.getVar('BBPATH').split(':')
+
         for path in ([topdir] + bbpaths):
             pluginpath = os.path.join(path, 'lib', 'bblayers')
             bb.utils.load_plugins(logger, plugins, pluginpath)
Signature · 1 line
2.39.5
#1 lore raw

PATCH v3 2/4 parse/ConfHandler: allow / in variable flags

From: Alexander Kanavin <[email protected]>

This is beneficial for config fragments, as their names are specified via flags, and those names can include slashes:

BB_CONF_FRAGMENT_SUMMARY[init/systemd] = "This fragment enables systemd as an init manager"

---
 lib/bb/parse/parse_py/ConfHandler.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/bb/parse/parse_py/ConfHandler.py +1 -1
index 7826dee7d3d..27665443dd4 100644
@@ -21,7 +21,7 @@ __config_regexp__  = re.compile( r"""
     ^
     (?P<exp>export\s+)?
     (?P<var>[a-zA-Z0-9\-_+.${}/~:]+?)
-    (\[(?P<flag>[a-zA-Z0-9\-_+.][a-zA-Z0-9\-_+.@]*)\])?
+    (\[(?P<flag>[a-zA-Z0-9\-_+.][a-zA-Z0-9\-_+.@/]*)\])?
 
     \s* (
         (?P<colon>:=) |
Signature · 1 line
2.39.5
#2 lore raw

PATCH v3 3/4 parse: add support for 'addfragments' directive

In reply to Alexander Kanavin

From: Alexander Kanavin <[email protected]>

It takes two parameters:
- location prefix for fragments
- name of variable that holds the list of enabled fragments, each of them prefixed by layer id

Implementation of this directive essentially expands the fragment list obtained from the variable into absolute fragment paths and hands them to the implementation of 'require'.

---
 lib/bb/parse/ast.py                  | 33 ++++++++++++++++++++++++++++
 lib/bb/parse/parse_py/ConfHandler.py |  6 +++++
 2 files changed, 39 insertions(+)
lib/bb/parse/ast.py +33 -0
index 001ba8d289a..d3b7fef9895 100644
@@ -326,6 +326,34 @@ class InheritDeferredNode(AstNode):
         inherits.append(self.inherit)
         data.setVar('__BBDEFINHERITS', inherits)
 
+class AddFragmentsNode(AstNode):
+    def __init__(self, filename, lineno, fragments_path_prefix, fragments_variable):
+        AstNode.__init__(self, filename, lineno)
+        self.path = fragments_path_prefix
+        self.variable = fragments_variable
+
+    def eval(self, data):
+        def find_fragment(layers, layerid, full_fragment_name):
+           for layerpath in layers.split():
+               candidate_fragment_path = os.path.join(layerpath, full_fragment_name)
+               if os.path.exists(candidate_fragment_path) and bb.utils.get_file_layer(candidate_fragment_path, data) == layerid:
+                   return candidate_fragment_path
+           return None
+
+        fragments = data.getVar(self.variable)
+        layers = data.getVar('BBLAYERS')
+
+        if not fragments:
+            return
+        for f in fragments.split():
+            layerid, fragment_name = f.split('/', 1)
+            full_fragment_name = data.expand("{}/{}.conf".format(self.path, fragment_name))
+            fragment_path = find_fragment(layers, layerid, full_fragment_name)
+            if fragment_path:
+                bb.parse.ConfHandler.include(self.filename, fragment_path, self.lineno, data, "include fragment")
+            else:
+                bb.error("Could not find fragment {} in enabled layers: {}".format(f, layers))
+
 def handleInclude(statements, filename, lineno, m, force):
     statements.append(IncludeNode(filename, lineno, m.group(1), force))
 
@@ -370,6 +398,11 @@ def handleInheritDeferred(statements, filename, lineno, m):
     classes = m.group(1)
     statements.append(InheritDeferredNode(filename, lineno, classes))
 
+def handleAddFragments(statements, filename, lineno, m):
+    fragments_path_prefix = m.group(1)
+    fragments_variable = m.group(2)
+    statements.append(AddFragmentsNode(filename, lineno, fragments_path_prefix, fragments_variable))
+
 def runAnonFuncs(d):
     code = []
     for funcname in d.getVar("__BBANONFUNCS", False) or []:
lib/bb/parse/parse_py/ConfHandler.py +6 -0
index 27665443dd4..35321dacfe1 100644
@@ -47,6 +47,7 @@ __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\-_+.][a-zA-Z0-9\-_+.@]+)\]$" )
 __addpylib_regexp__      = re.compile(r"addpylib\s+(.+)\s+(.+)" )
+__addfragments_regexp__  = re.compile(r"addfragments\s+(.+)\s+(.+)" )
 
 def init(data):
     return
@@ -197,6 +198,11 @@ def feeder(lineno, s, fn, statements, baseconfig=False, conffile=True):
         ast.handlePyLib(statements, fn, lineno, m)
         return
 
+    m = __addfragments_regexp__.match(s)
+    if m:
+        ast.handleAddFragments(statements, fn, lineno, m)
+        return
+
     raise ParseError("unparsed line: '%s'" % s, fn, lineno);
 
 # Add us to the handlers list
Signature · 1 line
2.39.5
#3 lore raw

Re: [bitbake-devel] [PATCH v3 3/4] parse: add support for 'addfragments' directive

Hi Alex,

Thanks for working on this. It is close but there is one small issue needing to be resolved below.

Quoted 24 lines · Alexander Kanavin via lists.openembedded.org

From: Alexander Kanavin <[email protected]>

It takes two parameters:
- location prefix for fragments
- name of variable that holds the list of enabled fragments, each of them prefixed by layer id

Implementation of this directive essentially expands the fragment list obtained from the variable into absolute fragment paths and hands them to the implementation of 'require'.

---
 lib/bb/parse/ast.py                  | 33 ++++++++++++++++++++++++++++ lib/bb/parse/parse_py/ConfHandler.py |  6 +++++

 2 files changed, 39 insertions(+)
lib/bb/parse/ast.py +0 -0
index 001ba8d289a..d3b7fef9895 100644
@@ -326,6 +326,34 @@ class InheritDeferredNode(AstNode):
          inherits.append(self.inherit)
          data.setVar('__BBDEFINHERITS', inherits)
Quoted 6 lines


+class AddFragmentsNode(AstNode):
+    def __init__(self, filename, lineno, fragments_path_prefix, fragments_variable):
+        AstNode.__init__(self, filename, lineno)
+        self.path = fragments_path_prefix
+        self.variable = fragments_variable

"path" in bitbake context becomes easily confusing. I think I'd prefer something like frag_pathprefix or something which makes it clear both that it isn't a full path and what kind of path it is.

Quoted 13 lines
lib/bb/parse/ast.py +13 -0
+
+    def eval(self, data):
+        def find_fragment(layers, layerid, full_fragment_name):
+           for layerpath in layers.split():
+               candidate_fragment_path = os.path.join(layerpath, full_fragment_name)
+               if os.path.exists(candidate_fragment_path) and bb.utils.get_file_layer(candidate_fragment_path, data) == layerid:
+                   return candidate_fragment_path
+           return None
+
+        fragments = data.getVar(self.variable)
+        layers = data.getVar('BBLAYERS')
+
+        if not fragments:

lib/bb/parse/ast.py class InheritDeferredNode(AstNode): · line 356

Quoted 10 lines
lib/bb/parse/ast.py +10 -0
+            return
+        for f in fragments.split():
+            layerid, fragment_name = f.split('/', 1)
+            full_fragment_name = data.expand("{}/{}.conf".format(self.path, fragment_name))
+            fragment_path = find_fragment(layers, layerid, full_fragment_name)
+            if fragment_path:
+                bb.parse.ConfHandler.include(self.filename, fragment_path, self.lineno, data, "include fragment")
+            else:
+                bb.error("Could not find fragment {} in enabled layers: {}".format(f, layers))
+

Whilst checking if the file exists and only including if present sounds like the right thing to do, it needs to be a bit more complex. The issue is that bitbake needs to track both the files it accesses but also the files it looked for but didn't find. If those files are then created, we need to reparse.

There are two ways to handle this, one is to trust that the bb.parse.ConfHandler code does already know how to do this and just call unconditionally until it matches a file. The apis might not let you easily know if it found a file.

The other way is to call bb.parse.mark_dependency() and just mark the accessed files that way.

Otherwise I think this looks good to me, thanks!

Cheers,

Richard

#4 lore raw

Re: [bitbake-devel] [PATCH v3 3/4] parse: add support for 'addfragments' directive

Quoted 6 lines · Richard Purdie

Whilst checking if the file exists and only including if present sounds like the right thing to do, it needs to be a bit more complex. The issue is that bitbake needs to track both the files it accesses but also the files it looked for but didn't find. If those files are then created, we need to reparse.

Quoted 7 lines

There are two ways to handle this, one is to trust that the bb.parse.ConfHandler code does already know how to do this and just call unconditionally until it matches a file. The apis might not let you easily know if it found a file.

The other way is to call bb.parse.mark_dependency() and just mark the accessed files that way.

After reading through usage of mark_dependency() in existing code, I need a bit more clarification there, because I'm not 100% sure you are correct, or alternatively I don't have complete understanding of how things work :)

The original 'include some/file' directive iterates over BBPATH, and appends some/file to each of those, regardless of whether they exist, and marks them as dependency in case they appear later. This is fine.

The fragments code takes a fragment name (which has a layer id as prefix), unambiguously converts that to a full file path that is checked for existence and hands it over to ConfHandler.include() (which calls mark_dependency() internally). If such conversion to full path fails, it calls bb.error, which immediately fails the whole thing. Would we want to still call mark_dependency() on a full path that does not exist in a case of such failure, and why? If the error is addressed and file is created, then bitbake will parse it anyway, no?

Alex

#5 lore raw

Re: [bitbake-devel] [PATCH v3 3/4] parse: add support for 'addfragments' directive

Quoted 25 lines · Alexander Kanavin
Quoted 6 lines · Richard Purdie

Whilst checking if the file exists and only including if present sounds like the right thing to do, it needs to be a bit more complex. The issue is that bitbake needs to track both the files it accesses but also the files it looked for but didn't find. If those files are then created, we need to reparse.

Quoted 7 lines

There are two ways to handle this, one is to trust that the bb.parse.ConfHandler code does already know how to do this and just call unconditionally until it matches a file. The apis might not let you easily know if it found a file.

The other way is to call bb.parse.mark_dependency() and just mark the accessed files that way.

After reading through usage of mark_dependency() in existing code, I need a bit more clarification there, because I'm not 100% sure you are correct, or alternatively I don't have complete understanding of how things work :)

The original 'include some/file' directive iterates over BBPATH, and appends some/file to each of those, regardless of whether they exist, and marks them as dependency in case they appear later. This is fine.

Quoted 9 lines

The fragments code takes a fragment name (which has a layer id as prefix), unambiguously converts that to a full file path that is checked for existence and hands it over to ConfHandler.include() (which calls mark_dependency() internally). If such conversion to full path fails, it calls bb.error, which immediately fails the whole thing. Would we want to still call mark_dependency() on a full path that does not exist in a case of such failure, and why? If the error is addressed and file is created, then bitbake will parse it anyway, no?

You're right, the loop in the fragment code is a little subtle. The code in question:

+ def find_fragment(layers, layerid, full_fragment_name):
+ for layerpath in layers.split():
+ candidate_fragment_path = os.path.join(layerpath, full_fragment_name)
+ if os.path.exists(candidate_fragment_path) and bb.utils.get_file_layer(candidate_fragment_path, data) == layerid:
+ return candidate_fragment_path
+ return None

looks like it loops checking for file existence but it is guarded by the layername matching check too. It shouldn't be possible for two layers to have the same layer name. I'm not sure how rigorous our checks are for that.

For some reason I was thinking that fragments with and without a layer prefix were possible but that isn't the case.

The patch is therefore probably ok but I am a bit worried about this potentially breaking in the future if someone else (or I!) miss the subtly in the code.

Cheers,

Richard

#6 lore raw

Re: [bitbake-devel] [PATCH v3 3/4] parse: add support for 'addfragments' directive

Quoted 3 lines · Richard Purdie

The patch is therefore probably ok but I am a bit worried about this potentially breaking in the future if someone else (or I!) miss the subtly in the code.

I still need to improve variable naming. I'll do that and send v2, but I'm not sure at the moment what can be done about this subtlety.

Alex

#7 lore raw

Re: [bitbake-devel] [PATCH v3 3/4] parse: add support for 'addfragments' directive

Quoted 10 lines · Alexander Kanavin
Quoted 4 lines · Richard Purdie

The patch is therefore probably ok but I am a bit worried about this
potentially breaking in the future if someone else (or I!) miss the subtly in the code.

I still need to improve variable naming. I'll do that and send v2, but I'm not sure at the moment what can be done about this subtlety.

Probably a comment:

# No need to use mark_dependency since we would only match a fragment

# from a specific layer and there can only be a single layer with a 
# given namespace.

Cheers,

Richard

#8 lore raw

Re: [bitbake-devel] [PATCH v3 3/4] parse: add support for 'addfragments' directive

Quoted 8 lines · Richard Purdie
Quoted 2 lines

I still need to improve variable naming. I'll do that and send v2, but I'm not sure at the moment what can be done about this subtlety.

Probably a comment:

# No need to use mark_dependency since we would only match a fragment

# from a specific layer and there can only be a single layer with a
# given namespace.

Variables renamed in v4. This comment added in v5 :)

Alex

#9 lore raw

PATCH v3 4/4 bitbake-config-build: add an alias to bitbake-layers intended for managing specific local configs

In reply to Alexander Kanavin

From: Alexander Kanavin <[email protected]>

This was prompted by adding support for config fragments (in a separate commit to oe-core); after some deliberation I concluded there should be a separate tool, as bitbake-layers is already somewhat over-stuffed, and this will give space for more build/conf/* operations in the future that anyone can come up with (such as tweaking site-specific items in site.conf etc.)

The alias completely reuses existing code via symlink and the difference is in where it looks for plugins.

---
 bin/bitbake-config-build | 1 +
 bin/bitbake-layers       | 6 ++++--
 2 files changed, 5 insertions(+), 2 deletions(-)
 create mode 120000 bitbake/bin/bitbake-config-build
bin/bitbake-config-build new file +1 -0
new file mode 120000
index 00000000000..11e6df80c4b
@@ -0,0 +1 @@
+bitbake-layers
\ No newline at end of file
bin/bitbake-layers +4 -2
index 613e675cb0d..f93d913a1da 100755
@@ -18,13 +18,14 @@ import warnings
 warnings.simplefilter("default")
 
 bindir = os.path.dirname(__file__)
+toolname = os.path.basename(__file__).split(".")[0]
 topdir = os.path.dirname(bindir)
 sys.path[0:0] = [os.path.join(topdir, 'lib')]
 
 import bb.tinfoil
 import bb.msg
 
-logger = bb.msg.logger_create('bitbake-layers', sys.stdout)
+logger = bb.msg.logger_create(toolname, sys.stdout)
 
 def main():
     parser = argparse.ArgumentParser(
@@ -67,7 +68,8 @@ def main():
             bbpaths = tinfoil.config_data.getVar('BBPATH').split(':')
 
         for path in ([topdir] + bbpaths):
-            pluginpath = os.path.join(path, 'lib', 'bblayers')
+            pluginbasepath = {"bitbake-layers":'bblayers', 'bitbake-config-build':'bbconfigbuild'}[toolname]
+            pluginpath = os.path.join(path, 'lib', pluginbasepath)
             bb.utils.load_plugins(logger, plugins, pluginpath)
 
         registered = False
Signature · 1 line
2.39.5
#10 lore raw
In reply to Alexander Kanavin

Hi Alex,

Quoted 11 lines

https://git.yocto/
project.org%2Fpoky%2Fcommit%2Fbitbake%2Fbin%2Fbitbake- layers%3Fid%3Df6de2b033d32c0f92f19f5a4a8c4c8874a00a8f7&data=05%7C02 %7Cchris.laplante%40agilent.com%7C97e94e28efaa4067611208dd07edc001%7 Ca9c0bc098b46420693512ba12fb4a5c0%7C0%7C0%7C638675439912466855% 7CUnknown%7CTWFpbGZsb3d8eyJFbXB0eU1hcGkiOnRydWUsIlYiOiIwLjAuMDA wMCIsIlAiOiJXaW4zMiIsIkFOIjoiTWFpbCIsIldUIjoyfQ%3D%3D%7C0%7C%7C%7C &sdata=Y05hVrsW%2Fo8KxXtUXrC62sAoPmA74U82IWtjyIGqxXo%3D&reserved= 0
erroneously moved tinfoil.prepare() out of try..finally block, where 'finally' contains a tinfoil.shutdown() call.

Why not just use a 'with' statement here?

Thanks,
Chris

#11 lore raw
Quoted 4 lines · On Mon, 25 Nov 2024 at 21:50, [email protected]…
Quoted 2 lines

erroneously moved tinfoil.prepare() out of try..finally block, where 'finally' contains a tinfoil.shutdown() call.

Why not just use a 'with' statement here?

Perhaps; can you send a followup? This already merged.

Alex

#12 lore raw
Quoted 5 lines
Quoted 1 line

Why not just use a 'with' statement here?

Perhaps; can you send a followup? This already merged.

Alex

Sure thing :).

Thanks,
Chris