Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,9 @@ kerf exec -u nobody web-server id
kerf show
kerf show web-server

# List the CPUs with the physical IDs that --cpus takes, and who holds each
kerf cpus

# Dump the device tree the kernel holds: DTB to replay, --dts to read
kerf dump -o host.dtb
kerf dump web-server -o web.dtb
Expand Down Expand Up @@ -368,6 +371,10 @@ pip install -e .
kerf --help
kerf init --help

# Find the physical IDs of the CPUs to hand over. On arm64 they are MPIDRs,
# written in hex: --cpus=0x100-0x103 takes the CPUs that exist in that range
kerf cpus

# Carve a pool out of the host: 7 CPUs (by APIC ID) and 1GB on their NUMA node
sudo kerf init --cpus=128-134 --memory=1GB --report
```
Expand Down
2 changes: 2 additions & 0 deletions src/kerf/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from .unload.main import unload
from .delete.main import delete
from .show.main import show
from .cpus.main import cpus
from .dump.main import dump
from .console.main import console
from .sign.main import sign
Expand All @@ -53,6 +54,7 @@ def main(ctx, debug):
main.add_command(unload)
main.add_command(delete)
main.add_command(show)
main.add_command(cpus)
main.add_command(dump)
main.add_command(console)
main.add_command(sign)
Expand Down
19 changes: 19 additions & 0 deletions src/kerf/cpus/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright 2026 Multikernel Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""List the CPUs of the machine by the physical IDs kerf names them by."""

from .main import cpus

__all__ = ["cpus"]
157 changes: 157 additions & 0 deletions src/kerf/cpus/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# Copyright 2026 Multikernel Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""List the CPUs of the machine by the physical IDs kerf names them by."""

from dataclasses import dataclass
from typing import Dict, List, Optional

import click

from ..baseline import BaselineManager
from ..exceptions import KernelInterfaceError, ParseError
from ..init.main import list_instance_names, pool_is_live, read_current_pool
from ..models import GlobalDeviceTree
from ..runtime import DeviceTreeManager
from ..topology import cpu_id_name, cpu_numa_nodes, format_cpu_id, logical_to_physical

UNKNOWN = "-"


@dataclass(frozen=True)
class CpuRow:
"""One CPU of the machine, as kerf cpus lists it."""

physical: int
logical: Optional[int]
node: Optional[int]
kind: Optional[int]
state: str


def instance_cpus() -> Dict[int, str]:
"""Map each CPU an instance holds to the name of that instance."""
manager = DeviceTreeManager()
owners: Dict[int, str] = {}
for name in list_instance_names():
try:
instance = manager.read_instance(name)
except (KernelInterfaceError, ParseError):
continue
for cpu in instance.resources.cpus:
owners[cpu] = name
return owners


def cpu_rows(
physical_of: Dict[int, int],
nodes: Dict[int, int],
pool: Optional[GlobalDeviceTree],
owners: Dict[int, str],
) -> List[CpuRow]:
"""
Describe every CPU the host or the pool knows of.

Args:
physical_of: Logical CPU number to physical ID, as the host reports it
nodes: Physical ID to NUMA node
pool: The live pool, or None if there is none
owners: Physical ID to the instance that holds the CPU

Returns:
One row per CPU: the host's in logical order, then the pool CPUs
the host no longer reports
"""
logical_of = {physical: logical for logical, physical in physical_of.items()}
boot_cpu = physical_of.get(0)
pool_cpus = pool.hardware.cpus if pool else None
in_pool = set(pool_cpus.available) | set(pool_cpus.unclaimed) if pool_cpus else set()
unclaimed = set(pool_cpus.unclaimed) if pool_cpus else set()
kinds = pool_cpus.kinds if pool_cpus else {}

def state(cpu: int) -> str:
if cpu in owners:
return owners[cpu]
if cpu in unclaimed:
return "pool (unclaimed)"
if cpu in in_pool:
return "pool"
return "host (boot)" if cpu == boot_cpu else "host"

# A pool CPU without a logical number sorts behind the ones that have one.
def position(cpu: int):
return (cpu not in logical_of, logical_of.get(cpu, cpu))

return [
CpuRow(
physical=cpu,
logical=logical_of.get(cpu),
node=nodes.get(cpu),
kind=kinds.get(cpu),
state=state(cpu),
)
for cpu in sorted(set(logical_of) | in_pool, key=position)
]


def render(rows: List[CpuRow]) -> str:
"""Lay the rows out as a table, with a KIND column where CPUs differ."""
def cell(value: Optional[int]) -> str:
return UNKNOWN if value is None else str(value)

with_kinds = any(row.kind is not None for row in rows)
table = [["CPU", cpu_id_name().upper(), "NODE"] + (["KIND"] if with_kinds else []) + ["STATE"]]
for row in rows:
table.append(
[cell(row.logical), format_cpu_id(row.physical), cell(row.node)]
+ ([cell(row.kind)] if with_kinds else [])
+ [row.state]
)

widths = [max(len(line[column]) for line in table) for column in range(len(table[0]))]
return "\n".join(
" ".join(text.ljust(width) for text, width in zip(line, widths)).rstrip()
for line in table
)


@click.command(name="cpus")
def cpus():
"""
List the CPUs of this machine and the physical IDs that name them.

--cpus takes physical CPU IDs, the APIC ID on x86 or the MPIDR on
arm64, which are the same in every kernel on the machine. This lists
them next to the logical CPU numbers of the host, with the NUMA node
of each CPU and who holds it: the host, the pool, or an instance.

A CPU the host gave away may have no logical number or node left to
show, which reads as "-".

Examples:

\b
kerf cpus
"""
pool = read_current_pool(BaselineManager())
if not pool_is_live(pool):
pool = None

rows = cpu_rows(logical_to_physical(), cpu_numa_nodes(), pool, instance_cpus() if pool else {})
if not rows:
raise click.ClickException(
"Could not read the physical CPU IDs (APIC ids from /proc/cpuinfo, "
"or MPIDRs from /sys/devices/system/cpu on arm64)."
)
click.echo(render(rows))
86 changes: 53 additions & 33 deletions src/kerf/create/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import sys
import traceback
from pathlib import Path
from typing import List, Optional
from typing import Iterable, List, Optional, Tuple
import click

from ..runtime import DeviceTreeManager
Expand All @@ -33,61 +33,81 @@
from ..resources import (
validate_cpu_allocation,
get_available_cpus,
known_cpu_ids,
)
from ..exceptions import ValidationError, KernelInterfaceError, ResourceError, ParseError
from ..topology import cpu_id_name
from ..topology import cpu_id_name, format_cpu_id


def parse_cpu_spec(cpu_spec: str) -> List[int]:
def parse_cpu_id(text: str) -> int:
"""Parse one physical CPU ID, decimal or 0x-prefixed hex."""
text = text.strip()
if text.lower().startswith("0x"):
return int(text, 16)
return int(text)


def parse_cpu_ranges(cpu_spec: str) -> List[Tuple[int, int]]:
"""
Parse CPU specification string into explicit CPU IDs.
Parse a CPU specification into the ranges it spells.

Supports formats:
- "4" (single CPU ID 4)
- "4-7" (range of CPUs: 4, 5, 6, 7)
- "4" or "0x100" (single CPU ID)
- "4-7" or "0x100-0x103" (range of CPUs)
- "4,5,6,7" (comma-separated list)
- "4-7,10-12" (mixed ranges and lists)

Args:
cpu_spec: CPU specification string

Returns:
List of explicit CPU IDs (sorted)
(first, last) per entry, a single CPU being a range of one

Raises:
ValueError: If specification is invalid
"""
cpu_spec = cpu_spec.strip()

# Explicit CPU specification
cpus = set()

# Split by comma
parts = [p.strip() for p in cpu_spec.split(",")]

for part in parts:
ranges = []
for part in cpu_spec.strip().split(","):
part = part.strip()
if "-" in part:
# Range format: "4-7"
try:
start, end = part.split("-", 1)
start = int(start.strip())
end = int(end.strip())
first, last = part.split("-", 1)
start, end = parse_cpu_id(first), parse_cpu_id(last)
if start > end:
raise ValueError(f"Invalid CPU range: {start} > {end}")
cpus.update(range(start, end + 1))
except ValueError as e:
raise ValueError(f"Invalid CPU range format '{part}': {e}") from e
ranges.append((start, end))
else:
# Single CPU
try:
cpus.add(int(part.strip()))
cpu = parse_cpu_id(part)
except ValueError as e:
raise ValueError(f"Invalid CPU ID '{part}': {e}") from e
ranges.append((cpu, cpu))
return ranges


if not cpus:
raise ValueError("CPU specification must include at least one CPU")
def expand_cpu_ranges(ranges: Iterable[Tuple[int, int]], known: Iterable[int]) -> List[int]:
"""
List the CPUs that ranges of physical IDs select.

Physical IDs are sparse, MPIDRs with gaps of whole affinity levels, so
a range selects the CPUs that exist between its ends rather than every
number. The ends are kept even if unknown, for validation to name them.

Args:
ranges: (first, last) pairs from parse_cpu_ranges()
known: Physical IDs of the CPUs that exist

return sorted(list(cpus))
Returns:
The selected CPU IDs, sorted
"""
known = set(known)
cpus = set()
for start, end in ranges:
cpus.update((start, end))
cpus.update(cpu for cpu in known if start < cpu < end)
return sorted(cpus)


def _find_consecutive_cpus(cpu_list: List[int], count: int) -> Optional[List[int]]:
Expand Down Expand Up @@ -366,7 +386,8 @@ def dump_overlay_for_debug(
"--cpus",
"-c",
help='Explicit CPU allocation by physical ID, the APIC ID on x86 or the MPIDR on arm64 '
'(e.g., "128", "128-134" for range, "128,130,132" for list), not logical CPU numbers. '
'(e.g., "128", "128-134" for range, "128,130,132" for list, "0x100-0x103" in hex), '
'not logical CPU numbers; "kerf cpus" lists them. A range takes the CPUs that exist in it. '
'Mutually exclusive with --cpu-count',
)
@click.option(
Expand Down Expand Up @@ -565,7 +586,7 @@ def create( # pylint: disable=too-many-arguments,too-many-positional-arguments
cpu_spec_value = cpu_count
else:
try:
cpu_spec_value = parse_cpu_spec(cpus)
cpu_spec_value = parse_cpu_ranges(cpus)
except ValueError as e:
click.echo(f"Error: Invalid {cpu_id_name()} specification '{cpus}': {e}", err=True)
sys.exit(2)
Expand Down Expand Up @@ -643,8 +664,7 @@ def create_instance_operation(current):
numa_nodes=numa_node_list,
)
else:
# Use explicitly specified CPUs
cpu_list = cpu_spec_value # cpu_spec_value is List[int]
cpu_list = expand_cpu_ranges(cpu_spec_value, known_cpu_ids(modified))

# Validate CPU allocation (against baseline and existing instances)
validate_cpu_allocation(modified, cpu_list)
Expand Down Expand Up @@ -691,10 +711,10 @@ def create_instance_operation(current):

click.echo(f"✓ Validation passed for instance '{name}'")
if is_count:
cpus_str = ", ".join(map(str, instance.resources.cpus))
cpus_str = ", ".join(map(format_cpu_id, instance.resources.cpus))
click.echo(f" CPUs: {cpu_spec_value} CPUs auto-allocated: {cpus_str}")
else:
click.echo(f" CPUs: {', '.join(map(str, instance.resources.cpus))}")
click.echo(f" CPUs: {', '.join(map(format_cpu_id, instance.resources.cpus))}")
if instance.resources.cpu_affinity:
click.echo(f" CPU Affinity: {instance.resources.cpu_affinity}")
if instance.resources.numa_nodes:
Expand Down Expand Up @@ -734,7 +754,7 @@ def create_instance_operation(current):
if verbose:
instance = manager.read_instance(name)
click.echo(f" Instance ID: {instance.id}")
click.echo(f" CPUs: {', '.join(map(str, instance.resources.cpus))}")
click.echo(f" CPUs: {', '.join(map(format_cpu_id, instance.resources.cpus))}")
if instance.resources.cpu_affinity:
click.echo(f" CPU Affinity: {instance.resources.cpu_affinity}")
if instance.resources.numa_nodes:
Expand Down
Loading
Loading