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
//! This crate is probably not what you hoped it was -- in fact, it's probably
//! exactly what you feared.  Rather than integrate against VirtualBox's COM
//! interfaces it will call the command line tools and parse their outputs.
//!
//! Perhaps not surprisingly, this crate originally began as a bash script and
//! slowly morphed into what it is today.
//!
//! # Examples
//!
//! Terminate a virtual machine named _myvm_ and revert it to a snapshot named
//! _mysnap_.
//!
//! ```no_run
//! use std::time::Duration;
//! use vboxhelper::*;
//!
//! let vm = "myvm".parse::<VmId>().unwrap();
//! controlvm::kill(&vm).unwrap();
//!
//! let ten_seconds = Duration::new(10, 0);
//! wait_for_croak(&vm, Some((ten_seconds, TimeoutAction::Error)));
//!
//! // revert to a snapshot
//! let snap = "mysnap".parse::<snapshot::SnapshotId>().unwrap();
//! snapshot::restore(&vm, Some(snap)).unwrap();
//! ```
//!
//! # VirtualBox Versions
//! This crate will generally attempt to track the latest version of
//! VirtualBox.

mod err;
mod platform;
mod strutils;

pub mod controlvm;
pub mod nics;
pub mod snapshot;
pub mod vmid;

use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Command;
use std::thread;
use std::time::{Duration, Instant};

use regex::Regex;

use err::Error;

use strutils::{buf_to_strlines, EmptyLine};

pub use vmid::VmId;


/// In what context a virtual machine is run.
pub enum RunContext {
  /// The virtual machine will run as a application on a Desktop GUI.
  GUI,

  /// The virtual machine will run as a background process.
  Headless
}


pub enum TimeoutAction {
  /// If the operation times out, then return an error.
  Error,

  /// If the operation times out, then kill the virtual machine
  Kill
}


pub fn have_vm(id: &VmId) -> Result<bool, Error> {
  let lst = get_vm_list()?;

  for (name, uuid) in lst {
    match id {
      VmId::Name(nm) => {
        if name == *nm {
          return Ok(true);
        }
      }
      VmId::Uuid(u) => {
        if uuid == *u {
          return Ok(true);
        }
      }
    }
  }
  Ok(false)
}


pub fn get_vm_list() -> Result<Vec<(String, uuid::Uuid)>, Error> {
  let mut cmd = Command::new(platform::get_cmd("VBoxManage"));
  cmd.args(&["list", "vms"]);
  let output = cmd.output().expect("Failed to execute VBoxManage");

  if !output.status.success() {
    let dbg = format!("{:?}", cmd);
    return Err(Error::CommandFailed(output.status.code(), dbg));
  }

  let lines = buf_to_strlines(&output.stdout, EmptyLine::Ignore);

  let mut out = Vec::new();

  for line in lines {
    // Make sure first character is '"'
    match line.find('"') {
      Some(idx) => {
        if idx != 0 {
          continue;
        }
      }
      None => continue
    }

    // Find last '"'
    let idx = match line.rfind('"') {
      Some(idx) => {
        if idx == 0 {
          continue;
        }
        idx
      }
      None => continue
    };


    let idx_ub = match line.rfind('{') {
      Some(idx) => {
        if idx == 0 {
          continue;
        }
        idx
      }
      None => continue
    };

    let idx_ue = match line.rfind('}') {
      Some(idx) => {
        if idx == 0 {
          continue;
        }
        idx
      }
      None => continue
    };

    let name = &line[1..idx];
    let uuidstr = &line[(idx_ub + 1)..idx_ue];
    let u = match uuid::Uuid::parse_str(uuidstr) {
      Ok(u) => u,
      Err(_) => continue
    };
    out.push((name.to_string(), u));
  }

  Ok(out)
}


