[projects/pld-ftp-admin] ftptree: read each rpm header once, in parallel, when checking a move

arekm arekm at pld-linux.org
Tue Oct 27 23:50:34 CET 2026


commit 06017a75d5c29d5438b731cf932d426f07e0b4fb
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Tue Oct 27 14:46:34 2026 +0100

    ftptree: read each rpm header once, in parallel, when checking a move
    
    The signature and obsoletes checks of a move each read the header of
    every rpm file of the moved packages, with a new rpm transaction set per
    file: 13214 reads and 265 s of a 531 s pfa-testmvpkg run.  The headers
    are now read once, by a pool of processes with one transaction set each,
    as many as there are CPUs or chunks of 16 files.  A test of 6006 files
    went from 23 s to 0.6 s here.
    
    The pool forks, as under spawn or forkserver, the default from Python
    3.14, the scripts would run again in each process.  An rpm file listed
    for a package but missing now counts as not signed, instead of stopping
    the check with a traceback.

 modules/ftptree.py | 108 +++++++++++++++++++++++++++++++++--------------------
 1 file changed, 68 insertions(+), 40 deletions(-)
---
diff --git a/modules/ftptree.py b/modules/ftptree.py
index 4775cab..f326211 100644
--- a/modules/ftptree.py
+++ b/modules/ftptree.py
@@ -1,18 +1,49 @@
 # vi: ts=8 sts=4 sw=4 et
 
+import collections
+import concurrent.futures
+import multiprocessing
 import os
 import re
+import signal
 import urllib.request
 
 import config
 import rpm
 from baseftptree import BaseFtpTree, BasePkg
 from common import fileexists, noarchcachedir
-from sign import is_signed
+from sign import signed_by_key
 
 errnum = 0
 quietmode = False
 
+# what the move checks take from an rpm header; error is set when rpm refused to read it
+RpmInfo = collections.namedtuple('RpmInfo', 'signed name obsoletes error')
+# files a process of the header pool reads per task
+READ_CHUNK = 16
+# the transaction set of a process of the header pool
+_ts = None
+
+def _start_reader():
+    global _ts
+    # Ctrl-C is for the script: a process stopped by it while holding a lock of the pool queues hangs the rest
+    signal.signal(signal.SIGINT, signal.SIG_IGN)
+    _ts = rpm.ts()
+    _ts.setVSFlags(rpm.RPMVSF_NODSAHEADER)
+
+def _read_rpm(path):
+    """RpmInfo of the rpm file at path, or None when there is no such file"""
+    if not os.path.exists(path):
+        return None
+    fdno = os.open(path, os.O_RDONLY)
+    try:
+        hdr = _ts.hdrFromFdno(fdno)
+    except rpm.error as e:
+        return RpmInfo(signed_by_key(None), None, [], f"{path}: {e}")
+    finally:
+        os.close(fdno)
+    return RpmInfo(signed_by_key(hdr), hdr[rpm.RPMTAG_NAME], list(hdr[rpm.RPMTAG_OBSOLETES]), None)
+
 class SomeError(Exception):
     def __init__(self):
         return
@@ -186,41 +217,6 @@ class Pkg(BasePkg):
                         files.append(self.tree.basedir + '/' + arch + '/RPMS/' + nvr)
         return files
 
-    def obsoletes(self):
-        """
-        Return obsoletes for all packages in Pkg:
-
-        {'php-geshi': set(['geshi'])}
-
-        """
-        def rpmhdr(pkg):
-            try:
-                ts = rpm.ts()
-                ts.setVSFlags(rpm.RPMVSF_NODSAHEADER)
-                fdno = os.open(pkg, os.O_RDONLY)
-                hdr = ts.hdrFromFdno(fdno)
-                os.close(fdno)
-            except rpm.error as e:
-                raise rpm.error(f"{pkg}: {e}")
-            return hdr
-
-        obsoletes = {}
-        for rpmfile in self.rpmfiles():
-            if not os.path.exists(rpmfile):
-                continue
-            hdr = rpmhdr(rpmfile)
-            if not hdr[rpm.RPMTAG_OBSOLETES]:
-                continue
-
-            name = hdr[rpm.RPMTAG_NAME]
-            if not name in obsoletes:
-                obsoletes[name] = set()
-
-            for tag in hdr[rpm.RPMTAG_OBSOLETES]:
-                obsoletes[name].add(tag)
-
-        return obsoletes
-
     def move(self, dsttree, test = False):
         if dsttree.has_key(self.nvr):
             movedany = False
