[projects/pld-ftp-admin] pfa-genindex: add -j to build several trees and archs at once

arekm arekm at pld-linux.org
Tue Oct 27 10:56:22 CET 2026


commit e9b760933e4f7182c30657af23ffaf6793f6e3d2
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Tue Oct 27 00:32:50 2026 +0100

    pfa-genindex: add -j to build several trees and archs at once
    
    The trees and archs were indexed one after another.  -j N builds up to N
    of them at once, by default one per 12 CPUs, as createrepo_c runs 12
    workers.  Each line a tool prints on stdout gets its tree and arch as a
    prefix; stderr is passed through as is.  poldek gets a cache directory
    per tree and arch, and a tree named twice (PLD and PLD/, or through a
    symlink) is built once, so no two jobs write the same index.  After
    Ctrl-C no other tool starts, and the trees are unlocked once the running
    ones end, also when Ctrl-C is pressed again.

 bin/pfa-genindex         | 91 +++++++++++++++++++++++++++++++++++++++---------
 shell/bash-completion.sh |  4 ++-
 2 files changed, 77 insertions(+), 18 deletions(-)
---
diff --git a/bin/pfa-genindex b/bin/pfa-genindex
index 2926c22..9851ed1 100755
--- a/bin/pfa-genindex
+++ b/bin/pfa-genindex
@@ -2,9 +2,12 @@
 # vi: ts=8 sts=4 sw=4 et
 
 import argparse
+import concurrent.futures
 import os
+import signal
 import subprocess
 import sys
+import threading
 import time
 
 INDEXES = ('poldek', 'yum')
@@ -19,12 +22,23 @@ def index_list(value):
     return indexes
 
 
+def jobs_count(value):
+    jobs = int(value)
+    if jobs < 1:
+        raise argparse.ArgumentTypeError(f'must be at least 1: {value}')
+    return jobs
+
+
 parser = argparse.ArgumentParser(
     description='Generate poldek indexes and yum/dnf repodata for ftp trees.',
     epilog='examples:\n  %(prog)s PLD\n  %(prog)s --index=poldek PLD test',
     formatter_class=argparse.RawDescriptionHelpFormatter)
 parser.add_argument('-q', '--quiet', action='store_true',
     help='less output; errors are still shown')
+# createrepo_c runs 12 workers, so this keeps them at about one per CPU
+parser.add_argument('-j', '--jobs', type=jobs_count, metavar='N',
+    default=max(1, len(os.sched_getaffinity(0)) // 12),
+    help='build up to N trees and archs at once (default: %(default)s, one per 12 CPUs)')
 # --index and the switches share one list, so they apply in command line order
 parser.add_argument('--index', dest='ops', action='append', type=index_list, metavar='LIST',
     help=f"comma separated index types to generate: {', '.join(INDEXES)} (default: {','.join(INDEXES)})")
@@ -67,8 +81,12 @@ from config import all_ftp_archs, ftp_dir
 if not quiet:
     print(f"poldek: {do_poldek}; yum: {do_yum}")
 
+# a tree named twice (PLD and PLD/, or a symlink) would get two jobs writing the same index at once
+named = {}
 for tree in trees:
     checkdir(tree)
+    named.setdefault(os.path.realpath(ftp_dir + tree), tree)
+trees = list(named.values())
 
 ftpio.connect('gen-indexes')
 home = os.environ['HOME']
@@ -76,27 +94,35 @@ home = os.environ['HOME']
 os.umask(0o022)
 os.nice(19)
 
+out = threading.Lock()
+stop = threading.Event()
 failed = []
 
 
-def run(what, argv):
-    # keep building the other indexes; every failure is reported at the end
-    print(' '.join(argv), flush=True)
+def run(prefix, tool, argv):
+    """Runs argv with each line of its stdout prefixed; returns its exit status."""
+    with out:
+        print(prefix + ' '.join(argv), flush=True)
     start = time.monotonic()
     try:
-        rc = subprocess.call(argv)
+        with subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
+                              text=True, errors='replace') as p:
+            for line in p.stdout:
+                with out:
+                    print(prefix + line.rstrip('\n'), flush=True)
     except OSError as e:
         # what the shell reported as "not found" before
-        print(f'{what}: {e}', file=sys.stderr)
-        rc = 127
+        with out:
+            print(f'{prefix}{tool}: {e}', file=sys.stderr, flush=True)
+        return 127
     if not quiet:
-        print(f'{what}: {time.monotonic() - start:.1f}s', flush=True)
-    if rc != 0:
-        failed.append(f'{what} exited with {rc}')
+        with out:
+            print(f'{prefix}{tool}: {time.monotonic() - start:.1f}s', flush=True)
+    return p.returncode
 
 
 comps_file = f'{ftp_dir}.stat/repodata/comps.xml'
-poldek = [f'{ftp_dir}.stat/bin/poldek-new', f'--cachedir={home}/tmp/poldek', '--conf', f'{ftp_dir}.stat/etc/poldek.conf', '--mkidxz']
+poldek = f'{ftp_dir}.stat/bin/poldek-new'
 yum = [f'{ftp_dir}.stat/bin/createrepo_c', '--database', '--update', '--skip-stat', '--workers=12', '--xz', f'--groupfile={comps_file}']
 
 
