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
use crate::cloudhv::api::{APIClient, RestoreConfig};
use crate::cloudhv::config::{CloudHypervisorConfig, DeviceConfig, VMConfig, VMSpec};
use crate::cloudhv::errors::{CloudHypervisorError, Result};
use crate::cloudhv::process::CloudHypervisorProcess;
use crate::cloudhv::snapshot::{SnapshotInfo, SnapshotManager};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VMHandle {
    pub id: String,
}

impl VMHandle {
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into() }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum VMStatus {
    Created,
    Running,
    Paused,
    Shutdown,
    Unknown,
}

#[derive(Clone)]
struct VMState {
    #[allow(dead_code)]
    spec: VMSpec,
    status: VMStatus,
}

pub struct CloudHypervisorRuntime {
    config: CloudHypervisorConfig,
    process: Arc<RwLock<Option<CloudHypervisorProcess>>>,
    api_client: Arc<RwLock<Option<APIClient>>>,
    vm_state: Arc<RwLock<Option<VMState>>>,
    snapshot_manager: Arc<SnapshotManager>,
}

impl CloudHypervisorRuntime {
    pub fn new(config: CloudHypervisorConfig) -> Result<Self> {
        config.validate()?;

        let snapshot_base = PathBuf::from("/tmp/ch-snapshots");
        let snapshot_manager = SnapshotManager::new(snapshot_base)?;

        Ok(Self {
            config,
            process: Arc::new(RwLock::new(None)),
            api_client: Arc::new(RwLock::new(None)),
            vm_state: Arc::new(RwLock::new(None)),
            snapshot_manager: Arc::new(snapshot_manager),
        })
    }

    pub fn start(&self) -> Result<()> {
        let mut process_guard = self
            .process
            .write()
            .map_err(|e| CloudHypervisorError::Process(format!("Failed to lock process: {}", e)))?;

        if process_guard.is_some() {
            return Err(CloudHypervisorError::Process(
                "Runtime already started".to_string(),
            ));
        }

        let mut process = CloudHypervisorProcess::new(&self.config.binary_path)?
            .with_api_socket(&self.config.api_socket_path);

        if let Some(log_file) = &self.config.log_file {
            process = process.with_log_file(log_file);
        }

        process = process
            .with_seccomp(self.config.seccomp)
            .with_landlock(self.config.landlock);

        process.start()?;

        let api_client = APIClient::new(&self.config.api_socket_path)?;

        let mut api_guard = self
            .api_client
            .write()
            .map_err(|e| CloudHypervisorError::Api(format!("Failed to lock API client: {}", e)))?;

        *api_guard = Some(api_client);
        *process_guard = Some(process);

        Ok(())
    }

    pub fn stop(&self) -> Result<()> {
        let mut process_guard = self
            .process
            .write()
            .map_err(|e| CloudHypervisorError::Process(format!("Failed to lock process: {}", e)))?;

        if let Some(mut process) = process_guard.take() {
            process.stop()?;
        }

        let mut api_guard = self
            .api_client
            .write()
            .map_err(|e| CloudHypervisorError::Api(format!("Failed to lock API client: {}", e)))?;
        *api_guard = None;

        Ok(())
    }

    pub async fn create_vm(&self, spec: VMSpec) -> Result<VMHandle> {
        let mut vm_state_guard = self.vm_state.write().map_err(|e| {
            CloudHypervisorError::InvalidState(format!("Failed to lock VM state: {}", e))
        })?;

        if vm_state_guard.is_some() {
            return Err(CloudHypervisorError::VmAlreadyExists(
                "Cloud Hypervisor runtime already has a VM. Each runtime instance manages exactly one VM.".to_string(),
            ));
        }

        let api_client = self.get_api_client()?;
        let vm_id = api_client.vm_create(spec.config.clone()).await?;
        let handle = VMHandle::new(vm_id.clone());

        *vm_state_guard = Some(VMState {
            spec,
            status: VMStatus::Created,
        });

        Ok(handle)
    }

