summaryrefslogtreecommitdiff
path: root/src/cmd/list.rs
blob: c83be26ebd84f0eee8df0a3e411028c76eac0c5e (plain)
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
//! The `list` sub-command.

use crate::config::Configuration;

use virt::connect::Connect;

/// Errors returned from this module.
#[derive(Debug, thiserror::Error)]
pub enum ListError {
    /// An error from libvirt.
    #[error(transparent)]
    VirtError(#[from] virt::error::Error),
}

/// The `list` sub-command.
///
/// Return all the virtual machines existing on the libvirt instance,
/// and their current state.
pub fn list(_config: &Configuration) -> Result<(), ListError> {
    let conn = Connect::open("qemu:///system")?;
    let domains = conn.list_all_domains(0)?;
    for domain in domains {
        let name = domain.get_name()?;
        let (state, _) = domain.get_state()?;
        let state = state_name(state);
        println!("{} {}", name, state);
    }

    Ok(())
}

fn state_name(state: virt::domain::DomainState) -> String {
    let name = match state {
        virt::domain::VIR_DOMAIN_NOSTATE => "none",
        virt::domain::VIR_DOMAIN_RUNNING => "running",
        virt::domain::VIR_DOMAIN_BLOCKED => "blocked",
        virt::domain::VIR_DOMAIN_PAUSED => "paused",
        virt::domain::VIR_DOMAIN_SHUTDOWN => "shutdown",
        virt::domain::VIR_DOMAIN_SHUTOFF => "shutoff",
        virt::domain::VIR_DOMAIN_CRASHED => "crashed",
        virt::domain::VIR_DOMAIN_PMSUSPENDED => "power management suspended",
        _ => "unknown",
    };
    name.to_string()
}