Skip to contentSkip to conversation

prserv: add support for an "upstream" server

PATCH New [email protected] 1 participant 9 messages May 11, 2024

lore
Share & tools
lore
#0 lore raw

v7 cover prserv: add support for an "upstream" server

From: Michael Opdenacker <[email protected]>

This makes it possible to customize an "upstream" distribution by modifying local packages. If the "upstream" package bears revision "x", the local one will have revision "x.y", this having priority over the upstream one.

Multiple levels of upstream servers are supported, so "x.y.z" revisions are possible too.

This version also supports multiple servers sharing the same database.

This also includes BitBake selftests to check the expected functionality and detect future regressions.

bitbake-selftest prserv.tests

The "oe-selftest --run-tests prservice" tests pass on the condition that this patch is applied to OE-core:
https://lore.kernel.org/openembedded-core/[email protected]/T/#u

---

Changes in V7:

- Remove no longer defined "self.server.table.sync()" call in prserv.py exception path.

Changes in V6:

- Harden the store_value() code to protect
it against storing the same value twice.

- Simplify the importone() hook, removing
its unnecessary "history" parameter.

- This fixes all errors in "oe-selftest -r prservice", once this OE-core patch is merged:
https://lore.kernel.org/openembedded-core/[email protected]/T/#u

- Make tests work in temporary directories.
Suggested by Joshua Watt

- Remove first version of readonly server tests which depended on the output of a previous test. One implementation of readonly server tests remains.

- Merge the upstream and read-only tests so that the read-only test part can reuse the databases and servers from the upstream one. Initially thought that the setUp (and tearDown) hooks were called only once for each test class, instead of for each test. Thanks to Joshua Watt for making me understand this.

- Merged two more tests and simplified their naming as, with one exception, the order of tests doesn't matter any more.

- Avoid a possible race condition at database
creation time. Suggested by Joshua Watt.

Changes in V5:

- Change the way the database is accessed and modified. As done in the Hash Server code, the database is not accessed through the cursor API.

This makes it possible to have multiple servers accessing the same database, typically one read-write server that is fed by the build machine, and one read-only server that is used to publish PR data to downstream users.

This switched sqlite3 to "WAL" journaling mode, and to "OFF" synchronous mode.

- Fix revision ordering issues, now computing the min and max values through dedicated Python functions, instead of letting the database do this with just string comparison, which was wrong in our case. Typically, "1.20" is greater for us than "1.3".

- Add BitBake selftests, in particular to make sure revision ordering is correct and the maximum and minimum values are correctly computed.

- An issue remains: the BitBake selftests that test database access through a read-only server while a read-write server is still running, still fail, because the database changes are apparently not stored to disk.

FAIL: test_3b_readonly (prserv.tests.PRUpstreamTests)

Changes in V4:

- Add BitBake selftests for the legacy and new PR server features
(database, client, server, support for upstream server, read-only mode, "history" and "no history" modes) To run only these tests:
bitbake-selftest prserv.tests

- Pass the "history" mode through the client requests, instead of storing it (globally) in the database name.

The PR database is now called "PRMAIN" instead of "PRMAIN_nohist". This should cause a regression for builds which already have a PR database.

- Fixes for "history" modes:
- Allow to store multiple PR values for the same checksum, needed for the "no history" mode.
- Make the "history" mode return the minimum stored PR value.

- Fixes and code reorganization for issues uncovered by the tests.

- Update the server version to "2.0.0"

Changes in V3:

- Revert the commit removing the so far unused "hist" mode, which we wish to keep for binary reproducibility sake.

- Simplification of get_value() function to take both "hist" and "nohist" modes with the same shared code.

- Add "history" parameter to the "getPR" request, so that the client can ask for the mode of its choice. This will also make it possible to implement tests for both modes.

Note that more requests ("export", "import"...) will also need a "history" parameter, in a future version, after the first tests are implemented.

- Several bug fixes.

- Put all the new features at the tip of the branch, to make the cleanup commits easier to merged.

Changes in V2:

- Add this new commit:
prserv: remove unused "hist" mode in the database backend

- Squash commit "prserv: fix read_only test" into commit "prserv: simplify the PRServerClient() interface" (Reported by Richard Purdie)

- Fix the code to support increasing "x.y.z" values, thus supporting several levels of upstream servers.

- db.py: remove duplicate definition of find_max_value() function in db.py