    pub async fn start_vm(&self, handle: &VMHandle) -> Result<()> {
        self.validate_vm_handle(handle)?;
        let api_client = self.get_api_client()?;

        api_client.vm_boot().await?;

        self.update_vm_status(VMStatus::Running)?;

        Ok(())
    }

    pub async fn stop_vm(&self, handle: &VMHandle, force: bool) -> Result<()> {
        self.validate_vm_handle(handle)?;
        let api_client = self.get_api_client()?;

        if force {
            api_client.vm_delete().await?;
        } else {
            api_client.vm_shutdown().await?;
        }

        self.update_vm_status(VMStatus::Shutdown)?;

        Ok(())
    }

    /// Gracefully stop a VM with timeout-based escalation.
    ///
    /// This method implements the zosbase shutdown strategy:
    /// 1. Try API shutdown first
    /// 2. Wait for api_timeout, then send SIGTERM if still running
    /// 3. Wait for sigterm_timeout, then send SIGKILL if still running
    ///
    /// # Example
    /// ```no_run
    /// use std::time::Duration;
    /// use herolib_virt::cloudhv::runtime::{CloudHypervisorRuntime, VMHandle};
    /// # async fn example(runtime: CloudHypervisorRuntime, handle: VMHandle) -> Result<(), Box<dyn std::error::Error>> {
    /// runtime.stop_vm_graceful(
    ///     &handle,
    ///     Duration::from_secs(5),   // Try API shutdown for 5 seconds
    ///     Duration::from_secs(5),   // Then SIGTERM for 5 seconds
    ///     Duration::from_secs(5),   // Then SIGKILL for 5 seconds
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn stop_vm_graceful(
        &self,
        handle: &VMHandle,
        api_timeout: std::time::Duration,
        sigterm_timeout: std::time::Duration,
        sigkill_timeout: std::time::Duration,
    ) -> Result<()> {
        use crate::cloudhv::discovery;
        use std::time::Instant;

        self.validate_vm_handle(handle)?;

        // Try to find the process
        let process_info = discovery::find_vm_process(&handle.id).ok();

        // Step 1: Try API shutdown
        let api_client = self.get_api_client()?;

        if let Err(e) = api_client.vm_shutdown().await {
            log::warn!("API shutdown failed: {}, will try signals", e);
        }

        // Wait for API shutdown to complete
        tokio::time::sleep(api_timeout).await;

        // Check if process is still running
        if let Some(ref info) = process_info {
            if !discovery::is_process_running(info.pid) {
                self.update_vm_status(VMStatus::Shutdown)?;
                return Ok(());
            }

            // Step 2: Send SIGTERM
            log::debug!(
                "VM still running after API shutdown, sending SIGTERM to PID {}",
                info.pid
            );
            unsafe {
                libc::kill(info.pid as i32, libc::SIGTERM);
            }

            // Wait for SIGTERM to complete
            let sigterm_start = Instant::now();
            while sigterm_start.elapsed() < sigterm_timeout {
                if !discovery::is_process_running(info.pid) {
                    self.update_vm_status(VMStatus::Shutdown)?;
                    return Ok(());
                }
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            }

            // Step 3: Send SIGKILL
            log::debug!(
                "VM still running after SIGTERM, sending SIGKILL to PID {}",
                info.pid
            );
            unsafe {
                libc::kill(info.pid as i32, libc::SIGKILL);
            }

            // Wait for SIGKILL to complete
            let sigkill_start = Instant::now();
            while sigkill_start.elapsed() < sigkill_timeout {
                if !discovery::is_process_running(info.pid) {
                    self.update_vm_status(VMStatus::Shutdown)?;
                    return Ok(());
                }
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            }

            // If still running after SIGKILL, something is very wrong
            if discovery::is_process_running(info.pid) {
                return Err(CloudHypervisorError::Process(format!(
                    "Failed to kill VM process {} after SIGKILL",
                    info.pid
                )));
            }
        }

        self.update_vm_status(VMStatus::Shutdown)?;
        Ok(())
    }

