herolib-virt 0.3.13

Virtualization and container management for herolib (buildah, nerdctl, kubernetes)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# herolib-virt Architecture Guide

## Overview

`herolib-virt` is a comprehensive virtualization and containerization library providing Rust bindings and Rhai scripting support for container image building, container management, virtual machine operations, and Kubernetes cluster management.

## System Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    herolib-virt Library                      │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌──────────────────────────────────────────────────────┐   │
│  │           User Application (Rust or Rhai)            │   │
│  └──────────────────────────────────────────────────────┘   │
│                           │                                  │
│           ┌───────────────┴───────────────┐                 │
│           ▼                               ▼                 │
│  ┌─────────────────────┐      ┌───────────────────────┐    │
│  │  Rhai Integration   │      │   Rust API Layer      │    │
│  │  (rhai module)      │      │                       │    │
│  │                     │      │ - Direct types        │    │
│  │ - Functions         │      │ - Trait implementations│    │
│  │ - Type bindings     │      │ - Error handling      │    │
│  │ - Fluent API        │      │                       │    │
│  └─────────────────────┘      └───────────────────────┘    │
│           │                               │                 │
│           └───────────────┬───────────────┘                 │
│                           ▼                                  │
│           ┌──────────────────────────────┐                  │
│           │    Core Module Implementations   │               │
│           └──────────────────────────────┘                  │
│                    │                                         │
│  ┌─────────────────┼────────────────────────────┐           │
│  │                 │                            │            │
│  ▼                 ▼                            ▼            │
│┌──────────┐  ┌──────────────┐  ┌──────────────────────┐    │
││ Buildah  │  │   Nerdctl    │  │  Kubernetes Module   │    │
││          │  │              │  │                      │    │
││- Builder │  │- Container   │  │- KubernetesManager  │    │
││- Images  │  │- Images      │  │- Build Machine      │    │
││- Remote  │  │- Health      │  │- Dev Machine        │    │
││- Content │  │- Logs        │  │- Registry           │    │
│└──────────┘  └──────────────┘  │- Traefik            │    │
│                                │- Fluent API         │    │
│  ┌──────────┐  ┌──────────┐   └──────────────────────┘    │
│  │ Cloud HV │  │  QCOW2   │                               │
│  │          │  │          │   ┌──────────────────────┐    │
│  │- VM Spec │  │- Create  │   │  Kubernetes Submodules  │    │
│  │- VM Ops  │  │- Snapshot│   │                      │    │
│  │- Paths   │  │- Info    │   │- config              │    │
│  │- Utils   │  │- Ubuntu  │   │- error               │    │
│  └──────────┘  └──────────┘   │- fluent              │    │
│                                │- kubebuilder        │    │
│                                │- kubernetes_manager │    │
│                                │- kubessh             │    │
│                                │- kubedevel           │    │
│                                │- registry            │    │
│                                │- traefik             │    │
│                                └──────────────────────┘    │
│                                                               │
└─────────────────────────────────────────────────────────────┘
            ┌──────────────┼──────────────┐
            ▼              ▼              ▼
      ┌──────────┐  ┌──────────┐  ┌──────────────┐
      │ buildah  │  │ nerdctl  │  │  kubectl /   │
      │          │  │          │  │  containerd  │
      └──────────┘  └──────────┘  └──────────────┘
            ┌──────────────┴──────────────┐
            ▼                             ▼
      ┌──────────────┐           ┌──────────────────┐
      │   Containerd │           │   Kubernetes API │
      │              │           │                  │
      │- Runtime     │           │- API Server      │
      │- Images      │           │- etcd            │
      │- Containers  │           │- Controllers     │
      └──────────────┘           └──────────────────┘
```

## Module Organization

### 1. Core Container Modules

#### Buildah (`src/buildah/`)
**Purpose**: Build OCI/Docker-compatible container images

**Key Components**:
- `Builder`: Main builder type with fluent API
- `BuildahError`: Error type
- `RemoteExecution`: SSH/kubectl remote build support
- `ContentOperations`: File/content operations in containers

**Key Responsibilities**:
- Container creation from base images
- Command execution in containers
- File/content management (write, read, copy)
- Image metadata configuration (entrypoint, cmd, env, labels)
- Image committing and persistence
- Registry push/pull operations

**Design Pattern**: Fluent builder with method chaining

```rust
builder.run("command")
       .write("content", "/path")
       .set_entrypoint("/bin/app")
       .commit("image:tag")?
