Skip to contentSkip to conversation

COW: Fix hardcoded magic numbers and work with python 3.13

PATCH In review Richard Purdie 2 participants 13 messages Oct 8, 2024 – Nov 21, 2024

lore
Share & tools
lore
#0 lore raw

PATCH 1/8 COW: Fix hardcoded magic numbers and work with python 3.13

The COW tests started failing on python 3.13. Looks like it is time to fix the FIXME and drop the magic numbers!

---
 lib/bb/COW.py | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
lib/bb/COW.py +6 -4
index 76bc08a3ea..4af03c54ad 100644
@@ -36,8 +36,9 @@ class COWDictMeta(COWMeta):
     __marker__ = tuple()
 
     def __str__(cls):
-        # FIXME: I have magic numbers!
-        return "<COWDict Level: %i Current Keys: %i>" % (cls.__count__, len(cls.__dict__) - 3)
+        ignored_keys = set(["__count__", "__doc__", "__module__", "__firstlineno__", "__static_attributes__"])
+        keys = set(cls.__dict__.keys()) - ignored_keys
+        return "<COWDict Level: %i Current Keys: %i>" % (cls.__count__, len(keys))
 
     __repr__ = __str__
 
@@ -161,8 +162,9 @@ class COWDictMeta(COWMeta):
 
 class COWSetMeta(COWDictMeta):
     def __str__(cls):
-        # FIXME: I have magic numbers!
-        return "<COWSet Level: %i Current Keys: %i>" % (cls.__count__, len(cls.__dict__) - 3)
+        ignored_keys = set(["__count__", "__doc__", "__module__", "__firstlineno__", "__static_attributes__"])
+        keys = set(cls.__dict__.keys()) - ignored_keys
+        return "<COWSet Level: %i Current Keys: %i>" % (cls.__count__, len(keys))
 
     __repr__ = __str__
 
#1 lore raw

PATCH 2/8 fetch2: Avoid deprecation warning

From re on python 3.13 onwards: "Passing count and flags as positional arguments is deprecated. In future Python versions they will be keyword-only parameters."

Avoid the warning.

---
 lib/bb/fetch2/__init__.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/bb/fetch2/__init__.py +1 -1
index 33a8086f27..b194a79be9 100644
@@ -237,7 +237,7 @@ class URI(object):
         # to RFC compliant URL format. E.g.:
         #   file://foo.diff -> file:foo.diff
         if urlp.scheme in self._netloc_forbidden:
-            uri = re.sub("(?<=:)//(?!/)", "", uri, 1)
+            uri = re.sub(r"(?<=:)//(?!/)", "", uri, count=1)
             reparse = 1
 
         if reparse:
#2 lore raw

PATCH 3/8 checksum/fetch2: Switch from persist_data to a standard cache file

In reply to Richard Purdie

The sqlite connection handling is causing problems with python 3.13. The connection can be closed at gc time which causing warnings and those can appear at 'random' points and break output, causing weird failures in different tinfoil tools and other tests.

Using sqlite as an IPC was never a great idea so drop that usage entirely and just use the standard cache mechanism we already have for other situations.

---
 lib/bb/cache.py           | 10 ++++++++++
 lib/bb/checksum.py        | 25 +++++++++++++++++++++++++
 lib/bb/cookerdata.py      |  5 +++--
 lib/bb/fetch2/__init__.py | 33 ++++++++++++++++++++-------------
 4 files changed, 58 insertions(+), 15 deletions(-)
lib/bb/cache.py +10 -0
index 958652e0e3..ec7b023fc7 100644
@@ -847,6 +847,16 @@ class MultiProcessCache(object):
         data = [{}]
         return data
 
+    def clear_cache(self):
+        if not self.cachefile:
+            bb.fatal("Can't clear invalid cachefile")
+
+        self.cachedata = self.create_cachedata()
+        self.cachedata_extras = self.create_cachedata()
+        with bb.utils.fileslocked([self.cachefile + ".lock"]):
+            bb.utils.remove(self.cachefile)
+            bb.utils.remove(self.cachefile + "-*")
+
     def save_extras(self):
         if not self.cachefile:
             return