- prserv.py: remove tabs before comments (Python didn't complain)

- db.py: now stores the revision ("value") as TEXT. This way we can store "1.0" without having it transformed to "1" when the default type was INTEGER.

- This allows to fix a regression when the first packages were created with 'r0.1' instead of 'r0.0' initially.

- find_max_value: now returns None instead of '0' when no value is found Before we couldn't tell the difference between a '0'
max value and the absence of such a value.

Cc Thomas Petazzoni <[email protected]>
Cc Joshua Watt <[email protected]>
Cc Tim Orling <[email protected]>

Michael Opdenacker (8):
prserv: declare "max_package_pr" client hook
prserv: move code from __init__ to bitbake-prserv
prserv: add "upstream" server support
prserv: enable database sharing
prserv: avoid possible race condition in database code
prserv: store_value() improvements
prserv: import simplification
prserv: add bitbake selftests

 bin/bitbake-prserv     |  26 ++-
 bin/bitbake-selftest   |   2 +
 lib/prserv/__init__.py |  97 ++++++++-
 lib/prserv/client.py   |  15 +-
 lib/prserv/db.py       | 452 ++++++++++++++++++-----------------------
 lib/prserv/serv.py     | 140 ++++++++++---
 lib/prserv/tests.py    | 386 +++++++++++++++++++++++++++++++++++
 7 files changed, 816 insertions(+), 302 deletions(-)
 create mode 100644 bitbake/lib/prserv/tests.py
Signature · 1 line
2.34.1
#1 lore raw

PATCH v7 1/8 prserv: declare "max_package_pr" client hook

From: Michael Opdenacker <[email protected]>

Add missing declaration for the max_package_pr client hook

Cc Joshua Watt <[email protected]>
Cc Tim Orling <[email protected]>
Cc Thomas Petazzoni <[email protected]>
---
 lib/prserv/client.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/prserv/client.py +1 -1
index 8471ee3046..99fc4e0f7f 100644
@@ -65,7 +65,7 @@ class PRAsyncClient(bb.asyncrpc.AsyncClient):
 class PRClient(bb.asyncrpc.Client):
     def __init__(self):
         super().__init__()
-        self._add_methods("getPR", "test_pr", "test_package", "importone", "export", "is_readonly")
+        self._add_methods("getPR", "test_pr", "test_package", "max_package_pr", "importone", "export", "is_readonly")
 
     def _get_async_client(self):
         return PRAsyncClient()
Signature · 1 line
2.34.1
#2 lore raw

PATCH v7 2/8 prserv: move code from __init__ to bitbake-prserv

In reply to [email protected]

From: Michael Opdenacker <[email protected]>

This script was the only user of this code.

Cc Joshua Watt <[email protected]>
Cc Tim Orling <[email protected]>
Cc Thomas Petazzoni <[email protected]>
---
 bin/bitbake-prserv     |  9 ++++++++-
 lib/prserv/__init__.py | 13 -------------
 2 files changed, 8 insertions(+), 14 deletions(-)
bin/bitbake-prserv +8 -1
index ad0a069401..920663a1d8 100755
@@ -21,6 +21,13 @@ VERSION = "1.1.0"
 PRHOST_DEFAULT="0.0.0.0"
 PRPORT_DEFAULT=8585
 
+def init_logger(logfile, loglevel):
+    numeric_level = getattr(logging, loglevel.upper(), None)
+    if not isinstance(numeric_level, int):
+        raise ValueError("Invalid log level: %s" % loglevel)
+    FORMAT = "%(asctime)-15s %(message)s"
+    logging.basicConfig(level=numeric_level, filename=logfile, format=FORMAT)
+
 def main():
     parser = argparse.ArgumentParser(
         description="BitBake PR Server. Version=%s" % VERSION,
@@ -72,7 +79,7 @@ def main():
     )
 
     args = parser.parse_args()
-    prserv.init_logger(os.path.abspath(args.log), args.loglevel)
+    init_logger(os.path.abspath(args.log), args.loglevel)
 
     if args.start:
         ret=prserv.serv.start_daemon(args.file, args.host, args.port, os.path.abspath(args.log), args.read_only)
lib/prserv/__init__.py +0 -13
index 0e0aa34d0e..94658b815d 100644
@@ -5,16 +5,3 @@
 #
 
 __version__ = "1.0.0"
-
-import os, time
-import sys, logging
-
-def init_logger(logfile, loglevel):
-    numeric_level = getattr(logging, loglevel.upper(), None)
-    if not isinstance(numeric_level, int):
-        raise ValueError("Invalid log level: %s" % loglevel)
-    FORMAT = "%(asctime)-15s %(message)s"
-    logging.basicConfig(level=numeric_level, filename=logfile, format=FORMAT)
-
-class NotFoundError(Exception):
-    pass
Signature · 1 line
2.34.1
#3 lore raw

PATCH v7 3/8 prserv: add "upstream" server support

In reply to [email protected]

From: Michael Opdenacker <[email protected]>

Introduce a PRSERVER_UPSTREAM variable that makes the local PR server connect to an "upstream" one.

This makes it possible to implement local fixes to an upstream package (revision "x", in a way that gives the local update priority (revision "x.y").

Update the calculation of the new revisions to support the case when prior revisions are not integers, but have an "x.y..." format."

Set the comments in the handle_get_pr() function in serv.py for details about the calculation of the local revision.

This is done by going on supporting the "history" mode that wasn't used so far (revisions can return to a previous historical value), in addition to the default "no history" mode (revisions can never decrease).

Rather than storing the history mode in the database table itself (i.e. "PRMAIN_hist" and "PRMAIN_nohist"), the history mode is now passed through the client requests. As a consequence, the table name is now "PRMAIN", which is incompatible with what was generated before, but avoids confusion if we kept the "PRMAIN_nohist" name for both "history" and "no history" modes.

Update the server version to "2.0.0".

Cc Joshua Watt <[email protected]>
Cc Tim Orling <[email protected]>
Cc Thomas Petazzoni <[email protected]>
---
 bin/bitbake-prserv     |  17 +++-
 lib/prserv/__init__.py |  90 +++++++++++++++++-
 lib/prserv/client.py   |  17 ++--
 lib/prserv/db.py       | 205 ++++++++++++++++++++++-------------------
 lib/prserv/serv.py     | 134 +++++++++++++++++++++++----
 5 files changed, 338 insertions(+), 125 deletions(-)
bin/bitbake-prserv +15 -2
index 920663a1d8..580e021fda 100755
@@ -16,7 +16,7 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), "lib
 import prserv
 import prserv.serv
 
-VERSION = "1.1.0"
+VERSION = "2.0.0"
 
 PRHOST_DEFAULT="0.0.0.0"
 PRPORT_DEFAULT=8585
@@ -77,12 +77,25 @@ def main():
         action="store_true",
         help="open database in read-only mode",
     )
