Skip to contentSkip to conversation

server/process: Fix lockfile contents check bug

PATCH In review Richard Purdie 2 participants 8 messages Jan 21, 2023

lore
Share & tools
lore
#0 lore raw

PATCH 1/6 server/process: Fix lockfile contents check bug

We need to check against the first line of the file, fix the typo.

---
 lib/bb/server/process.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/bb/server/process.py +1 -1
index 4bd68b1e7f..01ce916a3d 100644
@@ -376,7 +376,7 @@ class ProcessServer():
                 lock = bb.utils.lockfile(lockfile, shared=False, retry=False, block=False)
                 if not lock:
                     newlockcontents = get_lock_contents(lockfile)
-                    if not newlockcontents.startswith([os.getpid() + "\n", os.getpid() + " "]):
+                    if not newlockcontents[0].startswith([os.getpid() + "\n", os.getpid() + " "]):
                         # A new server was started, the lockfile contents changed, we can exit
                         serverlog("Lockfile now contains different contents, exiting: " + str(newlockcontents))
                         return
Signature · 1 line
2.37.2
#1 lore raw

PATCH 2/6 cooker: Fix siggen recipe cache race issue

We need to reset the cache before the start() call which starts the parsing processs, tweak the code to ensure this is the case.

---
 lib/bb/cooker.py | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
lib/bb/cooker.py +1 -2
index 617d582acc..d15ad2fb2e 100644
@@ -2187,12 +2187,11 @@ class CookerParser(object):
         self.num_processes = min(int(self.cfgdata.getVar("BB_NUMBER_PARSE_THREADS") or
                                  multiprocessing.cpu_count()), self.toparse)
 
+        bb.cache.SiggenRecipeInfo.reset()
         self.start()
         self.haveshutdown = False
         self.syncthread = None
 
-        bb.cache.SiggenRecipeInfo.reset()
-
     def start(self):
         self.results = self.load_cached()
         self.processes = []
Signature · 1 line
2.37.2
#2 lore raw

PATCH 3/6 cache: Only write files if we have data

In reply to Richard Purdie

By writing the cache files only if there is data to write, we can save a bit of time.

---
 lib/bb/cache.py | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
lib/bb/cache.py +15 -3
index ee924b2d2b..c19fe26f1b 100644
@@ -873,6 +873,14 @@ class MultiProcessCache(object):
         if not self.cachefile:
             return
 
+        have_data = False
+        for c in self.cachedata_extras:
+            if c:
+                have_data = True
+                break
+        if not have_data:
+            return
+
         glf = bb.utils.lockfile(self.cachefile + ".lock", shared=True)
 
         i = os.getpid()
@@ -907,6 +915,8 @@ class MultiProcessCache(object):
 
         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) + '-')]:
             f = os.path.join(os.path.dirname(self.cachefile), f)
             try:
@@ -921,12 +931,14 @@ class MultiProcessCache(object):
                 os.unlink(f)
                 continue
 
+            have_data = True
             self.merge_data(extradata, data)
             os.unlink(f)
 
-        with open(self.cachefile, "wb") as f:
-            p = pickle.Pickler(f, -1)
-            p.dump([data, self.__class__.CACHE_VERSION])
+        if have_data:
+            with open(self.cachefile, "wb") as f:
+                p = pickle.Pickler(f, -1)
+                p.dump([data, self.__class__.CACHE_VERSION])
 
         bb.utils.unlockfile(glf)
 
Signature · 1 line
2.37.2
#3 lore raw

Re: [bitbake-devel] [PATCH 3/6] cache: Only write files if we have data

Hmm have_data = any(self.cachedata_extras) perhaps?

Sent from my iPhone

Quoted 68 lines · Richard Purdie

By writing the cache files only if there is data to write, we can save a bit of time.

---
lib/bb/cache.py | 18 +++++++++++++++---

1 file changed, 15 insertions(+), 3 deletions(-)
lib/bb/cache.py +15 -3
index ee924b2d2b..c19fe26f1b 100644
@@ -873,6 +873,14 @@ class MultiProcessCache(object):
        if not self.cachefile:
            return
 