@@ -267,6 +263,8 @@ class FtpTree(BaseFtpTree):
         self.marked4removal = []
         self.marked4moving = []
         self.pkgnames = []
+        # file -> RpmInfo, so each rpm header is read once
+        self.__rpmcache = {}
         self.__loadpkgnames()
         if loadall:
             for pkgname in self.pkgnames:
@@ -497,6 +495,25 @@ class FtpTree(BaseFtpTree):
             return rc == 1 # pkg > x
         return list(filter(filter_older_pkgs, self.__find_other_pkgs(pkg, self)))
 
+    def __rpminfo(self, pkgs):
+        """RpmInfo of every rpm file of pkgs (None for a missing one), read in parallel"""
+        todo = [f for f in dict.fromkeys(f for pkg in pkgs for f in pkg.rpmfiles()) if f not in self.__rpmcache]
+        if todo:
+            # with fork the pool starts all its processes at once, so no more than there are tasks
+            workers = min(len(os.sched_getaffinity(0)), -(-len(todo) // READ_CHUNK))
+            try:
+                # not spawn or forkserver: the scripts have no __main__ guard, so they would run again
+                with concurrent.futures.ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context('fork'),
+                                                            initializer=_start_reader) as pool:
+                    self.__rpmcache.update(zip(todo, pool.map(_read_rpm, todo, chunksize=READ_CHUNK)))
+            finally:
+                # a pool stopped while it starts (Ctrl-C, no room for more processes) leaves the
+                # processes it started waiting for work, and the exit waiting for them
+                for p in multiprocessing.active_children():
+                    p.terminate()
+                    p.join()
+        return self.__rpmcache
+
     def __checksigns(self, tree, pkgs, test = False):
         """
         Checks if pkgs in tree are all signed.
@@ -506,10 +523,14 @@ class FtpTree(BaseFtpTree):
         if not tree.treename in config.signed_trees:
             return
 
+        # with no sign_key no file is signed by it, so nothing to read
+        info = {} if config.sign_key == None else self.__rpminfo(pkgs)
         for pkg in pkgs:
             unsigned = 0
             for file in pkg.rpmfiles():
-                if not is_signed(file):
+                r = info.get(file)
+                # a missing file counts as not signed
+                if r is None or not r.signed:
                     unsigned += 1
 
             if unsigned != 0:
@@ -534,10 +555,17 @@ class FtpTree(BaseFtpTree):
         for nvr in tree.pkgnames:
             byname.setdefault('-'.join(nvr.split('-')[:-2]), []).append(nvr)
 
+        info = self.__rpminfo(pkgs)
         for pkg in pkgs:
-            obsoletes = pkg.obsoletes()
-            if not obsoletes:
-                continue
+            # {'php-geshi': {'geshi'}}: the names each rpm of pkg obsoletes, by its name
+            obsoletes = {}
+            for file in pkg.rpmfiles():
+                if info[file] is None:
+                    continue
+                if info[file].error:
+                    raise rpm.error(info[file].error)
+                if info[file].obsoletes:
+                    obsoletes.setdefault(info[file].name, set()).update(info[file].obsoletes)
 
             for pn, setlist in obsoletes.items():
                 for item in setlist:
================================================================

---- gitweb:

http://git.pld-linux.org/gitweb.cgi/projects/pld-ftp-admin.git/commitdiff/dcb7070978482eea3347fd0bed77fd94e0d0de4e



More information about the pld-cvs-commit mailing list