lib/bb/checksum.py +25 -0
index 557793d366..3fb39a303e 100644
@@ -142,3 +142,28 @@ class FileChecksumCache(MultiProcessCache):
 
         checksums.sort(key=operator.itemgetter(1))
         return checksums
+
+class RevisionsCache(MultiProcessCache):
+    cache_file_name = "local_srcrevisions.dat"
+    CACHE_VERSION = 1
+
+    def __init__(self):
+        MultiProcessCache.__init__(self)
+
+    def get_revs(self):
+        return self.cachedata[0]
+
+    def get_rev(self, k):
+        if k in self.cachedata_extras[0]:
+            return self.cachedata_extras[0][k]
+        if k in self.cachedata[0]:
+            return self.cachedata[0][k]
+        return None
+
+    def set_rev(self, k, v):
+        self.cachedata[0][k] = v
+        self.cachedata_extras[0][k] = v
+
+    def merge_data(self, source, dest):
+        for h in source[0]:
+            dest[0][h] = source[0][h]
lib/bb/cookerdata.py +3 -2
index 3ad5cf3dd0..1f447d30c2 100644
@@ -1,3 +1,4 @@
+
 #
 # Copyright (C) 2003, 2004  Chris Larson
 # Copyright (C) 2003, 2004  Phil Blundell
@@ -267,8 +268,8 @@ class CookerDataBuilder(object):
         try:
             self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
 
-            if self.data.getVar("BB_WORKERCONTEXT", False) is None and not worker:
-                bb.fetch.fetcher_init(self.data)
+            servercontext = self.data.getVar("BB_WORKERCONTEXT", False) is None and not worker
+            bb.fetch.fetcher_init(self.data, servercontext)
             bb.parse.init_parser(self.data)
 
             bb.event.fire(bb.event.ConfigParsed(), self.data)
lib/bb/fetch2/__init__.py +20 -13
index b194a79be9..add742bfad 100644
@@ -23,13 +23,14 @@ import collections
 import subprocess
 import pickle
 import errno
-import bb.persist_data, bb.utils
+import bb.utils
 import bb.checksum
 import bb.process
 import bb.event
 
 __version__ = "2"
 _checksum_cache = bb.checksum.FileChecksumCache()
+_revisions_cache = bb.checksum.RevisionsCache()
 
 logger = logging.getLogger("BitBake.Fetcher")
 
@@ -493,18 +494,23 @@ methods = []
 urldata_cache = {}
 saved_headrevs = {}
 
-def fetcher_init(d):
+def fetcher_init(d, servercontext=True):
     """
     Called to initialize the fetchers once the configuration data is known.
     Calls before this must not hit the cache.
     """
 
-    revs = bb.persist_data.persist('BB_URI_HEADREVS', d)
+    _checksum_cache.init_cache(d.getVar("BB_CACHEDIR"))
+    _revisions_cache.init_cache(d.getVar("BB_CACHEDIR"))
+
+    if not servercontext:
+        return
+
     try:
         # fetcher_init is called multiple times, so make sure we only save the
         # revs the first time it is called.
         if not bb.fetch2.saved_headrevs:
-            bb.fetch2.saved_headrevs = dict(revs)
+            bb.fetch2.saved_headrevs = _revisions_cache.get_revs()
     except:
         pass
 
@@ -514,11 +520,10 @@ def fetcher_init(d):
         logger.debug("Keeping SRCREV cache due to cache policy of: %s", srcrev_policy)
     elif srcrev_policy == "clear":
         logger.debug("Clearing SRCREV cache due to cache policy of: %s", srcrev_policy)
-        revs.clear()
+        _revisions_cache.clear_cache()
     else:
         raise FetchError("Invalid SRCREV cache policy of: %s" % srcrev_policy)
 
-    _checksum_cache.init_cache(d.getVar("BB_CACHEDIR"))
 
     for m in methods:
         if hasattr(m, "init"):
@@ -526,9 +531,11 @@ def fetcher_init(d):
 
 def fetcher_parse_save():
     _checksum_cache.save_extras()
