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
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::process::Command;

use anyhow::{anyhow, Context, Result};
use lazy_static::lazy_static;
use log::{debug, info};
use regex::Regex;
use walkdir::WalkDir;

lazy_static! {
    static ref NAME_RE: Regex = Regex::new("displayname = \"(.*)\"").unwrap();
}

/// Actions available to run for VMs with `vmrun` CLI
#[derive(Copy, Clone, Debug)]
pub enum Action {
    Start,
    Stop,
    Suspend,
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let value = match self {
            Action::Start => "start",
            Action::Stop => "stop",
            Action::Suspend => "suspend",
        };
        write!(f, "{}", value)
    }
}

/// Representation of a VM with gathered info from `vmrun` and the `.vmx` file
#[derive(Debug)]
pub struct Vm {
    pub name: String,
    pub vmx: PathBuf,
    pub is_running: bool,
}

impl Vm {
    /// Gather VM info from the `.vmx` file
    pub fn from_vmx(vmx: PathBuf) -> Result<Self> {
        let name = Self::extract_vmx_name(&vmx)?;
        debug!("Found '{}' at '{:?}'", name, vmx);
        Ok(Self {
            name,
            vmx,
            is_running: false,
        })
    }

    /// Extract the VM Display Name from the `.vmx` file
    fn extract_vmx_name(vmx: &PathBuf) -> Result<String> {
        let input = File::open(vmx)?;
        let buffered = BufReader::new(input);

        for line in buffered.lines() {
            if let Ok(line) = line {
                if let Some(caps) = NAME_RE.captures(&line) {
                    return Ok(caps.get(1).expect("displayname match").as_str().to_string());
                }
            }
        }
        Ok("Unknown".to_string())
    }

    /// Run an action using `vmrun`
    pub fn manage(&self, action: Action) -> Result<()> {
        debug!(
            "Running 'vmrun {} {}",
            action.to_string(),
            self.vmx.to_str().unwrap()
        );
        Command::new("vmrun")
            .arg(&action.to_string())
            .arg(&self.vmx.to_str().unwrap())
            .output()
            .context("Running vmrun")?;
        info!("{}ed {}", action, self.name);
        Ok(())
    }
}

/// Walk the given path, searching for `.vmx` files
pub fn get_vms(path: &str) -> Result<Vec<Vm>> {
    let running_vms = get_running_vms()?;

    let mut vms: Vec<_> = WalkDir::new(path)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|d| {
            if let Some(e) = d.path().extension() {
                e == "vmx"
            } else {
                false
            }
        })
        .filter_map(|entry| Vm::from_vmx(entry.into_path()).ok())
        .collect();

    for mut vm in vms.iter_mut() {
        if running_vms.contains(&vm.vmx.to_str().unwrap().to_owned()) {
            vm.is_running = true;
        }
    }
    Ok(vms)
}

/// Search for a given VM by name
pub fn get_vm(path: &str, name: &str) -> Result<Vm> {
    get_vms(path)?
        .into_iter()
        .find(|vm| String::from(&vm.name).to_lowercase() == name.to_lowercase())
        .ok_or_else(|| anyhow!("No VM found matching '{}'", name))
}

/// Gather list of running VMs (by .vmx path) from `vmrun`
pub fn get_running_vms() -> Result<Vec<String>> {
    let output = Command::new("vmrun").arg("list").output()?;
    Ok(String::from_utf8(output.stdout)
        .unwrap()
        .lines()
        .skip(1)
        .map(|l| l.to_owned())
        .collect())
}