okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-142-amd' into f-1425a6ef1d76

main
2.6 KiB68 linesraw
1"""Split a launcher's allowed physical cores between independent Linux instances."""
2from __future__ import annotations
3
4import argparse
5import os
6from pathlib import Path
7import sys
8
9
10def partition_cpu_sets(count: int, allowed: set[int], reserved: set[int] | None = None,
11                       sys_root: Path = Path("/sys")) -> list[list[int]]:
12    if count < 1:
13        raise ValueError("the instance count must be positive")
14    if not allowed:
15        raise ValueError("no CPUs are allowed for this launcher")
16    if count == 1 and not reserved:
17        return [sorted(allowed)]
18    cores: dict[tuple[int, int], list[int]] = {}
19    occupied: set[tuple[int, int]] = set()
20    for cpu in sorted(allowed | (reserved or set())):
21        topology = sys_root / "devices/system/cpu" / f"cpu{cpu}" / "topology"
22        try:
23            key = (int((topology / "physical_package_id").read_text()),
24                   int((topology / "core_id").read_text()))
25        except (OSError, ValueError) as error:
26            raise ValueError(f"cannot read physical-core topology for CPU {cpu}: {error}") from error
27        if cpu in allowed:
28            cores.setdefault(key, []).append(cpu)
29        if reserved and cpu in reserved:
30            occupied.add(key)
31    available = sorted((cpus for key, cpus in cores.items() if key not in occupied), key=min)
32    if len(available) < count:
33        raise ValueError(
34            f"{count} instances need at least {count} free physical cores, but only {len(available)} "
35            "are available; restart the managed instances together or expand the launcher's CPU set"
36        )
37    size, extra = divmod(len(available), count)
38    result, start = [], 0
39    for index in range(count):
40        end = start + size + (index < extra)
41        result.append(sorted(cpu for siblings in available[start:end] for cpu in siblings))
42        start = end
43    return result
44
45
46def main() -> int:
47    parser = argparse.ArgumentParser(description=__doc__)
48    parser.add_argument("instances", type=int)
49    parser.add_argument("--exclude-pid", type=int, action="append", default=[])
50    options = parser.parse_args()
51    try:
52        reserved: set[int] = set()
53        for pid in options.exclude_pid:
54            try:
55                reserved.update(os.sched_getaffinity(pid))
56            except ProcessLookupError:
57                continue
58        groups = partition_cpu_sets(options.instances, os.sched_getaffinity(0), reserved)
59    except (OSError, ValueError) as error:
60        print(f"CPU affinity: {error}", file=sys.stderr)
61        return 1
62    for group in groups:
63        print(",".join(str(cpu) for cpu in group))
64    return 0
65
66
67if __name__ == "__main__":
68    raise SystemExit(main())