Issue 384: support virtualbox 4.1.2r73507

This commit is contained in:
Andrea Turli 2011-08-21 18:19:31 +01:00
parent 04dde80bd4
commit 2274e7d4e6
1 changed files with 525 additions and 434 deletions

View File

@ -20,16 +20,15 @@ package org.jclouds.virtualbox.experiment;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.propagate; import static com.google.common.base.Throwables.propagate;
import static org.jclouds.compute.options.RunScriptOptions.Builder.blockOnPort; import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
import java.rmi.RemoteException; import java.rmi.RemoteException;
@ -63,6 +62,7 @@ import org.virtualbox_4_1.IStorageController;
import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.MachineState; import org.virtualbox_4_1.MachineState;
import org.virtualbox_4_1.NATProtocol; import org.virtualbox_4_1.NATProtocol;
import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.SessionState; import org.virtualbox_4_1.SessionState;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VirtualBoxManager; import org.virtualbox_4_1.VirtualBoxManager;
@ -77,435 +77,526 @@ import com.google.common.io.Closeables;
@Test(groups = "live", testName = "virtualbox.VirtualboxAdministrationKickstartTest") @Test(groups = "live", testName = "virtualbox.VirtualboxAdministrationKickstartTest")
public class VirtualboxAdministrationKickstartLiveTest { public class VirtualboxAdministrationKickstartLiveTest {
protected String provider = "virtualbox"; protected String provider = "virtualbox";
protected String identity; protected String identity;
protected String credential; protected String credential;
protected URI endpoint; protected URI endpoint;
protected String apiVersion; protected String apiVersion;
protected String vmName; protected String vmName;
VirtualBoxManager manager = VirtualBoxManager.createInstance(""); VirtualBoxManager manager = VirtualBoxManager.createInstance("");
protected Predicate<IPSocket> socketTester; protected Predicate<IPSocket> socketTester;
protected String settingsFile; // Fully qualified path where the settings protected String settingsFile; // Fully qualified path where the settings
protected String osTypeId; // Guest OS Type ID. protected String osTypeId; // Guest OS Type ID.
protected String vmId; // Machine UUID (optional). protected String vmId; // Machine UUID (optional).
protected boolean forceOverwrite; protected boolean forceOverwrite;
protected String diskFormat; protected String diskFormat;
protected String workingDir; protected String workingDir;
protected String originalDisk; protected String originalDisk;
protected String clonedDisk; protected String clonedDisk;
protected String guestAdditionsDvd; protected String guestAdditionsDvd;
private URI gaIsoUrl; private URI gaIsoUrl;
private String gaIsoName; private String gaIsoName;
private URI distroIsoUrl; private URI distroIsoUrl;
private String distroIsoName; private String distroIsoName;
private String controllerIDE; private String controllerIDE;
private String controllerSATA; private String controllerSATA;
private String keyboardSequence; private String keyboardSequence;
private String preseedUrl; private String preseedUrl;
private ComputeServiceContext context; private ComputeServiceContext context;
private String hostId = "host"; private String hostId = "host";
private String guestId = "guest"; private String guestId = "guest";
private String majorVersion; private String majorVersion;
private String minorVersion; private String minorVersion;
protected void setupCredentials() { protected void setupCredentials() {
identity = System.getProperty("test." + provider + ".identity", "administrator"); identity = System.getProperty("test." + provider + ".identity",
credential = System.getProperty("test." + provider + ".credential", "12345"); "administrator");
endpoint = URI.create(System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/")); credential = System.getProperty("test." + provider + ".credential",
apiVersion = System.getProperty("test." + provider + ".apiversion", "4.1.2r73507"); "12345");
majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0); endpoint = URI.create(System.getProperty("test." + provider
minorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 1); + ".endpoint", "http://localhost:18083/"));
} apiVersion = System.getProperty("test." + provider + ".apiversion",
"4.1.2r73507");
protected Logger logger() { majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0);
return context.utils().loggerFactory().getLogger("jclouds.compute"); minorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 1);
} }
protected void setupConfigurationProperties() { protected Logger logger() {
return context.utils().loggerFactory().getLogger("jclouds.compute");
controllerIDE = System.getProperty("test." + provider + ".controllerIde", "IDE Controller"); }
controllerSATA = System.getProperty("test." + provider + ".controllerSata", "SATA Controller");
diskFormat = System.getProperty("test." + provider + ".diskformat", ""); protected void setupConfigurationProperties() {
// VBOX controllerIDE = System.getProperty("test." + provider
settingsFile = null; + ".controllerIde", "IDE Controller");
osTypeId = System.getProperty("test." + provider + ".osTypeId", ""); controllerSATA = System.getProperty("test." + provider
vmId = System.getProperty("test." + provider + ".vmId", null); + ".controllerSata", "SATA Controller");
forceOverwrite = true; diskFormat = System.getProperty("test." + provider + ".diskformat", "");
vmName = System.getProperty("test." + provider + ".vmname", "jclouds-virtualbox-kickstart-admin");
// VBOX
workingDir = System.getProperty("user.home") + File.separator settingsFile = null;
+ System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test"); osTypeId = System.getProperty("test." + provider + ".osTypeId", "");
if (new File(workingDir).mkdir()) vmId = System.getProperty("test." + provider + ".vmId", null);
; forceOverwrite = true;
gaIsoName = System.getProperty("test." + provider + ".gaIsoName", "VBoxGuestAdditions_" + majorVersion vmName = System.getProperty("test." + provider + ".vmname",
+ "-update-" + minorVersion + ".iso"); "jclouds-virtualbox-kickstart-admin");
gaIsoUrl = URI.create(System.getProperty("test." + provider + ".gaIsoUrl",
"http://download.virtualbox.org/virtualbox/" + majorVersion + "/VBoxGuestAdditions_" + majorVersion + ".iso")); workingDir = System.getProperty("user.home")
+ File.separator
distroIsoName = System.getProperty("test." + provider + ".distroIsoName", "ubuntu-11.04-server-i386.iso"); + System.getProperty("test." + provider + ".workingDir",
distroIsoUrl = URI.create(System.getProperty("test." + provider + ".distroIsoUrl", "jclouds-virtualbox-test");
"http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso")); if (new File(workingDir).mkdir())
;
originalDisk = workingDir + File.separator + "VDI" + File.separator // gaIsoName = System.getProperty("test." + provider + ".gaIsoName",
+ System.getProperty("test." + provider + ".originalDisk", "centos-5.2-x86.vdi"); // "VBoxGuestAdditions_" + majorVersion + "-update-" + minorVersion +
clonedDisk = workingDir + File.separator + System.getProperty("test." + provider + ".clonedDisk", "template.vdi"); // ".iso");
guestAdditionsDvd = workingDir gaIsoName = System.getProperty("test." + provider + ".gaIsoName",
+ File.separator "VBoxGuestAdditions_" + majorVersion + ".iso");
+ System.getProperty("test." + provider + ".guestAdditionsDvd", "VBoxGuestAdditions_" + majorVersion gaIsoUrl = URI.create(System.getProperty("test." + provider
+ "-update-" + minorVersion + ".iso"); + ".gaIsoUrl", "http://download.virtualbox.org/virtualbox/"
+ majorVersion + "/" + gaIsoName));
preseedUrl = System.getProperty("test." + provider + ".preseedurl", "http://dl.dropbox.com/u/693111/preseed.cfg");
distroIsoName = System.getProperty("test." + provider
keyboardSequence = System.getProperty("test." + provider + ".keyboardSequence", "<Esc> <Esc> <Enter> " + ".distroIsoName", "ubuntu-11.04-server-i386.iso");
+ "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg " distroIsoUrl = URI
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " " .create(System
+ "fb=false debconf/frontend=noninteractive " .getProperty("test." + provider + ".distroIsoUrl",
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false " "http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso"));
+ "initrd=/install/initrd.gz -- <Enter>");
originalDisk = workingDir
} + File.separator
+ "VDI"
@BeforeGroups(groups = "live") + File.separator
protected void setupClient() throws Exception { + System.getProperty("test." + provider + ".originalDisk",
context = TestUtils.computeServiceForLocalhost(); "centos-5.2-x86.vdi");
socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 130, 10, TimeUnit.SECONDS); clonedDisk = workingDir
setupCredentials(); + File.separator
setupConfigurationProperties(); + System.getProperty("test." + provider + ".clonedDisk",
downloadFileUnlessPresent(distroIsoUrl, workingDir, distroIsoName); "disk.vdi");
downloadFileUnlessPresent(gaIsoUrl, workingDir, gaIsoName); guestAdditionsDvd = workingDir
installVbox(); + File.separator
checkVboxVersionExpected(); + System.getProperty("test." + provider + ".guestAdditionsDvd",
if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint.getHost(), endpoint.getPort()))) "VBoxGuestAdditions_" + majorVersion + "-update-"
startupVboxWebServer(); + minorVersion + ".iso");
configureJettyServer(); preseedUrl = System.getProperty("test." + provider + ".preseedurl",
} "http://dl.dropbox.com/u/693111/preseed.cfg");
private void configureJettyServer() throws Exception { keyboardSequence = System
Server server = new Server(8080); .getProperty(
"test." + provider + ".keyboardSequence",
ResourceHandler resource_handler = new ResourceHandler(); "<Esc> <Esc> <Enter> "
resource_handler.setDirectoriesListed(true); + "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg "
resource_handler.setWelcomeFiles(new String[] { "index.html" }); + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us "
+ "hostname="
resource_handler.setResourceBase("."); + vmName
logger().info("serving " + resource_handler.getBaseResource()); + " "
+ "fb=false debconf/frontend=noninteractive "
HandlerList handlers = new HandlerList(); + "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() }); + "initrd=/install/initrd.gz -- <Enter>");
server.setHandler(handlers);
}
server.start();
} @BeforeGroups(groups = "live")
protected void setupClient() throws Exception {
void installVbox() throws IOException, InterruptedException { context = TestUtils.computeServiceForLocalhost();
if (runScriptOnNode(hostId, "VBoxManage -version").getExitCode() != 0) { socketTester = new RetryablePredicate<IPSocket>(
logger().debug("installing virtualbox"); new InetSocketAddressConnect(), 130, 10, TimeUnit.SECONDS);
if (isOSX(hostId)) setupCredentials();
;// TODO setupConfigurationProperties();
else downloadFileUnlessPresent(distroIsoUrl, workingDir, distroIsoName);
runScriptOnNode(hostId, "apt-get --yes install virtualbox-ose"); downloadFileUnlessPresent(gaIsoUrl, workingDir, gaIsoName);
// TODO other platforms
} installVbox();
} checkVboxVersionExpected();
if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint
void checkVboxVersionExpected() throws IOException, InterruptedException { .getHost(), endpoint.getPort())))
logger().debug("checking virtualbox version"); startupVboxWebServer();
assertEquals(runScriptOnNode(hostId, "VBoxManage -version").getOutput().trim(), apiVersion); configureJettyServer();
} }
/** private void configureJettyServer() throws Exception {
* Server server = new Server(8080);
* @param command
* absolute path to command. For ubuntu 10.04: /usr/bin/vboxwebsrv ResourceHandler resource_handler = new ResourceHandler();
* @throws IOException resource_handler.setDirectoriesListed(true);
* @throws InterruptedException resource_handler.setWelcomeFiles(new String[] { "index.html" });
*/
void startupVboxWebServer() { resource_handler.setResourceBase(".");
logger().debug("disabling password access"); logger().info("serving " + resource_handler.getBaseResource());
runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null");
logger().debug("starting vboxwebsrv"); HandlerList handlers = new HandlerList();
String vboxwebsrv = "vboxwebsrv -t 5 -v"; handlers.setHandlers(new Handler[] { resource_handler,
if (isOSX(hostId)) new DefaultHandler() });
vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/&&" + vboxwebsrv; server.setHandler(handlers);
// allow jclouds to background the process, this is why we don't specify
// -b; logs will go corresponding to task name in this case under server.start();
// /tmp/vboxwebsrv }
runScriptOnNode(hostId, vboxwebsrv,
blockOnPort(endpoint.getPort(), 10).blockOnComplete(false).nameTask("vboxwebsrv")); void installVbox() {
} if (runScriptOnNode(hostId, "VBoxManage --version").getExitCode() != 0) {
logger().debug("installing virtualbox");
protected boolean isOSX(String id) { if (isOSX(hostId))
return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription() ;// TODO
.equals("Mac OS X"); else {
} // TODO other platforms
runScriptOnNode(hostId, "cat > /etc/apt/sources.list.d/TODO");
@BeforeMethod runScriptOnNode(
protected void setupManager() { hostId,
manager.connect(endpoint.toASCIIString(), identity, credential); "wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | apt-key add -");
} runScriptOnNode(hostId, "apt-get update");
runScriptOnNode(hostId, "apt-get --yes install virtualbox-4.1");
@AfterMethod }
protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
manager.disconnect(); }
manager.cleanup(); }
}
void checkVboxVersionExpected() throws IOException, InterruptedException {
public void testCreateVirtualMachine() { logger().debug("checking virtualbox version");
IMachine newVM = manager.getVBox().createMachine(settingsFile, vmName, osTypeId, vmId, forceOverwrite); assertEquals(runScriptOnNode(hostId, "VBoxManage -version").getOutput()
manager.getVBox().registerMachine(newVM); .trim(), apiVersion);
assertEquals(newVM.getName(), vmName); }
}
/**
@Test(dependsOnMethods = "testCreateVirtualMachine") *
public void testChangeRAM() { * @param command
Long memorySize = new Long(1024); * absolute path to command. For ubuntu 10.04:
ISession session = manager.getSessionObject(); * /usr/bin/vboxwebsrv
IMachine machine = manager.getVBox().findMachine(vmName); * @throws IOException
machine.lockMachine(session, LockType.Write); * @throws InterruptedException
IMachine mutable = session.getMachine(); */
mutable.setMemorySize(memorySize); void startupVboxWebServer() {
mutable.saveSettings(); logger().debug("disabling password access");
session.unlockMachine(); runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null");
assertEquals(manager.getVBox().findMachine(vmName).getMemorySize(), memorySize); logger().debug("starting vboxwebsrv");
} String vboxwebsrv = "vboxwebsrv -t 10000 -v -b";
if (isOSX(hostId))
@Test(dependsOnMethods = "testChangeRAM") vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/&&"
public void testCreateScsiController() { + vboxwebsrv;
ISession session = manager.getSessionObject(); // allow jclouds to background the process, this is why we don't specify
IMachine machine = manager.getVBox().findMachine(vmName); // -b;
machine.lockMachine(session, LockType.Write); // logs will go corresponding to task name in this case under
IMachine mutable = session.getMachine(); // /tmp/vboxwebsrv
mutable.addStorageController(controllerSATA, StorageBus.SATA); runScriptOnNode(
mutable.saveSettings(); hostId,
session.unlockMachine(); vboxwebsrv,
assertEquals(manager.getVBox().findMachine(vmName).getStorageControllers().size(), 2); runAsRoot(false).wrapInInitScript(false)
} .blockOnPort(endpoint.getPort(), 10)
.blockOnComplete(false).nameTask("vboxwebsrv"));
@Test(dependsOnMethods = "testCreateScsiController") }
public void testCreateAndAttachHardDisk() {
IMedium hd = null; protected boolean isOSX(String id) {
if (!new File(clonedDisk).exists()) { return context.getComputeService().getNodeMetadata(hostId)
hd = manager.getVBox().createHardDisk(diskFormat, clonedDisk); .getOperatingSystem().getDescription().equals("Mac OS X");
long size = 2 * 1024 * 1024 * 1024 - 1; }
hd.createBaseStorage(new Long(size), new Long(MediumVariant.VMDK_SPLIT_2_G.ordinal()));
} else @BeforeMethod
hd = manager.getVBox().openMedium(clonedDisk, DeviceType.HardDisk, AccessMode.ReadWrite, forceOverwrite); protected void setupManager() {
ISession session = manager.getSessionObject(); manager.connect(endpoint.toASCIIString(), identity, credential);
IMachine machine = manager.getVBox().findMachine(vmName); }
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine(); @AfterMethod
mutable.attachDevice(controllerSATA, 0, 0, DeviceType.HardDisk, hd); protected void disconnectAndClenaupManager() throws RemoteException,
mutable.saveSettings(); // write settings to xml MalformedURLException {
session.unlockMachine(); manager.disconnect();
assertEquals(hd.getId().equals(""), false); manager.cleanup();
} }
@Test(dependsOnMethods = "testCreateAndAttachHardDisk") public void testCreateVirtualMachine() {
public void testConfigureNIC() { /*
ISession session = manager.getSessionObject(); * IMachine machine = manager.getVBox().findMachine(vmName); if(machine
IMachine machine = manager.getVBox().findMachine(vmName); * != null) { ISession session = manager.getSessionObject();
machine.lockMachine(session, LockType.Write); * machine.lockMachine(session, LockType.Write); IMachine mutable =
IMachine mutable = session.getMachine(); * session.getMachine(); List<IMedium> media =
* machine.unregister(CleanupMode.Full); machine.delete(media);
// network BRIDGED to access HTTP server * mutable.saveSettings(); session.unlockMachine();
String hostInterface = null; *
String command = "VBoxManage list bridgedifs"; * }
try { */
Process child = Runtime.getRuntime().exec(command); IMachine newVM = manager.getVBox().createMachine(settingsFile, vmName,
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(child.getInputStream())); osTypeId, vmId, forceOverwrite);
String line = ""; manager.getVBox().registerMachine(newVM);
boolean found = false; assertNotNull(newVM.getName());
}
while ((line = bufferedReader.readLine()) != null && !found) {
@Test(dependsOnMethods = "testCreateVirtualMachine")
if (line.split(":")[0].contains("Name")) { public void testChangeRAM() {
hostInterface = line.split(":")[1]; Long memorySize = new Long(1024);
} ISession session = manager.getSessionObject();
if (line.split(":")[0].contains("Status") && line.split(":")[1].contains("Up")) { IMachine machine = manager.getVBox().findMachine(vmName);
System.out.println("bridge: " + hostInterface.trim()); machine.lockMachine(session, LockType.Write);
found = true; IMachine mutable = session.getMachine();
} mutable.setMemorySize(memorySize);
} mutable.saveSettings();
session.unlockMachine();
// NAT assertEquals(manager.getVBox().findMachine(vmName).getMemorySize(),
// mutable.getNetworkAdapter(new Long(0)).attachToNAT(); TODO: this no memorySize);
// longer exists! }
mutable.getNetworkAdapter(new Long(0)).setNATNetwork("");
machine.getNetworkAdapter(new Long(0)).getNatDriver() @Test(dependsOnMethods = "testChangeRAM")
.addRedirect("guestssh", NATProtocol.TCP, "127.0.0.1", 2222, "", 22); public void testCreateIdeController() {
mutable.getNetworkAdapter(new Long(0)).setEnabled(true); ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
mutable.saveSettings(); machine.lockMachine(session, LockType.Write);
session.unlockMachine(); IMachine mutable = session.getMachine();
mutable.addStorageController(controllerIDE, StorageBus.IDE);
} catch (IOException e) { mutable.saveSettings();
propagate(e); session.unlockMachine();
} assertEquals(manager.getVBox().findMachine(vmName)
} .getStorageControllers().size(), 1);
}
@Test(dependsOnMethods = "testConfigureNIC")
public void testStartVirtualMachine() throws InterruptedException { @Test(dependsOnMethods = "testCreateIdeController")
IMachine machine = manager.getVBox().findMachine(vmName); public void testAttachIsoDvd() {
ISession session = manager.getSessionObject(); IMedium distroMedium = manager.getVBox().openMedium(
launchVMProcess(machine, session); workingDir + "/" + distroIsoName, DeviceType.DVD,
assertEquals(machine.getState(), MachineState.Running); AccessMode.ReadOnly, forceOverwrite);
try {
Thread.sleep(5000); ISession session = manager.getSessionObject();
} catch (InterruptedException e) { IMachine machine = manager.getVBox().findMachine(vmName);
propagate(e); machine.lockMachine(session, LockType.Write);
} IMachine mutable = session.getMachine();
mutable.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium);
sendKeyboardSequence(keyboardSequence); mutable.saveSettings(); // write settings to xml
} session.unlockMachine();
assertEquals(distroMedium.getId().equals(""), false);
@Test(dependsOnMethods = "testStartVirtualMachine") }
public void testConfigureGuestAdditions() {
// Configure your system for building kernel modules by running @Test(dependsOnMethods = "testAttachIsoDvd")
runScriptOnNode(guestId, "m-a prepare -i"); public void testCreateAndAttachHardDisk() throws InterruptedException {
runScriptOnNode(guestId, "mount -o loop /usr/share/virtualbox/VBoxGuestAdditions.iso /mnt"); IMedium hd = null;
runScriptOnNode(guestId, "/mnt/VBoxLinuxAdditions.run"); if (!new File(clonedDisk).exists()) {
} hd = manager.getVBox().createHardDisk(diskFormat, clonedDisk);
long size = 4L * 1024L * 1024L * 1024L - 4L;
@Test(dependsOnMethods = "testConfigureGuestAdditions") IProgress progress = hd.createBaseStorage(new Long(size), new Long(
public void testStopVirtualMachine() { MediumVariant.STANDARD.ordinal()));
IMachine machine = manager.getVBox().findMachine(vmName); progress.wait();
powerDownMachine(machine); }
assertEquals(machine.getState(), MachineState.PoweredOff);
} ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
/** machine.lockMachine(session, LockType.Write);
* @param machine IMachine mutable = session.getMachine();
*/ mutable.attachDevice(controllerIDE, 0, 1, DeviceType.HardDisk, hd);
private void powerDownMachine(IMachine machine) { mutable.saveSettings();
try { session.unlockMachine();
ISession machineSession = manager.openMachineSession(machine); assertEquals(hd.getId().equals(""), false);
IProgress progress = machineSession.getConsole().powerDown(); }
progress.waitForCompletion(-1);
machineSession.unlockMachine(); @Test(dependsOnMethods = "testCreateAndAttachHardDisk")
public void testConfigureNIC() {
while (!machine.getSessionState().equals(SessionState.Unlocked)) { ISession session = manager.getSessionObject();
try { IMachine machine = manager.getVBox().findMachine(vmName);
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState()); machine.lockMachine(session, LockType.Write);
Thread.sleep(1000); IMachine mutable = session.getMachine();
} catch (InterruptedException e) {
e.printStackTrace(); // NAT
} mutable.getNetworkAdapter(new Long(0)).setAttachmentType(
} NetworkAttachmentType.NAT);
machine.getNetworkAdapter(new Long(0))
} catch (Exception e) { .getNatDriver()
e.printStackTrace(); .addRedirect("guestssh", NATProtocol.TCP, "127.0.0.1", 2222,
} "", 22);
} mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
@Test(dependsOnMethods = "testStopVirtualMachine") mutable.saveSettings();
public void cleanUp() throws IOException { session.unlockMachine();
ISession session = manager.getSessionObject(); }
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write); @Test(dependsOnMethods = "testConfigureNIC")
IMachine mutable = session.getMachine(); public void testConfigureVRDE() {
mutable.getNetworkAdapter(new Long(0)).getNatDriver().removeRedirect("guestssh"); ISession session = manager.getSessionObject();
// detach disk from controller IMachine machine = manager.getVBox().findMachine(vmName);
mutable.detachDevice(controllerIDE, 0, 0); machine.lockMachine(session, LockType.Write);
mutable.saveSettings(); IMachine mutable = session.getMachine();
session.unlockMachine(); mutable.getVRDEServer().setEnabled(new Boolean(true));
mutable.saveSettings(); // write settings to xml
for (IStorageController storageController : machine.getStorageControllers()) { session.unlockMachine();
if (storageController.getName().equals(controllerSATA)) { }
session = manager.getSessionObject();
machine.lockMachine(session, LockType.Write); @Test(dependsOnMethods = "testConfigureNIC")
public void testStartVirtualMachine() throws InterruptedException {
mutable = session.getMachine(); IMachine machine = manager.getVBox().findMachine(vmName);
mutable.detachDevice(storageController.getName(), 1, 1); ISession session = manager.getSessionObject();
mutable.saveSettings(); launchVMProcess(machine, session);
session.unlockMachine(); assertEquals(machine.getState(), MachineState.Running);
} try {
} Thread.sleep(5000);
} } catch (InterruptedException e) {
propagate(e);
@AfterClass }
void stopVboxWebServer() throws IOException {
runScriptOnNode(guestId, "pidof vboxwebsrv | xargs kill"); sendKeyboardSequence(keyboardSequence);
} }
protected ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) { @Test(dependsOnMethods = "testStartVirtualMachine")
ExecResponse toReturn = context.getComputeService().runScriptOnNode(nodeId, command, options); public void testConfigureGuestAdditions() {
assert toReturn.getExitCode() == 0 : toReturn; // Configure your system for building kernel modules by running
return toReturn; runScriptOnNode(guestId, "m-a prepare -i");
} runScriptOnNode(guestId,
"mount -o loop /usr/share/virtualbox/VBoxGuestAdditions.iso /mnt");
protected ExecResponse runScriptOnNode(String nodeId, String command) { runScriptOnNode(guestId, "/mnt/VBoxLinuxAdditions.run");
return runScriptOnNode(nodeId, command, wrapInInitScript(false)); }
}
@Test(dependsOnMethods = "testConfigureGuestAdditions")
private File downloadFileUnlessPresent(URI sourceURL, String destinationDir, String filename) throws Exception { public void testStopVirtualMachine() {
IMachine machine = manager.getVBox().findMachine(vmName);
File iso = new File(destinationDir, filename); powerDownMachine(machine);
assertEquals(machine.getState(), MachineState.PoweredOff);
if (!iso.exists()) { }
InputStream is = context.utils().http().get(sourceURL);
checkNotNull(is, "%s not found", sourceURL); /**
try { * @param machine
ByteStreams.copy(is, new FileOutputStream(iso)); */
} finally { private void powerDownMachine(IMachine machine) {
Closeables.closeQuietly(is); try {
} ISession machineSession = manager.openMachineSession(machine);
} IProgress progress = machineSession.getConsole().powerDown();
return iso; progress.waitForCompletion(-1);
} machineSession.unlockMachine();
private void sendKeyboardSequence(String keyboardSequence) throws InterruptedException { while (!machine.getSessionState().equals(SessionState.Unlocked)) {
String[] sequenceSplited = keyboardSequence.split(" "); try {
for (String word : sequenceSplited) { System.out
String converted = stringToKeycode(word); .println("waiting for unlocking session - session state: "
for (String string : converted.split(" ")) { + machine.getSessionState());
Thread.sleep(1000);
runScriptOnNode(hostId, "VBoxManage controlvm " + vmName + " keyboardputscancode " + string); } catch (InterruptedException e) {
if (converted.contains(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Return>"))) e.printStackTrace();
Thread.sleep(180); }
} }
}
} catch (Exception e) {
} e.printStackTrace();
}
private String stringToKeycode(String s) { }
StringBuilder keycodes = new StringBuilder(); @Test(dependsOnMethods = "testStopVirtualMachine")
for (String specialButton : KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.keySet()) { public void cleanUp() throws IOException {
if (s.startsWith(specialButton)) { ISession session = manager.getSessionObject();
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get(specialButton)); IMachine machine = manager.getVBox().findMachine(vmName);
return keycodes.toString(); machine.lockMachine(session, LockType.Write);
} IMachine mutable = session.getMachine();
} mutable.getNetworkAdapter(new Long(0)).getNatDriver()
.removeRedirect("guestssh");
int i = 0; // detach disk from controller
while (i < s.length()) { mutable.detachDevice(controllerIDE, 0, 0);
String digit = s.substring(i, i + 1); mutable.saveSettings();
String hex = KeyboardScancodes.NORMAL_KEYBOARD_BUTTON_MAP.get(digit); session.unlockMachine();
keycodes.append(hex + " ");
i++; for (IStorageController storageController : machine
} .getStorageControllers()) {
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Spacebar>") + " "); if (storageController.getName().equals(controllerSATA)) {
session = manager.getSessionObject();
return keycodes.toString(); machine.lockMachine(session, LockType.Write);
}
mutable = session.getMachine();
/** mutable.detachDevice(storageController.getName(), 1, 1);
* mutable.saveSettings();
* @param machine session.unlockMachine();
* @param session }
*/ }
private void launchVMProcess(IMachine machine, ISession session) { }
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1); @AfterClass
session.unlockMachine(); void stopVboxWebServer() throws IOException {
} runScriptOnNode(guestId, "pidof vboxwebsrv | xargs kill");
}
protected ExecResponse runScriptOnNode(String nodeId, String command,
RunScriptOptions options) {
ExecResponse toReturn = context.getComputeService().runScriptOnNode(
nodeId, command, options);
assert toReturn.getExitCode() == 0 : toReturn;
return toReturn;
}
protected ExecResponse runScriptOnNode(String nodeId, String command) {
return runScriptOnNode(nodeId, command, wrapInInitScript(false));
}
private File downloadFileUnlessPresent(URI sourceURL,
String destinationDir, String filename) throws Exception {
File iso = new File(destinationDir, filename);
if (!iso.exists()) {
InputStream is = context.utils().http().get(sourceURL);
checkNotNull(is, "%s not found", sourceURL);
try {
ByteStreams.copy(is, new FileOutputStream(iso));
} finally {
Closeables.closeQuietly(is);
}
}
return iso;
}
private void sendKeyboardSequence(String keyboardSequence)
throws InterruptedException {
String[] sequenceSplited = keyboardSequence.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : sequenceSplited) {
String converted = stringToKeycode(word);
for (String string : converted.split(" ")) {
sb.append("vboxmanage controlvm " + vmName
+ " keyboardputscancode " + string + "; ");
if (string
.contains(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.get("<Return>"))) {
runScriptOnNode(hostId, sb.toString(), runAsRoot(false)
.wrapInInitScript(false));
sb = new StringBuilder();
}
}
}
runScriptOnNode(hostId, sb.toString(), runAsRoot(false)
.wrapInInitScript(false));
}
private String stringToKeycode(String s) {
StringBuilder keycodes = new StringBuilder();
for (String specialButton : KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.keySet()) {
if (s.startsWith(specialButton)) {
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.get(specialButton));
return keycodes.toString();
}
}
int i = 0;
while (i < s.length()) {
String digit = s.substring(i, i + 1);
String hex = KeyboardScancodes.NORMAL_KEYBOARD_BUTTON_MAP
.get(digit);
keycodes.append(hex + " ");
if (i != 0 && i % 14 == 0)
keycodes.append(" ");
i++;
}
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.get("<Spacebar>") + " ");
return keycodes.toString();
}
/**
*
* @param machine
* @param session
*/
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
session.unlockMachine();
}
} }