+    parser.add_argument(
+        "-u",
+        "--upstream",
+        default=os.environ.get("PRSERVER_UPSTREAM", None),
+        help="Upstream PR service (host:port)",
+    )
 
     args = parser.parse_args()
     init_logger(os.path.abspath(args.log), args.loglevel)
 
     if args.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(
+            args.file,
+            args.host,
+            args.port,
+            os.path.abspath(args.log),
+            args.read_only,
+            args.upstream
+        )
     elif args.stop:
         ret=prserv.serv.stop_daemon(args.host, args.port)
     else:
lib/prserv/__init__.py +89 -1

93 lines not on this page · raw message

lib/prserv/client.py +9 -8
index 99fc4e0f7f..565c6f3872 100644
@@ -6,6 +6,7 @@
 
 import logging
 import bb.asyncrpc
+from . import create_async_client
 
 logger = logging.getLogger("BitBake.PRserv")
 
@@ -13,16 +14,16 @@ class PRAsyncClient(bb.asyncrpc.AsyncClient):
     def __init__(self):
         super().__init__("PRSERVICE", "1.0", logger)
 
-    async def getPR(self, version, pkgarch, checksum):
+    async def getPR(self, version, pkgarch, checksum, history=False):
         response = await self.invoke(
-            {"get-pr": {"version": version, "pkgarch": pkgarch, "checksum": checksum}}
+            {"get-pr": {"version": version, "pkgarch": pkgarch, "checksum": checksum, "history": history}}
         )
         if response:
             return response["value"]
 
-    async def test_pr(self, version, pkgarch, checksum):
+    async def test_pr(self, version, pkgarch, checksum, history=False):
         response = await self.invoke(
-            {"test-pr": {"version": version, "pkgarch": pkgarch, "checksum": checksum}}
+            {"test-pr": {"version": version, "pkgarch": pkgarch, "checksum": checksum, "history": history}}
         )
         if response:
             return response["value"]
@@ -41,16 +42,16 @@ class PRAsyncClient(bb.asyncrpc.AsyncClient):
         if response:
             return response["value"]
 
-    async def importone(self, version, pkgarch, checksum, value):
+    async def importone(self, version, pkgarch, checksum, value, history=False):
         response = await self.invoke(
-            {"import-one": {"version": version, "pkgarch": pkgarch, "checksum": checksum, "value": value}}
+            {"import-one": {"version": version, "pkgarch": pkgarch, "checksum": checksum, "value": value, "history": history}}
         )
         if response:
             return response["value"]
 
-    async def export(self, version, pkgarch, checksum, colinfo):
+    async def export(self, version, pkgarch, checksum, colinfo, history=False):
         response = await self.invoke(
-            {"export": {"version": version, "pkgarch": pkgarch, "checksum": checksum, "colinfo": colinfo}}
+            {"export": {"version": version, "pkgarch": pkgarch, "checksum": checksum, "colinfo": colinfo, "history": history}}
         )
         if response:
             return (response["metainfo"], response["datainfo"])
lib/prserv/db.py +108 -97

285 lines not on this page · raw message

lib/prserv/serv.py +117 -17

228 lines not on this page · raw message

Signature · 1 line
2.34.1
#4 lore raw

PATCH v7 4/8 prserv: enable database sharing

In reply to [email protected]

From: Michael Opdenacker <[email protected]>

sqlite3 can allow multiple processes to access the database simultaneously, but it must be opened correctly. The key change is that the database is no longer opened in "exclusive" mode (defaulting to shared mode). In addition, the journal is set to "WAL" mode, as this is the most efficient for dealing with simultaneous access between different processes. In order to keep the database performance, synchronous mode is set to "off". The WAL journal will protect against incomplete transactions in any given client, however the database will not be protected against unexpected power loss from the OS (which is a fine trade off for performance, and also the same as the previous implementation).