+    _revisions_cache.save_extras()
 
 def fetcher_parse_done():
     _checksum_cache.save_merge()
+    _revisions_cache.save_merge()
 
 def fetcher_compare_revisions(d):
     """
@@ -536,7 +543,7 @@ def fetcher_compare_revisions(d):
     when bitbake was started and return true if they have changed.
     """
 
-    headrevs = dict(bb.persist_data.persist('BB_URI_HEADREVS', d))
+    headrevs = _revisions_cache.get_revs()
     return headrevs != bb.fetch2.saved_headrevs
 
 def mirror_from_string(data):
@@ -1662,13 +1669,13 @@ class FetchMethod(object):
         if not hasattr(self, "_latest_revision"):
             raise ParameterError("The fetcher for this URL does not support _latest_revision", ud.url)
 
-        revs = bb.persist_data.persist('BB_URI_HEADREVS', d)
         key = self.generate_revision_key(ud, d, name)
-        try:
-            return revs[key]
-        except KeyError:
-            revs[key] = rev = self._latest_revision(ud, d, name)
-            return rev
+
+        rev = _revisions_cache.get_rev(key)
+        if rev is None:
+            rev = self._latest_revision(ud, d, name)
+            _revisions_cache.set_rev(key, rev)
+        return rev
 
     def sortable_revision(self, ud, d, name):
         latest_rev = self._build_revision(ud, d, name)
#3 lore raw

RE: [bitbake-devel] [PATCH 3/8] checksum/fetch2: Switch from persist_data to a standard cache file

Hi Richard, Steve,

Quoted 10 lines

-----Original Message-----
From: [email protected] <bitbake- [email protected]> On Behalf Of Richard Purdie via lists.openembedded.org
Sent: Tuesday, October 8, 2024 8:36 AM
To: [email protected]
Subject: [bitbake-devel] [PATCH 3/8] checksum/fetch2: Switch from persist_data to a standard cache file

Quoted 7 lines

The sqlite connection handling is causing problems with python 3.13. The connection can be closed at gc time which causing warnings and those can appear at 'random' points and break output, causing weird failures in different tinfoil tools and other tests.

Using sqlite as an IPC was never a great idea so drop that usage entirely and just use the standard cache mechanism we already have for other situations.

