Phase 1: local kernel catalog scaffolding

Introduces a read/write kernel catalog on disk without any network
dependency, so later phases (image register --kernel-ref, import, pull)
can build on a working foundation.

Layout: adds KernelsDir to paths.Layout, ensured under
~/.local/state/banger/kernels/. Each cataloged kernel lives at
<KernelsDir>/<name>/ with a manifest.json alongside vmlinux and optional
initrd.img / modules/.

New internal/kernelcat package owns the disk format:
- Entry (Name, Distro, Arch, KernelVersion, SHA256, Source, ImportedAt)
- ValidateName (alphanumeric + dots/hyphens/underscores, no traversal)
- ReadLocal / ListLocal / WriteLocal / DeleteLocal
- SumFile helper

The daemon exposes three RPC methods dispatched in daemon.go:
kernel.list, kernel.show, kernel.delete. Implementations live in a new
internal/daemon/kernels.go and are thin wrappers over kernelcat using
d.layout.KernelsDir.

CLI: new top-level `banger kernel` with list / show / rm subcommands
mirroring the image-command pattern (ensureDaemon, RPC call, table or
JSON output). No sudo required — kernel ops are user-space only.

Users can now manually populate ~/.local/state/banger/kernels/<name>/
and see it via `banger kernel list`. Phase 2 wires --kernel-ref into
image register; Phase 3 adds `banger kernel import`; Phase 4 adds
remote pulls.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Thales Maciel 2026-04-16 14:21:10 -03:00
parent ca4865447c
commit 83cc3aee15
No known key found for this signature in database
GPG key ID: 33112E6833C34679
9 changed files with 691 additions and 3 deletions

View file

@ -0,0 +1,184 @@
// Package kernelcat is the on-disk catalog of Firecracker-ready kernel
// bundles. Each entry lives at <kernelsDir>/<name>/ and contains a
// manifest.json alongside the vmlinux, optional initrd.img, and optional
// modules/ tree. The package owns the layout, manifest read/write, and
// validation; it does not talk to the network (remote pulls are layered on
// later).
package kernelcat
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
// Filenames used inside an entry directory.
const (
manifestFilename = "manifest.json"
kernelFilename = "vmlinux"
initrdFilename = "initrd.img"
modulesDirName = "modules"
)
// Entry describes a cataloged kernel bundle. Paths are absolute and
// populated from the entry's on-disk layout when read via ReadLocal /
// ListLocal; they are never written into the manifest itself.
type Entry struct {
Name string `json:"name"`
Distro string `json:"distro,omitempty"`
Arch string `json:"arch,omitempty"`
KernelVersion string `json:"kernel_version,omitempty"`
SHA256 string `json:"sha256,omitempty"`
Source string `json:"source,omitempty"`
ImportedAt time.Time `json:"imported_at"`
// Populated on read, not persisted:
KernelPath string `json:"-"`
InitrdPath string `json:"-"`
ModulesDir string `json:"-"`
}
// namePattern matches names that are safe as single filesystem components.
// Intentionally strict so entry names stay short and script-friendly.
var namePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$`)
// ValidateName returns an error unless name is a non-empty identifier made
// of alphanumerics, dots, hyphens, and underscores, starting with an
// alphanumeric and at most 64 characters long.
func ValidateName(name string) error {
if strings.TrimSpace(name) == "" {
return errors.New("kernel name is required")
}
if !namePattern.MatchString(name) {
return fmt.Errorf("invalid kernel name %q: use alphanumerics, dots, hyphens, underscores (<=64 chars, starts with alphanumeric)", name)
}
return nil
}
// EntryDir returns the absolute directory path for name under kernelsDir.
func EntryDir(kernelsDir, name string) string {
return filepath.Join(kernelsDir, name)
}
// ReadLocal reads the manifest for name and resolves per-artifact paths.
// Returns os.ErrNotExist-compatible error if the entry is missing.
func ReadLocal(kernelsDir, name string) (Entry, error) {
if err := ValidateName(name); err != nil {
return Entry{}, err
}
dir := EntryDir(kernelsDir, name)
data, err := os.ReadFile(filepath.Join(dir, manifestFilename))
if err != nil {
return Entry{}, err
}
var entry Entry
if err := json.Unmarshal(data, &entry); err != nil {
return Entry{}, fmt.Errorf("parse manifest for %q: %w", name, err)
}
if entry.Name == "" {
entry.Name = name
}
if entry.Name != name {
return Entry{}, fmt.Errorf("manifest name %q does not match directory %q", entry.Name, name)
}
entry.KernelPath = filepath.Join(dir, kernelFilename)
if fi, err := os.Stat(filepath.Join(dir, initrdFilename)); err == nil && !fi.IsDir() {
entry.InitrdPath = filepath.Join(dir, initrdFilename)
}
if fi, err := os.Stat(filepath.Join(dir, modulesDirName)); err == nil && fi.IsDir() {
entry.ModulesDir = filepath.Join(dir, modulesDirName)
}
return entry, nil
}
// ListLocal returns every entry under kernelsDir with a readable manifest,
// sorted by name. Directories without a manifest are skipped silently so
// partial imports don't break the list.
func ListLocal(kernelsDir string) ([]Entry, error) {
dirEntries, err := os.ReadDir(kernelsDir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
entries := make([]Entry, 0, len(dirEntries))
for _, de := range dirEntries {
if !de.IsDir() {
continue
}
name := de.Name()
if err := ValidateName(name); err != nil {
continue
}
entry, err := ReadLocal(kernelsDir, name)
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
entries = append(entries, entry)
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
return entries, nil
}
// WriteLocal persists entry's manifest.json. The caller is responsible for
// placing vmlinux / initrd.img / modules/ under the entry dir first.
func WriteLocal(kernelsDir string, entry Entry) error {
if err := ValidateName(entry.Name); err != nil {
return err
}
dir := EntryDir(kernelsDir, entry.Name)
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
if entry.ImportedAt.IsZero() {
entry.ImportedAt = time.Now().UTC()
}
data, err := json.MarshalIndent(entry, "", " ")
if err != nil {
return err
}
return os.WriteFile(filepath.Join(dir, manifestFilename), append(data, '\n'), 0o644)
}
// DeleteLocal removes the entry directory entirely. Missing entries are a
// no-op so callers can idempotently clean up.
func DeleteLocal(kernelsDir, name string) error {
if err := ValidateName(name); err != nil {
return err
}
dir := EntryDir(kernelsDir, name)
if _, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
return os.RemoveAll(dir)
}
// SumFile returns the hex-encoded SHA256 of the file at path.
func SumFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, f); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}

View file

@ -0,0 +1,171 @@
package kernelcat
import (
"errors"
"os"
"path/filepath"
"testing"
"time"
)
func TestValidateName(t *testing.T) {
t.Parallel()
cases := []struct {
name string
wantErr bool
}{
{"void-6.12", false},
{"alpine_3.20", false},
{"a", false},
{"Void-6.12", false},
{"", true},
{"-leading-dash", true},
{".leading-dot", true},
{"has space", true},
{"has/slash", true},
{"../escape", true},
}
for _, tc := range cases {
err := ValidateName(tc.name)
if tc.wantErr && err == nil {
t.Errorf("ValidateName(%q) err=nil, want error", tc.name)
}
if !tc.wantErr && err != nil {
t.Errorf("ValidateName(%q) err=%v, want nil", tc.name, err)
}
}
}
func TestWriteAndReadLocalRoundTrip(t *testing.T) {
t.Parallel()
dir := t.TempDir()
entry := Entry{
Name: "void-6.12",
Distro: "void",
Arch: "x86_64",
KernelVersion: "6.12.79_1",
SHA256: "deadbeef",
Source: "import:testdata",
}
if err := WriteLocal(dir, entry); err != nil {
t.Fatalf("WriteLocal: %v", err)
}
kernelPath := filepath.Join(dir, entry.Name, "vmlinux")
if err := os.WriteFile(kernelPath, []byte("kernel-bytes"), 0o644); err != nil {
t.Fatalf("write kernel: %v", err)
}
modulesPath := filepath.Join(dir, entry.Name, "modules", "6.12.79_1", "modules.dep")
if err := os.MkdirAll(filepath.Dir(modulesPath), 0o755); err != nil {
t.Fatalf("mkdir modules: %v", err)
}
if err := os.WriteFile(modulesPath, []byte(""), 0o644); err != nil {
t.Fatalf("write modules stub: %v", err)
}
got, err := ReadLocal(dir, entry.Name)
if err != nil {
t.Fatalf("ReadLocal: %v", err)
}
if got.Name != entry.Name || got.Distro != "void" || got.KernelVersion != "6.12.79_1" {
t.Fatalf("ReadLocal round-trip mismatch: %+v", got)
}
if got.KernelPath != kernelPath {
t.Errorf("KernelPath = %q, want %q", got.KernelPath, kernelPath)
}
if got.InitrdPath != "" {
t.Errorf("InitrdPath = %q, want empty (no initrd on disk)", got.InitrdPath)
}
if got.ModulesDir != filepath.Join(dir, entry.Name, "modules") {
t.Errorf("ModulesDir = %q", got.ModulesDir)
}
if got.ImportedAt.IsZero() {
t.Errorf("ImportedAt not populated by WriteLocal")
}
if time.Since(got.ImportedAt) > time.Minute {
t.Errorf("ImportedAt too far in the past: %v", got.ImportedAt)
}
}
func TestReadLocalRejectsMismatchedName(t *testing.T) {
t.Parallel()
dir := t.TempDir()
entryDir := filepath.Join(dir, "void-6.12")
if err := os.MkdirAll(entryDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(entryDir, manifestFilename), []byte(`{"name":"other"}`), 0o644); err != nil {
t.Fatal(err)
}
if _, err := ReadLocal(dir, "void-6.12"); err == nil {
t.Fatal("ReadLocal should reject manifest with mismatched name")
}
}
func TestListLocalSkipsManifestless(t *testing.T) {
t.Parallel()
dir := t.TempDir()
if err := WriteLocal(dir, Entry{Name: "alpine-3.20"}); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(dir, "orphan"), 0o755); err != nil {
t.Fatal(err)
}
entries, err := ListLocal(dir)
if err != nil {
t.Fatalf("ListLocal: %v", err)
}
if len(entries) != 1 || entries[0].Name != "alpine-3.20" {
t.Fatalf("ListLocal = %+v, want one alpine-3.20", entries)
}
}
func TestListLocalReturnsEmptyForMissingDir(t *testing.T) {
t.Parallel()
entries, err := ListLocal(filepath.Join(t.TempDir(), "nope"))
if err != nil {
t.Fatalf("ListLocal: %v", err)
}
if len(entries) != 0 {
t.Fatalf("ListLocal = %v, want empty", entries)
}
}
func TestDeleteLocalRemovesEntry(t *testing.T) {
t.Parallel()
dir := t.TempDir()
if err := WriteLocal(dir, Entry{Name: "void-6.12"}); err != nil {
t.Fatal(err)
}
if err := DeleteLocal(dir, "void-6.12"); err != nil {
t.Fatalf("DeleteLocal: %v", err)
}
if _, err := os.Stat(EntryDir(dir, "void-6.12")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected entry dir removed, stat err=%v", err)
}
}
func TestDeleteLocalIdempotent(t *testing.T) {
t.Parallel()
if err := DeleteLocal(t.TempDir(), "never-existed"); err != nil {
t.Fatalf("DeleteLocal on missing entry: %v", err)
}
}
func TestSumFileMatchesSHA256(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "data")
if err := os.WriteFile(path, []byte("banger"), 0o644); err != nil {
t.Fatal(err)
}
sum, err := SumFile(path)
if err != nil {
t.Fatalf("SumFile: %v", err)
}
// precomputed sha256("banger")
const want = "e0c69eae8afb38872fa425c2cdba794176f3b9d97e8eefb7b0e7c831f566458f"
if sum != want {
t.Fatalf("SumFile = %q, want %q", sum, want)
}
}