The use of a database cursor enabled to remove the _execute() wrapper. The cursor automatically makes sure that the query happens in an atomic transaction and commits when finished.

This also removes the need for a "dirty" flag for the database and for explicit database syncing, which simplifies the code.

---
 lib/prserv/db.py   | 322 +++++++++++++++++++++------------------------
 lib/prserv/serv.py |   9 --
 2 files changed, 151 insertions(+), 180 deletions(-)
lib/prserv/db.py +151 -171
index b2520f3158..f430586d73 100644
@@ -8,21 +8,13 @@ import logging
 import os.path
 import errno
 import prserv
-import time
+import sqlite3
 
+from contextlib import closing
 from . import increase_revision, revision_greater, revision_smaller
 
-try:
-    import sqlite3
-except ImportError:
-    from pysqlite2 import dbapi2 as sqlite3
-
 logger = logging.getLogger("BitBake.PRserv")
 
-sqlversion = sqlite3.sqlite_version_info
-if sqlversion[0] < 3 or (sqlversion[0] == 3 and sqlversion[1] < 3):
-    raise Exception("sqlite3 version 3.3.0 or later is required.")
-
 #
 # "No History" mode - for a given query tuple (version, pkgarch, checksum),
 # the returned value will be the largest among all the values of the same
@@ -31,40 +23,28 @@ if sqlversion[0] < 3 or (sqlversion[0] == 3 and sqlversion[1] < 3):
 # "History" mode - Return a new higher value for previously unseen query
 # tuple (version, pkgarch, checksum), otherwise return historical value.
 # Value can decrement if returning to a previous build.
-#
 
 class PRTable(object):
     def __init__(self, conn, table, read_only):
         self.conn = conn
         self.read_only = read_only
-        self.dirty = False
         self.table = table
 
-        if self.read_only:
-            table_exists = self._execute(
-                        "SELECT count(*) FROM sqlite_master \
-                        WHERE type='table' AND name='%s'" % (self.table))
-            if not table_exists:
-                raise prserv.NotFoundError
-        else:
-            self._execute("CREATE TABLE IF NOT EXISTS %s \
-                        (version TEXT NOT NULL, \
-                        pkgarch TEXT NOT NULL,  \
-                        checksum TEXT NOT NULL, \
-                        value TEXT, \
-                        PRIMARY KEY (version, pkgarch, checksum, value));" % self.table)
-
-    def _execute(self, *query):
-        """Execute a query, waiting to acquire a lock if necessary"""
-        start = time.time()
-        end = start + 20
-        while True:
-            try:
-                return self.conn.execute(*query)
-            except sqlite3.OperationalError as exc:
-                if "is locked" in str(exc) and end > time.time():
-                    continue
-                raise exc
+        with closing(self.conn.cursor()) as cursor:
+            if self.read_only:
+                table_exists = cursor.execute(
+                            "SELECT count(*) FROM sqlite_master \
+                            WHERE type='table' AND name='%s'" % (self.table))
+                if not table_exists:
+                    raise prserv.NotFoundError
+            else:
+                cursor.execute("CREATE TABLE IF NOT EXISTS %s \
+                            (version TEXT NOT NULL, \
+                            pkgarch TEXT NOT NULL,  \
+                            checksum TEXT NOT NULL, \
+                            value TEXT, \
+                            PRIMARY KEY (version, pkgarch, checksum, value));" % self.table)
+                self.conn.commit()
 
     def _extremum_value(self, rows, is_max):
         value = None
@@ -88,49 +68,42 @@ class PRTable(object):
     def _min_value(self, rows):
         return self._extremum_value(rows, False)
 
-    def sync(self):
-        if not self.read_only:
-            self.conn.commit()
-            self._execute("BEGIN EXCLUSIVE TRANSACTION")
-
-    def sync_if_dirty(self):
-        if self.dirty:
-            self.sync()
-            self.dirty = False
-
     def test_package(self, version, pkgarch):
         """Returns whether the specified package version is found in the database for the specified architecture"""
 
         # Just returns the value if found or None otherwise
-        data=self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=?;" % self.table,
-                           (version, pkgarch))
-        row=data.fetchone()
-        if row is not None:
-            return True
-        else:
-            return False
+        with closing(self.conn.cursor()) as cursor:
+            data=cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=?;" % self.table,
+                               (version, pkgarch))
+            row=data.fetchone()
+            if row is not None:
+                return True
+            else:
+                return False
 
     def test_value(self, version, pkgarch, value):
         """Returns whether the specified value is found in the database for the specified package and architecture"""
 
         # Just returns the value if found or None otherwise