    pub async fn pause_vm(&self, handle: &VMHandle) -> Result<()> {
        self.validate_vm_handle(handle)?;
        let api_client = self.get_api_client()?;

        api_client.vm_pause().await?;

        self.update_vm_status(VMStatus::Paused)?;

        Ok(())
    }

    pub async fn resume_vm(&self, handle: &VMHandle) -> Result<()> {
        self.validate_vm_handle(handle)?;
        let api_client = self.get_api_client()?;

        api_client.vm_resume().await?;

        self.update_vm_status(VMStatus::Running)?;

        Ok(())
    }

    pub async fn reset_vm(&self, handle: &VMHandle) -> Result<()> {
        self.validate_vm_handle(handle)?;
        let api_client = self.get_api_client()?;

        api_client.vm_power_button().await?;

        Ok(())
    }

    pub async fn resize_memory(&self, handle: &VMHandle, size: u64) -> Result<()> {
        self.validate_vm_handle(handle)?;

        let vm_state_guard = self.vm_state.read().map_err(|e| {
            CloudHypervisorError::InvalidState(format!("Failed to lock VM state: {}", e))
        })?;

        if let Some(state) = vm_state_guard.as_ref() {
            let current_memory = state.spec.config.memory.size;

            if size < current_memory {
                return Err(CloudHypervisorError::NotSupported {
                    feature: "Memory hot-shrink".to_string(),
                    reason: "Cloud Hypervisor only supports growing memory, not shrinking. Memory can only be increased from its initial size.".to_string(),
                });
            }
        }

        let api_client = self.get_api_client()?;
        api_client.vm_resize_memory(size).await?;

        Ok(())
    }

    pub async fn add_vcpu(&self, handle: &VMHandle, count: u32) -> Result<()> {
        self.validate_vm_handle(handle)?;

        if count == 0 {
            return Err(CloudHypervisorError::Validation(
                "vCPU count must be greater than 0".to_string(),
            ));
        }

        let api_client = self.get_api_client()?;
        let vm_info = api_client.vm_info().await?;

        let current_vcpus = vm_info.config["cpus"]["boot_vcpus"].as_u64().unwrap_or(1) as u32;
        let new_vcpus = current_vcpus + count;

        api_client.vm_resize_vcpu(new_vcpus).await?;

        Ok(())
    }

    pub async fn remove_vcpu(&self, _handle: &VMHandle, _count: u32) -> Result<()> {
        Err(CloudHypervisorError::NotSupported {
            feature: "vCPU hot-removal".to_string(),
            reason: "Cloud Hypervisor does not support vCPU hot-removal. This is a fundamental limitation of the Linux kernel's vCPU management and ACPI hotplug subsystem. You can only hot-add vCPUs, not remove them.".to_string(),
        })
    }

    pub async fn get_vm_status(&self, handle: &VMHandle) -> Result<VMStatus> {
        self.validate_vm_handle(handle)?;

        let vm_state_guard = self.vm_state.read().map_err(|e| {
            CloudHypervisorError::InvalidState(format!("Failed to lock VM state: {}", e))
        })?;

        vm_state_guard
            .as_ref()
            .map(|state| state.status.clone())
            .ok_or_else(|| CloudHypervisorError::VmNotFound(handle.id.clone()))
    }

    pub async fn add_device(&self, handle: &VMHandle, device: DeviceConfig) -> Result<String> {
        self.validate_vm_handle(handle)?;
        let api_client = self.get_api_client()?;

        let device_id = api_client.vm_add_device(device).await?;

        Ok(device_id)
    }

