magikpod 0.2.2

Kubernetes-compatible pod orchestration layer
# magikpod

Kubernetes-compatible pod orchestration layer for heterogeneous isolation technologies.

[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
[![Rust](https://img.shields.io/badge/rust-2024-orange.svg)](https://www.rust-lang.org/)
[![Crates.io](https://img.shields.io/crates/v/magikpod.svg)](https://crates.io/crates/magikpod)
[![Documentation](https://docs.rs/magikpod/badge.svg)](https://docs.rs/magikpod)

## Overview

`magikpod` provides pod-level abstractions on top of the OCI-compliant [`magikrun`](https://github.com/magikrun/magikrun) runtime layer. It enables running multi-container pods across different isolation technologies with a unified API.

### Features

- **Pod lifecycle management**: Create, start, stop, delete with proper cleanup
- **Namespace sharing**: Containers within a pod share network, IPC, and UTS namespaces
- **Pause containers**: Hold namespaces alive for the pod's lifetime
- **Multi-container coordination**: Init containers, sidecars, cleanup ordering
- **Kubernetes-compatible manifests**: Parse standard Pod YAML/JSON specs
- **Multiple runtime classes**: Native containers, WebAssembly, MicroVMs

## Runtime Classes

| Runtime Class | Executor | Linux | macOS | Isolation | Use Case |
|---------------|----------|:-----:|:-----:|-----------|----------|
| `pod-containers` | youki ||| Medium | Standard container workloads |
| `pod-wasm` | wasmtime ||| Low | Portable, sandboxed modules |
| `pod-microvm-containers` | krun ||| High | Security-sensitive workloads |

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                         magikpod                               │
├─────────────────────────────────────────────────────────────────┤
│  PodManager trait                                               │
│  ├── create_sandbox() → Creates isolation boundary              │
│  ├── get_namespace_paths() → Returns NS paths for joining       │
│  ├── run_container() → Runs container in sandbox                │
│  ├── signal_container() → Delivers signals                      │
│  └── delete_sandbox() → Cleans up all resources                 │
├─────────────────────────────────────────────────────────────────┤
│                   Pod Manager Implementations                   │
│  ┌───────────────┐ ┌───────────────┐ ┌───────────────┐          │
│  │NativePodManager│ │WasmPodManager │ │MicroVmPodMgr │          │
│  │ (youki + pause)│ │ (wasmtime)    │ │(krun + agent)│          │
│  └───────────────┘ └───────────────┘ └───────────────┘          │
├─────────────────────────────────────────────────────────────────┤
│  TSI Module (MicroVM only)                                      │
│  └── vsock-based communication with guest agent                 │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│                         magikrun                                │
│           Pure OCI Runtime (create/start/kill/delete)           │
└─────────────────────────────────────────────────────────────────┘
```

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
magikpod = "0.1"
```

## Quick Start

```rust
use magikpod::{PodSpec, PodOrchestrator, PodManagerRegistry, NativePodManager};
use magikrun::runtimes::NativeRuntime;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create runtime and pod manager
    let runtime = NativeRuntime::new("/usr/bin/youki");
    let mut registry = PodManagerRegistry::new();
    registry.register(Box::new(NativePodManager::new(Box::new(runtime))));

    // Parse pod manifest
    let yaml = r#"
    apiVersion: v1
    kind: Pod
    metadata:
      name: nginx-pod
      namespace: default
    spec:
      containers:
      - name: nginx
        image: nginx:1.25
        ports:
        - containerPort: 80
    "#;

    let spec = PodSpec::from_yaml(yaml.as_bytes())?;
    
    // Run pod
    let orchestrator = PodOrchestrator::new(registry);
    let pod_id = orchestrator.run_pod(&spec).await?;
    
    println!("Pod started: {}", pod_id);
    
    // Stop pod (30s grace period)
    orchestrator.stop_pod(&pod_id, 30).await?;
    
    Ok(())
}
```

## Pod Manifest Format

magikpod supports Kubernetes-compatible pod manifests:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: multi-container-pod
  namespace: production
  labels:
    app: myapp
spec:
  runtimeClassName: pod-containers  # or pod-wasm, pod-microvm-containers
  containers:
  - name: app
    image: myapp:v1.0
    command: ["/app/server"]
    args: ["--port", "8080"]
    env:
    - name: LOG_LEVEL
      value: info
    ports:
    - containerPort: 8080
    resources:
      limits:
        memory: "256Mi"
        cpu: "500m"
    volumeMounts:
    - name: config
      mountPath: /etc/myapp
      readOnly: true
  - name: sidecar
    image: envoy:v1.28
    ports:
    - containerPort: 9901
  volumes:
  - name: config
    configMap:
      name: myapp-config
```

## Security Model

Resource limits are enforced at all layers to prevent DoS attacks:

| Limit | Value | Description |
|-------|-------|-------------|
| `MAX_PODS` | 1024 | Maximum pods per orchestrator |
| `MAX_CONTAINERS_PER_POD` | 16 | Maximum containers per pod |
| `MAX_VOLUMES_PER_POD` | 64 | Maximum volumes per pod |
| `MAX_MANIFEST_SIZE` | 1 MiB | Maximum manifest file size |
| `MAX_ENV_VARS_PER_CONTAINER` | 256 | Maximum env vars per container |
| `MAX_GRACE_PERIOD_SECS` | 300 | Maximum termination grace period |

All names are validated against RFC 1123 DNS subdomain rules.

## TSI (Transparent Socket Impersonation)

For MicroVM pods, magikpod includes a guest agent (`magikagent`) that runs inside the VM and handles:

- Signal delivery to containers
- Container status queries
- Health probes (liveness/readiness)
- Exec sessions via nsenter
- Log streaming (planned)

Communication uses vsock (AF_VSOCK) with JSON-over-newline protocol:

```
Host                             Guest (magikagent)
  │                                 │
  │  {"action":"signal",...}\n      │
  │────────────────────────────────▶│
  │                                 │
  │  {"status":"ok",...}\n          │
  │◀────────────────────────────────│
```

## Modules

| Module | Description |
|--------|-------------|
| `constants` | Resource limits, timeouts, and paths |
| `error` | Structured error types |
| `manifest` | Kubernetes-compatible pod/container spec parsing |
| `pod` | Pod and container state types |
| `sandbox` | Core `PodManager` trait and `PodOrchestrator` |
| `managers` | Runtime-specific pod manager implementations |
| `tsi` | MicroVM guest agent communication protocol |

## Building

```bash
# Build library
cargo build --release

# Build guest agent binary
cargo build --release --bin magikagent

# Run tests
cargo test

# Generate documentation
cargo doc --open
```

## Requirements

### Native Containers (`pod-containers`)

- Linux with cgroup v2
- OCI-compliant runtime (youki, crun, runc)

### WebAssembly (`pod-wasm`)

- wasmtime runtime
- Cross-platform (Linux, macOS)

### MicroVMs (`pod-microvm-containers`)

- Linux: KVM support
- macOS: Hypervisor.framework
- libkrun runtime

## Contributing

Contributions are welcome! 

## License

Apache 2.0 - see [LICENSE](LICENSE) for details.