-        data=self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? and value=?;" % self.table,
-                           (version, pkgarch, value))
-        row=data.fetchone()
-        if row is not None:
-            return True
-        else:
-            return False
+        with closing(self.conn.cursor()) as cursor:
+            data=cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=? and value=?;" % self.table,
+                               (version, pkgarch, value))
+            row=data.fetchone()
+            if row is not None:
+                return True
+            else:
+                return False
 
 
     def find_package_max_value(self, version, pkgarch):
         """Returns the greatest value for (version, pkgarch), or None if not found. Doesn't create a new value"""
 
-        data = self._execute("SELECT value FROM %s where version=? AND pkgarch=?;" % (self.table),
-                             (version, pkgarch))
-        rows = data.fetchall()
-        value = self._max_value(rows)
-        return value
+        with closing(self.conn.cursor()) as cursor:
+            data = cursor.execute("SELECT value FROM %s where version=? AND pkgarch=?;" % (self.table),
+                                 (version, pkgarch))
+            rows = data.fetchall()
+            value = self._max_value(rows)
+            return value
 
     def find_value(self, version, pkgarch, checksum, history=False):
         """Returns the value for the specified checksum if found or None otherwise."""
@@ -145,10 +118,11 @@ class PRTable(object):
         """Returns the maximum (if is_max is True) or minimum (if is_max is False) value
            for (version, pkgarch, checksum), or None if not found. Doesn't create a new value"""
 
-        data = self._execute("SELECT value FROM %s where version=? AND pkgarch=? AND checksum=?;" % (self.table),
-                             (version, pkgarch, checksum))
-        rows = data.fetchall()
-        return self._extremum_value(rows, is_max)
+        with closing(self.conn.cursor()) as cursor:
+            data = cursor.execute("SELECT value FROM %s where version=? AND pkgarch=? AND checksum=?;" % (self.table),
+                                 (version, pkgarch, checksum))
+            rows = data.fetchall()
+            return self._extremum_value(rows, is_max)
 
     def find_max_value(self, version, pkgarch, checksum):
         return self._find_extremum_value(version, pkgarch, checksum, True)
@@ -160,26 +134,27 @@ class PRTable(object):
         """Take and increase the greatest "<base>.y" value for (version, pkgarch), or return "<base>.0" if not found.
         This doesn't store a new value."""
 
-        data = self._execute("SELECT value FROM %s where version=? AND pkgarch=? AND value LIKE '%s.%%';" % (self.table, base),
-                             (version, pkgarch))
-        rows = data.fetchall()
-        value = self._max_value(rows)
+        with closing(self.conn.cursor()) as cursor:
+            data = cursor.execute("SELECT value FROM %s where version=? AND pkgarch=? AND value LIKE '%s.%%';" % (self.table, base),
+                                 (version, pkgarch))
+            rows = data.fetchall()
+            value = self._max_value(rows)
 
-        if value is not None:
-            return increase_revision(value)
-        else:
-            return base + ".0"
+            if value is not None:
+                return increase_revision(value)
+            else:
+                return base + ".0"
 
     def store_value(self, version, pkgarch, checksum, value):
         """Store new value in the database"""
 
-        try:
-            self._execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
-                       (version, pkgarch, checksum, value))
-        except sqlite3.IntegrityError as exc:
-            logger.error(str(exc))
-
-        self.dirty = True
+        with closing(self.conn.cursor()) as cursor:
+            try:
+                cursor.execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
+                           (version, pkgarch, checksum, value))
+            except sqlite3.IntegrityError as exc:
+                logger.error(str(exc))
+            self.conn.commit()
 
     def _get_value(self, version, pkgarch, checksum, history):
 
@@ -215,54 +190,56 @@ class PRTable(object):
             return None
 
         val = None
-        data = self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=?;" % self.table,
+        with closing(self.conn.cursor()) as cursor:
+            data = cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=?;" % self.table,
                            (version, pkgarch, checksum))
-        row = data.fetchone()
-        if row is not None:
-            val=row[0]
-        else:
-            #no value found, try to insert
-            try:
-                self._execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
-                           (version, pkgarch, checksum, value))
-            except sqlite3.IntegrityError as exc:
-                logger.error(str(exc))
+            row = data.fetchone()
+            if row is not None:
+                val=row[0]
+            else:
+                #no value found, try to insert
+                try:
+                    cursor.execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
+                               (version, pkgarch, checksum, value))
+                except sqlite3.IntegrityError as exc:
+                    logger.error(str(exc))
 
-            self.dirty = True
+                self.conn.commit()
 
-            data = self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=?;" % self.table,
+                data = cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=?;" % self.table,
                            (version, pkgarch, checksum))
-            row = data.fetchone()
-            if row is not None:
-                val = row[0]
+                row = data.fetchone()
+                if row is not None:
+                    val = row[0]
         return val
 
     def _import_no_hist(self, version, pkgarch, checksum, value):
         if self.read_only:
             return None
 
-        try:
-            #try to insert
-            self._execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
-                           (version, pkgarch, checksum, value))
-        except sqlite3.IntegrityError as exc:
-            #already have the record, try to update
+        with closing(self.conn.cursor()) as cursor:
             try:
-                self._execute("UPDATE %s SET value=? WHERE version=? AND pkgarch=? AND checksum=? AND value<?"
-                              % (self.table),
-                               (value, version, pkgarch, checksum, value))
+                #try to insert
+                cursor.execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
+                               (version, pkgarch, checksum, value))
             except sqlite3.IntegrityError as exc:
-                logger.error(str(exc))
+                #already have the record, try to update
+                try:
+                    cursor.execute("UPDATE %s SET value=? WHERE version=? AND pkgarch=? AND checksum=? AND value<?"
+                                  % (self.table),
+                                   (value, version, pkgarch, checksum, value))
+                except sqlite3.IntegrityError as exc:
+                    logger.error(str(exc))
 
-        self.dirty = True
+                self.conn.commit()
 
-        data = self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=? AND value>=?;" % self.table,
+            data = cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=? AND value>=?;" % self.table,
                             (version, pkgarch, checksum, value))
-        row=data.fetchone()
-        if row is not None:
-            return row[0]
-        else:
-            return None
+            row=data.fetchone()
+            if row is not None:
+                return row[0]
+            else:
+                return None
 
     def importone(self, version, pkgarch, checksum, value, history=False):
         if history:
@@ -272,56 +249,57 @@ class PRTable(object):
 
     def export(self, version, pkgarch, checksum, colinfo, history=False):
         metainfo = {}
-        #column info
-        if colinfo:
-            metainfo["tbl_name"] = self.table
-            metainfo["core_ver"] = prserv.__version__
-            metainfo["col_info"] = []
-            data = self._execute("PRAGMA table_info(%s);" % self.table)
+        with closing(self.conn.cursor()) as cursor:
+            #column info
+            if colinfo:
+                metainfo["tbl_name"] = self.table
+                metainfo["core_ver"] = prserv.__version__
+                metainfo["col_info"] = []
+                data = cursor.execute("PRAGMA table_info(%s);" % self.table)
+                for row in data:
+                    col = {}
+                    col["name"] = row["name"]
+                    col["type"] = row["type"]
+                    col["notnull"] = row["notnull"]
+                    col["dflt_value"] = row["dflt_value"]
+                    col["pk"] = row["pk"]
+                    metainfo["col_info"].append(col)
+
+            #data info
+            datainfo = []
+
+            if history:
+                sqlstmt = "SELECT * FROM %s as T1 WHERE 1=1 " % self.table
+            else:
+                sqlstmt = "SELECT T1.version, T1.pkgarch, T1.checksum, T1.value FROM %s as T1, \
+                        (SELECT version, pkgarch, max(value) as maxvalue FROM %s GROUP BY version, pkgarch) as T2 \
+                        WHERE T1.version=T2.version AND T1.pkgarch=T2.pkgarch AND T1.value=T2.maxvalue " % (self.table, self.table)
+            sqlarg = []
+            where = ""
+            if version:
+                where += "AND T1.version=? "
+                sqlarg.append(str(version))
+            if pkgarch:
+                where += "AND T1.pkgarch=? "
+                sqlarg.append(str(pkgarch))
+            if checksum:
+                where += "AND T1.checksum=? "
+                sqlarg.append(str(checksum))
+
+            sqlstmt += where + ";"
+
+            if len(sqlarg):
+                data = cursor.execute(sqlstmt, tuple(sqlarg))
+            else:
+                data = cursor.execute(sqlstmt)
             for row in data:
-                col = {}
-                col["name"] = row["name"]
-                col["type"] = row["type"]
-                col["notnull"] = row["notnull"]
-                col["dflt_value"] = row["dflt_value"]
-                col["pk"] = row["pk"]
-                metainfo["col_info"].append(col)
-
-        #data info
-        datainfo = []
-
-        if history:
-            sqlstmt = "SELECT * FROM %s as T1 WHERE 1=1 " % self.table
-        else:
-            sqlstmt = "SELECT T1.version, T1.pkgarch, T1.checksum, T1.value FROM %s as T1, \
-                    (SELECT version, pkgarch, max(value) as maxvalue FROM %s GROUP BY version, pkgarch) as T2 \
-                    WHERE T1.version=T2.version AND T1.pkgarch=T2.pkgarch AND T1.value=T2.maxvalue " % (self.table, self.table)
-        sqlarg = []
-        where = ""
-        if version:
-            where += "AND T1.version=? "
-            sqlarg.append(str(version))
-        if pkgarch:
-            where += "AND T1.pkgarch=? "
-            sqlarg.append(str(pkgarch))
-        if checksum:
-            where += "AND T1.checksum=? "
-            sqlarg.append(str(checksum))
-
-        sqlstmt += where + ";"
-
-        if len(sqlarg):
-            data = self._execute(sqlstmt, tuple(sqlarg))
-        else:
-            data = self._execute(sqlstmt)
-        for row in data:
-            if row["version"]:
-                col = {}
-                col["version"] = row["version"]
-                col["pkgarch"] = row["pkgarch"]
-                col["checksum"] = row["checksum"]
-                col["value"] = row["value"]
-                datainfo.append(col)
+                if row["version"]:
+                    col = {}
+                    col["version"] = row["version"]
+                    col["pkgarch"] = row["pkgarch"]
+                    col["checksum"] = row["checksum"]
+                    col["value"] = row["value"]
+                    datainfo.append(col)
         return (metainfo, datainfo)
 
     def dump_db(self, fd):