+        have_data = False
+        for c in self.cachedata_extras:
+            if c:
+                have_data = True
+                break
+        if not have_data:
+            return
+
        glf = bb.utils.lockfile(self.cachefile + ".lock", shared=True)
 
        i = os.getpid()
@@ -907,6 +915,8 @@ class MultiProcessCache(object):
 
        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) + '-')]:
            f = os.path.join(os.path.dirname(self.cachefile), f)
            try:
@@ -921,12 +931,14 @@ class MultiProcessCache(object):
                os.unlink(f)
                continue
 
+            have_data = True
            self.merge_data(extradata, data)
            os.unlink(f)
 
-        with open(self.cachefile, "wb") as f:
-            p = pickle.Pickler(f, -1)
-            p.dump([data, self.__class__.CACHE_VERSION])
+        if have_data:
+            with open(self.cachefile, "wb") as f:
+                p = pickle.Pickler(f, -1)
+                p.dump([data, self.__class__.CACHE_VERSION])
 
        bb.utils.unlockfile(glf)
 
Signature · 10 lines
2.37.2


-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#14331): https://lists.openembedded.org/g/bitbake-devel/message/14331
Mute This Topic: https://lists.openembedded.org/mt/96443149/3617123
Group Owner: [email protected]
Unsubscribe: https://lists.openembedded.org/g/bitbake-devel/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-
#4 lore raw

Re: [bitbake-devel] [PATCH 3/6] cache: Only write files if we have data

Quoted 1 line · Christopher Larson

Hmm have_data = any(self.cachedata_extras) perhaps?

That looks a lot neater! :)

Cheers,

Richard

#5 lore raw

PATCH 4/6 cooker: Fix parsing race around cache handling

In reply to Richard Purdie

When draining the result queue from the parsing processes, cache objects can be created even if they are then immediately destroyed. The reset in the sync code needs to happen after any objects have been created.

Change the ordering to fix this. This ordering has caused various cache errors, particularly when interrupting parsing with Ctrl+C.

---
 lib/bb/cooker.py | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
lib/bb/cooker.py +8 -8
index d15ad2fb2e..527f6a0421 100644
@@ -2233,6 +2233,14 @@ class CookerParser(object):
         else:
             bb.error("Parsing halted due to errors, see error messages above")
 
+        # Cleanup the queue before call process.join(), otherwise there might be
+        # deadlocks.
+        while True:
+            try:
+               self.result_queue.get(timeout=0.25)
+            except queue.Empty:
+                break
+
         def sync_caches():
             for c in self.bb_caches.values():
                 bb.cache.SiggenRecipeInfo.reset()
@@ -2243,14 +2251,6 @@ class CookerParser(object):
 
         self.parser_quit.set()
 
-        # Cleanup the queue before call process.join(), otherwise there might be
-        # deadlocks.
-        while True:
-            try:
-               self.result_queue.get(timeout=0.25)
-            except queue.Empty:
-                break
-
         for process in self.processes:
             process.join(0.5)
 
Signature · 1 line
2.37.2
#6 lore raw

PATCH 5/6 data: Add sup0port for new BB_HASH_CODEPARSER_VALS for cache optimisation

In reply to Richard Purdie

Currently the codeparser cache ends up being extended for every parse run since there are values in the functions such as the result of os.getpid() from LOGFIFO in OE-Core.

Digging into that issue, there are also lots of similar but different functions being parsed where the change might just be a path to WORKDIR, a change in PN or PV or something like DATE/TIME.

There is no reason we have to use these changing values when computing the dependenies of the functions. Even with a small tweak like:

BB_HASH_CODEPARSER_VALS = "LOGFIFO=/ T=/ WORKDIR=/ DATE=1234 TIME=1234 PV=0.0-1 PN=nopn"

the cache is reduced from ~4.6MB, increasing by ~300kb for every parse run to around 1.3MB and remaining static for oe-core and meta-oe. In my local build, admittedly heavily experimented with, the cache had grown to 120MB.

