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/exceptions.py ADDED
@@ -0,0 +1,49 @@
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
+ Exception classes for kerf validation and processing errors.
17
+ """
18
+
19
+
20
+ class KerfError(Exception):
21
+ """Base exception for all kerf errors."""
22
+
23
+
24
+ class ValidationError(KerfError):
25
+ """Raised when validation fails."""
26
+
27
+
28
+ class ParseError(KerfError):
29
+ """Raised when parsing DTS/DTB fails."""
30
+
31
+
32
+ class ResourceConflictError(ValidationError):
33
+ """Raised when resource conflicts are detected."""
34
+
35
+
36
+ class ResourceExhaustionError(ValidationError):
37
+ """Raised when resources are over-allocated."""
38
+
39
+
40
+ class InvalidReferenceError(ValidationError):
41
+ """Raised when invalid device references are found."""
42
+
43
+
44
+ class KernelInterfaceError(KerfError):
45
+ """Raised when kernel interface operations fail."""
46
+
47
+
48
+ class ResourceError(KerfError):
49
+ """Raised when resource allocation operations fail."""
kerf/exec/__init__.py ADDED
@@ -0,0 +1,21 @@
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 execution subcommand implementation.
17
+ """
18
+
19
+ from .main import exec_cmd
20
+
21
+ __all__ = ["exec_cmd"]
kerf/exec/main.py ADDED
@@ -0,0 +1,260 @@
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 execution subcommand implementation using reboot syscall with MULTIKERNEL command.
17
+ """
18
+
19
+ import ctypes
20
+ import os
21
+ import platform
22
+ import sys
23
+ from pathlib import Path
24
+ from typing import Optional
25
+
26
+ import click
27
+ import rdtsc
28
+
29
+ from ..models import InstanceState
30
+ from ..utils import get_instance_id_from_name
31
+
32
+
33
+ LINUX_REBOOT_MAGIC1 = 0xFEE1DEAD
34
+ LINUX_REBOOT_MAGIC2 = 672274793 # 0x28121969
35
+ LINUX_REBOOT_CMD_MULTIKERNEL = 0x4D4B4C49
36
+
37
+ SYS_REBOOT_X86_64 = 169
38
+ SYS_REBOOT_ARM64 = 142
39
+ SYS_REBOOT_ARM = 88
40
+ SYS_REBOOT_X86 = 88
41
+
42
+ def get_reboot_syscall():
43
+ """Get the reboot syscall number for current architecture."""
44
+ arch = platform.machine().lower()
45
+ if arch in ("x86_64", "amd64"):
46
+ return SYS_REBOOT_X86_64
47
+ if arch in ("aarch64", "arm64"):
48
+ return SYS_REBOOT_ARM64
49
+ if arch.startswith("arm"):
50
+ return SYS_REBOOT_ARM
51
+ if arch in ("i386", "i686", "x86"):
52
+ return SYS_REBOOT_X86
53
+ click.echo(
54
+ f"Warning: Unknown architecture '{arch}', assuming x86_64 syscall number", err=True
55
+ )
56
+ return SYS_REBOOT_X86_64
57
+
58
+
59
+ class MultikernelBootArgs(ctypes.Structure):
60
+ """Structure for multikernel boot arguments."""
61
+
62
+ _fields_ = [
63
+ ("mk_id", ctypes.c_int),
64
+ ]
65
+
66
+
67
+ def boot_multikernel(mk_id: int) -> int:
68
+ libc = ctypes.CDLL(None, use_errno=True)
69
+ syscall_fn = libc.syscall
70
+
71
+ syscall_num = get_reboot_syscall()
72
+
73
+ args = MultikernelBootArgs()
74
+ args.mk_id = mk_id # pylint: disable=attribute-defined-outside-init
75
+
76
+ # syscall signature: long syscall(long number, ...)
77
+ # reboot: long syscall(SYS_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
78
+ # LINUX_REBOOT_CMD_MULTIKERNEL, &args)
79
+ syscall_fn.argtypes = [
80
+ ctypes.c_long, # syscall number
81
+ ctypes.c_ulong, # LINUX_REBOOT_MAGIC1
82
+ ctypes.c_ulong, # LINUX_REBOOT_MAGIC2
83
+ ctypes.c_ulong, # LINUX_REBOOT_CMD_MULTIKERNEL
84
+ ctypes.POINTER(MultikernelBootArgs), # &args
85
+ ]
86
+ syscall_fn.restype = ctypes.c_long
87
+
88
+ result = syscall_fn(
89
+ syscall_num,
90
+ LINUX_REBOOT_MAGIC1,
91
+ LINUX_REBOOT_MAGIC2,
92
+ LINUX_REBOOT_CMD_MULTIKERNEL,
93
+ ctypes.byref(args),
94
+ )
95
+
96
+ if result < 0:
97
+ errno_value = ctypes.get_errno()
98
+ raise OSError(errno_value, os.strerror(errno_value))
99
+
100
+ return result
101
+
102
+
103
+ @click.command(name="exec")
104
+ @click.argument("name", required=False)
105
+ @click.option("--id", type=int, help="Multikernel instance ID to boot (alternative to name)")
106
+ @click.option("--console", "attach_console", is_flag=True, help="Attach to console after boot")
107
+ @click.option("--verbose", "-v", is_flag=True, help="Verbose output")
108
+ def exec_cmd(name: Optional[str], id: Optional[int], attach_console: bool, verbose: bool):
109
+ """
110
+ Boot a multikernel instance using the reboot syscall.
111
+
112
+ This command boots a previously loaded multikernel instance by name or ID using
113
+ the reboot syscall with the MULTIKERNEL command.
114
+
115
+ Use --console to immediately attach to the instance's console after boot.
116
+ Press Ctrl+] followed by . to detach from the console.
117
+
118
+ Examples:
119
+
120
+ kerf exec web-server
121
+ kerf exec --id=1
122
+ kerf exec web-server --console
123
+ """
124
+ try:
125
+ if not name and id is None:
126
+ click.echo("Error: Either instance name or --id must be provided", err=True)
127
+ click.echo("Usage: kerf exec <name> or kerf exec --id=<id>", err=True)
128
+ sys.exit(2)
129
+
130
+ instance_name = None
131
+ instance_id = None
132
+
133
+ if name:
134
+ # Use name, convert to ID
135
+ instance_name = name
136
+ instance_id = get_instance_id_from_name(name)
137
+
138
+ if instance_id is None:
139
+ click.echo(f"Error: Instance '{name}' not found", err=True)
140
+ click.echo("Check available instances in /sys/fs/multikernel/instances/", err=True)
141
+ sys.exit(1)
142
+
143
+ if verbose:
144
+ click.echo(f"Instance name: {name} (ID: {instance_id})")
145
+ else:
146
+ # Use ID directly, need to find name for status check
147
+ instance_id = id
148
+
149
+ if instance_id < 1 or instance_id > 511:
150
+ click.echo(f"Error: --id must be between 1 and 511 (got {instance_id})", err=True)
151
+ sys.exit(2)
152
+
153
+ instances_dir = Path("/sys/fs/multikernel/instances")
154
+ if instances_dir.exists():
155
+ for inst_dir in instances_dir.iterdir():
156
+ if inst_dir.is_dir():
157
+ found_id = get_instance_id_from_name(inst_dir.name)
158
+ if found_id == instance_id:
159
+ instance_name = inst_dir.name
160
+ break
161
+
162
+ if not instance_name:
163
+ click.echo(f"Error: Instance with ID {instance_id} not found", err=True)
164
+ click.echo("Check available instances in /sys/fs/multikernel/instances/", err=True)
165
+ sys.exit(1)
166
+
167
+ status_path = Path(f"/sys/fs/multikernel/instances/{instance_name}/status")
168
+ if verbose:
169
+ click.echo(f"Checking if kernel image is loaded for instance '{instance_name}'...")
170
+ click.echo(f"Status file: {status_path}")
171
+
172
+ if not status_path.exists():
173
+ click.echo(f"Error: Instance '{instance_name}' status file not found", err=True)
174
+ click.echo(
175
+ f"Please ensure the instance exists and load a kernel image using: kerf load --id={instance_id} --kernel=<path>",
176
+ err=True,
177
+ )
178
+ sys.exit(1)
179
+
180
+ try:
181
+ with open(status_path, "r", encoding="utf-8") as f:
182
+ status = f.read().strip()
183
+
184
+ status_lower = status.lower()
185
+ if status_lower != InstanceState.LOADED.value:
186
+ click.echo(
187
+ f"Error: Kernel image not loaded for instance '{instance_name}' (ID: {instance_id})",
188
+ err=True,
189
+ )
190
+ click.echo(
191
+ f"Current status: '{status}' (expected: '{InstanceState.LOADED.value}')",
192
+ err=True,
193
+ )
194
+ click.echo(
195
+ f"Please load a kernel image first using: kerf load --id={instance_id} --kernel=<path>",
196
+ err=True,
197
+ )
198
+ sys.exit(1)
199
+
200
+ if verbose:
201
+ click.echo(f"Instance status: '{status}'")
202
+ except (OSError, IOError) as e:
203
+ click.echo(f"Error: Failed to read status file: {e}", err=True)
204
+ click.echo(
205
+ f"Please ensure the instance exists and load a kernel image using: kerf load --id={instance_id} --kernel=<path>",
206
+ err=True,
207
+ )
208
+ sys.exit(1)
209
+
210
+ if verbose:
211
+ click.echo(f"✓ Kernel image found for instance '{instance_name}'")
212
+ click.echo(f"Instance ID to boot: {instance_id}")
213
+ click.echo(f"Using reboot syscall with command: 0x{LINUX_REBOOT_CMD_MULTIKERNEL:x}")
214
+ tsc = rdtsc.get_cycles()
215
+ click.echo(f"Calling reboot syscall at TSC {tsc}")
216
+ else:
217
+ click.echo(f"Booting instance '{instance_name}' (ID: {instance_id})...")
218
+
219
+ result = boot_multikernel(instance_id)
220
+
221
+ if verbose:
222
+ click.echo(f"✓ Boot command executed successfully (result: {result})")
223
+ else:
224
+ click.echo("✓ Boot command executed successfully")
225
+
226
+ # Attach to console if requested
227
+ if attach_console:
228
+ from ..console import run_console
229
+
230
+ console_result = run_console(instance_id, instance_name, verbose)
231
+ if console_result != 0:
232
+ sys.exit(console_result)
233
+
234
+ # Note: If successful, this syscall will reboot the system and boot the
235
+ # specified multikernel instance, so we may not reach this point.
236
+
237
+ except OSError as e:
238
+ click.echo(f"Error: reboot syscall failed: {e}", err=True)
239
+ if e.errno == 1: # EPERM
240
+ click.echo("Note: This operation requires root privileges", err=True)
241
+ elif e.errno == 22: # EINVAL
242
+ click.echo(
243
+ f"Error: Invalid arguments for instance '{instance_name}' (ID: {instance_id})",
244
+ err=True,
245
+ )
246
+ click.echo(
247
+ "The kernel may not support the MULTIKERNEL reboot command, or the instance ID is invalid.",
248
+ err=True,
249
+ )
250
+ elif e.errno == 3: # ESRCH
251
+ click.echo("Note: Multikernel instance not found or not loaded.", err=True)
252
+ sys.exit(1)
253
+
254
+ except Exception as e:
255
+ click.echo(f"Unexpected error: {e}", err=True)
256
+ if verbose:
257
+ import traceback
258
+
259
+ traceback.print_exc()
260
+ sys.exit(1)
kerf/init/__init__.py ADDED
@@ -0,0 +1,13 @@
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.