@@ -345,14 +323,15 @@ class PRData(object):
                 raise e
         uri = "file:%s%s" % (self.filename, "?mode=ro" if self.read_only else "")
         logger.debug("Opening PRServ database '%s'" % (uri))
-        self.connection=sqlite3.connect(uri, uri=True, isolation_level="EXCLUSIVE", check_same_thread = False)
+        self.connection=sqlite3.connect(uri, uri=True)
         self.connection.row_factory=sqlite3.Row
-        if not self.read_only:
-            self.connection.execute("pragma synchronous = off;")
-            self.connection.execute("PRAGMA journal_mode = MEMORY;")
+        self.connection.execute("PRAGMA synchronous = OFF;")
+        self.connection.execute("PRAGMA journal_mode = WAL;")
+        self.connection.commit()
         self._tables={}
 
     def disconnect(self):
+        self.connection.commit()
         self.connection.close()
 
     def __getitem__(self, tblname):
@@ -370,3 +349,4 @@ class PRData(object):
             del self._tables[tblname]
         logger.info("drop table %s" % (tblname))
         self.connection.execute("DROP TABLE IF EXISTS %s;" % tblname)
+        self.connection.commit()
lib/prserv/serv.py +0 -9
index 05573d06cc..3992056f88 100644
@@ -42,10 +42,7 @@ class PRServerClient(bb.asyncrpc.AsyncServerConnection):
         try:
             return await super().dispatch_message(msg)
         except:
-            self.server.table.sync()
             raise
-        else:
-            self.server.table.sync_if_dirty()
 
     async def handle_test_pr(self, request):
         '''Finds the PR value corresponding to the request. If not found, returns None and doesn't insert a new value'''
@@ -233,15 +230,9 @@ class PRServer(bb.asyncrpc.AsyncServer):
         return tasks
 
     async def stop(self):
-        self.table.sync_if_dirty()
         self.db.disconnect()
         await super().stop()
 
-    def signal_handler(self):
-        super().signal_handler()
-        if self.table:
-            self.table.sync()
-
 class PRServSingleton(object):
     def __init__(self, dbfile, logfile, host, port, upstream):
         self.dbfile = dbfile
Signature · 1 line
2.34.1
#5 lore raw

PATCH v7 5/8 prserv: avoid possible race condition in database code

In reply to [email protected]

From: Michael Opdenacker <[email protected]>

Remove a possible race condition by allowing a read-only server to create the PR table anyway. This avoids a failure if both a read-only and read-write server try to access an empty database at the same time.

---
 lib/prserv/db.py | 25 +++++++++++--------------
 1 file changed, 11 insertions(+), 14 deletions(-)
lib/prserv/db.py +11 -14
index f430586d73..79c9001bf5 100644
@@ -30,21 +30,18 @@ class PRTable(object):
         self.read_only = read_only
         self.table = table
 
+        # Creating the table even if the server is read-only.
+        # This avoids a race condition if a shared database
+        # is accessed by a read-only server first.
+
         with closing(self.conn.cursor()) as cursor:
-            if self.read_only:
-                table_exists = cursor.execute(
-                            "SELECT count(*) FROM sqlite_master \
-                            WHERE type='table' AND name='%s'" % (self.table))
-                if not table_exists:
-                    raise prserv.NotFoundError
-            else:
-                cursor.execute("CREATE TABLE IF NOT EXISTS %s \
-                            (version TEXT NOT NULL, \
-                            pkgarch TEXT NOT NULL,  \
-                            checksum TEXT NOT NULL, \
-                            value TEXT, \
-                            PRIMARY KEY (version, pkgarch, checksum, value));" % self.table)
-                self.conn.commit()
+            cursor.execute("CREATE TABLE IF NOT EXISTS %s \
+                        (version TEXT NOT NULL, \
+                        pkgarch TEXT NOT NULL,  \
+                        checksum TEXT NOT NULL, \
+                        value TEXT, \
+                        PRIMARY KEY (version, pkgarch, checksum, value));" % self.table)
+            self.conn.commit()
 
     def _extremum_value(self, rows, is_max):
         value = None
Signature · 1 line
2.34.1
#6 lore raw

PATCH v7 6/8 prserv: store_value() improvements

In reply to [email protected]

From: Michael Opdenacker <[email protected]>

Add a test_checksum_value() to test whether a (version, pkgarch, checksum, value) entry already exists in the database.

This is used to protect the store_value() function from an error when trying to store a duplicate entry in the database.

Also check whether the current database is open in read-only mode.