The benefits of doing this are:

* faster load time for bitbake since the cache is smaller to read from disk and load into memory
* being able to skip saving the cache upon shutdown
* lower memory footprint for bitbake
* faster codeparser data lookups (since there is less data to search)

We only use these special values when passing code fragments to the codeparser to parse so the real variable values should otherwise be used in the hash data.

The overall effect of this change, combined with others to avoid saving unchanged cache files can be ~2s on a ~16s parse on my local system and results in a more responsive feeling bitbake. It also allows parsing performance to be investigated more consistently.

---
 lib/bb/data.py             | 15 ++++++++++-----
 lib/bb/tests/codeparser.py | 14 +++++++-------
 2 files changed, 17 insertions(+), 12 deletions(-)
lib/bb/data.py +10 -5
index 841369699e..f3ae062022 100644
@@ -261,7 +261,7 @@ 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, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d):
+def build_dependencies(key, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d, codeparsedata):
     def handle_contains(value, contains, exclusions, d):
         newvalue = []
         if value:
@@ -312,14 +312,14 @@ def build_dependencies(key, keys, mod_funcs, shelldeps, varflagsexcl, ignored_va
             value = varflags.get("vardepvalue")
         elif varflags.get("func"):
             if varflags.get("python"):
-                value = d.getVarFlag(key, "_content", False)
+                value = codeparsedata.getVarFlag(key, "_content", False)
                 parser = bb.codeparser.PythonParser(key, logger)
                 parser.parse_python(value, filename=varflags.get("filename"), lineno=varflags.get("lineno"))
                 deps = deps | parser.references
                 deps = deps | (keys & parser.execs)
                 value = handle_contains(value, parser.contains, exclusions, d)
             else:
-                value, parsedvar = d.getVarFlag(key, "_content", False, retparser=True)
+                value, parsedvar = codeparsedata.getVarFlag(key, "_content", False, retparser=True)
                 parser = bb.codeparser.ShellParser(key, logger)
                 parser.parse_shell(parsedvar.value)
                 deps = deps | shelldeps
@@ -378,12 +378,17 @@ def generate_dependencies(d, ignored_vars):
     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')
 
+    codeparserd = d.createCopy()
+    for forced in (d.getVar('BB_HASH_CODEPARSER_VALS') or "").split():
+        key, value = forced.split("=", 1)
+        codeparserd.setVar(key, value)
+
     deps = {}
     values = {}
 
     tasklist = d.getVar('__BBTASKS', False) or []
     for task in tasklist:
-        deps[task], values[task] = build_dependencies(task, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d)
+        deps[task], values[task] = build_dependencies(task, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d, codeparserd)
         newdeps = deps[task]
         seen = set()
         while newdeps:
@@ -392,7 +397,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, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d)
+                    deps[dep], values[dep] = build_dependencies(dep, keys, mod_funcs, shelldeps, varflagsexcl, ignored_vars, d, codeparserd)
                 newdeps |=  deps[dep]
             newdeps -= seen
         #print "For %s: %s" % (task, str(deps[task]))
lib/bb/tests/codeparser.py +7 -7
index a508f23bcb..7f5d59ca74 100644
@@ -318,7 +318,7 @@ d.getVar(a(), False)
             "filename": "example.bb",
         })
 
-        deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d)
+        deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d)
 
         self.assertEqual(deps, set(["somevar", "bar", "something", "inexpand", "test", "test2", "a"]))
 
@@ -365,7 +365,7 @@ esac
         self.d.setVarFlags("FOO", {"func": True})
         self.setEmptyVars(execs)
 
-        deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d)
+        deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d)
 
         self.assertEqual(deps, set(["somevar", "inverted"] + execs))
 
@@ -375,7 +375,7 @@ esac
         self.d.setVar("FOO", "foo=oe_libinstall; eval $foo")
         self.d.setVarFlag("FOO", "vardeps", "oe_libinstall")
 
-        deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d)
+        deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d)
 
         self.assertEqual(deps, set(["oe_libinstall"]))
 
