This commit is contained in:
devdatt 2026-01-18 13:54:08 +05:30
parent a742846d2a
commit f7963edb2a
1 changed files with 33 additions and 37 deletions

View File

@ -16,63 +16,59 @@ function getNumaTopology(): array
if (preg_match('/node (\d+) cpus:\s+(.*)/', $line, $m)) { if (preg_match('/node (\d+) cpus:\s+(.*)/', $line, $m)) {
$node = (int)$m[1]; $node = (int)$m[1];
$cpus = array_map('intval', preg_split('/\s+/', trim($m[2]))); $cpus = array_map('intval', preg_split('/\s+/', trim($m[2])));
$nodes[$node] = $cpus;
/* use EVEN CPUs only: 0,2,4,... */
$nodes[$node] = array_values(
array_filter($cpus, fn($c) => $c % 2 === 0)
);
} }
} }
ksort($nodes); // ensure deterministic order
return $nodes; return $nodes;
} }
/* Get total CPU cores */ /* Allocate core in strict round-robin */
function getTotalCores(): int
{
return intval(trim(shell_exec("nproc")));
}
/* Allocate next free core */
function allocateCore(int $serviceId): array function allocateCore(int $serviceId): array
{ {
global $coreFile; global $coreFile;
$map = json_decode(file_get_contents($coreFile), true) ?: []; $map = json_decode(file_get_contents($coreFile), true) ?: [];
$usedCores = array_column($map, 'cpu');
$nodes = getNumaTopology(); $nodes = getNumaTopology();
$nodeIds = array_keys($nodes);
$nodeCount = count($nodeIds);
/* Alternate NUMA nodes */ $nodeIds = array_keys($nodes);
$nodeCount = count($nodeIds); // ✅ calculated BEFORE processing
if ($nodeCount === 0) {
return ["node" => 0, "cpu" => 0];
}
$index = count($map); $index = count($map);
$node = $nodeIds[$index % $nodeCount];
foreach ($nodes[$node] as $cpu) { /* Round-robin node selection */
if (!in_array($cpu, $usedCores, true)) { $nodePos = $index % $nodeCount;
$map[$serviceId] = [ $node = $nodeIds[$nodePos];
"node" => $node,
"cpu" => $cpu /* Per-node CPU index */
]; $cpuIndex = intdiv($index, $nodeCount);
file_put_contents($coreFile, json_encode($map, JSON_PRETTY_PRINT));
return $map[$serviceId]; /* Wrap safely if CPUs exhausted */
} if (!isset($nodes[$node][$cpuIndex])) {
$cpuIndex = $cpuIndex % count($nodes[$node]);
} }
/* Fallback: any free CPU */ $cpu = $nodes[$node][$cpuIndex];
foreach ($nodes as $n => $cpus) {
foreach ($cpus as $cpu) {
if (!in_array($cpu, $usedCores, true)) {
$map[$serviceId] = ["node" => $n, "cpu" => $cpu];
file_put_contents($coreFile, json_encode($map, JSON_PRETTY_PRINT));
return $map[$serviceId];
}
}
}
/* Absolute fallback */ $map[$serviceId] = [
return ["node" => 0, "cpu" => 0]; "node" => $node,
"cpu" => $cpu
];
file_put_contents($coreFile, json_encode($map, JSON_PRETTY_PRINT));
return $map[$serviceId];
} }
/* Free core */
/* Free core on delete */
function freeCore(int $serviceId): void function freeCore(int $serviceId): void
{ {
global $coreFile; global $coreFile;