Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
282 lines (224 loc) · 9.69 KB
/
Copy pathutils.py
File metadata and controls
282 lines (224 loc) · 9.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""CPU/priority helpers using direct syscalls where possible."""
from __future__ import annotations
import os
import subprocess
import logging
log = logging.getLogger(__name__)
def get_process_tids(pid: int) -> list[int]:
"""Return all thread IDs for a process (including the main thread).
Games like attila.exe have 70+ threads each with their own Linux TID.
Setting affinity on only the main PID leaves all other threads unrestricted."""
task_dir = f"/proc/{pid}/task"
try:
return [int(t) for t in os.listdir(task_dir)]
except OSError:
return []
def cpulist_to_set(cpulist: str) -> set[int]:
"""Parse '0-7,16-23' → {0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23}."""
result = set()
for part in cpulist.strip().split(","):
part = part.strip()
if not part:
continue
if "-" in part:
lo, hi = part.split("-", 1)
result.update(range(int(lo.strip()), int(hi.strip()) + 1))
else:
result.add(int(part))
return result
def cpulist_to_online_set(cpulist: str) -> set[int]:
"""Parse an affinity and restrict it to CPUs currently online."""
return cpulist_to_set(cpulist) & get_online_cpus()
def _online_affinity(cpus: set[int]) -> set[int]:
"""Restrict an affinity target to CPUs that can currently accept work."""
return set(cpus) & get_online_cpus()
def _set_thread_affinity_set(tid: int, cpus: set[int]) -> bool:
"""Single low-level process/thread affinity write boundary."""
try:
os.sched_setaffinity(tid, cpus)
return True
except (PermissionError, ProcessLookupError, OSError) as exc:
log.debug("sched_setaffinity tid=%d: %s", tid, exc)
return False
def get_thread_affinity_set(tid: int) -> set[int] | None:
"""Read one live thread mask, returning None when the thread is unavailable."""
try:
return set(os.sched_getaffinity(tid))
except (PermissionError, ProcessLookupError, OSError):
return None
def set_process_affinity_set(pid: int, cpus: set[int]) -> bool:
"""Apply and verify one exact online mask on every live process thread.
A second bounded pass catches threads created during the first pass. TIDs
that disappear while the operation is in flight are not treated as live
failures, but every thread still present must read back the requested mask.
"""
cpuset = _online_affinity(cpus)
if not cpuset:
log.debug("set_process_affinity_set: no requested CPUs are currently online")
return False
pending = set(get_process_tids(pid))
if not pending:
return False
successful_writes = 0
vanished: set[int] = set()
for _attempt in range(2):
for tid in sorted(pending):
if _set_thread_affinity_set(tid, cpuset):
successful_writes += 1
observed = set(get_process_tids(pid))
mismatched = {
tid for tid in observed
if get_thread_affinity_set(tid) != cpuset
}
live_after_reads = set(get_process_tids(pid))
vanished.update(pending - live_after_reads)
# Discard read failures for threads that vanished, and schedule threads
# created during verification for the next bounded pass.
pending = (
(mismatched & live_after_reads)
| (live_after_reads - observed)
)
if live_after_reads and not pending:
log.debug(
"affinity pid=%d cpulist=%s: verified; writes=%d vanished=%d",
pid, _cpuset_to_cpulist(cpuset), successful_writes, len(vanished),
)
return True
log.warning(
"affinity pid=%d cpulist=%s: %d live thread(s) failed verification",
pid, _cpuset_to_cpulist(cpuset), len(pending),
)
return False
def set_affinity(pid: int, cpulist: str) -> bool:
"""Parse, apply, and verify one exact mask on all live process threads."""
try:
cpuset = cpulist_to_set(cpulist)
except ValueError as exc:
log.warning("set_affinity: bad cpulist %r: %s", cpulist, exc)
return False
return set_process_affinity_set(pid, cpuset)
def set_thread_affinity_set(tid: int, cpus: set[int]) -> bool:
"""Apply one exact online mask to a single thread."""
cpuset = _online_affinity(cpus)
if not cpuset:
log.debug("set_thread_affinity_set: no requested CPUs are currently online")
return False
return _set_thread_affinity_set(tid, cpuset)
def set_thread_affinity(tid: int, cpulist: str) -> bool:
"""Parse and apply CPU affinity to one thread."""
try:
cpuset = cpulist_to_set(cpulist)
except ValueError as exc:
log.warning("set_thread_affinity: bad cpulist %r: %s", cpulist, exc)
return False
return set_thread_affinity_set(tid, cpuset)
def get_affinity_str(pid: int) -> str:
"""Read current affinity of main thread, return as cpulist string."""
cpuset = get_thread_affinity_set(pid)
return _cpuset_to_cpulist(cpuset) if cpuset else ""
def get_aggregate_affinity_str(pid: int, fallback: str = "") -> str:
"""Return the union of the live affinity masks for every process thread."""
aggregate: set[int] = set()
for tid in get_process_tids(pid):
affinity = get_thread_affinity_set(tid)
if affinity is None:
# A thread may exit between listing /proc/<pid>/task and this read.
continue
aggregate.update(affinity)
return _cpuset_to_cpulist(aggregate) if aggregate else fallback
def _cpuset_to_cpulist(cpus: set[int]) -> str:
"""Convert {0,1,2,3,5} → '0-3,5'."""
if not cpus:
return ""
sorted_cpus = sorted(cpus)
ranges = []
start = sorted_cpus[0]
end = sorted_cpus[0]
for c in sorted_cpus[1:]:
if c == end + 1:
end = c
else:
ranges.append(f"{start}-{end}" if start != end else str(start))
start = end = c
ranges.append(f"{start}-{end}" if start != end else str(start))
return ",".join(ranges)
def _set_thread_nice_batch(tids: list[int], nice: int) -> set[int]:
"""Single low-level niceness write boundary for process and thread callers."""
tids = sorted(set(tids))
if not tids or any(tid <= 0 for tid in tids) or not -20 <= nice <= 19:
log.debug("invalid niceness request tids=%s nice=%s", tids, nice)
return set()
if nice < 0:
import nice_helper
return nice_helper.set_negative_nice_threads(tids, nice)
try:
result = subprocess.run(
["renice", "-n", str(nice), "-p", *map(str, tids)],
capture_output=True,
text=True,
timeout=5,
)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as exc:
log.warning("renice nice=%d failed: %s", nice, exc)
return set()
if result.returncode == 0:
log.debug("renice nice=%d: applied to %d thread(s)", nice, len(tids))
return set(tids)
log.warning("renice nice=%d failed: %s", nice, result.stderr.strip())
return set()
def set_process_nice(pid: int, nice: int) -> bool:
"""Apply one exact nice value to every currently visible process thread."""
return bool(_set_thread_nice_batch(get_process_tids(pid), nice))
def set_nice(pid: int, nice: int) -> bool:
"""Compatibility adapter for applying process-wide niceness."""
return set_process_nice(pid, nice)
def set_thread_nice(tid: int, nice: int) -> bool:
"""Apply one exact nice value to a single thread."""
return tid in _set_thread_nice_batch([tid], nice)
def get_thread_nice(tid: int) -> int:
"""Read one live thread's nice value."""
return os.getpriority(os.PRIO_PROCESS, tid)
def set_nice_threads(tids: list[int], nice: int) -> set[int]:
"""Compatibility adapter for a thread batch, returning successful TIDs."""
return _set_thread_nice_batch(tids, nice)
def set_ionice(pid: int, ionice_class: int, ionice_level: int | None = None) -> bool:
"""Set I/O priority via ionice.
class: 1=realtime, 2=best-effort, 3=idle
level: 0-7 (only for classes 1 and 2)
Returns True on success."""
try:
cmd = ["ionice", "-c", str(ionice_class)]
if ionice_level is not None and ionice_class in (1, 2):
cmd += ["-n", str(ionice_level)]
cmd += ["-p", str(pid)]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
if result.returncode == 0:
log.debug("ionice pid=%d class=%d level=%s: OK", pid, ionice_class, ionice_level)
return True
log.warning("ionice pid=%d class=%d failed: %s", pid, ionice_class, result.stderr.strip())
return False
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
log.warning("ionice error pid=%d: %s", pid, e)
return False
def get_online_cpus() -> set[int]:
"""Compatibility wrapper; CPU discovery is centralized in cpu_tools."""
import cpu_tools
return cpu_tools.get_cpu_info().online
def get_cpu_count() -> int:
"""Return total number of logical CPUs, including any currently offline ones.
Uses /sys/devices/system/cpu/present instead of os.cpu_count() because
os.cpu_count() may omit offline CPUs, which breaks affinity validation."""
import cpu_tools
return cpu_tools.get_cpu_info().cpu_count
def validate_cpulist(cpulist: str) -> bool:
"""Check that cpulist string is valid (e.g. '0-3,5,7')."""
if not cpulist or not cpulist.strip():
return False
max_cpu = get_cpu_count() - 1
try:
cpus = cpulist_to_set(cpulist)
except ValueError:
return False
if not cpus:
return False
return all(0 <= c <= max_cpu for c in cpus)