```

#### Nerdctl (`src/nerdctl/`)
**Purpose**: Container lifecycle management with containerd

**Key Components**:
- `Container`: Container type with state
- `ContainerBuilder`: Fluent builder for container creation
- `ContainerStatus`: Enum for container states
- `HealthCheck`: Health check configuration
- Image operations (pull, push, list, remove)
- Container operations (create, run, start, stop, remove)

**Key Responsibilities**:
- Container CRUD operations
- Image management
- Port mapping and networking
- Resource limits (CPU, memory)
- Environment variable management
- Volume mounting
- Health check configuration
- Log retrieval and monitoring

**Design Pattern**: 
- Direct functions for simple operations
- Builder pattern for complex configurations
- Stateful Container type for tracking state

### 2. Virtual Machine Modules

#### Cloud Hypervisor (`src/cloudhv/`)
**Purpose**: Virtual machine creation and lifecycle management

**Key Components**:
- `VmSpec`: VM specification (CPU, memory, disk, firmware)
- `VmRuntime`: Runtime state of a VM
- `VmRecord`: Persistent VM record
- Error types and utilities

**Key Responsibilities**:
- VM creation and deletion
- Start/stop/reboot operations
- VM info queries
- VM listing and discovery
- Path management for VM data

**Design Pattern**: Functional API with structured data

```rust
let spec = VmSpec { ... };
vm_create(&spec)?;
vm_start("vm-id")?;
```

#### QCOW2 (`src/qcow2/`)
**Purpose**: QCOW2 disk image management

**Key Components**:
- `create()`: Create new disk images
- `snapshot_*()`: Snapshot operations
- `info()`: Image information
- `build_ubuntu_24_04_base()`: Cloud image builder

**Key Responsibilities**:
- Disk image creation with sparse allocation
- Snapshot creation/deletion/listing
- Image information queries
- Ubuntu cloud image downloading and preparation
- Resize operations

**Design Pattern**: Functional API wrapping qemu-img CLI

### 3. Kubernetes Module (`src/kubernetes/`)

The Kubernetes module is the most complex, with multiple specialized sub-modules:

#### Architecture

```
kubernetes/
├── kubernetes_manager.rs     # Main API entry point
├── fluent.rs                # Builder pattern for resources
├── kubebuilder.rs           # Container image building in K8s
├── kubedevel.rs             # SSH dev environment
├── kubessh.rs               # SSH client for pods
├── registry.rs              # Registry deployment
├── traefik.rs               # Ingress/routing config
├── config.rs                # Configuration types
└── error.rs                 # Error types
```

**Key Components**:

1. **KubernetesManager**
   - Primary entry point
   - Namespace-scoped operations
   - Resource CRUD operations
   - Pattern-based deletion
   - Async/await based

2. **Fluent Builders**
   - `PodBuilder`, `ServiceBuilder`, `DeploymentBuilder`
   - `ConfigMapBuilder`, `SecretBuilder`
   - Chainable configuration
   - Type-safe K8s resource creation

3. **BuildMachine**
   - Runs Buildah in Kubernetes pods
   - Builds container images in-cluster
   - Integrates with registries

4. **DevelopmentMachine**
   - SSH-accessible development environment
   - Interactive pod shells
   - Port forwarding

5. **RegistryDeployer**
   - Deploy Docker/OCI registries in K8s
   - Authentication and secrets
   - Storage configuration

6. **Traefik Integration**
   - Ingress route configuration
   - Load balancing
   - TLS/SSL setup
   - Middleware support

**Design Pattern**: 
- Primary: Async functional API with `KubernetesManager`
- Secondary: Fluent builders for complex resources
- Namespace scoping: Each manager instance = one namespace

### 4. Rhai Integration (`src/rhai/`)

**Purpose**: Expose all functionality to Rhai scripting language

**Key Components**:
- `buildah.rs`: Buildah Rhai bindings
- `nerdctl.rs`: Nerdctl Rhai bindings  
- `cloudhv.rs`: Cloud HV Rhai bindings
- `qcow2.rs`: QCOW2 Rhai bindings
- `kubernetes/`: Kubernetes Rhai bindings

**Integration Patterns**:
- Each module implements `IntoRhai` trait
- Type conversions for compatibility
- Function registration in Rhai engine
- Special fluent APIs for scripting (e.g., `bah()` for Buildah)

**Design**: Mirrored module structure with Rhai-specific adaptations

## Design Patterns

### 1. Async/Await First

All Kubernetes operations are async and require a tokio runtime:

```rust
#[tokio::main]
async fn main() {
    let km = KubernetesManager::new("default").await?;
    let pods = km.pods_list().await?;
}
```

**Why**: 
- Better performance with multiple concurrent operations
- Aligns with Kubernetes API patterns
- Modern Rust best practice

### 2. Builder Pattern

Used for complex configurations:

```rust
ContainerBuilder::new("name", "image")
    .port(80, 8080)
    .env("KEY", "value")
    .memory_limit("512m")
    .build()?
