refactored tests so that admin starts first via @BeforeSuite

This commit is contained in:
Adrian Cole 2011-10-10 23:43:57 -07:00
parent b2ade042bc
commit 0f73d04fca
4 changed files with 789 additions and 895 deletions

View File

@ -0,0 +1,215 @@
/**
*
* Copyright (C) 2009 Global Cloud Specialists, Inc. <info@globalcloudspecialists.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.virtualbox.experiment;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.logging.Logger;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
public class SetupVirtualBoxForLiveTest {
private String provider = "virtualbox";
private URI endpoint;
private String apiVersion;
private String workingDir;
private URI gaIsoUrl;
private String gaIsoName;
private URI distroIsoUrl;
private String distroIsoName;
private ComputeServiceContext context;
private String hostId = "host";
private String guestId = "guest";
private String majorVersion;
private URI vboxDmg;
private String vboxVersionName;
public void setupCredentials() {
endpoint = URI.create(System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/"));
apiVersion = System.getProperty("test." + provider + ".apiversion", "4.1.2r73507");
majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0);
}
public Logger logger() {
return context.utils().loggerFactory().getLogger("jclouds.compute");
}
public void setupConfigurationProperties() {
workingDir = System.getProperty("user.home") + File.separator
+ System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test");
if (new File(workingDir).mkdir())
;
gaIsoName = System.getProperty("test." + provider + ".gaIsoName", "VBoxGuestAdditions_" + majorVersion + ".iso");
gaIsoUrl = URI.create(System.getProperty("test." + provider + ".gaIsoUrl",
"http://download.virtualbox.org/virtualbox/" + majorVersion + "/" + gaIsoName));
distroIsoName = System.getProperty("test." + provider + ".distroIsoName", "ubuntu-11.04-server-i386.iso");
distroIsoUrl = URI.create(System.getProperty("test." + provider + ".distroIsoUrl",
"http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso"));
vboxDmg = URI.create(System.getProperty("test." + provider + ".vboxDmg",
"http://download.virtualbox.org/virtualbox/4.1.2/VirtualBox-4.1.2-73507-OSX.dmg"));
vboxVersionName = System.getProperty("test" + provider + ".vboxVersionName", "VirtualBox-4.1.2-73507-OSX.dmg");
}
public void configureJettyServer() throws Exception {
Server server = new Server(8080);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "index.html" });
resource_handler.setResourceBase(".");
logger().info("serving " + resource_handler.getBaseResource());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
server.start();
}
@BeforeSuite
public void setupClient() throws Exception {
context = TestUtils.computeServiceForLocalhostAndGuest();
setupCredentials();
setupConfigurationProperties();
downloadFileUnlessPresent(distroIsoUrl, workingDir, distroIsoName);
downloadFileUnlessPresent(gaIsoUrl, workingDir, gaIsoName);
installVbox();
checkVboxVersionExpected();
if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint.getHost(), endpoint.getPort())))
startupVboxWebServer();
configureJettyServer();
}
public void installVbox() throws Exception {
if (runScriptOnNode(hostId, "VBoxManage --version", runAsRoot(false).wrapInInitScript(false)).getExitCode() != 0) {
logger().debug("installing virtualbox");
if (isOSX(hostId)) {
downloadFileUnlessPresent(vboxDmg, workingDir, vboxVersionName);
runScriptOnNode(hostId, "hdiutil attach " + workingDir + "/" + vboxVersionName);
runScriptOnNode(hostId,
"installer -pkg /Volumes/VirtualBox/VirtualBox.mpkg -target /Volumes/Macintosh\\ HD");
} else {
// TODO other platforms
runScriptOnNode(hostId, "cat > /etc/apt/sources.list.d/TODO");
runScriptOnNode(hostId,
"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");
}
}
}
public void checkVboxVersionExpected() throws IOException, InterruptedException {
logger().debug("checking virtualbox version");
assertEquals(runScriptOnNode(hostId, "VBoxManage -version").getOutput().trim(), apiVersion);
}
/**
*
* @param command
* absolute path to command. For ubuntu 10.04: /usr/bin/vboxwebsrv
* @throws IOException
* @throws InterruptedException
*/
public void startupVboxWebServer() {
logger().debug("disabling password access");
runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null", runAsRoot(false).wrapInInitScript(false));
logger().debug("starting vboxwebsrv");
String vboxwebsrv = "vboxwebsrv -t 10000 -v -b";
if (isOSX(hostId))
vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " + vboxwebsrv;
runScriptOnNode(hostId, vboxwebsrv, runAsRoot(false).wrapInInitScript(false).blockOnPort(endpoint.getPort(), 10)
.blockOnComplete(false).nameTask("vboxwebsrv"));
}
public boolean isOSX(String id) {
return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription().equals(
"Mac OS X");
}
public 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;
}
@AfterSuite
public void stopVboxWebServer() throws IOException {
runScriptOnNode(guestId, "pidof vboxwebsrv | xargs kill");
}
public ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) {
ExecResponse toReturn = context.getComputeService().runScriptOnNode(nodeId, command, options);
assert toReturn.getExitCode() == 0 : toReturn;
return toReturn;
}
public ExecResponse runScriptOnNode(String nodeId, String command) {
return runScriptOnNode(nodeId, command, wrapInInitScript(false));
}
}

View File

