# Cloud Hypervisor SAL - Rhai Scripts

This directory contains production-ready Rhai scripts demonstrating all features of the Cloud Hypervisor Service Abstraction Layer.

## Available Scripts

### 01_basic_vm_template.rhai
**Basic VM Template - Start Here**

A simple, well-documented template for creating and running VMs. Perfect starting point for your own scripts.

**Features:**
- Auto-detects Cloud Hypervisor binary
- Basic VM configuration (kernel, initramfs, disk)
- Clean lifecycle: create → start → run → stop

**Usage:**
```bash
sudo herodo 01_basic_vm_template.rhai
```

**What to customize:**
- Kernel path
- Initramfs path
- Disk image path
- CPU count and memory size

---

### 02_vm_lifecycle_control.rhai
**Complete VM Lifecycle Control**

Demonstrates all VM control operations with proper state transitions.

**Features:**
- Start, pause, resume, reset (reboot), stop
- Status checking after each operation
- Proper sleep delays between operations
- Shows VM state management

**Usage:**
```bash
sudo herodo 02_vm_lifecycle_control.rhai
```

**Learn about:**
- VM state transitions
- Pause/resume for maintenance
- VM reset (reboot) operation
- Status monitoring

---

### 03_resource_hotadd.rhai
**Dynamic Resource Scaling**

Shows how to dynamically increase CPU and memory while VM is running.

**Features:**
- Memory hot-add (1GB → 2GB → 4GB)
- vCPU hot-add (2 → 4 → 6 CPUs)
- Demonstrates incremental scaling
- No VM restart required

**Usage:**
```bash
sudo herodo 03_resource_hotadd.rhai
```

**Learn about:**
- Live memory expansion
- Live CPU scaling
- Resource management best practices

**Important:** Memory and vCPU can only be **increased**, never decreased.

---

### 04_device_hotplug.rhai
**Device Hot-Plug Operations**

Demonstrates adding and removing devices at runtime without VM restart.

**Features:**
- Hot-plug virtio-blk (disk) devices
- Hot-plug virtio-net (network) devices
- Hot-plug virtio-fs (filesystem) devices
- Hot-unplug devices

**Usage:**
```bash
sudo herodo 04_device_hotplug.rhai
```

**Learn about:**
- Runtime device management
- Supported device types for hot-plug
- Device ID management

**Important:** VFIO devices cannot be hot-plugged and must be configured at VM creation.

---

### 05_snapshot_operations.rhai
**Snapshot Management**

Complete snapshot lifecycle: create, list, delete, and restore.

**Features:**
- Create multiple snapshots
- List all snapshots for a VM
- Delete specific snapshots
- Snapshot metadata management

**Usage:**
```bash
sudo herodo 05_snapshot_operations.rhai
```

**Learn about:**
- Snapshot creation workflow
- Snapshot organization
- Snapshot cleanup

**Important:** Snapshots are **host-local only** and cannot be restored on different machines.

---

### 06_error_handling_guide.rhai
**Error Handling & API Limitations**

Educational script documenting supported vs unsupported operations.

**Features:**
- Shows supported operations (vCPU/memory hot-add, device hot-plug)
- Explains unsupported operations (vCPU/memory removal, VFIO hot-plug)
- Documents API limitations with clear explanations
- Best practices for error handling

**Usage:**
```bash
sudo herodo 06_error_handling_guide.rhai
```

**Learn about:**
- What operations are supported
- Why certain operations are not supported
- Linux kernel and Cloud Hypervisor limitations
- How to handle errors gracefully

---

## Quick Start

### 1. Start with the Template
```bash
# Copy and customize the template
cp 01_basic_vm_template.rhai my_vm.rhai
# Edit paths in my_vm.rhai
nano my_vm.rhai
# Run your script
sudo herodo my_vm.rhai
```

### 2. Prerequisites

Before running any script, ensure you have:
- Cloud Hypervisor installed (`/usr/local/bin/cloud-hypervisor` or in PATH)
- Linux kernel with KVM support
- VM images (kernel, initramfs, disk)
- Appropriate permissions (run with `sudo`)

### 3. Common Configuration

All scripts require these paths to be customized:
```rhai
let kernel_path = "/path/to/vmlinux";        // Your kernel
let initramfs_path = "/path/to/initrd.img";  // Your initramfs
let disk_path = "/path/to/disk.img";         // Your disk image
```

## Script Execution Order

For learning, we recommend running scripts in this order:

1. **01_basic_vm_template.rhai** - Learn basic VM creation
2. **02_vm_lifecycle_control.rhai** - Learn VM state management
3. **03_resource_hotadd.rhai** - Learn dynamic scaling
4. **04_device_hotplug.rhai** - Learn device management
5. **05_snapshot_operations.rhai** - Learn snapshot workflow
6. **06_error_handling_guide.rhai** - Learn limitations and best practices

## Common Patterns

### Runtime Initialization
```rhai
let runtime = RuntimeBuilder()
    .api_socket("/tmp/ch-vm.sock");

if !init_runtime(runtime) {
    print("❌ Failed to initialize runtime. Exiting.");
    return;
}
```

### VM Creation
```rhai
let vm = VMBuilder()
    .kernel(kernel_path)
    .initramfs(initramfs_path)
    .cmdline("console=ttyS0 root=/dev/vda1")
    .memory(2048)
    .cpus(2)
    .virtio_blk(disk_path, false)
    .build();

let handle = create_vm(vm);
```

### Sleep Between Operations
Always add sleep delays between operations to allow VM to stabilize:
```rhai
start_vm(handle);
sleep(3000);  // Wait 3 seconds
pause_vm(handle);
sleep(2000);  // Wait 2 seconds
resume_vm(handle);
```

## Troubleshooting

### Script fails with "Failed to initialize runtime"
- Check Cloud Hypervisor is installed: `which cloud-hypervisor`
- Verify binary path or let it auto-detect
- Ensure you have permissions: run with `sudo`

### Script fails with "API socket not found"
- Ensure socket path is unique per VM
- Check no other VM is using the same socket
- Verify socket directory exists and is writable

### VM fails to start
- Verify kernel path is correct
- Verify initramfs path is correct
- Ensure disk image exists and has correct permissions
- Check Cloud Hypervisor logs if specified

### Device hot-plug fails
- Ensure VM is running (not paused or stopped)
- Verify device paths exist
- Check device ID is unique
- Remember: VFIO devices cannot be hot-plugged

## Best Practices

1. **Always check `init_runtime()` return value** - Don't continue if initialization fails
2. **Use unique socket paths** - Each VM needs its own API socket
3. **Add sleep delays** - Allow VM to stabilize between operations (2-5 seconds)
4. **Handle errors gracefully** - Check return values and provide clear error messages
5. **Clean up resources** - Always stop VMs when done
6. **Document your scripts** - Add comments explaining what each section does

## Security Notes

- Scripts require `sudo` for KVM access and network configuration
- API sockets should be in secure directories (`/tmp` or user-owned)
- Never expose API sockets over the network
- Use seccomp and landlock when available (enabled by default)

## Additional Resources

- Main README: `../README.md` - Complete API reference
- Examples: `../examples/README.md` - More complex examples
- Source code: `../src/` - Implementation details

## Contributing

When adding new scripts:
1. Follow the naming convention: `NN_descriptive_name.rhai`
2. Add comprehensive comments
3. Include proper error handling
4. Add sleep delays between operations
5. Update this README with script description
6. Test thoroughly before committing