```

**Why**:
- Type-safe configuration
- Readable, fluent API
- Defaults handling
- Chainable method calls

### 3. Error Handling

Each module has its own error type:
- `BuildahError`
- `NerdctlError`
- `CloudHvError`
- `Qcow2Error`
- `KubernetesError`

All implement `std::error::Error` and provide detailed context.

### 4. Namespace Scoping (Kubernetes)

Each `KubernetesManager` is tied to a namespace:

```rust
let prod = KubernetesManager::new("prod").await?;
let dev = KubernetesManager::new("dev").await?;
```

**Rationale**:
- Prevents accidental cross-namespace operations
- Type-safe namespace selection
- Clearer code intent

### 5. Functional and Object-Oriented Mix

Different modules use different paradigms:

- **Functional**: CloudHV, QCOW2 (simple wrapped CLIs)
- **Object-Oriented**: Buildah, Nerdctl (stateful builders)
- **Async Object-Oriented**: Kubernetes (complex state + async)

This allows each module to use the best fit paradigm.

## Data Flow Examples

### Container Image Building (Buildah)

```
User Code
Builder::new() ─→ Create container from base image
builder.run() ─→ Execute command in container
builder.write() ─→ Write files/content to container
builder.config() ─→ Set metadata (env, labels, etc.)
builder.commit() ─→ Commit to image in local storage
Result: Image ID/Name
```

### Container Lifecycle (Nerdctl)

```
User Code
ContainerBuilder ─→ Configure container
builder.build() ─→ Create container
container_start() ─→ Start container
container_info() ─→ Get status/info
container_stop() ─→ Stop gracefully
container_remove() ─→ Delete container
```

### Kubernetes Deployment

```
User Code
KubernetesManager::new("ns") ─→ Connect to cluster/namespace
DeploymentBuilder ─→ Configure deployment
builder.apply() ─→ Create deployment in K8s
km.deployment_get() ─→ Wait for readiness
Result: Running pods
```

### VM Lifecycle (Cloud HV + QCOW2)

```
User Code
qcow2::create() ─→ Create disk image
VmSpec ─→ Define VM configuration
vm_create() ─→ Create VM
vm_start() ─→ Boot VM
vm_info() ─→ Check status
vm_stop() ─→ Shutdown
vm_delete() ─→ Remove VM
```

## Dependency Management

### External Dependencies

**Container/Image Building**:
- `buildah` CLI
- Podman/Docker runtime (for image operations)

**Container Management**:
- `nerdctl` CLI
- Containerd runtime

**VM Management**:
- `cloud-hypervisor` binary
- `qemu-img` tool (for QCOW2)

**Kubernetes Management**:
- Kubernetes cluster (1.20+)
- kubeconfig file
- `kubectl` (optional, for debugging)

### Internal Dependencies

```
herolib-virt
├── herolib-os          # OS utilities (process, filesystem)
├── herolib-core        # Core types and traits
└── External crates
    ├── tokio           # Async runtime
    ├── serde/serde_json # Serialization
    ├── rhai            # Scripting language
    ├── kube            # Kubernetes client (optional)
    └── ... others ...
```

## Feature Flags

```rust
// Cargo.toml
herolib-virt = { version = "...", features = ["rhai", "kubernetes"] }
```

- **rhai** (default): Enable Rhai scripting support
- **kubernetes**: Enable Kubernetes management
- **full**: Enable all features

## Performance Characteristics

### Memory Usage
- Base library: ~50 MB (without features)
- With Kubernetes: +100 MB (for kube client)
- With Rhai: +30 MB (for script engine)

### Network I/O
- Kubernetes operations: Minimal (API calls)
- Container operations: Depends on image size
- Registry operations: Can be large (image pulls)

### Execution Time
- Container creation: 100ms - 1s
- Image build: 1s - 10m (depends on layers)
- VM creation: 2 - 5 seconds
- Disk image creation: ~100ms

## Testing Strategy

Each module includes:
- Unit tests for individual functions
- Integration tests for workflows
- Example scripts (Rhai and Rust)
- Error path testing

**Run tests**:
```bash
cargo test
cargo test --features kubernetes
```

## Extension Points

To extend herolib-virt:

1. **Add new container runtime**: Create `new_runtime/` module
2. **Add new VM hypervisor**: Create `new_hypervisor/` module
3. **Add Rhai bindings**: Implement `IntoRhai` traits
4. **Add error types**: Implement `std::error::Error`

## Best Practices

1. **Always use builders for complex configs**
2. **Handle errors explicitly** - don't unwrap
3. **Use async/await for Kubernetes** - don't block
4. **Namespace your Kubernetes operations** - don't use default
5. **Clean up resources** - remove containers, stop VMs
6. **Use snapshots** - create before major changes
7. **Log operations** - enable debug for troubleshooting
8. **Test in dev first** - before production

## Security Considerations

1. **Credentials**: Use RBAC, service accounts, kubeconfig
2. **Network**: Use TLS for registry access
3. **Permissions**: Minimum required for operations
4. **Secrets**: Don't log sensitive values
5. **Images**: Use signed/verified images when possible
6. **Isolation**: Separate namespaces for different concerns

## See Also

- README.md - Feature overview
- src/buildah/README.md - Buildah details
- src/kubernetes/README.md - Kubernetes details
- src/qcow2/README.md - QCOW2 details
- Examples in examples/ and rhaiexamples/