    pub async fn remove_device(&self, handle: &VMHandle, device_id: &str) -> Result<()> {
        self.validate_vm_handle(handle)?;
        let api_client = self.get_api_client()?;

        api_client.vm_remove_device(device_id).await?;

        Ok(())
    }

    /// Creates a snapshot of the VM.
    ///
    /// **IMPORTANT**: Snapshots are host-local only and cannot be restored
    /// on a different physical machine. Attempting cross-host restore will fail.
    /// Snapshots contain host-specific memory addresses and device state.
    pub async fn create_snapshot(&self, handle: &VMHandle, path: &Path) -> Result<()> {
        self.validate_vm_handle(handle)?;
        let api_client = self.get_api_client()?;

        let destination_url = format!("file://{}", path.display());
        api_client.vm_snapshot(&destination_url).await?;

        let snapshot_name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("snapshot");

        self.snapshot_manager
            .create_snapshot(&handle.id, snapshot_name, &destination_url)?;

        Ok(())
    }

    /// Restores a VM from a snapshot.
    ///
    /// **IMPORTANT**: Snapshots are host-local only. This will only work if the
    /// snapshot was created on the same physical machine with the same kernel
    /// and Cloud Hypervisor version.
    pub async fn restore_snapshot(&self, path: &Path) -> Result<VMHandle> {
        let mut vm_state_guard = self.vm_state.write().map_err(|e| {
            CloudHypervisorError::InvalidState(format!("Failed to lock VM state: {}", e))
        })?;

        if vm_state_guard.is_some() {
            return Err(CloudHypervisorError::VmAlreadyExists(
                "Cannot restore snapshot: runtime already has a VM".to_string(),
            ));
        }

        let api_client = self.get_api_client()?;

        let source_url = format!("file://{}", path.display());
        let restore_config = RestoreConfig {
            source_url,
            prefault: false,
        };

        api_client.vm_restore(restore_config).await?;

        let _vm_info = api_client.vm_info().await?;
        let vm_id = uuid::Uuid::new_v4().to_string();
        let handle = VMHandle::new(vm_id.clone());

        *vm_state_guard = Some(VMState {
            spec: VMSpec {
                id: vm_id,
                config: VMConfig::new(),
            },
            status: VMStatus::Created,
        });

        Ok(handle)
    }

    pub fn list_snapshots(&self, vm_id: &str) -> Result<Vec<SnapshotInfo>> {
        self.snapshot_manager.list_snapshots(vm_id)
    }

    pub fn delete_snapshot(&self, vm_id: &str, name: &str) -> Result<()> {
        self.snapshot_manager.delete_snapshot(vm_id, name)
    }

    pub fn get_api_client(&self) -> Result<APIClient> {
        let api_guard = self
            .api_client
            .read()
            .map_err(|e| CloudHypervisorError::Api(format!("Failed to lock API client: {}", e)))?;

        api_guard
            .as_ref()
            .cloned()
            .ok_or_else(|| CloudHypervisorError::Api("Runtime not started".to_string()))
    }

    fn validate_vm_handle(&self, handle: &VMHandle) -> Result<()> {
        let vm_state_guard = self.vm_state.read().map_err(|e| {
            CloudHypervisorError::InvalidState(format!("Failed to lock VM state: {}", e))
        })?;

        vm_state_guard
            .as_ref()
            .ok_or_else(|| CloudHypervisorError::VmNotFound(handle.id.clone()))?;

        Ok(())
    }

    fn update_vm_status(&self, status: VMStatus) -> Result<()> {
        let mut vm_state_guard = self.vm_state.write().map_err(|e| {
            CloudHypervisorError::InvalidState(format!("Failed to lock VM state: {}", e))
        })?;

        if let Some(state) = vm_state_guard.as_mut() {
            state.status = status;
        }

        Ok(())
    }
}

impl Drop for CloudHypervisorRuntime {
    fn drop(&mut self) {
        let _ = self.stop();
    }
}