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); $nodeIds = array_keys($nodes);
$nodeCount = count($nodeIds); $nodeCount = count($nodeIds); // ✅ calculated BEFORE processing
if ($nodeCount === 0) {
return ["node" => 0, "cpu" => 0];
}
/* Alternate NUMA nodes */
$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;
$node = $nodeIds[$nodePos];
/* Per-node CPU index */
$cpuIndex = intdiv($index, $nodeCount);
/* Wrap safely if CPUs exhausted */
if (!isset($nodes[$node][$cpuIndex])) {
$cpuIndex = $cpuIndex % count($nodes[$node]);
}
$cpu = $nodes[$node][$cpuIndex];
$map[$serviceId] = [ $map[$serviceId] = [
"node" => $node, "node" => $node,
"cpu" => $cpu "cpu" => $cpu
]; ];
file_put_contents($coreFile, json_encode($map, JSON_PRETTY_PRINT)); file_put_contents($coreFile, json_encode($map, JSON_PRETTY_PRINT));
return $map[$serviceId]; return $map[$serviceId];
} }
}
/* Fallback: any free CPU */ /* Free core */
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 */
return ["node" => 0, "cpu" => 0];
}
/* Free core on delete */
function freeCore(int $serviceId): void function freeCore(int $serviceId): void
{ {
global $coreFile; global $coreFile;