@@ -384,7 +384,7 @@ esac
         self.d.setVar("FOO", "foo=oe_libinstall; eval $foo")
         self.d.setVarFlag("FOO", "vardeps", "${@'oe_libinstall'}")
 
-        deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d)
+        deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), set(), set(), self.d, self.d)
 
         self.assertEqual(deps, set(["oe_libinstall"]))
 
@@ -399,7 +399,7 @@ esac
         # Check dependencies
         self.d.setVar('ANOTHERVAR', expr)
         self.d.setVar('TESTVAR', 'anothervalue testval testval2')
-        deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), set(), self.d)
+        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,
                           'TESTVAR{anothervalue} = Set',
@@ -418,14 +418,14 @@ esac
         self.d.setVar('ANOTHERVAR', varval)
         self.d.setVar('TESTVAR', 'anothervalue testval testval2')
         self.d.setVar('TESTVAR2', 'testval3')
-        deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), set(["TESTVAR"]), self.d)
+        deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), set(["TESTVAR"]), self.d, self.d)
         self.assertEqual(sorted(values.splitlines()), sorted([varval]))
         self.assertEqual(deps, set(["TESTVAR2"]))
         self.assertEqual(self.d.getVar('ANOTHERVAR').split(), ['testval3', 'anothervalue'])
 
         # Check the vardepsexclude flag is handled by contains functionality
         self.d.setVarFlag('ANOTHERVAR', 'vardepsexclude', 'TESTVAR')
-        deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), set(), set(), self.d)
+        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([varval]))
         self.assertEqual(deps, set(["TESTVAR2"]))
         self.assertEqual(self.d.getVar('ANOTHERVAR').split(), ['testval3', 'anothervalue'])
Signature · 1 line
2.37.2
#7 lore raw

PATCH 6/6 data_smart: Small optimisation to _findVar()

In reply to Richard Purdie

Some users of _findVar don't need the override data and even getVarFlag doesn't need it in some common cases (parsing=True).

Rearrange the code as the current overridedata approach doesn't need to be in the _findVar code anyway. This removes some search overhead from a critical path.

---
 lib/bb/data_smart.py | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)
lib/bb/data_smart.py +9 -7
index e2c93597e5..c597dbade8 100644
@@ -515,18 +515,18 @@ class DataSmart(MutableMapping):
         dest = self.dict
         while dest:
             if var in dest:
-                return dest[var], self.overridedata.get(var, None)
+                return dest[var]
 
             if "_data" not in dest:
                 break
             dest = dest["_data"]
-        return None, self.overridedata.get(var, None)
+        return None
 
     def _makeShadowCopy(self, var):
         if var in self.dict:
             return
 
-        local_var, _ = self._findVar(var)
+        local_var = self._findVar(var)
 
         if local_var:
             self.dict[var] = copy.copy(local_var)
@@ -782,10 +782,12 @@ class DataSmart(MutableMapping):
         if expand and cachename in self.expand_cache:
             return self.expand_cache[cachename].value
 
-        local_var, overridedata = self._findVar(var)
+        local_var = self._findVar(var)
         value = None
         removes = set()
-        if flag == "_content" and overridedata is not None and not parsing:
+        if flag == "_content" and not parsing:
+            overridedata = self.overridedata.get(var, None)
+        if flag == "_content" and not parsing and overridedata is not None:
             match = False
             active = {}
             self.need_overrides()
@@ -900,7 +902,7 @@ class DataSmart(MutableMapping):
     def delVarFlag(self, var, flag, **loginfo):
         self.expand_cache = {}
 
-        local_var, _ = self._findVar(var)
+        local_var = self._findVar(var)
         if not local_var:
             return
         if not var in self.dict:
@@ -943,7 +945,7 @@ class DataSmart(MutableMapping):
             self.dict[var][i] = flags[i]
 
     def getVarFlags(self, var, expand = False, internalflags=False):
-        local_var, _ = self._findVar(var)
+        local_var = self._findVar(var)
         flags = {}
 
         if local_var:
Signature · 1 line
2.37.2