Cc Joshua Watt <[email protected]>
Cc Tim Orling <[email protected]>
Cc Thomas Petazzoni <[email protected]>
---
 lib/prserv/db.py | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)
lib/prserv/db.py +16 -6
index 79c9001bf5..88ed8e2125 100644
@@ -78,6 +78,18 @@ class PRTable(object):
             else:
                 return False
 
+    def test_checksum_value(self, version, pkgarch, checksum, value):
+        """Returns whether the specified value is found in the database for the specified package, architecture and checksum"""
+
+        with closing(self.conn.cursor()) as cursor:
+            data=cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=? and checksum=? and value=?;" % self.table,
+                               (version, pkgarch, checksum, value))
+            row=data.fetchone()
+            if row is not None:
+                return True
+            else:
+                return False
+
     def test_value(self, version, pkgarch, value):
         """Returns whether the specified value is found in the database for the specified package and architecture"""
 
@@ -143,15 +155,13 @@ class PRTable(object):
                 return base + ".0"
 
     def store_value(self, version, pkgarch, checksum, value):
-        """Store new value in the database"""
+        """Store value in the database"""
 
-        with closing(self.conn.cursor()) as cursor:
-            try:
+        if not self.read_only and not self.test_checksum_value(version, pkgarch, checksum, value):
+            with closing(self.conn.cursor()) as cursor:
                 cursor.execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
                            (version, pkgarch, checksum, value))
-            except sqlite3.IntegrityError as exc:
-                logger.error(str(exc))
-            self.conn.commit()
+                self.conn.commit()
 
     def _get_value(self, version, pkgarch, checksum, history):
 
Signature · 1 line
2.34.1
#7 lore raw

PATCH v7 7/8 prserv: import simplification

In reply to [email protected]

From: Michael Opdenacker <[email protected]>

Simplify the importone() hook:
- to make it independent from the "history" mode which is client specific.
- remove the "history" parameter
- we want all values to be imported for binary reproducibility purposes.
- using the store_value() function (which warrants you don't save the same value twice and doesn't write when you're using a read-only server) is enough.

Cc Joshua Watt <[email protected]>
Cc Tim Orling <[email protected]>
Cc Thomas Petazzoni <[email protected]>
---
 lib/prserv/client.py |  4 +--
 lib/prserv/db.py     | 64 +++-----------------------------------------
 lib/prserv/serv.py   |  3 +--
 3 files changed, 6 insertions(+), 65 deletions(-)
lib/prserv/client.py +2 -2
index 565c6f3872..9f5794c433 100644
@@ -42,9 +42,9 @@ class PRAsyncClient(bb.asyncrpc.AsyncClient):
         if response:
             return response["value"]
 
-    async def importone(self, version, pkgarch, checksum, value, history=False):
+    async def importone(self, version, pkgarch, checksum, value):
         response = await self.invoke(
-            {"import-one": {"version": version, "pkgarch": pkgarch, "checksum": checksum, "value": value, "history": history}}
+            {"import-one": {"version": version, "pkgarch": pkgarch, "checksum": checksum, "value": value}}
         )
         if response:
             return response["value"]
lib/prserv/db.py +3 -61

70 lines not on this page · raw message

lib/prserv/serv.py +1 -2
index 3992056f88..e175886308 100644
@@ -179,9 +179,8 @@ class PRServerClient(bb.asyncrpc.AsyncServerConnection):
             pkgarch = request["pkgarch"]
             checksum = request["checksum"]
             value = request["value"]
-            history = request["history"]
 
-            value = self.server.table.importone(version, pkgarch, checksum, value, history)
+            value = self.server.table.importone(version, pkgarch, checksum, value)
             if value is not None:
                 response = {"value": value}
 
Signature · 1 line
2.34.1
#8 lore raw

PATCH v7 8/8 prserv: add bitbake selftests

In reply to [email protected]

From: Michael Opdenacker <[email protected]>

Run them with "bitbake-selftest prserv.tests"

Cc Joshua Watt <[email protected]>
Cc Tim Orling <[email protected]>
Cc Thomas Petazzoni <[email protected]>
---
 bin/bitbake-selftest |   2 +
 lib/prserv/tests.py  | 386 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 388 insertions(+)
 create mode 100644 bitbake/lib/prserv/tests.py
bin/bitbake-selftest +2 -0
index f25f23b1ae..ce901232fe 100755
@@ -15,6 +15,7 @@ import unittest
 try:
     import bb
     import hashserv
+    import prserv
     import layerindexlib
 except RuntimeError as exc:
     sys.exit(str(exc))
@@ -33,6 +34,7 @@ tests = ["bb.tests.codeparser",
          "bb.tests.utils",
          "bb.tests.compression",
          "hashserv.tests",
+         "prserv.tests",
          "layerindexlib.tests.layerindexobj",
          "layerindexlib.tests.restapi",
          "layerindexlib.tests.cooker"]
lib/prserv/tests.py new file +386 -0

386 lines not on this page · raw message

Signature · 1 line
2.34.1