@@ -105,14 +131,31 @@ def build(tree, arch):
 
     poldek goes first, as the freshness check of the repodata reads its index.
     """
+    prefix = f'[{tree}/{arch}] '
+
+    def step(tool, argv):
+        # no new tool after an interrupt; a tool killed by a signal was interrupted too
+        if stop.is_set():
+            return False
+        rc = run(prefix, tool, argv)
+        if rc != 0:
+            failed.append(f'{tree}/{arch}: {tool} exited with {rc}')
+        return rc >= 0
+
     archdir = f'{ftp_dir}{tree}/{arch}'
     dirs = ['RPMS']
     if arch != 'noarch' and config.separate_debuginfo:
         dirs.append('debuginfo')
 
     if do_poldek:
+        # a cache of its own, as jobs run at once; the tree lock keeps other processes out of it
+        cachedir = f'{home}/tmp/poldek/{tree}-{arch}'
+        # poldek mkdirs only the last component of --cachedir
+        os.makedirs(os.path.dirname(cachedir), mode=0o711, exist_ok=True)
         for d in dirs:
-            run(f'{tree}/{arch}: poldek', poldek + ['-s', f'{archdir}/{d}/', '--mkidxz', '--mkidx-type', 'pndir'])
+            if not step('poldek', [poldek, f'--cachedir={cachedir}', '--conf', f'{ftp_dir}.stat/etc/poldek.conf',
+                                   '--mkidxz', '-s', f'{archdir}/{d}/', '--mkidxz', '--mkidx-type', 'pndir']):
+                return
 
     if do_yum:
         poldek_idx = f'{archdir}/RPMS/packages.ndir.md'
@@ -120,16 +163,19 @@ def build(tree, arch):
         if freshen and os.path.exists(poldek_idx) and os.path.exists(repodata_idx) \
             and not os.path.getmtime(comps_file) > os.path.getmtime(repodata_idx) \
             and not os.path.getmtime(poldek_idx) > os.path.getmtime(repodata_idx):
-            print(f'{tree}/{arch}: repodata indexes already fresh')
+            with out:
+                print(f'{prefix}repodata indexes already fresh', flush=True)
             return
         cachedir = f'{home}/tmp/createrepo/{tree}-{arch}'
         # createrepo_c mkdirs only the last component of --cachedir
         os.makedirs(os.path.dirname(cachedir), mode=0o711, exist_ok=True)
         for d in dirs:
-            run(f'{tree}/{arch}: createrepo_c', yum + [f'--cachedir={cachedir}', f'{archdir}/{d}'])
+            if not step('createrepo_c', yum + [f'--cachedir={cachedir}', f'{archdir}/{d}']):
+                return
 
 
 locked = []
+pool = concurrent.futures.ThreadPoolExecutor(args.jobs)
 try:
     for tree in trees:
         if not ftpio.lock(tree, True):
@@ -137,11 +183,22 @@ try:
             sys.exit(1)
         locked.append(tree)
     if do_yum:
-        run('comps.xml checkout', ['git', '-C', f'{ftp_dir}.stat/repodata', 'checkout'] + (['--quiet'] if quiet else []) + ['HEAD', 'repodata/comps.xml'])
-    for tree in trees:
-        for arch in all_ftp_archs:
-            build(tree, arch)
+        # in the pool too, as only the pool waits for its tools after Ctrl-C
+        rc = pool.submit(run, '', 'comps.xml checkout', ['git', '-C', f'{ftp_dir}.stat/repodata', 'checkout']
+                         + (['--quiet'] if quiet else []) + ['HEAD', 'repodata/comps.xml']).result()
+        if rc != 0:
+            failed.append(f'comps.xml checkout exited with {rc}')
+    jobs = [pool.submit(build, tree, arch) for tree in trees for arch in all_ftp_archs]
+    for job in jobs:
+        job.result()
+except KeyboardInterrupt:
+    failed.append('interrupted')
 finally:
+    # a second Ctrl-C must not skip the unlock; the running tools got it already
+    signal.signal(signal.SIGINT, signal.SIG_IGN)
+    # start no new tool, and wait for the running ones before unlocking the trees
+    stop.set()
+    pool.shutdown(cancel_futures=True)
     # ftpiod drops a lock whoever asks, so only ours
     for tree in locked:
         ftpio.unlock(tree)
diff --git a/shell/bash-completion.sh b/shell/bash-completion.sh
index 0af06d4..cce9928 100644
--- a/shell/bash-completion.sh
+++ b/shell/bash-completion.sh
@@ -43,9 +43,11 @@ _pfa-genindex()
 
     if [[ "$prev" == --index ]]; then
         COMPREPLY=( $( compgen -W 'poldek yum' -- "$cur" ) )
+    elif [[ "$prev" == -j || "$prev" == --jobs ]]; then
+        return
     elif [[ "$cur" == -* ]]; then
         COMPREPLY=( $( compgen -W '\
-            -h --help -q --quiet --index \
+            -h --help -q --quiet -j --jobs --index \
             --nopoldek --noyum \
             --poldek --yum \
             ' \
================================================================

---- gitweb:

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



More information about the pld-cvs-commit mailing list