kerf-multikernel 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kerf/__init__.py +74 -0
- kerf/baseline.py +187 -0
- kerf/cli.py +56 -0
- kerf/console/__init__.py +21 -0
- kerf/console/main.py +252 -0
- kerf/create/__init__.py +17 -0
- kerf/create/main.py +780 -0
- kerf/data/__init__.py +24 -0
- kerf/data/kerf-init +0 -0
- kerf/daxfs/__init__.py +31 -0
- kerf/daxfs/mkdaxfs.py +597 -0
- kerf/delete/__init__.py +21 -0
- kerf/delete/main.py +238 -0
- kerf/docker/__init__.py +21 -0
- kerf/docker/image.py +234 -0
- kerf/dtc/__init__.py +27 -0
- kerf/dtc/cells.py +51 -0
- kerf/dtc/extractor.py +362 -0
- kerf/dtc/overlay.py +378 -0
- kerf/dtc/parser.py +1548 -0
- kerf/dtc/reporter.py +308 -0
- kerf/dtc/validator.py +792 -0
- kerf/exceptions.py +49 -0
- kerf/exec/__init__.py +21 -0
- kerf/exec/main.py +260 -0
- kerf/init/__init__.py +13 -0
- kerf/init/main.py +696 -0
- kerf/kill/__init__.py +21 -0
- kerf/kill/main.py +275 -0
- kerf/lazy_cma.py +132 -0
- kerf/load/__init__.py +21 -0
- kerf/load/main.py +613 -0
- kerf/metadata.py +134 -0
- kerf/models.py +241 -0
- kerf/resources.py +369 -0
- kerf/runtime.py +527 -0
- kerf/show/__init__.py +21 -0
- kerf/show/main.py +616 -0
- kerf/unload/__init__.py +21 -0
- kerf/unload/main.py +310 -0
- kerf/update/__init__.py +15 -0
- kerf/update/main.py +450 -0
- kerf/utils.py +95 -0
- kerf/vmlinuz.py +213 -0
- kerf_multikernel-0.1.0.dist-info/LICENSE +201 -0
- kerf_multikernel-0.1.0.dist-info/METADATA +382 -0
- kerf_multikernel-0.1.0.dist-info/RECORD +49 -0
- kerf_multikernel-0.1.0.dist-info/WHEEL +4 -0
- kerf_multikernel-0.1.0.dist-info/entry_points.txt +3 -0
kerf/load/main.py
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
# Copyright 2025 Multikernel Technologies, Inc.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""
|
|
16
|
+
Kernel loading subcommand implementation using kexec_file_load syscall.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import ctypes
|
|
20
|
+
import os
|
|
21
|
+
import platform
|
|
22
|
+
import sys
|
|
23
|
+
from datetime import datetime, timezone
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Optional
|
|
26
|
+
|
|
27
|
+
import click
|
|
28
|
+
|
|
29
|
+
from ..metadata import (
|
|
30
|
+
inspect_initrd_image,
|
|
31
|
+
inspect_kernel_image,
|
|
32
|
+
save_instance_metadata,
|
|
33
|
+
)
|
|
34
|
+
from ..utils import get_instance_id_from_name, get_instance_name_from_id
|
|
35
|
+
from ..vmlinuz import BZIMAGE_HEADER_SIZE, VmlinuzError, is_bzimage, open_kernel_fd
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# KEXEC flags definitions
|
|
39
|
+
KEXEC_FILE_NO_INITRAMFS = 0x00000004
|
|
40
|
+
KEXEC_FILE_DEBUG = 0x00000008
|
|
41
|
+
KEXEC_MULTIKERNEL = 0x00000010
|
|
42
|
+
KEXEC_MK_ID_MASK = 0x0000FFE0
|
|
43
|
+
KEXEC_MK_ID_SHIFT = 5
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def KEXEC_MK_ID(id: int) -> int: # pylint: disable=invalid-name
|
|
47
|
+
"""Generate KEXEC_MK_ID flag value from kernel ID."""
|
|
48
|
+
return (id << KEXEC_MK_ID_SHIFT) & KEXEC_MK_ID_MASK
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# Syscall numbers (architecture-dependent)
|
|
52
|
+
# For x86_64: 320, for x86: 320, for ARM64: 294, for ARM: 382
|
|
53
|
+
SYS_KEXEC_FILE_LOAD_X86_64 = 320
|
|
54
|
+
SYS_KEXEC_FILE_LOAD_ARM64 = 294
|
|
55
|
+
SYS_KEXEC_FILE_LOAD_ARM = 382
|
|
56
|
+
SYS_KEXEC_FILE_LOAD_X86 = 320
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build_ip_param(
|
|
60
|
+
ip_addr: Optional[str],
|
|
61
|
+
gateway: Optional[str],
|
|
62
|
+
netmask: str,
|
|
63
|
+
hostname: Optional[str],
|
|
64
|
+
nic: Optional[str],
|
|
65
|
+
) -> Optional[str]:
|
|
66
|
+
"""
|
|
67
|
+
Build Linux kernel ip= boot parameter.
|
|
68
|
+
|
|
69
|
+
Format: ip=<client-ip>:<server-ip>:<gw-ip>:<netmask>:<hostname>:<device>:<autoconf>
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
ip_addr: Client IP address or "dhcp"
|
|
73
|
+
gateway: Gateway IP address
|
|
74
|
+
netmask: Network mask
|
|
75
|
+
hostname: Hostname
|
|
76
|
+
nic: Network interface name
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
ip= parameter string, or None if no IP configuration
|
|
80
|
+
"""
|
|
81
|
+
if not ip_addr:
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
if ip_addr.lower() == "dhcp":
|
|
85
|
+
if nic:
|
|
86
|
+
return f"ip=:::::::{nic}:dhcp"
|
|
87
|
+
return "ip=dhcp"
|
|
88
|
+
|
|
89
|
+
# Static IP configuration
|
|
90
|
+
# Format: ip=<client-ip>:<server-ip>:<gw-ip>:<netmask>:<hostname>:<device>:<autoconf>
|
|
91
|
+
parts = [
|
|
92
|
+
ip_addr, # client-ip
|
|
93
|
+
"", # server-ip (empty)
|
|
94
|
+
gateway or "", # gw-ip
|
|
95
|
+
netmask, # netmask
|
|
96
|
+
hostname or "", # hostname
|
|
97
|
+
nic or "", # device
|
|
98
|
+
"off", # autoconf (off for static)
|
|
99
|
+
]
|
|
100
|
+
return "ip=" + ":".join(parts)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def get_kexec_file_load_syscall():
|
|
104
|
+
"""Get the kexec_file_load syscall number for current architecture."""
|
|
105
|
+
arch = platform.machine().lower()
|
|
106
|
+
if arch in ("x86_64", "amd64"):
|
|
107
|
+
return SYS_KEXEC_FILE_LOAD_X86_64
|
|
108
|
+
if arch in ("aarch64", "arm64"):
|
|
109
|
+
return SYS_KEXEC_FILE_LOAD_ARM64
|
|
110
|
+
if arch.startswith("arm"):
|
|
111
|
+
return SYS_KEXEC_FILE_LOAD_ARM
|
|
112
|
+
if arch in ("i386", "i686", "x86"):
|
|
113
|
+
return SYS_KEXEC_FILE_LOAD_X86
|
|
114
|
+
# Default to x86_64, but warn
|
|
115
|
+
click.echo(
|
|
116
|
+
f"Warning: Unknown architecture '{arch}', assuming x86_64 syscall number", err=True
|
|
117
|
+
)
|
|
118
|
+
return SYS_KEXEC_FILE_LOAD_X86_64
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def kexec_file_load(
|
|
122
|
+
kernel_fd: int, initrd_fd: int, cmdline: str, flags: int, debug: bool = False
|
|
123
|
+
) -> int:
|
|
124
|
+
"""
|
|
125
|
+
Call kexec_file_load syscall.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
kernel_fd: File descriptor for kernel image
|
|
129
|
+
initrd_fd: File descriptor for initrd (use -1 if not provided)
|
|
130
|
+
cmdline: Boot command line string
|
|
131
|
+
flags: KEXEC flags (e.g., KEXEC_MULTIKERNEL | KEXEC_MK_ID(id))
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
0 on success, -errno on failure
|
|
135
|
+
|
|
136
|
+
Raises:
|
|
137
|
+
OSError: If syscall fails
|
|
138
|
+
"""
|
|
139
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
140
|
+
syscall_fn = libc.syscall
|
|
141
|
+
|
|
142
|
+
syscall_num = get_kexec_file_load_syscall()
|
|
143
|
+
|
|
144
|
+
# Prepare cmdline
|
|
145
|
+
# kexec_file_load expects: cmdline_len is length INCLUDING null terminator
|
|
146
|
+
# cmdline is pointer to null-terminated string (or NULL)
|
|
147
|
+
# Note: kexec-tools uses strlen(cmdline) + 1 for cmdline_len
|
|
148
|
+
cmdline_buf = None
|
|
149
|
+
if cmdline:
|
|
150
|
+
cmdline_bytes = cmdline.encode("utf-8")
|
|
151
|
+
cmdline_buf = ctypes.create_string_buffer(cmdline_bytes)
|
|
152
|
+
cmdline_len = len(cmdline_bytes) + 1
|
|
153
|
+
cmdline_ptr = cmdline_buf
|
|
154
|
+
else:
|
|
155
|
+
cmdline_len = 0
|
|
156
|
+
cmdline_ptr = None
|
|
157
|
+
|
|
158
|
+
# syscall signature: long syscall(long number, ...)
|
|
159
|
+
# kexec_file_load: long kexec_file_load(int kernel_fd, int initrd_fd,
|
|
160
|
+
# unsigned long cmdline_len,
|
|
161
|
+
# const char *cmdline,
|
|
162
|
+
# unsigned long flags)
|
|
163
|
+
syscall_fn.argtypes = [
|
|
164
|
+
ctypes.c_long, # syscall number
|
|
165
|
+
ctypes.c_int, # kernel_fd
|
|
166
|
+
ctypes.c_int, # initrd_fd
|
|
167
|
+
ctypes.c_ulong, # cmdline_len
|
|
168
|
+
ctypes.c_char_p, # cmdline (c_char_p handles None as NULL)
|
|
169
|
+
ctypes.c_ulong, # flags
|
|
170
|
+
]
|
|
171
|
+
syscall_fn.restype = ctypes.c_long
|
|
172
|
+
|
|
173
|
+
if debug:
|
|
174
|
+
click.echo(
|
|
175
|
+
f"DEBUG: syscall_num={syscall_num}, kernel_fd={kernel_fd}, initrd_fd={initrd_fd}, cmdline_len={cmdline_len}, flags=0x{flags:x}",
|
|
176
|
+
err=True,
|
|
177
|
+
)
|
|
178
|
+
click.echo(
|
|
179
|
+
f"DEBUG: KEXEC_MULTIKERNEL=0x{KEXEC_MULTIKERNEL:x}, KEXEC_MK_ID_MASK=0x{KEXEC_MK_ID_MASK:x}, KEXEC_MK_ID_SHIFT={KEXEC_MK_ID_SHIFT}",
|
|
180
|
+
err=True,
|
|
181
|
+
)
|
|
182
|
+
if cmdline:
|
|
183
|
+
click.echo(f"DEBUG: cmdline='{cmdline}', cmdline_ptr={cmdline_ptr}", err=True)
|
|
184
|
+
# Verify the buffer content
|
|
185
|
+
click.echo(
|
|
186
|
+
f"DEBUG: cmdline_buf.value={cmdline_buf.value!r}, len={len(cmdline_buf.value)}",
|
|
187
|
+
err=True,
|
|
188
|
+
)
|
|
189
|
+
else:
|
|
190
|
+
click.echo("DEBUG: cmdline_ptr=NULL", err=True)
|
|
191
|
+
|
|
192
|
+
result = syscall_fn(syscall_num, kernel_fd, initrd_fd, cmdline_len, cmdline_ptr, flags)
|
|
193
|
+
|
|
194
|
+
if debug:
|
|
195
|
+
click.echo(f"DEBUG: syscall returned: {result}", err=True)
|
|
196
|
+
|
|
197
|
+
if result < 0:
|
|
198
|
+
# Get errno
|
|
199
|
+
errno_value = ctypes.get_errno()
|
|
200
|
+
if errno_value == 0:
|
|
201
|
+
# If errno is 0 but result is negative, use -result as errno
|
|
202
|
+
# This handles cases where the syscall returns -errno directly
|
|
203
|
+
errno_value = -result
|
|
204
|
+
raise OSError(errno_value, os.strerror(errno_value))
|
|
205
|
+
|
|
206
|
+
return result
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@click.command()
|
|
210
|
+
@click.pass_context
|
|
211
|
+
@click.argument("name", required=False)
|
|
212
|
+
@click.option("--kernel", "-k", required=True, help="Path to kernel image file")
|
|
213
|
+
@click.option("--initrd", "-i", help="Path to initrd image file (optional)")
|
|
214
|
+
@click.option("--cmdline", "-c", help="Boot command line parameters")
|
|
215
|
+
@click.option("--id", type=int, help="Multikernel instance ID (1-511)")
|
|
216
|
+
@click.option("--image", help="Docker image to use as rootfs (e.g., nginx:latest)")
|
|
217
|
+
@click.option("--entrypoint", help="Override image entrypoint for init")
|
|
218
|
+
@click.option("--rootfs-dir", help="Use existing directory as rootfs instead of Docker image")
|
|
219
|
+
@click.option("--ip", "ip_addr", help="IP address for spawn kernel (or 'dhcp')")
|
|
220
|
+
@click.option("--gateway", help="Default gateway IP address")
|
|
221
|
+
@click.option("--netmask", default="255.255.255.0", help="Network mask (default: 255.255.255.0)")
|
|
222
|
+
@click.option("--nic", help="Network interface name (e.g., eth0)")
|
|
223
|
+
@click.option("--hostname", help="Hostname for spawn kernel")
|
|
224
|
+
@click.option("--console", "console_device", help="Console device (e.g., mktty0)")
|
|
225
|
+
@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
|
|
226
|
+
def load( # pylint: disable=too-many-arguments,too-many-positional-arguments,too-many-locals
|
|
227
|
+
ctx: click.Context,
|
|
228
|
+
name: Optional[str],
|
|
229
|
+
kernel: str,
|
|
230
|
+
initrd: Optional[str],
|
|
231
|
+
cmdline: Optional[str],
|
|
232
|
+
id: Optional[int],
|
|
233
|
+
image: Optional[str],
|
|
234
|
+
entrypoint: Optional[str],
|
|
235
|
+
rootfs_dir: Optional[str],
|
|
236
|
+
ip_addr: Optional[str],
|
|
237
|
+
gateway: Optional[str],
|
|
238
|
+
netmask: str,
|
|
239
|
+
nic: Optional[str],
|
|
240
|
+
hostname: Optional[str],
|
|
241
|
+
console_device: Optional[str],
|
|
242
|
+
verbose: bool,
|
|
243
|
+
):
|
|
244
|
+
"""
|
|
245
|
+
Load kernel image using kexec_file_load syscall.
|
|
246
|
+
|
|
247
|
+
This command loads a kernel image into memory using the kexec_file_load
|
|
248
|
+
syscall. The kernel is loaded in multikernel mode with the specified ID.
|
|
249
|
+
|
|
250
|
+
Both an uncompressed ELF vmlinux and a compressed bzImage (vmlinuz) are
|
|
251
|
+
accepted. For a bzImage, the embedded vmlinux is extracted in userspace
|
|
252
|
+
before loading, since the kernel side only accepts ELF images. Note that
|
|
253
|
+
an extracted vmlinux carries no signature, so this will not work on
|
|
254
|
+
hosts enforcing kexec signature verification (Secure Boot lockdown).
|
|
255
|
+
|
|
256
|
+
When --image or --rootfs-dir is provided, a daxfs image is created and the
|
|
257
|
+
kernel boots directly into daxfs as root filesystem (no initrd needed if
|
|
258
|
+
daxfs is built into the kernel).
|
|
259
|
+
|
|
260
|
+
If the spawn kernel builds daxfs as a module, pass --initrd with an
|
|
261
|
+
initramfs containing daxfs.ko and an init that loads the module, mounts
|
|
262
|
+
daxfs using the rootflags= parameters from the command line, and
|
|
263
|
+
switch_roots into it (exec'ing /init).
|
|
264
|
+
|
|
265
|
+
Examples:
|
|
266
|
+
|
|
267
|
+
kerf load web-server --kernel=/boot/vmlinuz --initrd=/boot/initrd.img \\
|
|
268
|
+
--cmdline="root=/dev/sda1"
|
|
269
|
+
kerf load --kernel=/boot/vmlinuz --initrd=/boot/initrd.img \\
|
|
270
|
+
--cmdline="root=/dev/sda1" --id=1
|
|
271
|
+
|
|
272
|
+
# Load with Docker image as rootfs
|
|
273
|
+
kerf load web-server --kernel=/boot/vmlinuz --image=nginx:latest
|
|
274
|
+
|
|
275
|
+
# Load with custom entrypoint
|
|
276
|
+
kerf load worker --kernel=/boot/vmlinuz --image=python:3.11 \\
|
|
277
|
+
--entrypoint=/app/worker.py
|
|
278
|
+
|
|
279
|
+
# Load with pre-extracted rootfs directory
|
|
280
|
+
kerf load custom --kernel=/boot/vmlinuz --rootfs-dir=/mnt/rootfs \\
|
|
281
|
+
--entrypoint=/sbin/init
|
|
282
|
+
|
|
283
|
+
# Load with static IP configuration
|
|
284
|
+
kerf load web-server --kernel=/boot/vmlinuz --image=nginx:latest \\
|
|
285
|
+
--ip=192.168.1.100 --gateway=192.168.1.1 --nic=eth0
|
|
286
|
+
|
|
287
|
+
# Load with DHCP
|
|
288
|
+
kerf load web-server --kernel=/boot/vmlinuz --image=nginx:latest \\
|
|
289
|
+
--ip=dhcp --nic=eth0
|
|
290
|
+
|
|
291
|
+
# Load with console enabled
|
|
292
|
+
kerf load web-server --kernel=/boot/vmlinuz --image=nginx:latest \\
|
|
293
|
+
--console=mktty0
|
|
294
|
+
"""
|
|
295
|
+
try:
|
|
296
|
+
if not name and id is None:
|
|
297
|
+
click.echo("Error: Either instance name or --id must be provided", err=True)
|
|
298
|
+
click.echo(
|
|
299
|
+
"Usage: kerf load <name> --kernel=<path> or kerf load --id=<id> --kernel=<path>",
|
|
300
|
+
err=True,
|
|
301
|
+
)
|
|
302
|
+
sys.exit(2)
|
|
303
|
+
|
|
304
|
+
if image and rootfs_dir:
|
|
305
|
+
click.echo("Error: --image and --rootfs-dir are mutually exclusive", err=True)
|
|
306
|
+
sys.exit(2)
|
|
307
|
+
|
|
308
|
+
if rootfs_dir and not entrypoint:
|
|
309
|
+
click.echo("Error: --entrypoint is required when using --rootfs-dir", err=True)
|
|
310
|
+
sys.exit(2)
|
|
311
|
+
|
|
312
|
+
if entrypoint and not image and not rootfs_dir:
|
|
313
|
+
click.echo("Error: --entrypoint requires --image or --rootfs-dir", err=True)
|
|
314
|
+
sys.exit(2)
|
|
315
|
+
|
|
316
|
+
instance_name = None
|
|
317
|
+
instance_id = None
|
|
318
|
+
|
|
319
|
+
if name:
|
|
320
|
+
instance_name = name
|
|
321
|
+
instance_id = get_instance_id_from_name(name)
|
|
322
|
+
|
|
323
|
+
if instance_id is None:
|
|
324
|
+
click.echo(f"Error: Instance '{name}' not found", err=True)
|
|
325
|
+
click.echo("Check available instances in /sys/fs/multikernel/instances/", err=True)
|
|
326
|
+
sys.exit(1)
|
|
327
|
+
|
|
328
|
+
if verbose:
|
|
329
|
+
click.echo(f"Instance name: {name} (ID: {instance_id})")
|
|
330
|
+
else:
|
|
331
|
+
instance_id = id
|
|
332
|
+
|
|
333
|
+
if instance_id < 1 or instance_id > 511:
|
|
334
|
+
click.echo(f"Error: --id must be between 1 and 511 (got {instance_id})", err=True)
|
|
335
|
+
sys.exit(2)
|
|
336
|
+
|
|
337
|
+
instance_name = get_instance_name_from_id(instance_id)
|
|
338
|
+
if not instance_name:
|
|
339
|
+
click.echo(f"Error: Instance with ID {instance_id} not found", err=True)
|
|
340
|
+
click.echo("Check available instances in /sys/fs/multikernel/instances/", err=True)
|
|
341
|
+
sys.exit(1)
|
|
342
|
+
|
|
343
|
+
if verbose:
|
|
344
|
+
click.echo(f"Instance name: {instance_name} (ID: {instance_id})")
|
|
345
|
+
|
|
346
|
+
# Validate kernel file
|
|
347
|
+
kernel_path = Path(kernel)
|
|
348
|
+
if not kernel_path.exists():
|
|
349
|
+
click.echo(f"Error: Kernel image '{kernel}' does not exist", err=True)
|
|
350
|
+
sys.exit(3) # File I/O error
|
|
351
|
+
|
|
352
|
+
if not kernel_path.is_file():
|
|
353
|
+
click.echo(f"Error: '{kernel}' is not a regular file", err=True)
|
|
354
|
+
sys.exit(3)
|
|
355
|
+
|
|
356
|
+
if verbose:
|
|
357
|
+
click.echo(f"Kernel image: {kernel_path}")
|
|
358
|
+
|
|
359
|
+
# Validate initrd file if provided
|
|
360
|
+
initrd_path = None
|
|
361
|
+
if initrd:
|
|
362
|
+
initrd_path = Path(initrd)
|
|
363
|
+
if not initrd_path.exists():
|
|
364
|
+
click.echo(f"Error: Initrd image '{initrd}' does not exist", err=True)
|
|
365
|
+
sys.exit(3)
|
|
366
|
+
|
|
367
|
+
if not initrd_path.is_file():
|
|
368
|
+
click.echo(f"Error: '{initrd}' is not a regular file", err=True)
|
|
369
|
+
sys.exit(3)
|
|
370
|
+
|
|
371
|
+
if verbose:
|
|
372
|
+
click.echo(f"Initrd image: {initrd_path}")
|
|
373
|
+
|
|
374
|
+
# Handle Docker image or rootfs directory
|
|
375
|
+
daxfs_image = None
|
|
376
|
+
init_path = None
|
|
377
|
+
image_id = None
|
|
378
|
+
|
|
379
|
+
if image:
|
|
380
|
+
from ..docker.image import extract_image, DockerError
|
|
381
|
+
from ..daxfs import create_daxfs_image, DaxfsError, inject_kerf_init
|
|
382
|
+
|
|
383
|
+
try:
|
|
384
|
+
if verbose:
|
|
385
|
+
click.echo(f"Extracting Docker image: {image}")
|
|
386
|
+
|
|
387
|
+
rootfs_path, default_cmd, image_id = extract_image(image, instance_name)
|
|
388
|
+
|
|
389
|
+
if verbose:
|
|
390
|
+
click.echo(f"Rootfs extracted to: {rootfs_path}")
|
|
391
|
+
click.echo(f"Image command: {default_cmd}")
|
|
392
|
+
|
|
393
|
+
if entrypoint:
|
|
394
|
+
init_path = entrypoint
|
|
395
|
+
elif default_cmd:
|
|
396
|
+
init_path = default_cmd[0]
|
|
397
|
+
else:
|
|
398
|
+
click.echo(
|
|
399
|
+
"Error: Image has no ENTRYPOINT/CMD, use --entrypoint to specify init",
|
|
400
|
+
err=True
|
|
401
|
+
)
|
|
402
|
+
sys.exit(2)
|
|
403
|
+
|
|
404
|
+
inject_kerf_init(rootfs_path)
|
|
405
|
+
if verbose:
|
|
406
|
+
click.echo(f"Injected /init wrapper (entrypoint: {init_path})")
|
|
407
|
+
|
|
408
|
+
if verbose:
|
|
409
|
+
click.echo(f"Creating daxfs image for instance {instance_name}...")
|
|
410
|
+
|
|
411
|
+
daxfs_image = create_daxfs_image(rootfs_path, instance_name)
|
|
412
|
+
|
|
413
|
+
if verbose:
|
|
414
|
+
click.echo(f"Daxfs image created at phys=0x{daxfs_image.phys_addr:x}, size={daxfs_image.size}")
|
|
415
|
+
click.echo(f"Entrypoint: {init_path}")
|
|
416
|
+
|
|
417
|
+
except DockerError as e:
|
|
418
|
+
click.echo(f"Error: Docker operation failed: {e}", err=True)
|
|
419
|
+
sys.exit(1)
|
|
420
|
+
except DaxfsError as e:
|
|
421
|
+
click.echo(f"Error: Daxfs image creation failed: {e}", err=True)
|
|
422
|
+
sys.exit(1)
|
|
423
|
+
except FileNotFoundError as e:
|
|
424
|
+
click.echo(f"Error: {e}", err=True)
|
|
425
|
+
sys.exit(1)
|
|
426
|
+
|
|
427
|
+
elif rootfs_dir:
|
|
428
|
+
from ..daxfs import create_daxfs_image, DaxfsError, inject_kerf_init
|
|
429
|
+
|
|
430
|
+
try:
|
|
431
|
+
rootfs_path = Path(rootfs_dir)
|
|
432
|
+
if not rootfs_path.is_dir():
|
|
433
|
+
click.echo(f"Error: Rootfs directory '{rootfs_dir}' does not exist", err=True)
|
|
434
|
+
sys.exit(3)
|
|
435
|
+
|
|
436
|
+
init_path = entrypoint
|
|
437
|
+
|
|
438
|
+
inject_kerf_init(str(rootfs_path))
|
|
439
|
+
if verbose:
|
|
440
|
+
click.echo(f"Injected /init wrapper (entrypoint: {init_path})")
|
|
441
|
+
|
|
442
|
+
if verbose:
|
|
443
|
+
click.echo(f"Using rootfs directory: {rootfs_path}")
|
|
444
|
+
click.echo(f"Creating daxfs image for instance {instance_name}...")
|
|
445
|
+
|
|
446
|
+
daxfs_image = create_daxfs_image(str(rootfs_path), instance_name)
|
|
447
|
+
|
|
448
|
+
if verbose:
|
|
449
|
+
click.echo(f"Daxfs image created at phys=0x{daxfs_image.phys_addr:x}, size={daxfs_image.size}")
|
|
450
|
+
click.echo(f"Entrypoint: {init_path}")
|
|
451
|
+
|
|
452
|
+
except DaxfsError as e:
|
|
453
|
+
click.echo(f"Error: Daxfs image creation failed: {e}", err=True)
|
|
454
|
+
sys.exit(1)
|
|
455
|
+
except FileNotFoundError as e:
|
|
456
|
+
click.echo(f"Error: {e}", err=True)
|
|
457
|
+
sys.exit(1)
|
|
458
|
+
|
|
459
|
+
# Always enable multikernel mode
|
|
460
|
+
mk_id_flags = KEXEC_MK_ID(instance_id)
|
|
461
|
+
flags = KEXEC_MULTIKERNEL | mk_id_flags
|
|
462
|
+
|
|
463
|
+
# If no initrd, set NO_INITRAMFS flag
|
|
464
|
+
if not initrd_path:
|
|
465
|
+
flags |= KEXEC_FILE_NO_INITRAMFS
|
|
466
|
+
|
|
467
|
+
if verbose:
|
|
468
|
+
click.echo(f"Multikernel mode enabled with ID: {instance_id}")
|
|
469
|
+
flag_parts = [f"KEXEC_MULTIKERNEL=0x{KEXEC_MULTIKERNEL:x}", f"KEXEC_MK_ID({instance_id})=0x{mk_id_flags:x}"]
|
|
470
|
+
if not initrd_path:
|
|
471
|
+
flag_parts.append(f"KEXEC_FILE_NO_INITRAMFS=0x{KEXEC_FILE_NO_INITRAMFS:x}")
|
|
472
|
+
click.echo(f"Flags: {', '.join(flag_parts)}, combined=0x{flags:x}")
|
|
473
|
+
|
|
474
|
+
# Prepare command line
|
|
475
|
+
cmdline_parts = []
|
|
476
|
+
if cmdline:
|
|
477
|
+
cmdline_parts.append(cmdline)
|
|
478
|
+
|
|
479
|
+
# Add daxfs root parameters if using daxfs. With an initrd, the
|
|
480
|
+
# kernel does not mount root itself; the initrd is expected to
|
|
481
|
+
# load daxfs, mount it using these same rootflags, and switch_root
|
|
482
|
+
# into it (exec'ing the injected /init).
|
|
483
|
+
if daxfs_image:
|
|
484
|
+
cmdline_parts.append("rootfstype=daxfs")
|
|
485
|
+
cmdline_parts.append(f"rootflags=phys=0x{daxfs_image.phys_addr:x},size={daxfs_image.size}")
|
|
486
|
+
cmdline_parts.append("init=/init")
|
|
487
|
+
if init_path:
|
|
488
|
+
# Quote entrypoint if it contains spaces
|
|
489
|
+
if ' ' in init_path:
|
|
490
|
+
cmdline_parts.append(f'kerf.entrypoint="{init_path}"')
|
|
491
|
+
else:
|
|
492
|
+
cmdline_parts.append(f"kerf.entrypoint={init_path}")
|
|
493
|
+
if verbose:
|
|
494
|
+
click.echo(f"Daxfs root: rootfstype=daxfs rootflags=phys=0x{daxfs_image.phys_addr:x},size={daxfs_image.size}")
|
|
495
|
+
if init_path:
|
|
496
|
+
click.echo(f"Entrypoint: kerf.entrypoint={init_path}")
|
|
497
|
+
|
|
498
|
+
# Add IP configuration if specified
|
|
499
|
+
ip_param = build_ip_param(ip_addr, gateway, netmask, hostname, nic)
|
|
500
|
+
if ip_param:
|
|
501
|
+
cmdline_parts.append(ip_param)
|
|
502
|
+
if verbose:
|
|
503
|
+
click.echo(f"Network config: {ip_param}")
|
|
504
|
+
|
|
505
|
+
# Add console device if specified
|
|
506
|
+
if console_device:
|
|
507
|
+
cmdline_parts.append(f"console={console_device}")
|
|
508
|
+
if verbose:
|
|
509
|
+
click.echo(f"Console: console={console_device}")
|
|
510
|
+
|
|
511
|
+
cmdline_str = " ".join(cmdline_parts)
|
|
512
|
+
|
|
513
|
+
if verbose:
|
|
514
|
+
click.echo(f"Command line: {cmdline_str if cmdline_str else '(empty)'}")
|
|
515
|
+
click.echo(f"Flags: 0x{flags:x}")
|
|
516
|
+
|
|
517
|
+
# Open kernel file, extracting the embedded vmlinux if it is a
|
|
518
|
+
# bzImage, since the kexec ELF loader only accepts vmlinux
|
|
519
|
+
try:
|
|
520
|
+
with open(kernel_path, "rb") as f:
|
|
521
|
+
kernel_is_bzimage = is_bzimage(f.read(BZIMAGE_HEADER_SIZE))
|
|
522
|
+
if kernel_is_bzimage and verbose:
|
|
523
|
+
click.echo("bzImage detected, extracting embedded vmlinux")
|
|
524
|
+
kernel_fd = open_kernel_fd(kernel_path)
|
|
525
|
+
except VmlinuzError as e:
|
|
526
|
+
click.echo(f"Error: {e}", err=True)
|
|
527
|
+
sys.exit(3)
|
|
528
|
+
except OSError as e:
|
|
529
|
+
click.echo(f"Error: Failed to open kernel image: {e}", err=True)
|
|
530
|
+
sys.exit(3)
|
|
531
|
+
|
|
532
|
+
# Open initrd file if provided
|
|
533
|
+
initrd_fd = -1
|
|
534
|
+
if initrd_path:
|
|
535
|
+
try:
|
|
536
|
+
initrd_fd = os.open(str(initrd_path), os.O_RDONLY)
|
|
537
|
+
except OSError as e:
|
|
538
|
+
os.close(kernel_fd)
|
|
539
|
+
click.echo(f"Error: Failed to open initrd image: {e}", err=True)
|
|
540
|
+
sys.exit(3)
|
|
541
|
+
|
|
542
|
+
try:
|
|
543
|
+
# Call kexec_file_load syscall
|
|
544
|
+
if verbose:
|
|
545
|
+
click.echo("Calling kexec_file_load syscall...")
|
|
546
|
+
|
|
547
|
+
debug = ctx.obj.get("debug", False) if ctx and ctx.obj else False
|
|
548
|
+
if debug:
|
|
549
|
+
flags |= KEXEC_FILE_DEBUG
|
|
550
|
+
result = kexec_file_load(kernel_fd, initrd_fd, cmdline_str, flags, debug=debug)
|
|
551
|
+
|
|
552
|
+
if verbose:
|
|
553
|
+
click.echo(f"✓ Kernel loaded successfully (result: {result})")
|
|
554
|
+
else:
|
|
555
|
+
click.echo("✓ Kernel loaded successfully")
|
|
556
|
+
|
|
557
|
+
# Record image provenance for kerf show; /proc/kimage only
|
|
558
|
+
# knows about the loaded segments, not the source file
|
|
559
|
+
rootfs_meta = None
|
|
560
|
+
if image or rootfs_dir:
|
|
561
|
+
rootfs_meta = {
|
|
562
|
+
"source": "docker" if image else "directory",
|
|
563
|
+
"image": image,
|
|
564
|
+
"path": str(rootfs_path),
|
|
565
|
+
"entrypoint": init_path,
|
|
566
|
+
}
|
|
567
|
+
if image_id:
|
|
568
|
+
rootfs_meta["image_id"] = image_id
|
|
569
|
+
if daxfs_image:
|
|
570
|
+
rootfs_meta["daxfs"] = {
|
|
571
|
+
"phys_addr": daxfs_image.phys_addr,
|
|
572
|
+
"size": daxfs_image.size,
|
|
573
|
+
}
|
|
574
|
+
try:
|
|
575
|
+
save_instance_metadata(instance_name, {
|
|
576
|
+
"kernel": inspect_kernel_image(kernel_path),
|
|
577
|
+
"initrd": inspect_initrd_image(initrd_path) if initrd_path else None,
|
|
578
|
+
"rootfs": rootfs_meta,
|
|
579
|
+
"loaded_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
580
|
+
})
|
|
581
|
+
except OSError as e:
|
|
582
|
+
click.echo(f"Warning: Failed to record instance metadata: {e}", err=True)
|
|
583
|
+
|
|
584
|
+
except OSError as e:
|
|
585
|
+
click.echo(f"Error: kexec_file_load failed: {e}", err=True)
|
|
586
|
+
if e.errno == 1: # EPERM
|
|
587
|
+
click.echo("Note: This operation requires root privileges", err=True)
|
|
588
|
+
elif e.errno == 16: # EBUSY
|
|
589
|
+
click.echo(
|
|
590
|
+
f"Note: Instance '{instance_name}' already has a kernel loaded. "
|
|
591
|
+
f"Run 'kerf unload {instance_name}' first.", err=True
|
|
592
|
+
)
|
|
593
|
+
elif e.errno == 22: # EINVAL
|
|
594
|
+
click.echo(
|
|
595
|
+
"Note: Invalid arguments. Check kernel image format and flags.", err=True
|
|
596
|
+
)
|
|
597
|
+
elif e.errno == 95: # EOPNOTSUPP
|
|
598
|
+
click.echo("Note: kexec_file_load not supported on this system.", err=True)
|
|
599
|
+
sys.exit(1)
|
|
600
|
+
|
|
601
|
+
finally:
|
|
602
|
+
# Clean up file descriptors
|
|
603
|
+
os.close(kernel_fd)
|
|
604
|
+
if initrd_fd >= 0:
|
|
605
|
+
os.close(initrd_fd)
|
|
606
|
+
|
|
607
|
+
except Exception as e:
|
|
608
|
+
click.echo(f"Unexpected error: {e}", err=True)
|
|
609
|
+
if verbose:
|
|
610
|
+
import traceback
|
|
611
|
+
|
|
612
|
+
traceback.print_exc()
|
|
613
|
+
sys.exit(1)
|