diff mbox series

[v6,5/8] prserv: avoid possible race condition in database code

Message ID 20240430171512.936371-6-michael.opdenacker@bootlin.com
State New
Headers show
Series prserv: add support for an "upstream" server | expand

Commit Message

Michael Opdenacker April 30, 2024, 5:15 p.m. UTC
From: Michael Opdenacker <michael.opdenacker@bootlin.com>

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.

Signed-off-by: Michael Opdenacker <michael.opdenacker@bootlin.com>
Suggested-by: Joshua Watt <jpewhacker@gmail.com>
Cc: Tim Orling <ticotimo@gmail.com>
Cc: Thomas Petazzoni <thomas.petazzoni@bootlin.com>
---
 lib/prserv/db.py | 25 +++++++++++--------------
 1 file changed, 11 insertions(+), 14 deletions(-)
diff mbox series

Patch

diff --git a/lib/prserv/db.py b/lib/prserv/db.py
index f430586d73..79c9001bf5 100644
--- a/lib/prserv/db.py
+++ b/lib/prserv/db.py
@@ -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