@ -18,7 +18,6 @@
*/ */
package org.jclouds.virtualbox.experiment; package org.jclouds.virtualbox.experiment;
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.runAsRoot; 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;
@ -27,35 +26,21 @@ import static org.testng.Assert.assertNotNull;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.logging.Logger;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.scriptbuilder.statements.login.AdminAccess; import org.jclouds.scriptbuilder.statements.login.AdminAccess;
import org.jclouds.scriptbuilder.statements.login.DefaultConfiguration; import org.jclouds.scriptbuilder.statements.login.DefaultConfiguration;
import org.jclouds.ssh.SshException; import org.jclouds.ssh.SshException;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.jclouds.virtualbox.settings.KeyboardScancodes; import org.jclouds.virtualbox.settings.KeyboardScancodes;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.AccessMode; import org.virtualbox_4_1.AccessMode;
@ -74,78 +59,45 @@ import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VirtualBoxManager; import org.virtualbox_4_1.VirtualBoxManager;
import org.virtualbox_4_1.jaxws.MediumVariant; import org.virtualbox_4_1.jaxws.MediumVariant;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
@Test(groups = "live", testName = "virtualbox.VirtualboxAdministrationKickstartTest") @Test(groups = "live", testName = "virtualbox.VirtualboxAdministrationKickstartTest")
public class VirtualboxAdministrationKickstartLiveTest { public class VirtualboxAdministrationKickstartLiveTest extends BaseVirtualBoxClientLiveTest {
protected String provider = "virtualbox"; private String hostId = "host"; // TODO: shared between classes; move to iTestContext
protected String identity; private String guestId = "guest"; // TODO: ^^
protected String credential; private String distroIsoName; // TODO: ^^
protected URI endpoint; private String workingDir;// TODO: ^^
protected String apiVersion;
protected String vmName;
VirtualBoxManager manager = VirtualBoxManager.createInstance(""); private String settingsFile; // Fully qualified path where the settings
protected Predicate<IPSocket> socketTester;
protected String settingsFile; // Fully qualified path where the settings
protected String osTypeId; // Guest OS Type ID.
protected String vmId; // Machine UUID (optional).
protected boolean forceOverwrite;
protected String diskFormat;
protected String workingDir;
protected String adminDisk;
protected String guestAdditionsDvd;
private URI gaIsoUrl;
private String gaIsoName;
private URI distroIsoUrl;
private String distroIsoName;
private String controllerIDE;
private String controllerSATA;
private String keyboardSequence; private String keyboardSequence;
private String preseedUrl;
private ComputeServiceContext context; private String vmId; // Machine UUID
private String hostId = "host"; private String vmName;
private String guestId = "guest"; private String controllerIDE;
private String majorVersion; private String osTypeId; // Guest OS Type ID.
private String minorVersion; private boolean forceOverwrite;
private URI vboxDmg; private String diskFormat;
private String vboxVersionName; private String adminDisk;
private String guestAdditionsDvd;
private String snapshotDescription; private String snapshotDescription;
protected void setupCredentials() { private VirtualBoxManager manager = VirtualBoxManager.createInstance("");
identity = System.getProperty("test." + provider + ".identity",
"administrator"); protected boolean isUbuntu(String id) {
credential = System.getProperty("test." + provider + ".credential", return context.getComputeService().getNodeMetadata(id).getOperatingSystem().getDescription().contains("ubuntu");
"12345");
endpoint = URI.create(System.getProperty("test." + provider
+ ".endpoint", "http://localhost:18083/"));
apiVersion = System.getProperty("test." + provider + ".apiversion",
"4.1.2r73507");
majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0);
minorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 1);
} }
protected Logger logger() { @BeforeMethod
return context.utils().loggerFactory().getLogger("jclouds.compute"); protected void setupManager() {
manager.connect(endpoint, identity, credential);
} }
protected void setupConfigurationProperties() { @BeforeClass
void setupConfigurationProperties() {
controllerIDE = System.getProperty("test." + provider controllerIDE = System.getProperty("test." + provider + ".controllerIde", "IDE Controller");
+ ".controllerIde", "IDE Controller");
controllerSATA = System.getProperty("test." + provider
+ ".controllerSata", "SATA Controller");
diskFormat = System.getProperty("test." + provider + ".diskformat", ""); diskFormat = System.getProperty("test." + provider + ".diskformat", "");
// VBOX // VBOX
@ -153,172 +105,96 @@ public class VirtualboxAdministrationKickstartLiveTest {
osTypeId = System.getProperty("test." + provider + ".osTypeId", ""); osTypeId = System.getProperty("test." + provider + ".osTypeId", "");
vmId = System.getProperty("test." + provider + ".vmId", null); vmId = System.getProperty("test." + provider + ".vmId", null);
forceOverwrite = true; forceOverwrite = true;
vmName = System.getProperty("test." + provider + ".vmname", vmName = System.getProperty("test." + provider + ".vmname", "jclouds-virtualbox-kickstart-admin");
"jclouds-virtualbox-kickstart-admin");
workingDir = System.getProperty("user.home") workingDir = System.getProperty("user.home") + File.separator
+ File.separator + System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test");
+ System.getProperty("test." + provider + ".workingDir", if (new File(workingDir).mkdir())
"jclouds-virtualbox-test"); ;
if (new File(workingDir).mkdir()); distroIsoName = System.getProperty("test." + provider + ".distroIsoName", "ubuntu-11.04-server-i386.iso");
gaIsoName = System.getProperty("test." + provider + ".gaIsoName", adminDisk = workingDir + File.separator + System.getProperty("test." + provider + ".adminDisk", "admin.vdi");
"VBoxGuestAdditions_" + majorVersion + ".iso"); String majorVersion = Iterables.get(Splitter.on('r').split(apiversion), 0);
gaIsoUrl = URI.create(System.getProperty("test." + provider
+ ".gaIsoUrl", "http://download.virtualbox.org/virtualbox/"
+ majorVersion + "/" + gaIsoName));
distroIsoName = System.getProperty("test." + provider
+ ".distroIsoName", "ubuntu-11.04-server-i386.iso");
distroIsoUrl = URI
.create(System
.getProperty("test." + provider + ".distroIsoUrl",
"http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso"));
vboxDmg = URI.create(System.getProperty("test." + provider + ".vboxDmg","http://download.virtualbox.org/virtualbox/4.1.2/VirtualBox-4.1.2-73507-OSX.dmg"));
vboxVersionName = System.getProperty("test" + provider + ".vboxVersionName", "VirtualBox-4.1.2-73507-OSX.dmg");
adminDisk = workingDir
+ File.separator
+ System.getProperty("test." + provider + ".adminDisk",
"admin.vdi");
guestAdditionsDvd = workingDir guestAdditionsDvd = workingDir
+ File.separator + File.separator
+ System.getProperty("test." + provider + ".guestAdditionsDvd", + System.getProperty("test." + provider + ".guestAdditionsDvd", "VBoxGuestAdditions_" + majorVersion
"VBoxGuestAdditions_" + majorVersion + ".iso"); + ".iso");
snapshotDescription = System
.getProperty("test." + provider + "snapshotdescription", "jclouds-virtualbox-snaphot");
preseedUrl = System.getProperty("test." + provider + ".preseedurl", keyboardSequence = System.getProperty("test." + provider + ".keyboardSequence", "<Esc><Esc><Enter> "
"http://dl.dropbox.com/u/693111/preseed.cfg");
snapshotDescription = System.getProperty("test." + provider + "snapshotdescription", "jclouds-virtualbox-snaphot");
keyboardSequence = System
.getProperty(
"test." + provider + ".keyboardSequence",
"<Esc><Esc><Enter> "
+ "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg " + "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg "
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " "
+ "hostname="
+ vmName
+ " "
+ "fb=false debconf/frontend=noninteractive " + "fb=false debconf/frontend=noninteractive "
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false " + "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
+ "initrd=/install/initrd.gz -- <Enter>"); + "initrd=/install/initrd.gz -- <Enter>");
} }
@BeforeGroups(groups = "live") public void sendKeyboardSequence(String keyboardSequence) throws InterruptedException {
protected void setupClient() throws Exception { String[] sequenceSplited = keyboardSequence.split(" ");
context = TestUtils.computeServiceForLocalhostAndGuest(); StringBuilder sb = new StringBuilder();
socketTester = new RetryablePredicate<IPSocket>( for (String line : sequenceSplited) {
new InetSocketAddressConnect(), 130, 10, TimeUnit.SECONDS); String converted = stringToKeycode(line);
setupCredentials(); for (String word : converted.split(" ")) {
setupConfigurationProperties(); sb.append("vboxmanage controlvm " + vmName + " keyboardputscancode " + word + "; ");
downloadFileUnlessPresent(distroIsoUrl, workingDir, distroIsoName);
downloadFileUnlessPresent(gaIsoUrl, workingDir, gaIsoName);
installVbox(); if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Enter>"))) {
checkVboxVersionExpected(); runScriptOnNode(hostId, sb.toString(), runAsRoot(false).wrapInInitScript(false));
if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint sb.delete(0, sb.length() - 1);
.getHost(), endpoint.getPort())))
startupVboxWebServer();
configureJettyServer();
} }
private void configureJettyServer() throws Exception { if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Return>"))) {
Server server = new Server(8080); runScriptOnNode(hostId, sb.toString(), runAsRoot(false).wrapInInitScript(false));
sb.delete(0, sb.length() - 1);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "index.html" });
resource_handler.setResourceBase(".");
logger().info("serving " + resource_handler.getBaseResource());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler,
new DefaultHandler() });
server.setHandler(handlers);
server.start();
} }
void installVbox() throws Exception {
if (runScriptOnNode(hostId, "VBoxManage --version", runAsRoot(false).wrapInInitScript(false)).getExitCode() != 0) {
logger().debug("installing virtualbox");
if (isOSX(hostId)) {
downloadFileUnlessPresent(vboxDmg, workingDir, vboxVersionName);
runScriptOnNode(hostId, "hdiutil attach " + workingDir + "/" + vboxVersionName);
runScriptOnNode(hostId, "installer -pkg /Volumes/VirtualBox/VirtualBox.mpkg -target /Volumes/Macintosh\\ HD");
} else {
// TODO other platforms
runScriptOnNode(hostId, "cat > /etc/apt/sources.list.d/TODO");
runScriptOnNode(
hostId,
"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");
} }
} }
} }
void checkVboxVersionExpected() throws IOException, InterruptedException { public ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) {
logger().debug("checking virtualbox version"); ExecResponse toReturn = context.getComputeService().runScriptOnNode(nodeId, command, options);
assertEquals(runScriptOnNode(hostId, "VBoxManage -version").getOutput() assert toReturn.getExitCode() == 0 : toReturn;
.trim(), apiVersion); return toReturn;
} }
/** public ExecResponse runScriptOnNode(String nodeId, String command) {
* return runScriptOnNode(nodeId, command, wrapInInitScript(false));
* @param command
* absolute path to command. For ubuntu 10.04:
* /usr/bin/vboxwebsrv
* @throws IOException
* @throws InterruptedException
*/
void startupVboxWebServer() {
logger().debug("disabling password access");
runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null", runAsRoot(false).wrapInInitScript(false));
logger().debug("starting vboxwebsrv");
String vboxwebsrv = "vboxwebsrv -t 10000 -v -b";
if (isOSX(hostId))
vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && "
+ vboxwebsrv;
runScriptOnNode(
hostId,
vboxwebsrv,
runAsRoot(false).wrapInInitScript(false)
.blockOnPort(endpoint.getPort(), 10)
.blockOnComplete(false)
.nameTask("vboxwebsrv"));
} }
protected boolean isOSX(String id) { public String stringToKeycode(String s) {
return context.getComputeService().getNodeMetadata(hostId) StringBuilder keycodes = new StringBuilder();
.getOperatingSystem().getDescription().equals("Mac OS X"); if (s.startsWith("<")) {
String[] specials = s.split("<");
for (int i = 1; i < specials.length; i++) {
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<" + specials[i]) + " ");
}
return keycodes.toString();
} }
protected boolean isUbuntu(String id) { int i = 0;
return context.getComputeService().getNodeMetadata(id) while (i < s.length()) {
.getOperatingSystem().getDescription().contains("ubuntu"); 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>") + " ");
@BeforeMethod return keycodes.toString();
protected void setupManager() {
manager.connect(endpoint.toASCIIString(), identity, credential);
} }
@AfterMethod @AfterMethod
protected void disconnectAndClenaupManager() throws RemoteException, protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
MalformedURLException {
manager.disconnect(); manager.disconnect();
manager.cleanup(); manager.cleanup();
} }
@Test @Test
public void testCreateVirtualMachine() { public void testCreateVirtualMachine() {
IMachine newVM = manager.getVBox().createMachine(settingsFile, vmName, IMachine newVM = manager.getVBox().createMachine(settingsFile, vmName, osTypeId, vmId, forceOverwrite);
osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(newVM); manager.getVBox().registerMachine(newVM);
assertNotNull(newVM.getName()); assertNotNull(newVM.getName());
} }
@ -333,8 +209,7 @@ public class VirtualboxAdministrationKickstartLiveTest {
mutable.setMemorySize(memorySize); mutable.setMemorySize(memorySize);
mutable.saveSettings(); mutable.saveSettings();
session.unlockMachine(); session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName).getMemorySize(), assertEquals(manager.getVBox().findMachine(vmName).getMemorySize(), memorySize);
memorySize);
} }
@Test(dependsOnMethods = "testChangeRAM") @Test(dependsOnMethods = "testChangeRAM")
@ -346,14 +221,12 @@ public class VirtualboxAdministrationKickstartLiveTest {
mutable.addStorageController(controllerIDE, StorageBus.IDE); mutable.addStorageController(controllerIDE, StorageBus.IDE);
mutable.saveSettings(); mutable.saveSettings();
session.unlockMachine(); session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName) assertEquals(manager.getVBox().findMachine(vmName).getStorageControllers().size(), 1);
.getStorageControllers().size(), 1);
} }
@Test(dependsOnMethods = "testCreateIdeController") @Test(dependsOnMethods = "testCreateIdeController")
public void testAttachIsoDvd() { public void testAttachIsoDvd() {
IMedium distroMedium = manager.getVBox().openMedium( IMedium distroMedium = manager.getVBox().openMedium(workingDir + "/" + distroIsoName, DeviceType.DVD,
workingDir + "/" + distroIsoName, DeviceType.DVD,
AccessMode.ReadOnly, forceOverwrite); AccessMode.ReadOnly, forceOverwrite);
ISession session = manager.getSessionObject(); ISession session = manager.getSessionObject();
@ -374,8 +247,8 @@ public class VirtualboxAdministrationKickstartLiveTest {
} }
hd = manager.getVBox().createHardDisk(diskFormat, adminDisk); hd = manager.getVBox().createHardDisk(diskFormat, adminDisk);
long size = 4L * 1024L * 1024L * 1024L - 4L; long size = 4L * 1024L * 1024L * 1024L - 4L;
IProgress progress = hd.createBaseStorage(new Long(size), new Long( IProgress progress = hd.createBaseStorage(new Long(size), new Long(MediumVariant.STANDARD.ordinal()));
MediumVariant.STANDARD.ordinal())); // TODO: poll?
ISession session = manager.getSessionObject(); ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName); IMachine machine = manager.getVBox().findMachine(vmName);
@ -395,11 +268,8 @@ public class VirtualboxAdministrationKickstartLiveTest {
IMachine mutable = session.getMachine(); IMachine mutable = session.getMachine();
// NAT // NAT
mutable.getNetworkAdapter(new Long(0)).setAttachmentType( mutable.getNetworkAdapter(new Long(0)).setAttachmentType(NetworkAttachmentType.NAT);
NetworkAttachmentType.NAT); machine.getNetworkAdapter(new Long(0)).getNatDriver().addRedirect("guestssh", NATProtocol.TCP, "127.0.0.1", 2222,
machine.getNetworkAdapter(new Long(0))
.getNatDriver()
.addRedirect("guestssh", NATProtocol.TCP, "127.0.0.1", 2222,
"", 22); "", 22);
mutable.getNetworkAdapter(new Long(0)).setEnabled(true); mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
@ -412,8 +282,8 @@ public class VirtualboxAdministrationKickstartLiveTest {
ISession session = manager.getSessionObject(); ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName); IMachine machine = manager.getVBox().findMachine(vmName);
IMedium distroMedium = manager.getVBox().openMedium(guestAdditionsDvd, DeviceType.DVD, IMedium distroMedium = manager.getVBox().openMedium(guestAdditionsDvd, DeviceType.DVD, AccessMode.ReadOnly,
AccessMode.ReadOnly, forceOverwrite); forceOverwrite);
machine.lockMachine(session, LockType.Write); machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine(); IMachine mutable = session.getMachine();
mutable.attachDevice(controllerIDE, 1, 1, DeviceType.DVD, distroMedium); mutable.attachDevice(controllerIDE, 1, 1, DeviceType.DVD, distroMedium);
@ -422,7 +292,6 @@ public class VirtualboxAdministrationKickstartLiveTest {
assertEquals(distroMedium.getId().equals(""), false); assertEquals(distroMedium.getId().equals(""), false);
} }
@Test(dependsOnMethods = "testAttachGuestAdditions") @Test(dependsOnMethods = "testAttachGuestAdditions")
public void testStartVirtualMachine() throws InterruptedException { public void testStartVirtualMachine() throws InterruptedException {
IMachine machine = manager.getVBox().findMachine(vmName); IMachine machine = manager.getVBox().findMachine(vmName);
@ -439,12 +308,12 @@ public class VirtualboxAdministrationKickstartLiveTest {
// test if the sshd on the guest is ready and meanwhile apply AdminAccess // test if the sshd on the guest is ready and meanwhile apply AdminAccess
boolean sshDeamonIsRunning = false; boolean sshDeamonIsRunning = false;
while(!sshDeamonIsRunning) { while (!sshDeamonIsRunning) {
try { try {
AdminAccess.standard().init(new DefaultConfiguration()).render(OsFamily.UNIX); AdminAccess.standard().init(new DefaultConfiguration()).render(OsFamily.UNIX);
if(runScriptOnNode(guestId, "id").getExitCode() == 0) if (runScriptOnNode(guestId, "id").getExitCode() == 0)
sshDeamonIsRunning = true; sshDeamonIsRunning = true;
} catch(SshException e) { } catch (SshException e) {
System.err.println("connection reset"); System.err.println("connection reset");
} }
} }
@ -453,16 +322,13 @@ public class VirtualboxAdministrationKickstartLiveTest {
@Test(dependsOnMethods = "testStartVirtualMachine") @Test(dependsOnMethods = "testStartVirtualMachine")
public void testConfigureGuestAdditions() { public void testConfigureGuestAdditions() {
// TODO generalize // TODO generalize
if(isUbuntu(guestId)) { if (isUbuntu(guestId)) {
/* /*
runScriptOnNode(guestId, * runScriptOnNode(guestId, "m-a prepare -i"); runScriptOnNode(guestId,
"m-a prepare -i"); * "mount -o loop /dev/dvd /media/cdrom"); runScriptOnNode(guestId,
runScriptOnNode(guestId, * "sh /media/cdrom/VBoxLinuxAdditions.run");
"mount -o loop /dev/dvd /media/cdrom"); *
runScriptOnNode(guestId, * runScriptOnNode(guestId, "/etc/init.d/vboxadd setup");
"sh /media/cdrom/VBoxLinuxAdditions.run");
runScriptOnNode(guestId, "/etc/init.d/vboxadd setup");
*/ */
runScriptOnNode(guestId, "rm /etc/udev/rules.d/70-persistent-net.rules"); runScriptOnNode(guestId, "rm /etc/udev/rules.d/70-persistent-net.rules");
runScriptOnNode(guestId, "mkdir /etc/udev/rules.d/70-persistent-net.rules"); runScriptOnNode(guestId, "mkdir /etc/udev/rules.d/70-persistent-net.rules");
@ -521,107 +387,19 @@ public class VirtualboxAdministrationKickstartLiveTest {
ISession session = manager.getSessionObject(); ISession session = manager.getSessionObject();
IMachine adminNode = manager.getVBox().findMachine(vmName); IMachine adminNode = manager.getVBox().findMachine(vmName);
adminNode.lockMachine(session, LockType.Write); adminNode.lockMachine(session, LockType.Write);
if(adminNode.getCurrentSnapshot() == null || !adminNode.getCurrentSnapshot().getDescription().equals(snapshotDescription)) { if (adminNode.getCurrentSnapshot() == null
|| !adminNode.getCurrentSnapshot().getDescription().equals(snapshotDescription)) {
manager.getSessionObject().getConsole().takeSnapshot(adminNode.getId(), snapshotDescription); manager.getSessionObject().getConsole().takeSnapshot(adminNode.getId(), snapshotDescription);
} }
session.unlockMachine(); session.unlockMachine();
} }
@AfterClass
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 line : sequenceSplited) {
String converted = stringToKeycode(line);
for (String word : converted.split(" ")) {
sb.append("vboxmanage controlvm " + vmName
+ " keyboardputscancode " + word + "; ");
if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Enter>"))) {
runScriptOnNode(hostId, sb.toString(), runAsRoot(false)
.wrapInInitScript(false));
sb.delete(0, sb.length()-1);
}
if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Return>"))) {
runScriptOnNode(hostId, sb.toString(), runAsRoot(false)
.wrapInInitScript(false));
sb.delete(0, sb.length()-1);
}
}
}
}
private String stringToKeycode(String s) {
StringBuilder keycodes = new StringBuilder();
if (s.startsWith("<")) {
String[] specials = s.split("<");
for (int i = 1; i < specials.length; i++) {
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.get("<" + specials[i]) + " ");
}
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 machine
* @param session * @param session
*/ */
private void launchVMProcess(IMachine machine, ISession session) { public void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", ""); IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1); prog.waitForCompletion(-1);
session.unlockMachine(); session.unlockMachine();
@ -630,7 +408,7 @@ public class VirtualboxAdministrationKickstartLiveTest {
/** /**
* @param machine * @param machine
*/ */
private void powerDownMachine(IMachine machine) { public void powerDownMachine(IMachine machine) {
try { try {
ISession machineSession = manager.openMachineSession(machine); ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown(); IProgress progress = machineSession.getConsole().powerDown();
@ -639,9 +417,7 @@ public class VirtualboxAdministrationKickstartLiveTest {
while (!machine.getSessionState().equals(SessionState.Unlocked)) { while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try { try {
System.out System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
.println("waiting for unlocking session - session state: "
+ machine.getSessionState());
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
@ -653,4 +429,4 @@ public class VirtualboxAdministrationKickstartLiveTest {
} }
} }
} }

View File

@ -20,42 +20,23 @@ package org.jclouds.virtualbox.experiment;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; 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;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.log.Log;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.encryption.bouncycastle.config.BouncyCastleCryptoModule;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.scriptbuilder.statements.login.AdminAccess;
import org.jclouds.scriptbuilder.statements.login.DefaultConfiguration;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshException;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeMethod;
@ -67,78 +48,42 @@ import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.ISession;
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.NetworkAdapterType;
import org.virtualbox_4_1.NetworkAttachmentType; import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.SessionState; import org.virtualbox_4_1.SessionState;
import org.virtualbox_4_1.VirtualBoxManager; import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Injector;
import com.google.inject.Module;
@Test(groups = "live", testName = "virtualbox.VirtualboxLiveTest") @Test(groups = "live", testName = "virtualbox.VirtualboxLiveTest")
public class VirtualboxLiveTest { public class VirtualboxLiveTest {
protected String provider = "virtualbox"; private String provider = "virtualbox";
protected String identity; private String identity;
protected String credential; private String credential;
protected URI endpoint; private URI endpoint;
protected String apiversion; private String vmName;
protected String vmName;
VirtualBoxManager manager = VirtualBoxManager.createInstance(""); private VirtualBoxManager manager = VirtualBoxManager.createInstance("");
protected Injector injector; private String settingsFile;
protected Predicate<IPSocket> socketTester; private String osTypeId;
protected SshClient.Factory sshFactory; private String vmId;
private boolean forceOverwrite;
protected String osUsername; private int numberOfVirtualMachine;
protected String osPassword;
protected String controller;
protected String diskFormat;
protected String settingsFile;
protected String osTypeId;
protected String vmId;
protected boolean forceOverwrite;
protected String workingDir;
protected String clonedDiskPath;
protected String format = "vdi";
protected int numberOfVirtualMachine;
protected String originalDisk;
private String clonedDisk;
private ComputeServiceContext context; private ComputeServiceContext context;
private String hostId = "host"; private String hostId = "host";
private String guestId = "guest";
private String majorVersion;
private String minorVersion;
private String apiVersion;
private String adminNodeName; private String adminNodeName;
private String snapshotDescription;
private String originalDiskPath;
protected Logger logger() { private Logger logger() {
return context.utils().loggerFactory().getLogger("jclouds.compute"); return context.utils().loggerFactory().getLogger("jclouds.compute");
} }
protected void setupCredentials() { private void setupCredentials() {
identity = System.getProperty("test." + provider + ".identity", identity = System.getProperty("test." + provider + ".identity", "administrator");
"administrator"); credential = System.getProperty("test." + provider + ".credential", "12345");
credential = System.getProperty("test." + provider + ".credential", endpoint = URI.create(System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/"));
"12345");
endpoint = URI.create(System.getProperty("test." + provider
+ ".endpoint", "http://localhost:18083/"));
apiVersion = System.getProperty("test." + provider + ".apiversion",
"4.1.2r73507");
majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0);
minorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 1);
} }
protected void setupConfigurationProperties() { private void setupConfigurationProperties() {
// VBOX // VBOX
settingsFile = null; settingsFile = null;
osTypeId = System.getProperty("test." + provider + ".osTypeId", ""); osTypeId = System.getProperty("test." + provider + ".osTypeId", "");
@ -147,44 +92,26 @@ public class VirtualboxLiveTest {
// OS specific information // OS specific information
adminNodeName = System.getProperty("test." + provider + ".adminnodename", "jclouds-virtualbox-kickstart-admin"); adminNodeName = System.getProperty("test." + provider + ".adminnodename", "jclouds-virtualbox-kickstart-admin");
vmName = checkNotNull(System.getProperty("test." + provider + ".vmname", "jclouds-virtualbox-node")); vmName = checkNotNull(System.getProperty("test." + provider + ".vmname", "jclouds-virtualbox-node"));
osUsername = System.getProperty("test." + provider + ".osusername", "toor");
osPassword = System.getProperty("test." + provider + ".ospassword", "password");
controller = System.getProperty("test." + provider + ".controller", "IDE Controller");
diskFormat = System.getProperty("test." + provider + ".diskformat", "");
workingDir = System.getProperty("user.home")
+ File.separator
+ System.getProperty("test." + provider + ".workingDir",
"jclouds-virtualbox-test");
originalDisk = System.getProperty("test." + provider + ".originalDisk", "admin.vdi");
originalDiskPath = workingDir + File.separator + originalDisk;
clonedDisk = System.getProperty("test." + provider + ".clonedDisk", "clone.vdi");
clonedDiskPath = workingDir + File.separator + clonedDisk;
numberOfVirtualMachine = Integer.parseInt(checkNotNull(System.getProperty("test." + provider numberOfVirtualMachine = Integer.parseInt(checkNotNull(System.getProperty("test." + provider
+ ".numberOfVirtualMachine", "1"))); + ".numberOfVirtualMachine", "1")));
} }
@BeforeGroups(groups = "live") @BeforeGroups(groups = "live")
protected void setupClient() throws Exception { public void setupClient() throws Exception {
context = TestUtils.computeServiceForLocalhostAndGuest(); context = TestUtils.computeServiceForLocalhostAndGuest();
socketTester = new RetryablePredicate<IPSocket>(
new InetSocketAddressConnect(), 130, 10, TimeUnit.SECONDS);
setupCredentials(); setupCredentials();
setupConfigurationProperties(); setupConfigurationProperties();
if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint.getHost(), endpoint.getPort()))) if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint.getHost(), endpoint.getPort())))
startupVboxWebServer(); startupVboxWebServer();
} }
@BeforeMethod @BeforeMethod
protected void setupManager() throws RemoteException, MalformedURLException { public void setupManager() throws RemoteException, MalformedURLException {
manager.connect(endpoint.toASCIIString(), identity, credential); manager.connect(endpoint.toASCIIString(), identity, credential);
} }
@AfterMethod @AfterMethod
protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException { public void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
manager.disconnect(); manager.disconnect();
manager.cleanup(); manager.cleanup();
} }
@ -203,9 +130,10 @@ public class VirtualboxLiveTest {
IMachine clonedVM = manager.getVBox().createMachine(settingsFile, instanceName, osTypeId, vmId, forceOverwrite); IMachine clonedVM = manager.getVBox().createMachine(settingsFile, instanceName, osTypeId, vmId, forceOverwrite);
List<CloneOptions> options = new ArrayList<CloneOptions>(); List<CloneOptions> options = new ArrayList<CloneOptions>();
options.add(CloneOptions.Link); options.add(CloneOptions.Link);
IProgress progress = adminNode.getCurrentSnapshot().getMachine().cloneTo(clonedVM,CloneMode.MachineState , options); IProgress progress = adminNode.getCurrentSnapshot().getMachine().cloneTo(clonedVM, CloneMode.MachineState,
options);
if(progress.getCompleted()) if (progress.getCompleted())
logger().debug("clone done"); logger().debug("clone done");
manager.getVBox().registerMachine(clonedVM); manager.getVBox().registerMachine(clonedVM);
@ -214,13 +142,12 @@ public class VirtualboxLiveTest {
clonedVM.lockMachine(session, LockType.Write); clonedVM.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine(); IMachine mutable = session.getMachine();
mutable.getNetworkAdapter(new Long(0)).setAttachmentType(NetworkAttachmentType.Bridged); mutable.getNetworkAdapter(new Long(0)).setAttachmentType(NetworkAttachmentType.Bridged);
String mac_address = manager.getVBox().getHost().generateMACAddress(); String mac_address = manager.getVBox().getHost().generateMACAddress();
System.out.println("mac_address " + mac_address); System.out.println("mac_address " + mac_address);
mutable.getNetworkAdapter(new Long(0)).setMACAddress(mac_address); mutable.getNetworkAdapter(new Long(0)).setMACAddress(mac_address);
if(isOSX(hostId)) { if (isOSX(hostId)) {
mutable.getNetworkAdapter(new Long(0)).setBridgedInterface(findBridgeInUse()); mutable.getNetworkAdapter(new Long(0)).setBridgedInterface(findBridgeInUse());
} else { } else {
mutable.getNetworkAdapter(new Long(0)).setBridgedInterface("virbr0"); mutable.getNetworkAdapter(new Long(0)).setBridgedInterface("virbr0");
@ -237,38 +164,48 @@ public class VirtualboxLiveTest {
int offset = 0, step = 2; int offset = 0, step = 2;
for (int j = 1; j <= 5; j++) { for (int j = 1; j <= 5; j++) {
macAddressOfClonedVM = new StringBuffer(macAddressOfClonedVM).insert(j * step + offset, ":").toString().toLowerCase(); macAddressOfClonedVM = new StringBuffer(macAddressOfClonedVM).insert(j * step + offset, ":").toString()
.toLowerCase();
offset++; offset++;
} }
String simplifiedMacAddressOfClonedVM = macAddressOfClonedVM; String simplifiedMacAddressOfClonedVM = macAddressOfClonedVM;
if(isOSX(hostId)) { if (isOSX(hostId)) {
if(simplifiedMacAddressOfClonedVM.contains("00")) if (simplifiedMacAddressOfClonedVM.contains("00"))
simplifiedMacAddressOfClonedVM = new StringBuffer(simplifiedMacAddressOfClonedVM).delete(simplifiedMacAddressOfClonedVM.indexOf("00"), simplifiedMacAddressOfClonedVM.indexOf("00") + 1).toString(); simplifiedMacAddressOfClonedVM = new StringBuffer(simplifiedMacAddressOfClonedVM).delete(
simplifiedMacAddressOfClonedVM.indexOf("00"), simplifiedMacAddressOfClonedVM.indexOf("00") + 1)
.toString();
if(simplifiedMacAddressOfClonedVM.contains("0")) if (simplifiedMacAddressOfClonedVM.contains("0"))
if(simplifiedMacAddressOfClonedVM.indexOf("0") + 1 != ':' && simplifiedMacAddressOfClonedVM.indexOf("0") - 1 != ':') if (simplifiedMacAddressOfClonedVM.indexOf("0") + 1 != ':'
simplifiedMacAddressOfClonedVM = new StringBuffer(simplifiedMacAddressOfClonedVM).delete(simplifiedMacAddressOfClonedVM.indexOf("0"), simplifiedMacAddressOfClonedVM.indexOf("0") + 1).toString(); && simplifiedMacAddressOfClonedVM.indexOf("0") - 1 != ':')
simplifiedMacAddressOfClonedVM = new StringBuffer(simplifiedMacAddressOfClonedVM).delete(
simplifiedMacAddressOfClonedVM.indexOf("0"), simplifiedMacAddressOfClonedVM.indexOf("0") + 1)
.toString();
} }
// TODO as we don't know the hostname (nor the IP address) of the cloned machine we can't use "ssh check" to check that the machine is up and running // TODO as we don't know the hostname (nor the IP address) of the cloned machine we can't use
// "ssh check" to check that the machine is up and running
// we need to find another way to check the machine is up: only at that stage a new IP would be used by the machine and arp will answer correctly // we need to find another way to check the machine is up: only at that stage a new IP would
// be used by the machine and arp will answer correctly
Thread.sleep(35000); // TODO to be removed asap Thread.sleep(35000); // TODO to be removed asap
runScriptOnNode(hostId, "for i in $(seq 1 254) ; do ping -c 1 -t 1 192.168.122.$i & done", runAsRoot(false).wrapInInitScript(false)); runScriptOnNode(hostId, "for i in $(seq 1 254) ; do ping -c 1 -t 1 192.168.122.$i & done", runAsRoot(false)
String arpLine = runScriptOnNode(hostId, "arp -an | grep " + simplifiedMacAddressOfClonedVM, runAsRoot(false).wrapInInitScript(false)).getOutput(); .wrapInInitScript(false));
String arpLine = runScriptOnNode(hostId, "arp -an | grep " + simplifiedMacAddressOfClonedVM,
runAsRoot(false).wrapInInitScript(false)).getOutput();
String ipAddress = arpLine.substring(arpLine.indexOf("(") + 1, arpLine.indexOf(")")); String ipAddress = arpLine.substring(arpLine.indexOf("(") + 1, arpLine.indexOf(")"));
System.out.println("IP address " + ipAddress); System.out.println("IP address " + ipAddress);
// TODO we need to redifine guest node at runtinme: in particular hostnmane and ssh port // TODO we need to redifine guest node at runtinme: in particular hostnmane and ssh port
//runScriptOnNode(guestId, "echo ciao"); // runScriptOnNode(guestId, "echo ciao");
} }
/** /**
* *
*/ */
protected String findBridgeInUse() { private String findBridgeInUse() {
// network // network
String hostInterface = null; String hostInterface = null;
String command = "vboxmanage list bridgedifs"; String command = "vboxmanage list bridgedifs";
@ -281,7 +218,7 @@ public class VirtualboxLiveTest {
while ((line = bufferedReader.readLine()) != null && !found) { while ((line = bufferedReader.readLine()) != null && !found) {
System.out.println("- " + line); System.out.println("- " + line);
if (line.split(":")[0].contains("Name")) { if (line.split(":")[0].contains("Name")) {
hostInterface = line.substring(line.indexOf(":") +1); hostInterface = line.substring(line.indexOf(":") + 1);
} }
if (line.split(":")[0].contains("Status") && line.split(":")[1].contains("Up")) { if (line.split(":")[0].contains("Status") && line.split(":")[1].contains("Up")) {
found = true; found = true;
@ -299,21 +236,6 @@ public class VirtualboxLiveTest {
session.unlockMachine(); session.unlockMachine();
} }
protected void checkSSH(IPSocket socket) {
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(osUsername, osPassword));
try {
client.connect();
ExecResponse exec = client.exec("touch /tmp/hello_" + System.currentTimeMillis());
exec = client.exec("echo hello");
System.out.println(exec);
assertEquals(exec.getOutput().trim(), "hello");
} finally {
if (client != null)
client.disconnect();
}
}
@Test(dependsOnMethods = "testStartAndValidateVirtualMachines") @Test(dependsOnMethods = "testStartAndValidateVirtualMachines")
public void testStopVirtualMachines() { public void testStopVirtualMachines() {
for (int i = 1; i < numberOfVirtualMachine + 1; i++) { for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
@ -341,43 +263,26 @@ public class VirtualboxLiveTest {
} }
} }
protected ExecResponse runScriptOnNode(String nodeId, String command, private ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) {
RunScriptOptions options) { ExecResponse toReturn = context.getComputeService().runScriptOnNode(nodeId, command, options);
ExecResponse toReturn = context.getComputeService().runScriptOnNode(
nodeId, command, options);
assert toReturn.getExitCode() == 0 : toReturn; assert toReturn.getExitCode() == 0 : toReturn;
return toReturn; return toReturn;
} }
protected ExecResponse runScriptOnNode(String nodeId, String command) { private boolean isOSX(String id) {
return runScriptOnNode(nodeId, command, wrapInInitScript(false)); return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription().equals(
"Mac OS X");
} }
protected boolean isOSX(String id) { private void startupVboxWebServer() {
return context.getComputeService().getNodeMetadata(hostId)
.getOperatingSystem().getDescription().equals("Mac OS X");
}
protected boolean isUbuntu(String id) {
return context.getComputeService().getNodeMetadata(id)
.getOperatingSystem().getDescription().contains("ubuntu");
}
void startupVboxWebServer() {
logger().debug("disabling password access"); logger().debug("disabling password access");
runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null", runAsRoot(false).wrapInInitScript(false)); runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null", runAsRoot(false).wrapInInitScript(false));
logger().debug("starting vboxwebsrv"); logger().debug("starting vboxwebsrv");
String vboxwebsrv = "vboxwebsrv -t 10000 -v -b"; String vboxwebsrv = "vboxwebsrv -t 10000 -v -b";
if (isOSX(hostId)) if (isOSX(hostId))
vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " + vboxwebsrv;
+ vboxwebsrv;
runScriptOnNode( runScriptOnNode(hostId, vboxwebsrv, runAsRoot(false).wrapInInitScript(false).blockOnPort(endpoint.getPort(), 10)
hostId, .blockOnComplete(false).nameTask("vboxwebsrv"));
vboxwebsrv,
runAsRoot(false).wrapInInitScript(false)
.blockOnPort(endpoint.getPort(), 10)
.blockOnComplete(false)
.nameTask("vboxwebsrv"));
} }
} }

View File

@ -25,26 +25,24 @@ package org.jclouds.virtualbox.functions;
* @author Andrea Turli, Mattias Holmqvist * @author Andrea Turli, Mattias Holmqvist
*/ */
import com.google.common.collect.Iterables; import static com.google.common.base.Predicates.equalTo;
import static com.google.common.collect.Iterables.any;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
import static org.testng.Assert.assertTrue;
import java.util.Set;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.VirtualBoxManager; import org.virtualbox_4_1.VirtualBoxManager;
import java.util.Set; @Test(groups = "live", singleThreaded = true, testName = "IsoToIMachineLiveTest")
public class IsoToIMachineLiveTest extends BaseVirtualBoxClientLiveTest {
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.collect.Iterables.*;
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
import static org.testng.Assert.assertTrue;
@Test(groups = "live", singleThreaded = true, testName = "IsoToIMachineTest")
public class IsoToIMachineTest extends BaseVirtualBoxClientLiveTest {
private String settingsFile = null; private String settingsFile = null;
private boolean forceOverwrite = true; private boolean forceOverwrite = true;