I revisited these warnings on Scarthgap (which doesn't yet have the persist_data changes), and was able to resolve them. Ultimately, it seemed the context managers were just not set up correctly for managing the Connection.

The __exit__ method of Connection only deals with transactions, and doesn't close any connection to the database: https://docs.python.org/3/library/sqlite3.html#how-to-use-the-connection-context-manager. But we were never using a context manager anyway when dealing with persist_data.

I was able to get rid of the warnings by adding this 'close' method to SQLTable:

def close(self):
self.connection.close()

And then changing usages of persist_data in fetch2 from something like this:

revs = bb.persist_data.persist('BB_URI_HEADREVS', d)

to this:

with contextlib.closing(bb.persist_data.persist('BB_URI_HEADREVS', d)) as revs:

I was wondering if you or Steve would be interested in a patch for this to apply to Scarthgap. If so, I'd be happy to send one in.

Thanks,
Chris

#4 lore raw

Re: [bitbake-devel] [PATCH 3/8] checksum/fetch2: Switch from persist_data to a standard cache file

Quoted 47 lines · On Wed, 2024-11-20 at 04:09 +0000, [email protected] wrote:

Hi Richard, Steve,

Quoted 18 lines

-----Original Message-----
From: [email protected] <bitbake- [email protected]> On Behalf Of Richard Purdie via lists.openembedded.org
Sent: Tuesday, October 8, 2024 8:36 AM
To: [email protected]
Subject: [bitbake-devel] [PATCH 3/8] checksum/fetch2: Switch from persist_data to a standard cache file

The sqlite connection handling is causing problems with python 3.13. The
connection can be closed at gc time which causing warnings and those can
appear at 'random' points and break output, causing weird failures in different
tinfoil tools and other tests.

Quoted 4 lines

Using sqlite as an IPC was never a great idea so drop that usage entirely and
just use the standard cache mechanism we already have for other situations.

I revisited these warnings on Scarthgap (which doesn't yet have the persist_data changes), and was able to resolve them. Ultimately, it seemed the context managers were just not set up correctly for managing the Connection.

The __exit__ method of Connection only deals with transactions, and doesn't close any connection to the database:
https://docs.python.org/3/library/sqlite3.html#how-to-use-the-connection-context-manager
. But we were never using a context manager anyway when dealing with persist_data.

I was able to get rid of the warnings by adding this 'close' method to SQLTable:

    def close(self):
        self.connection.close()

And then changing usages of persist_data in fetch2 from something like this:

revs = bb.persist_data.persist('BB_URI_HEADREVS', d)

Quoted 8 lines

to this:

with contextlib.closing(bb.persist_data.persist('BB_URI_HEADREVS', d)) as revs:

I was wondering if you or Steve would be interested in a patch for this to apply to Scarthgap. If so, I'd be happy to send one in.

I think scarthgap and older users would probably appreciate having this fixed so I'd be willing to take a patch.

Cheers,

Richard

#5 lore raw

RE: [bitbake-devel] [PATCH 3/8] checksum/fetch2: Switch from persist_data to a standard cache file

Hi Richard,

Quoted 5 lines
Quoted 2 lines

I was wondering if you or Steve would be interested in a patch for this to apply to Scarthgap. If so, I'd be happy to send one in.

I think scarthgap and older users would probably appreciate having this fixed so I'd be willing to take a patch.

OK, will do!

Question about sending the patches though: I don't think there are stable release branches for BitBake, so do I just send the patches to oe-core with the 'bitbake/' path and 'bitbake: ' commit message prefixes? (With the [scarthgap] subject prefix, of course)

And if so, do you want me to update the stable release section in the manual to mention this? https://docs.yoctoproject.org/contributor-guide/submit-changes.html#submitting-changes-to-stable-release-branches

Thanks,
Chris

#6 lore raw

Re: [bitbake-devel] [PATCH 3/8] checksum/fetch2: Switch from persist_data to a standard cache file

Quoted 12 lines · On Thu, 2024-11-21 at 17:30 +0000, [email protected] wrote:

Hi Richard,

Quoted 7 lines
Quoted 3 lines

I was wondering if you or Steve would be interested in a patch for
this to apply to Scarthgap. If so, I'd be happy to send one in.

I think scarthgap and older users would probably appreciate having this fixed so
I'd be willing to take a patch.

OK, will do!

Quoted 8 lines

Question about sending the patches though: I don't think there are stable release branches for BitBake, so do I just send the patches to oe-core with the 'bitbake/' path and 'bitbake: ' commit message prefixes?  (With the [scarthgap] subject prefix, of course)

And if so, do you want me to update the stable release section in the manual to mention this?
https://docs.yoctoproject.org/contributor-guide/submit-changes.html#submitting-changes-to-stable-release-branches

kirkstone is based on the 2.0 bitbake branch, scarthgap on 2.8 and styhead on 2.10 so those are LTS branches and are where we'd need patches. Prefix would be [2.0] with a note on why it wasn't needed for master in the commit message.

Cheers,

Richard

#7 lore raw

RE: [bitbake-devel] [PATCH 3/8] checksum/fetch2: Switch from persist_data to a standard cache file

Quoted 5 lines

kirkstone is based on the 2.0 bitbake branch, scarthgap on 2.8 and styhead on 2.10 so those are LTS branches and are where we'd need patches. Prefix would be [2.0] with a note on why it wasn't needed for master in the commit message.

Ah gotcha, will do. Thanks again!

Chris

#8 lore raw

PATCH 4/8 persist_data: Remove it

In reply to Richard Purdie

It was never a great solution to persisting data and there are much better ones now. The last user has been replaced so drop the code and tests.

---
 bin/bitbake-selftest         |   1 -
 lib/bb/persist_data.py       | 271 -----------------------------------
 lib/bb/tests/persist_data.py | 129 -----------------
 3 files changed, 401 deletions(-)
 delete mode 100644 lib/bb/persist_data.py
 delete mode 100644 lib/bb/tests/persist_data.py
bin/bitbake-selftest +0 -1
index ce901232fe..1b7a783fdc 100755
@@ -28,7 +28,6 @@ tests = ["bb.tests.codeparser",
          "bb.tests.event",
          "bb.tests.fetch",
          "bb.tests.parse",
-         "bb.tests.persist_data",
          "bb.tests.runqueue",
          "bb.tests.siggen",
          "bb.tests.utils",
lib/bb/persist_data.py deleted +0 -271

271 lines not on this page · raw message

lib/bb/tests/persist_data.py deleted +0 -129

129 lines not on this page · raw message

#9 lore raw

PATCH 5/8 bb/exceptions: Drop obsolete 2.6 code

In reply to Richard Purdie

In python 3 we should always have named tuples in this context. Drop the obsolete exception handling.

---
 lib/bb/exceptions.py | 8 +-------
 1 file changed, 1 insertion(+), 7 deletions(-)
lib/bb/exceptions.py +1 -7
index 801db9c82f..acf546de1d 100644
@@ -38,14 +38,8 @@ 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:
+    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':
#10 lore raw

PATCH 6/8 exceptions: Add hack to workaround python 3.13 failures

In reply to Richard Purdie
---
 lib/bb/exceptions.py | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
lib/bb/exceptions.py +5 -1
index acf546de1d..60643bd642 100644
@@ -47,7 +47,11 @@ def _get_frame_args(frame):
         cls = self.__class__.__name__
 
         arginfo.args.pop(0)
-        del arginfo.locals['self']
+        try:
+            del arginfo.locals['self']
+        except TypeError:
+            # FIXME - python 3.13 FrameLocalsProxy can't be modified
+            pass
     else:
         cls = None
 
#11 lore raw

PATCH 7/8 toaster/tests: Fix kirkstone numbering

In reply to Richard Purdie

When the fixtures were updated for the styhead release, the test cases were not updated to match. Fix this.

---
 lib/toaster/tests/functional/test_create_new_project.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/toaster/tests/functional/test_create_new_project.py +1 -1
index cdfdd9ab20..c3b5679514 100644
@@ -110,7 +110,7 @@ class TestCreateNewProject(SeleniumFunctionalTestCase):
           - Release: Yocto Project 4.0 "Kirkstone" (option value: 4)
           - Merge Toaster settings: True
         """
-        release = '4'
+        release = '5'
         release_title = 'Yocto Project 4.0 "Kirkstone"'
         project_name = 'projectkirkstone'
         self._create_test_new_project(
#12 lore raw

PATCH 8/8 toaster/tests: Improve a test to give better debug output

In reply to Richard Purdie

"False is not True" is not a helpful error messgae. "XXX not in YYY" is much more helpful. Tweak the test to give more meaninful failure messages using assertIn rather than assertTrue.

---
 lib/toaster/tests/functional/test_project_page.py | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
lib/toaster/tests/functional/test_project_page.py +4 -4
index 0e36b44ffd..deb26812ea 100644
@@ -719,16 +719,16 @@ class TestProjectPage(SeleniumFunctionalTestCase):
         remove_layer_btn.click()
         self.wait_until_visible('#change-notification', poll=2)
         change_notification = self.find('#change-notification')
-        self.assertTrue(
-            f'You have removed 1 layer from your project' in str(change_notification.text)
+        self.assertIn(
+            f'You have removed 1 layer from your project', str(change_notification.text)
         )
         # check add layer button works, 18 is the random layer id
         add_layer_btn = self.find('#add-remove-layer-btn')
         add_layer_btn.click()
         self.wait_until_visible('#change-notification')
         change_notification = self.find('#change-notification')
-        self.assertTrue(
-            f'You have added 1 layer to your project' in str(change_notification.text)
+        self.assertIn(
+            f'You have added 1 layer to your project', str(change_notification.text)
         )
         # check tabs(layers, recipes, machines) are displayed
         tabs = self.find_all('.nav-tabs li')