/// Get information about a virtual machine as a map.
pub fn get_vm_info_map(id: &VmId) -> Result<HashMap<String, String>, Error> {
  let mut cmd = Command::new(platform::get_cmd("VBoxManage"));
  cmd.arg("showvminfo");
  let id_str = id.to_string();
  cmd.arg(&id_str);
  cmd.arg("--machinereadable");

  let output = cmd.output().expect("Failed to execute VBoxManage");

  let lines = strutils::buf_to_strlines(&output.stdout, EmptyLine::Ignore);

  let mut map = HashMap::new();

  // refine as we go along
  let re = Regex::new(r#"^"?(?P<key>[^"=]+)"?="?(?P<val>[^"=]*)"?$"#).unwrap();

  // ToDo: Handle multiline entires, like descriptions
  for line in lines {
    //println!("line: {}", line);
    let line = line.trim_end();

    if let Some(cap) = re.captures(&line) {
      //println!("key: '{}'", &cap[1]);
      //println!("value: '{}'", &cap[2]);

      map.insert(cap[1].to_string(), cap[2].to_string());
    } else {
      println!("Ignored line: {}", line);
    }
  }

  Ok(map)
}


#[derive(PartialEq, Eq)]
/// VirtualBox virtual machine states.
pub enum VmState {
  /// This isn't actually a VirtualBox virtual machine state; it's used as a
  /// placeholder if an unknown state is encountered.
  Unknown,

  /// The virtual machine is powered off.
  PowerOff,

  /// The virtual machine is currently starting up.
  Starting,

  /// The virtual machine is currently up and running.
  Running,

  /// The virtual machine is currently paused.
  Paused,

  /// The virtual machine is currently shutting down.
  Stopping
}

impl From<&str> for VmState {
  fn from(s: &str) -> Self {
    match s {
      "poweroff" => VmState::PowerOff,
      "starting" => VmState::Starting,
      "running" => VmState::Running,
      "paused" => VmState::Paused,
      "stopping" => VmState::Stopping,
      _ => VmState::Unknown
    }
  }
}

impl From<&String> for VmState {
  fn from(s: &String) -> Self {
    match s.as_ref() {
      "poweroff" => VmState::PowerOff,
      "starting" => VmState::Starting,
      "running" => VmState::Running,
      "paused" => VmState::Paused,
      "stopping" => VmState::Stopping,
      _ => VmState::Unknown
    }
  }
}


/// A structured representation of a virtual machine's state and configuration.
pub struct VmInfo {
  pub shares_map: HashMap<String, PathBuf>,
  pub shares_list: Vec<(String, PathBuf)>,
  pub state: VmState,
  pub snapshots: Option<snapshot::Snapshots>,
  pub nics: Vec<nics::NICInfo>
}


/// Get structured information about a virtual machine.
pub fn get_vm_info(id: &VmId) -> Result<VmInfo, Error> {
  let map = get_vm_info_map(id)?;

  let mut shares_list = Vec::new();
  let mut shares_map = HashMap::new();

  //
  // Parse shares
  //
  let mut idx = 1;
  loop {
    let name_key = format!("SharedFolderNameMachineMapping{}", idx);
    let path_key = format!("SharedFolderPathMachineMapping{}", idx);

    let name = match map.get(&name_key) {
      Some(nm) => nm.clone(),
      None => break
    };
    let pathname = match map.get(&path_key) {
      Some(pn) => PathBuf::from(pn),
      None => break
    };

    shares_map.insert(name.clone(), pathname.clone());
    shares_list.push((name, pathname));

    idx += 1;
  }

  //
  // Get VM State
  //
  let state = match map.get("VMState") {
    Some(s) => VmState::from(s),
    None => VmState::Unknown
  };

  //
  // Parse snapshots
  //
  let snaps = snapshot::get_from_map(&map)?;

  //
  // Parse NICs
  //
  let nics = nics::get_from_map(&map)?;

  Ok(VmInfo {
    state,
    shares_map,
    shares_list,
    snapshots: snaps,
    nics
  })
}


/// Check whether a virtual machine is currently in a certain state.
pub fn is_vm_state(id: &VmId, state: VmState) -> Result<bool, Error> {
  let vmi = get_vm_info(id)?;
  Ok(vmi.state == state)
}


/// Wait for a virtual machine to self-terminate.
///
/// The caller can choose to pass a timeout and what action should be taken if
/// the operation times out.  If the timeout occurs the caller can choose
/// whether to return a timeout error or kill the virtual machine.
///
/// ```no_run
/// use std::time::Duration;
/// use vboxhelper::{TimeoutAction, wait_for_croak, VmId};
/// fn impatient() {
///   let twenty_seconds = Duration::new(20, 0);
///   let vmid = VmId::from("myvm");
///   wait_for_croak(&vmid, Some((twenty_seconds, TimeoutAction::Kill)));
/// }
/// ```
///
/// This function polls `is_vm_state()` which calls `get_vm_info()`.  A very
/// sad state of affairs.  :(
pub fn wait_for_croak(
  id: &VmId,
  timeout: Option<(Duration, TimeoutAction)>
) -> Result<(), Error> {
  let start = Instant::now();
  loop {
    let poweroff = is_vm_state(id, VmState::PowerOff)?;
    if poweroff {
      break;
    }
    if let Some((ref max_dur, ref action)) = timeout {
      let duration = start.elapsed();
      if duration > *max_dur {
        match action {
          TimeoutAction::Error => return Err(Error::Timeout),
          TimeoutAction::Kill => {
            controlvm::kill(id)?;

            // ToDo: Give it some time to croak.  If it doesn't, then return
            //       an "uncroakable vm" error.
            break;
          }
        }
      }
    }

    // Why 11?  Because it's more than 10, and it's a prime.  I don't know why
    // 11 is a prime -- ask the universe.
    let eleven_secs = Duration::from_secs(11);
    thread::sleep(eleven_secs);
  }
  Ok(())
}


/*
fn foo() {
  let _map = get_vm_info_map("hello").unwrap();
}
*/

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :