fixed headers and formatting

This commit is contained in:
Adrian Cole 2011-07-27 02:48:11 -07:00
parent d8dee64cf7
commit 21821231cb
6 changed files with 1098 additions and 991 deletions

View File

@ -1,3 +1,21 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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 org.eclipse.jetty.server.Handler;
@ -8,22 +26,22 @@ import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.util.log.Log;
public class FileServer {
public static void main(String[] args) throws Exception {
Server server = new Server(args.length == 0?8080:Integer.parseInt(args[0]));
public static void main(String[] args) throws Exception {
Server server = new Server(args.length == 0 ? 8080 : Integer.parseInt(args[0]));
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[]{ "index.html" });
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "index.html" });
resource_handler.setResourceBase(args.length == 2?args[1]:".");
Log.info("serving " + resource_handler.getBaseResource());
resource_handler.setResourceBase(args.length == 2 ? args[1] : ".");
Log.info("serving " + resource_handler.getBaseResource());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
server.start();
server.join();
}
server.start();
server.join();
}
}

View File

@ -1,3 +1,21 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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 java.io.FileNotFoundException;

View File

@ -1,4 +1,23 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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 com.google.common.base.Throwables.propagate;
import static org.jclouds.compute.options.RunScriptOptions.Builder.blockOnPort;
@ -58,143 +77,135 @@ import com.google.common.io.Closeables;
@Test(groups = "live", testName = "virtualbox.VirtualboxAdministrationKickstartTest")
public class VirtualboxAdministrationKickstartLiveTest {
protected String provider = "virtualbox";
protected String identity;
protected String credential;
protected URI endpoint;
protected String apiVersion;
protected String vmName;
protected String provider = "virtualbox";
protected String identity;
protected String credential;
protected URI endpoint;
protected String apiVersion;
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 osTypeId; // Guest OS Type ID.
protected String vmId; // Machine UUID (optional).
protected boolean forceOverwrite;
protected String diskFormat;
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 originalDisk;
protected String clonedDisk;
protected String workingDir;
protected String originalDisk;
protected String clonedDisk;
protected String guestAdditionsDvd;
private URI gaIsoUrl;
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 vdiName;
private String preseedUrl;
private String gaIsoName;
private URI distroIsoUrl;
private String distroIsoName;
private String controllerIDE;
private String controllerSATA;
private String keyboardSequence;
private String preseedUrl;
protected Server server = null;
private ComputeServiceContext context;
private String hostId = "host";
private String guestId = "guest";
private String majorVersion;
private String minorVersion;
protected void setupCredentials() {
identity = System.getProperty("test." + provider + ".identity", "administrator");
credential = System.getProperty("test." + provider + ".credential", "12345");
endpoint = URI.create(System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/"));
apiVersion = System.getProperty("test." + provider + ".apiversion", "4.1.0r73009");
majorVersion = Iterables.get(Splitter.on('r').split(apiVersion),0);
minorVersion = Iterables.get(Splitter.on('r').split(apiVersion),1);
majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0);
minorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 1);
}
protected Logger logger() {
return context.utils().loggerFactory().getLogger("jclouds.compute");
}
protected void setupConfigurationProperties() {
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
settingsFile = null;
osTypeId = System.getProperty("test." + provider + ".osTypeId", "");
vmId = System.getProperty("test." + provider + ".vmId", null);
forceOverwrite = true;
vmName = System.getProperty("test." + provider + ".vmname", "jclouds-virtualbox-kickstart-admin");
controllerIDE = System.getProperty("test." + provider + ".controllerIde", "IDE Controller");
controllerSATA = System.getProperty("test." + provider + ".controllerSata", "SATA Controller");
diskFormat = System.getProperty("test." + provider + ".diskformat", "");
workingDir = System.getProperty("user.home")
+ File.separator + System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test");
if (new File(workingDir).mkdir())
;
vdiName = System.getProperty("test." + provider + ".vdiName", "centos-5.2-x86.7z");
gaIsoName = System.getProperty("test." + provider + ".gaIsoName", "VBoxGuestAdditions_"+majorVersion+"-update-"+minorVersion+".iso");
gaIsoUrl = URI.create(System.getProperty("test." + provider + ".gaIsoUrl", "http://download.virtualbox.org/virtualbox/"+majorVersion+"/VBoxGuestAdditions_"+majorVersion+"-update-"+minorVersion+".iso"));
// VBOX
settingsFile = null;
osTypeId = System.getProperty("test." + provider + ".osTypeId", "");
vmId = System.getProperty("test." + provider + ".vmId", null);
forceOverwrite = true;
vmName = System.getProperty("test." + provider + ".vmname", "jclouds-virtualbox-kickstart-admin");
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"));
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
+ "-update-" + minorVersion + ".iso");
gaIsoUrl = URI.create(System.getProperty("test." + provider + ".gaIsoUrl",
"http://download.virtualbox.org/virtualbox/" + majorVersion + "/VBoxGuestAdditions_" + majorVersion
+ "-update-" + minorVersion + ".iso"));
originalDisk = workingDir + File.separator + "VDI" + File.separator + System.getProperty("test." + provider + ".originalDisk",
"centos-5.2-x86.vdi");
clonedDisk = workingDir + File.separator + System.getProperty("test." + provider + ".clonedDisk",
"template.vdi");
guestAdditionsDvd = workingDir + File.separator + System.getProperty("test." + provider + ".guestAdditionsDvd",
"VBoxGuestAdditions_"+majorVersion+"-update-"+minorVersion+".iso");
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"));
preseedUrl = System.getProperty("test." + provider + ".preseedurl",
"http://dl.dropbox.com/u/693111/preseed.cfg");
originalDisk = workingDir + File.separator + "VDI" + File.separator
+ System.getProperty("test." + provider + ".originalDisk", "centos-5.2-x86.vdi");
clonedDisk = workingDir + File.separator + System.getProperty("test." + provider + ".clonedDisk", "template.vdi");
guestAdditionsDvd = workingDir
+ File.separator
+ System.getProperty("test." + provider + ".guestAdditionsDvd", "VBoxGuestAdditions_" + majorVersion
+ "-update-" + minorVersion + ".iso");
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 "
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us "
+ "hostname="
+ vmName
+ " "
+ "fb=false debconf/frontend=noninteractive "
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
+ "initrd=/install/initrd.gz -- <Enter>");
preseedUrl = System.getProperty("test." + provider + ".preseedurl", "http://dl.dropbox.com/u/693111/preseed.cfg");
}
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 "
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " "
+ "fb=false debconf/frontend=noninteractive "
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
+ "initrd=/install/initrd.gz -- <Enter>");
@BeforeGroups(groups = "live")
protected void setupClient() throws Exception {
context = TestUtils.computeServiceForLocalhost();
socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 130, 10,
TimeUnit.SECONDS);
setupCredentials();
setupConfigurationProperties();
}
@BeforeGroups(groups = "live")
protected void setupClient() throws Exception {
context = TestUtils.computeServiceForLocalhost();
socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 130, 10, TimeUnit.SECONDS);
setupCredentials();
setupConfigurationProperties();
downloadFileUnlessPresent(distroIsoUrl, workingDir, distroIsoName);
downloadFileUnlessPresent(gaIsoUrl, workingDir, gaIsoName);
installVbox();
checkVboxVersionExpected();
if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint.getHost(), endpoint.getPort())))
startupVboxWebServer();
installVbox();
checkVboxVersionExpected();
if (!new InetSocketAddressConnect().apply(new IPSocket(endpoint.getHost(), endpoint.getPort())))
startupVboxWebServer();
configureJettyServer();
}
configureJettyServer();
}
private void configureJettyServer() throws Exception {
Server server = new Server(8080);
private 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" });
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());
resource_handler.setResourceBase(".");
logger().info("serving " + resource_handler.getBaseResource());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler,
new DefaultHandler() });
server.setHandler(handlers);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
server.start();
}
server.start();
}
void installVbox() throws IOException, InterruptedException {
if (runScriptOnNode(hostId, "VBoxManage -version").getExitCode() != 0) {
@ -211,8 +222,8 @@ public class VirtualboxAdministrationKickstartLiveTest {
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
@ -227,293 +238,275 @@ public class VirtualboxAdministrationKickstartLiveTest {
if (isOSX(hostId))
vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/&&" + vboxwebsrv;
// 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 /tmp/vboxwebsrv
// -b; logs will go corresponding to task name in this case under
// /tmp/vboxwebsrv
runScriptOnNode(hostId, vboxwebsrv,
blockOnPort(endpoint.getPort(), 10).blockOnComplete(false).nameTask("vboxwebsrv"));
}
protected boolean isOSX(String id) {
return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription().equals("Mac OS X");
return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription()
.equals("Mac OS X");
}
@BeforeMethod
protected void setupManager() {
manager.connect(endpoint.toASCIIString(), identity, credential);
}
@BeforeMethod
protected void setupManager() {
manager.connect(endpoint.toASCIIString(), identity, credential);
}
@AfterMethod
protected void disconnectAndClenaupManager() throws RemoteException,
MalformedURLException {
manager.disconnect();
manager.cleanup();
}
@AfterMethod
protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
manager.disconnect();
manager.cleanup();
}
public void testCreateVirtualMachine() {
IMachine newVM = manager.getVBox().createMachine(settingsFile, vmName,
osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(newVM);
assertEquals(newVM.getName(), vmName);
}
public void testCreateVirtualMachine() {
IMachine newVM = manager.getVBox().createMachine(settingsFile, vmName, osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(newVM);
assertEquals(newVM.getName(), vmName);
}
@Test(dependsOnMethods = "testCreateVirtualMachine")
public void testChangeRAM() {
Long memorySize = new Long(1024);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.setMemorySize(memorySize);
mutable.saveSettings();
session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName).getMemorySize(),
memorySize);
}
@Test(dependsOnMethods = "testCreateVirtualMachine")
public void testChangeRAM() {
Long memorySize = new Long(1024);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.setMemorySize(memorySize);
mutable.saveSettings();
session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName).getMemorySize(), memorySize);
}
@Test(dependsOnMethods = "testChangeRAM")
public void testCreateScsiController() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.addStorageController(controllerSATA, StorageBus.SATA);
mutable.saveSettings();
session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName)
.getStorageControllers().size(), 2);
}
@Test(dependsOnMethods = "testChangeRAM")
public void testCreateScsiController() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.addStorageController(controllerSATA, StorageBus.SATA);
mutable.saveSettings();
session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName).getStorageControllers().size(), 2);
}
@Test(dependsOnMethods = "testCreateScsiController")
public void testCreateAndAttachHardDisk() {
IMedium hd = null;
if (!new File(clonedDisk).exists()) {
hd = manager.getVBox().createHardDisk(diskFormat, clonedDisk);
long size = 2 * 1024 * 1024 * 1024 - 1;
hd.createBaseStorage(new Long(size), new Long(
MediumVariant.VMDK_SPLIT_2_G.ordinal()));
} else
hd = manager.getVBox().openMedium(clonedDisk, DeviceType.HardDisk,
AccessMode.ReadWrite, forceOverwrite);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.attachDevice(controllerSATA, 0, 0, DeviceType.HardDisk, hd);
mutable.saveSettings(); // write settings to xml
session.unlockMachine();
assertEquals(hd.getId().equals(""), false);
}
@Test(dependsOnMethods = "testCreateScsiController")
public void testCreateAndAttachHardDisk() {
IMedium hd = null;
if (!new File(clonedDisk).exists()) {
hd = manager.getVBox().createHardDisk(diskFormat, clonedDisk);
long size = 2 * 1024 * 1024 * 1024 - 1;
hd.createBaseStorage(new Long(size), new Long(MediumVariant.VMDK_SPLIT_2_G.ordinal()));
} else
hd = manager.getVBox().openMedium(clonedDisk, DeviceType.HardDisk, AccessMode.ReadWrite, forceOverwrite);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.attachDevice(controllerSATA, 0, 0, DeviceType.HardDisk, hd);
mutable.saveSettings(); // write settings to xml
session.unlockMachine();
assertEquals(hd.getId().equals(""), false);
}
@Test(dependsOnMethods = "testCreateAndAttachHardDisk")
public void testConfigureNIC() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
@Test(dependsOnMethods = "testCreateAndAttachHardDisk")
public void testConfigureNIC() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
// network BRIDGED to access HTTP server
String hostInterface = null;
String command = "VBoxManage list bridgedifs";
try {
Process child = Runtime.getRuntime().exec(command);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(child.getInputStream()));
String line = "";
boolean found = false;
// network BRIDGED to access HTTP server
String hostInterface = null;
String command = "VBoxManage list bridgedifs";
try {
Process child = Runtime.getRuntime().exec(command);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(child.getInputStream()));
String line = "";
boolean found = false;
while ((line = bufferedReader.readLine()) != null && !found) {
while ((line = bufferedReader.readLine()) != null && !found) {
if (line.split(":")[0].contains("Name")) {
hostInterface = line.split(":")[1];
}
if (line.split(":")[0].contains("Status")
&& line.split(":")[1].contains("Up")) {
System.out.println("bridge: " + hostInterface.trim());
found = true;
}
}
if (line.split(":")[0].contains("Name")) {
hostInterface = line.split(":")[1];
}
if (line.split(":")[0].contains("Status") && line.split(":")[1].contains("Up")) {
System.out.println("bridge: " + hostInterface.trim());
found = true;
}
}
// NAT
// mutable.getNetworkAdapter(new Long(0)).attachToNAT(); TODO: this no longer exists!
mutable.getNetworkAdapter(new Long(0)).setNATNetwork("");
machine.getNetworkAdapter(new Long(0))
.getNatDriver()
.addRedirect("guestssh", NATProtocol.TCP, "127.0.0.1",
2222, "", 22);
mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
// NAT
// mutable.getNetworkAdapter(new Long(0)).attachToNAT(); TODO: this no
// longer exists!
mutable.getNetworkAdapter(new Long(0)).setNATNetwork("");
machine.getNetworkAdapter(new Long(0)).getNatDriver()
.addRedirect("guestssh", NATProtocol.TCP, "127.0.0.1", 2222, "", 22);
mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
mutable.saveSettings();
session.unlockMachine();
mutable.saveSettings();
session.unlockMachine();
} catch (IOException e) {
propagate(e);
}
}
} catch (IOException e) {
propagate(e);
}
}
@Test(dependsOnMethods = "testConfigureNIC")
public void testStartVirtualMachine() throws InterruptedException {
IMachine machine = manager.getVBox().findMachine(vmName);
ISession session = manager.getSessionObject();
launchVMProcess(machine, session);
assertEquals(machine.getState(), MachineState.Running);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
propagate(e);
}
@Test(dependsOnMethods = "testConfigureNIC")
public void testStartVirtualMachine() throws InterruptedException {
IMachine machine = manager.getVBox().findMachine(vmName);
ISession session = manager.getSessionObject();
launchVMProcess(machine, session);
assertEquals(machine.getState(), MachineState.Running);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
propagate(e);
}
sendKeyboardSequence(keyboardSequence);
}
sendKeyboardSequence(keyboardSequence);
}
@Test(dependsOnMethods = "testStartVirtualMachine")
public void testConfigureGuestAdditions() {
// Configure your system for building kernel modules by running
runScriptOnNode(guestId, "m-a prepare -i");
runScriptOnNode(guestId, "mount -o loop /usr/share/virtualbox/VBoxGuestAdditions.iso /mnt");
runScriptOnNode(guestId, "/mnt/VBoxLinuxAdditions.run");
}
@Test(dependsOnMethods = "testStartVirtualMachine")
public void testConfigureGuestAdditions() {
// Configure your system for building kernel modules by running
runScriptOnNode(guestId, "m-a prepare -i");
runScriptOnNode(guestId, "mount -o loop /usr/share/virtualbox/VBoxGuestAdditions.iso /mnt");
runScriptOnNode(guestId, "/mnt/VBoxLinuxAdditions.run");
}
@Test(dependsOnMethods = "testConfigureGuestAdditions")
public void testStopVirtualMachine() {
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
assertEquals(machine.getState(), MachineState.PoweredOff);
}
@Test(dependsOnMethods = "testConfigureGuestAdditions")
public void testStopVirtualMachine() {
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
assertEquals(machine.getState(), MachineState.PoweredOff);
}
/**
* @param machine
*/
private void powerDownMachine(IMachine machine) {
try {
ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
/**
* @param machine
*/
private void powerDownMachine(IMachine machine) {
try {
ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try {
System.out.println("waiting for unlocking session - session state: "
+ machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try {
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test(dependsOnMethods = "testStopVirtualMachine")
public void cleanUp() throws IOException {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.getNetworkAdapter(new Long(0)).getNatDriver()
.removeRedirect("guestssh");
// detach disk from controller
mutable.detachDevice(controllerIDE, 0, 0);
mutable.saveSettings();
session.unlockMachine();
@Test(dependsOnMethods = "testStopVirtualMachine")
public void cleanUp() throws IOException {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.getNetworkAdapter(new Long(0)).getNatDriver().removeRedirect("guestssh");
// detach disk from controller
mutable.detachDevice(controllerIDE, 0, 0);
mutable.saveSettings();
session.unlockMachine();
for (IStorageController storageController : machine
.getStorageControllers()) {
if (storageController.getName().equals(controllerSATA)) {
session = manager.getSessionObject();
machine.lockMachine(session, LockType.Write);
for (IStorageController storageController : machine.getStorageControllers()) {
if (storageController.getName().equals(controllerSATA)) {
session = manager.getSessionObject();
machine.lockMachine(session, LockType.Write);
mutable = session.getMachine();
mutable.detachDevice(storageController.getName(), 1, 1);
mutable.saveSettings();
session.unlockMachine();
}
}
}
mutable = session.getMachine();
mutable.detachDevice(storageController.getName(), 1, 1);
mutable.saveSettings();
session.unlockMachine();
}
}
}
@AfterClass
void stopVboxWebServer() throws IOException {
@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;
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 {
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;
}
File iso = new File(destinationDir, filename);
private void sendKeyboardSequence(String keyboardSequence) throws InterruptedException {
String[] sequenceSplited = keyboardSequence.split(" ");
for (String word : sequenceSplited) {
String converted = stringToKeycode(word);
for (String string : converted.split(" ")) {
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;
}
runScriptOnNode(hostId , "VBoxManage controlvm " + vmName + " keyboardputscancode "
+ string);
if (converted
.contains(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.get("<Return>")))
Thread.sleep(180);
}
}
private void sendKeyboardSequence(String keyboardSequence) throws InterruptedException {
String[] sequenceSplited = keyboardSequence.split(" ");
for (String word : sequenceSplited) {
String converted = stringToKeycode(word);
for (String string : converted.split(" ")) {
}
runScriptOnNode(hostId, "VBoxManage controlvm " + vmName + " keyboardputscancode " + string);
if (converted.contains(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Return>")))
Thread.sleep(180);
}
}
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();
}
}
private String stringToKeycode(String s) {
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 + " ");
i++;
}
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP
.get("<Spacebar>") + " ");
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();
}
}
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 + " ");
i++;
}
keycodes.append(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get("<Spacebar>") + " ");
/**
*
* @param machine
* @param session
*/
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
session.unlockMachine();
}
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();
}
}

View File

@ -1,3 +1,21 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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 org.testng.Assert.assertEquals;
@ -50,457 +68,475 @@ import com.google.inject.Injector;
@Test(groups = "live", testName = "virtualbox.VirtualboxAdministrationTest")
public class VirtualboxAdministrationLiveTest {
protected String provider = "virtualbox";
protected String identity;
protected String credential;
protected String endpoint;
protected String apiversion;
protected String vmName;
protected String provider = "virtualbox";
protected String identity;
protected String credential;
protected String endpoint;
protected String apiversion;
protected String vmName;
VirtualBoxManager manager = VirtualBoxManager.createInstance("");
VirtualBoxManager manager = VirtualBoxManager.createInstance("");
protected Injector injector;
protected Predicate<IPSocket> socketTester;
protected SshClient.Factory sshFactory;
protected Injector injector;
protected Predicate<IPSocket> socketTester;
protected SshClient.Factory sshFactory;
protected String settingsFile; // Fully qualified path where the settings file should be created, or NULL for a default
// folder and file based on the name argument (see composeMachineFilename()).
protected String settingsFile; // Fully qualified path where the settings
// file should be created, or NULL for a
// default
// folder and file based on the name argument (see composeMachineFilename()).
protected String osTypeId; // Guest OS Type ID.
protected String vmId; // Machine UUID (optional).
protected boolean forceOverwrite; // If true, an existing machine settings file will be overwritten.
protected String osUsername;
protected String osPassword;
protected String controller;
protected String diskFormat;
protected String osTypeId; // Guest OS Type ID.
protected String vmId; // Machine UUID (optional).
protected boolean forceOverwrite; // If true, an existing machine settings
// file will be overwritten.
protected String workingDir;
protected String originalDisk;
protected String clonedDisk;
protected String osUsername;
protected String osPassword;
protected String controller;
protected String diskFormat;
protected String guestAdditionsDvdName;
private String vdiUrl;
private String gaIsoUrl;
private String vboxwebsrvStartCommand;
// private Process pr;
private String vdiName;
private String gaIsoName;
private String admin_pwd;
private String hostUsername;
private String hostPassword;
private String install7zip;
private String run7zip;
private String installVboxOse;
protected String workingDir;
protected String originalDisk;
protected String clonedDisk;
/**
*
*
*
* @param workingDir
* @param vdiUrl
* @param proxy Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 5865));
* @return
* @throws Exception
*/
private File downloadFile(String sourceURL, String destinationDir, String vboxGuestAdditionsName, Proxy proxy) throws Exception {
String absolutePathName = destinationDir + File.separator + vboxGuestAdditionsName;
File iso = new File(absolutePathName);
protected String guestAdditionsDvdName;
private String vdiUrl;
private String gaIsoUrl;
private String vboxwebsrvStartCommand;
// private Process pr;
private String vdiName;
private String gaIsoName;
private String admin_pwd;
private String hostUsername;
private String hostPassword;
private String install7zip;
private String run7zip;
private String installVboxOse;
final URL isoURL = new URL(sourceURL);
final HttpURLConnection uc = (HttpURLConnection) isoURL.openConnection(); // isoURL.openConnection(proxy);
uc.connect();
if(!iso.exists()) {
System.out.println("Start download " + sourceURL + " to " + absolutePathName);
Files.copy(new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return uc.getInputStream();
}
}, iso);
}
return iso;
}
protected void setupCredentials() {
identity = System.getProperty("test." + provider + ".identity", "administrator");
credential = System.getProperty("test." + provider + ".credential", "12345");
endpoint = System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/");
apiversion = System.getProperty("test." + provider + ".apiversion");
}
/**
*
*
*
* @param workingDir
* @param vdiUrl
* @param proxy
* Proxy proxy = new Proxy(Proxy.Type.HTTP, new
* InetSocketAddress("localhost", 5865));
* @return
* @throws Exception
*/
private File downloadFile(String sourceURL, String destinationDir, String vboxGuestAdditionsName, Proxy proxy)
throws Exception {
protected void setupConfigurationProperties() {
String absolutePathName = destinationDir + File.separator + vboxGuestAdditionsName;
File iso = new File(absolutePathName);
admin_pwd = System.getProperty("test." + provider + ".admin_pwd", "password");
// OS
osUsername = System.getProperty("test." + provider + ".osusername", "root");
osPassword = System.getProperty("test." + provider + ".ospassword", "toortoor");
controller = System.getProperty("test." + provider + ".controller", "IDE Controller");
// Create disk If the @a format attribute is empty or null then the default storage format specified by ISystemProperties#defaultHardDiskFormat
diskFormat = System.getProperty("test." + provider + ".diskformat", "");
//VBOX
settingsFile = null; // Fully qualified path where the settings file should be created, or NULL for a default
// folder and file based on the name argument (see composeMachineFilename()).
osTypeId = System.getProperty("test." + provider + ".osTypeId", ""); // Guest OS Type ID.
vmId = System.getProperty("test." + provider + ".vmId", null); // Machine UUID (optional).
forceOverwrite = true; // If true, an existing machine settings file will be overwritten.
vmName = System.getProperty("test." + provider + ".vmname", "jclouds-virtualbox-admin");
workingDir = System.getProperty("user.home") + File.separator + System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test") ;
if(new File(workingDir).mkdir());
vdiName = System.getProperty("test." + provider + ".vdiName", "centos-5.2-x86.7z");
vdiUrl = System.getProperty("test." + provider + ".vdiUrl", "http://leaseweb.dl.sourceforge.net/project/virtualboximage/CentOS/5.2/centos-5.2-x86.7z");
gaIsoName = System.getProperty("test." + provider + ".gaIsoName", "VBoxGuestAdditions_4.0.2-update-69551.iso");
gaIsoUrl = System.getProperty("test." + provider + ".gaIsoUrl", "http://download.virtualbox.org/virtualbox/4.0.2/VBoxGuestAdditions_4.0.2-update-69551.iso");
vboxwebsrvStartCommand = System.getProperty("test." + provider + ".vboxwebsrvStartCommand","/usr/bin/vboxwebsrv");
originalDisk = workingDir + File.separator + "VDI" +File.separator + System.getProperty("test." + provider + ".originalDisk", "centos-5.2-x86.vdi");
clonedDisk = workingDir + File.separator + System.getProperty("test." + provider + ".clonedDisk", "template.vdi");
guestAdditionsDvdName = workingDir + File.separator + System.getProperty("test." + provider + ".guestAdditionsDvdName", "VBoxGuestAdditions_4.0.2-update-69551.iso");
final URL isoURL = new URL(sourceURL);
final HttpURLConnection uc = (HttpURLConnection) isoURL.openConnection(); // isoURL.openConnection(proxy);
uc.connect();
if (!iso.exists()) {
System.out.println("Start download " + sourceURL + " to " + absolutePathName);
Files.copy(new InputSupplier<InputStream>() {
install7zip = System.getProperty("test." + provider + ".install7zip", "sudo -S apt-get --yes install p7zip");
run7zip = System.getProperty("test." + provider + ".run7zip", "p7zip -d ");
installVboxOse = System.getProperty("test." + provider + ".installvboxose", "sudo -S apt-get --yes install virtualbox-ose");
if(!new File(originalDisk).exists()) {
IPSocket socket = new IPSocket("127.0.0.1", 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(hostUsername, hostPassword));
try {
File vdi7z = downloadFile(vdiUrl, workingDir, vdiName, null);
client.connect();
ExecResponse exec = client.exec("echo " + admin_pwd + " | " + install7zip + "; cd " + workingDir + "; " + run7zip + vdi7z.getName());
System.out.println(exec);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null)
client.disconnect();
}
}
@Override
public InputStream getInput() throws IOException {
return uc.getInputStream();
}
if(!new File(guestAdditionsDvdName).exists()) {
try {
File gaIso = downloadFile(gaIsoUrl, workingDir, gaIsoName, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, iso);
}
return iso;
}
@BeforeGroups(groups = "live")
protected void setupClient() throws IOException, InterruptedException {
protected void setupCredentials() {
identity = System.getProperty("test." + provider + ".identity", "administrator");
credential = System.getProperty("test." + provider + ".credential", "12345");
endpoint = System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/");
apiversion = System.getProperty("test." + provider + ".apiversion");
}
hostUsername = System.getProperty("test." + provider + ".hostusername", "toor");
hostPassword = System.getProperty("test." + provider + ".hostpassword", "password");
protected void setupConfigurationProperties() {
injector = Guice.createInjector(new SshjSshClientModule(),
new SLF4JLoggingModule(), new BouncyCastleCryptoModule());
sshFactory = injector.getInstance(SshClient.Factory.class);
socketTester = new RetryablePredicate<IPSocket>(
new InetSocketAddressConnect(), 3600, 1, TimeUnit.SECONDS);
injector.injectMembers(socketTester);
setupCredentials();
setupConfigurationProperties();
installVbox();
// startup vbox web server
startupVboxWebServer(vboxwebsrvStartCommand);
}
admin_pwd = System.getProperty("test." + provider + ".admin_pwd", "password");
// OS
osUsername = System.getProperty("test." + provider + ".osusername", "root");
osPassword = System.getProperty("test." + provider + ".ospassword", "toortoor");
controller = System.getProperty("test." + provider + ".controller", "IDE Controller");
// Create disk If the @a format attribute is empty or null then the
// default storage format specified by
// ISystemProperties#defaultHardDiskFormat
diskFormat = System.getProperty("test." + provider + ".diskformat", "");
private void installVbox() throws IOException, InterruptedException {
IPSocket socket = new IPSocket("127.0.0.1", 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(hostUsername, hostPassword));
try {
client.connect();
ExecResponse exec = client.exec("echo " + hostPassword + " | " + installVboxOse);
System.out.println(exec);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null)
client.disconnect();
}
// VBOX
settingsFile = null; // Fully qualified path where the settings file
// should be created, or NULL for a default
// folder and file based on the name argument (see
// composeMachineFilename()).
}
osTypeId = System.getProperty("test." + provider + ".osTypeId", ""); // Guest
// OS
// Type
// ID.
vmId = System.getProperty("test." + provider + ".vmId", null); // Machine
// UUID
// (optional).
forceOverwrite = true; // If true, an existing machine settings file will
// be overwritten.
vmName = System.getProperty("test." + provider + ".vmname", "jclouds-virtualbox-admin");
/**
*
* @param command absolute path to command. For ubuntu 10.04: /usr/bin/vboxwebsrv
* @throws IOException
* @throws InterruptedException
*/
private void startupVboxWebServer(String command) throws IOException, InterruptedException {
// Disable login credential: $
//rt.exec("VBoxManage setproperty websrvauthlibrary null");
IPSocket socket = new IPSocket("127.0.0.1", 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(hostUsername, hostPassword));
try {
client.connect();
ExecResponse exec = client.exec(command + " --timeout 50000 -b");
System.out.println(exec.getOutput());
System.out.println(exec);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null)
client.disconnect();
}
workingDir = System.getProperty("user.home") + File.separator
+ System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test");
if (new File(workingDir).mkdir())
;
vdiName = System.getProperty("test." + provider + ".vdiName", "centos-5.2-x86.7z");
vdiUrl = System.getProperty("test." + provider + ".vdiUrl",
"http://leaseweb.dl.sourceforge.net/project/virtualboximage/CentOS/5.2/centos-5.2-x86.7z");
gaIsoName = System.getProperty("test." + provider + ".gaIsoName", "VBoxGuestAdditions_4.0.2-update-69551.iso");
gaIsoUrl = System.getProperty("test." + provider + ".gaIsoUrl",
"http://download.virtualbox.org/virtualbox/4.0.2/VBoxGuestAdditions_4.0.2-update-69551.iso");
vboxwebsrvStartCommand = System
.getProperty("test." + provider + ".vboxwebsrvStartCommand", "/usr/bin/vboxwebsrv");
originalDisk = workingDir + File.separator + "VDI" + File.separator
+ System.getProperty("test." + provider + ".originalDisk", "centos-5.2-x86.vdi");
clonedDisk = workingDir + File.separator + System.getProperty("test." + provider + ".clonedDisk", "template.vdi");
guestAdditionsDvdName = workingDir
+ File.separator
+ System.getProperty("test." + provider + ".guestAdditionsDvdName",
"VBoxGuestAdditions_4.0.2-update-69551.iso");
}
install7zip = System.getProperty("test." + provider + ".install7zip", "sudo -S apt-get --yes install p7zip");
run7zip = System.getProperty("test." + provider + ".run7zip", "p7zip -d ");
installVboxOse = System.getProperty("test." + provider + ".installvboxose",
"sudo -S apt-get --yes install virtualbox-ose");
if (!new File(originalDisk).exists()) {
IPSocket socket = new IPSocket("127.0.0.1", 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(hostUsername, hostPassword));
try {
File vdi7z = downloadFile(vdiUrl, workingDir, vdiName, null);
client.connect();
ExecResponse exec = client.exec("echo " + admin_pwd + " | " + install7zip + "; cd " + workingDir + "; "
+ run7zip + vdi7z.getName());
System.out.println(exec);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null)
client.disconnect();
}
}
if (!new File(guestAdditionsDvdName).exists()) {
try {
File gaIso = downloadFile(gaIsoUrl, workingDir, gaIsoName, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@BeforeMethod
protected void setupManager() {
manager.connect(endpoint, identity, credential);
}
@BeforeGroups(groups = "live")
protected void setupClient() throws IOException, InterruptedException {
@AfterMethod
protected void disconnectAndClenaupManager() throws RemoteException,
MalformedURLException {
manager.disconnect();
manager.cleanup();
}
hostUsername = System.getProperty("test." + provider + ".hostusername", "toor");
hostPassword = System.getProperty("test." + provider + ".hostpassword", "password");
public void testCreateVirtualMachine() {
IMachine newVM = manager.getVBox().createMachine(settingsFile, vmName,
osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(newVM);
assertEquals(newVM.getName(), vmName);
}
injector = Guice.createInjector(new SshjSshClientModule(), new SLF4JLoggingModule(),
new BouncyCastleCryptoModule());
sshFactory = injector.getInstance(SshClient.Factory.class);
socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 3600, 1, TimeUnit.SECONDS);
injector.injectMembers(socketTester);
@Test(dependsOnMethods = "testCreateVirtualMachine")
public void testChangeRAM() {
Long memorySize = new Long(2048);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.setMemorySize(memorySize);
mutable.saveSettings();
session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName)
.getMemorySize(), memorySize);
}
@Test(dependsOnMethods = "testChangeRAM")
public void testCreateDiskController() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.addStorageController(controller, StorageBus.IDE);
mutable.saveSettings();
session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName)
.getStorageControllers().size(), 1);
}
setupCredentials();
setupConfigurationProperties();
@Test(dependsOnMethods = "testCreateDiskController")
public void testCloneAndAttachHardDisk() {
IMedium hd = manager.getVBox().openMedium(originalDisk,
DeviceType.HardDisk, AccessMode.ReadOnly, forceOverwrite);
IMedium clonedHd = null;
if(!new File(clonedDisk).exists()) {
clonedHd = manager.getVBox().createHardDisk(diskFormat, clonedDisk);
IProgress cloning = hd.cloneTo(clonedHd, new Long(MediumVariant.VMDK_SPLIT_2_G.ordinal()), null);
cloning.waitForCompletion(-1);
} else
clonedHd = manager.getVBox().openMedium(clonedDisk,
DeviceType.HardDisk, AccessMode.ReadOnly, forceOverwrite);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.attachDevice(controller, 0, 0, DeviceType.HardDisk, clonedHd);
mutable.saveSettings(); // write settings to xml
session.unlockMachine();
assertEquals(hd.getId().equals(""), false);
}
installVbox();
// startup vbox web server
startupVboxWebServer(vboxwebsrvStartCommand);
}
@Test(dependsOnMethods = "testCloneAndAttachHardDisk")
public void testConfigureNIC() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
private void installVbox() throws IOException, InterruptedException {
IPSocket socket = new IPSocket("127.0.0.1", 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(hostUsername, hostPassword));
try {
client.connect();
ExecResponse exec = client.exec("echo " + hostPassword + " | " + installVboxOse);
System.out.println(exec);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null)
client.disconnect();
}
/*
* NAT
*/
// mutable.getNetworkAdapter(new Long(0)).attachToNAT(); not in 4.1
mutable.getNetworkAdapter(new Long(0)).setNATNetwork("");
mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
mutable.saveSettings();
session.unlockMachine();
}
machine.lockMachine(session, LockType.Write);
mutable = session.getMachine();
machine.getNetworkAdapter(new Long(0))
.getNatDriver()
.addRedirect("guestssh", NATProtocol.TCP, "127.0.0.1", 2222, "", 22);
mutable.saveSettings();
session.unlockMachine();
}
/**
*
* @param command
* absolute path to command. For ubuntu 10.04: /usr/bin/vboxwebsrv
* @throws IOException
* @throws InterruptedException
*/
private void startupVboxWebServer(String command) throws IOException, InterruptedException {
// Disable login credential: $
// rt.exec("VBoxManage setproperty websrvauthlibrary null");
IPSocket socket = new IPSocket("127.0.0.1", 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(hostUsername, hostPassword));
try {
client.connect();
ExecResponse exec = client.exec(command + " --timeout 50000 -b");
System.out.println(exec.getOutput());
System.out.println(exec);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null)
client.disconnect();
}
@Test(dependsOnMethods = "testConfigureNIC")
public void testAttachGuestAdditions() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
}
IMedium guestAdditionsDVD = manager.getVBox().openMedium(guestAdditionsDvdName,
DeviceType.DVD, AccessMode.ReadOnly, forceOverwrite);
for (IStorageController storageController : machine
.getStorageControllers()) {
// for DVD we choose IDE
if (storageController.getName().equals(controller)) {
@BeforeMethod
protected void setupManager() {
manager.connect(endpoint, identity, credential);
}
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
@AfterMethod
protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
manager.disconnect();
manager.cleanup();
}
// IDE secondary slave [1:1]
mutable.attachDevice(storageController.getName(),
new Integer(1), new Integer(1), DeviceType.DVD,
guestAdditionsDVD);
mutable.saveSettings();
session.unlockMachine();
}
}
}
public void testCreateVirtualMachine() {
IMachine newVM = manager.getVBox().createMachine(settingsFile, vmName, osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(newVM);
assertEquals(newVM.getName(), vmName);
}
@Test(dependsOnMethods = "testAttachGuestAdditions")
public void testStartVirtualMachine() {
IMachine machine = manager.getVBox().findMachine(vmName);
ISession session = manager.getSessionObject();
launchVMProcess(machine, session);
assertEquals(machine.getState(), MachineState.Running);
}
@Test(dependsOnMethods = "testCreateVirtualMachine")
public void testChangeRAM() {
Long memorySize = new Long(2048);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.setMemorySize(memorySize);
mutable.saveSettings();
session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName).getMemorySize(), memorySize);
}
/**
*
* @param machine
* @param session
*/
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
session.unlockMachine();
}
@Test(dependsOnMethods = "testChangeRAM")
public void testCreateDiskController() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.addStorageController(controller, StorageBus.IDE);
mutable.saveSettings();
session.unlockMachine();
assertEquals(manager.getVBox().findMachine(vmName).getStorageControllers().size(), 1);
}
@Test(dependsOnMethods = "testStartVirtualMachine")
public void testInstallGuestAdditionsThroughNATPortForwarding() {
@Test(dependsOnMethods = "testCreateDiskController")
public void testCloneAndAttachHardDisk() {
IMedium hd = manager.getVBox().openMedium(originalDisk, DeviceType.HardDisk, AccessMode.ReadOnly, forceOverwrite);
IMedium clonedHd = null;
if (!new File(clonedDisk).exists()) {
clonedHd = manager.getVBox().createHardDisk(diskFormat, clonedDisk);
IProgress cloning = hd.cloneTo(clonedHd, new Long(MediumVariant.VMDK_SPLIT_2_G.ordinal()), null);
cloning.waitForCompletion(-1);
} else
clonedHd = manager.getVBox().openMedium(clonedDisk, DeviceType.HardDisk, AccessMode.ReadOnly, forceOverwrite);
IPSocket socket = new IPSocket("127.0.0.1", 2222);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(osUsername, osPassword));
try {
client.connect();
ExecResponse exec = client.exec("yum install gcc kernel kernel-devel -y");
System.out.println(exec);
} finally {
if (client != null)
client.disconnect();
}
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.attachDevice(controller, 0, 0, DeviceType.HardDisk, clonedHd);
mutable.saveSettings(); // write settings to xml
session.unlockMachine();
assertEquals(hd.getId().equals(""), false);
}
//manually restart
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
launchVMProcess(machine, manager.getSessionObject());
@Test(dependsOnMethods = "testCloneAndAttachHardDisk")
public void testConfigureNIC() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
socketTester.apply(socket);
client = sshFactory.create(socket, new Credentials(osUsername, osPassword));
try {
client.connect();
ExecResponse exec = client.exec("mkdir -p /media/cdrom; mount /dev/cdrom /media/cdrom; sh /media/cdrom/VBoxLinuxAdditions.run --nox11 force");
System.out.println(exec);
exec = client.exec("echo '/usr/sbin/VBoxService' >> /etc/rc.d/rc.local");
System.out.println(exec);
} finally {
if (client != null)
client.disconnect();
}
}
/*
* NAT
*/
// mutable.getNetworkAdapter(new Long(0)).attachToNAT(); not in 4.1
mutable.getNetworkAdapter(new Long(0)).setNATNetwork("");
mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
mutable.saveSettings();
session.unlockMachine();
@Test(dependsOnMethods = "testInstallGuestAdditionsThroughNATPortForwarding")
public void testStopVirtualMachine() {
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
assertEquals(machine.getState(), MachineState.PoweredOff);
}
machine.lockMachine(session, LockType.Write);
mutable = session.getMachine();
machine.getNetworkAdapter(new Long(0)).getNatDriver()
.addRedirect("guestssh", NATProtocol.TCP, "127.0.0.1", 2222, "", 22);
mutable.saveSettings();
session.unlockMachine();
}
/**
* @param machine
*/
private void powerDownMachine(IMachine machine) {
try {
ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
@Test(dependsOnMethods = "testConfigureNIC")
public void testAttachGuestAdditions() {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
while(!machine.getSessionState().equals(SessionState.Unlocked)){
try {
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
IMedium guestAdditionsDVD = manager.getVBox().openMedium(guestAdditionsDvdName, DeviceType.DVD,
AccessMode.ReadOnly, forceOverwrite);
for (IStorageController storageController : machine.getStorageControllers()) {
// for DVD we choose IDE
if (storageController.getName().equals(controller)) {
} catch (Exception e) {
e.printStackTrace();
}
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
}
// IDE secondary slave [1:1]
mutable.attachDevice(storageController.getName(), new Integer(1), new Integer(1), DeviceType.DVD,
guestAdditionsDVD);
mutable.saveSettings();
session.unlockMachine();
}
}
}
@Test(dependsOnMethods = "testStopVirtualMachine")
public void cleanUp() throws IOException {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.getNetworkAdapter(new Long(0)).getNatDriver().removeRedirect("guestssh");
// detach disk from controller
mutable.detachDevice(controller, 0, 0);
mutable.saveSettings();
session.unlockMachine();
@Test(dependsOnMethods = "testAttachGuestAdditions")
public void testStartVirtualMachine() {
IMachine machine = manager.getVBox().findMachine(vmName);
ISession session = manager.getSessionObject();
launchVMProcess(machine, session);
assertEquals(machine.getState(), MachineState.Running);
}
for (IStorageController storageController : machine
.getStorageControllers()) {
if (storageController.getName().equals(controller)) {
session = manager.getSessionObject();
machine.lockMachine(session, LockType.Write);
/**
*
* @param machine
* @param session
*/
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
session.unlockMachine();
}
mutable = session.getMachine();
mutable.detachDevice(storageController.getName(), 1, 1);
mutable.saveSettings();
session.unlockMachine();
}
}
}
@AfterClass
void stopVboxWebServer() throws IOException{
// stop vbox web server
IPSocket socket = new IPSocket("127.0.0.1", 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(hostUsername, hostPassword));
try {
client.connect();
ExecResponse exec = client.exec("pidof vboxwebsrv | xargs kill");
System.out.println(exec.getOutput());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null)
client.disconnect();
} }
@Test(dependsOnMethods = "testStartVirtualMachine")
public void testInstallGuestAdditionsThroughNATPortForwarding() {
IPSocket socket = new IPSocket("127.0.0.1", 2222);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(osUsername, osPassword));
try {
client.connect();
ExecResponse exec = client.exec("yum install gcc kernel kernel-devel -y");
System.out.println(exec);
} finally {
if (client != null)
client.disconnect();
}
// manually restart
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
launchVMProcess(machine, manager.getSessionObject());
socketTester.apply(socket);
client = sshFactory.create(socket, new Credentials(osUsername, osPassword));
try {
client.connect();
ExecResponse exec = client
.exec("mkdir -p /media/cdrom; mount /dev/cdrom /media/cdrom; sh /media/cdrom/VBoxLinuxAdditions.run --nox11 force");
System.out.println(exec);
exec = client.exec("echo '/usr/sbin/VBoxService' >> /etc/rc.d/rc.local");
System.out.println(exec);
} finally {
if (client != null)
client.disconnect();
}
}
@Test(dependsOnMethods = "testInstallGuestAdditionsThroughNATPortForwarding")
public void testStopVirtualMachine() {
IMachine machine = manager.getVBox().findMachine(vmName);
powerDownMachine(machine);
assertEquals(machine.getState(), MachineState.PoweredOff);
}
/**
* @param machine
*/
private void powerDownMachine(IMachine machine) {
try {
ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try {
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test(dependsOnMethods = "testStopVirtualMachine")
public void cleanUp() throws IOException {
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(vmName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
mutable.getNetworkAdapter(new Long(0)).getNatDriver().removeRedirect("guestssh");
// detach disk from controller
mutable.detachDevice(controller, 0, 0);
mutable.saveSettings();
session.unlockMachine();
for (IStorageController storageController : machine.getStorageControllers()) {
if (storageController.getName().equals(controller)) {
session = manager.getSessionObject();
machine.lockMachine(session, LockType.Write);
mutable = session.getMachine();
mutable.detachDevice(storageController.getName(), 1, 1);
mutable.saveSettings();
session.unlockMachine();
}
}
}
@AfterClass
void stopVboxWebServer() throws IOException {
// stop vbox web server
IPSocket socket = new IPSocket("127.0.0.1", 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, new Credentials(hostUsername, hostPassword));
try {
client.connect();
ExecResponse exec = client.exec("pidof vboxwebsrv | xargs kill");
System.out.println(exec.getOutput());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null)
client.disconnect();
}
}
}

View File

@ -1,3 +1,21 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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;
@ -45,261 +63,267 @@ import com.google.inject.Injector;
@Test(groups = "live", testName = "virtualbox.VirtualboxLiveTest")
public class VirtualboxLiveTest {
protected String provider = "virtualbox";
protected String identity;
protected String credential;
protected String endpoint;
protected String apiversion;
protected String vmName;
protected String provider = "virtualbox";
protected String identity;
protected String credential;
protected String endpoint;
protected String apiversion;
protected String vmName;
VirtualBoxManager manager = VirtualBoxManager.createInstance(null);
VirtualBoxManager manager = VirtualBoxManager.createInstance(null);
protected Injector injector;
protected Predicate<IPSocket> socketTester;
protected SshClient.Factory sshFactory;
protected Injector injector;
protected Predicate<IPSocket> socketTester;
protected SshClient.Factory sshFactory;
protected String osUsername;
protected String osPassword;
protected String controller;
protected String diskFormat;
protected String osUsername;
protected String osPassword;
protected String controller;
protected String diskFormat;
protected String settingsFile; // Fully qualified path where the settings file should be created, or NULL for a default
// folder and file based on the name argument (see composeMachineFilename()).
protected String settingsFile; // Fully qualified path where the settings
// file should be created, or NULL for a
// default
// folder and file based on the name argument (see composeMachineFilename()).
protected String osTypeId; // Guest OS Type ID.
protected String vmId; // Machine UUID (optional).
protected boolean forceOverwrite; // If true, an existing machine settings file will be overwritten.
protected String osTypeId; // Guest OS Type ID.
protected String vmId; // Machine UUID (optional).
protected boolean forceOverwrite; // If true, an existing machine settings
// file will be overwritten.
protected String workingDir;
protected String originalDiskPath;
protected String clonedDiskPath;
protected String workingDir;
protected String originalDiskPath;
protected String clonedDiskPath;
// Create disk If the @a format attribute is empty or null then the default
// storage format specified by ISystemProperties#defaultHardDiskFormat
String format = "vdi";
// Create disk If the @a format attribute is empty or null then the default
// storage format specified by ISystemProperties#defaultHardDiskFormat
String format = "vdi";
protected int numberOfVirtualMachine ;
protected int numberOfVirtualMachine;
@BeforeClass
protected void setupConfigurationProperties() {
//VBOX
settingsFile = null; // Fully qualified path where the settings file should be created, or NULL for a default
// folder and file based on the name argument (see composeMachineFilename()).
osTypeId = System.getProperty("test." + provider + ".osTypeId", ""); // Guest OS Type ID.
vmId = System.getProperty("test." + provider + ".vmId", null); // Machine UUID (optional).
forceOverwrite = true; // If true, an existing machine settings file will be overwritten.
@BeforeClass
protected void setupConfigurationProperties() {
// VBOX
settingsFile = null; // Fully qualified path where the settings file
// should be created, or NULL for a default
// folder and file based on the name argument (see
// composeMachineFilename()).
osTypeId = System.getProperty("test." + provider + ".osTypeId", ""); // Guest
// OS
// Type
// ID.
vmId = System.getProperty("test." + provider + ".vmId", null); // Machine
// UUID
// (optional).
forceOverwrite = true; // If true, an existing machine settings file will
// be overwritten.
// OS specific information
vmName = checkNotNull(System.getProperty("test." + provider + ".vmname"));
osUsername = System.getProperty("test." + provider + ".osusername", "root");
osPassword = System.getProperty("test." + provider + ".ospassword", "toortoor");
controller = System.getProperty("test." + provider + ".controller", "IDE Controller");
diskFormat = System.getProperty("test." + provider + ".diskformat", "");
// OS specific information
vmName = checkNotNull(System.getProperty("test." + provider + ".vmname"));
osUsername = System.getProperty("test." + provider + ".osusername", "root");
osPassword = System.getProperty("test." + provider + ".ospassword", "toortoor");
controller = System.getProperty("test." + provider + ".controller", "IDE Controller");
diskFormat = System.getProperty("test." + provider + ".diskformat", "");
workingDir = checkNotNull(
System.getProperty("test." + provider + ".workingDir"));
originalDiskPath = workingDir
+ File.separator
+ checkNotNull(System.getProperty("test." + provider
+ ".originalDisk"));
numberOfVirtualMachine = Integer.parseInt(checkNotNull(System.getProperty("test." + provider + ".numberOfVirtualMachine")));
}
@BeforeClass
protected void setupCredentials() throws RemoteException,
MalformedURLException {
identity = System.getProperty("test." + provider + ".identity", "administrator");
credential = System.getProperty("test." + provider + ".credential", "12345");
endpoint = System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/");
apiversion = System.getProperty("test." + provider + ".apiversion");
injector = Guice.createInjector(new SshjSshClientModule(),
new SLF4JLoggingModule(), new BouncyCastleCryptoModule());
sshFactory = injector.getInstance(SshClient.Factory.class);
socketTester = new RetryablePredicate<IPSocket>(
new InetSocketAddressConnect(), 180, 1, TimeUnit.SECONDS);
injector.injectMembers(socketTester);
}
@BeforeMethod
protected void setupManager() throws RemoteException, MalformedURLException {
manager.connect(endpoint, identity, credential);
}
workingDir = checkNotNull(System.getProperty("test." + provider + ".workingDir"));
@AfterMethod
protected void disconnectAndClenaupManager() throws RemoteException,
MalformedURLException {
manager.disconnect();
manager.cleanup();
}
originalDiskPath = workingDir + File.separator
+ checkNotNull(System.getProperty("test." + provider + ".originalDisk"));
@Test
public void testStartVirtualMachines() {
IMedium clonedHd = cloneDisk(MediumType.MultiAttach);
for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
createVirtualMachine(i, clonedHd);
}
}
numberOfVirtualMachine = Integer.parseInt(checkNotNull(System.getProperty("test." + provider
+ ".numberOfVirtualMachine")));
}
private void createVirtualMachine(int i, IMedium clonedHd) {
String instanceName = vmName + "_" + i;
@BeforeClass
protected void setupCredentials() throws RemoteException, MalformedURLException {
identity = System.getProperty("test." + provider + ".identity", "administrator");
credential = System.getProperty("test." + provider + ".credential", "12345");
endpoint = System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/");
apiversion = System.getProperty("test." + provider + ".apiversion");
IMachine newVM = manager.getVBox().createMachine(settingsFile, instanceName, osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(newVM);
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(instanceName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
// disk
mutable.addStorageController(controller, StorageBus.IDE);
mutable.attachDevice(controller, 0, 0, DeviceType.HardDisk, clonedHd);
// network
String hostInterface = null;
String command = "vboxmanage list bridgedifs";
try {
Process child = Runtime.getRuntime().exec(command);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(child.getInputStream()));
String line = "";
boolean found = false;
injector = Guice.createInjector(new SshjSshClientModule(), new SLF4JLoggingModule(),
new BouncyCastleCryptoModule());
sshFactory = injector.getInstance(SshClient.Factory.class);
socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 180, 1, TimeUnit.SECONDS);
injector.injectMembers(socketTester);
}
while ( (line = bufferedReader.readLine()) != null && !found){
@BeforeMethod
protected void setupManager() throws RemoteException, MalformedURLException {
manager.connect(endpoint, identity, credential);
}
if(line.split(":")[0].contains("Name") ){
hostInterface = line.split(":")[1];
}
if( line.split(":")[0].contains("Status") && line.split(":")[1].contains("Up") ){
System.out.println("bridge: " + hostInterface.trim());
found = true;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO: lookup translations for 4.1 for the below
// mutable.getNetworkAdapter(new Long(0)).attachToBridgedInterface();
// mutable.getNetworkAdapter(new Long(0)).setHostInterface(hostInterface.trim());
mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
@AfterMethod
protected void disconnectAndClenaupManager() throws RemoteException, MalformedURLException {
manager.disconnect();
manager.cleanup();
}
mutable.saveSettings();
session.unlockMachine();
}
@Test
public void testStartVirtualMachines() {
IMedium clonedHd = cloneDisk(MediumType.MultiAttach);
for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
createVirtualMachine(i, clonedHd);
}
}
private void createVirtualMachine(int i, IMedium clonedHd) {
/**
* @param instanceName
* @return
*/
private IMedium cloneDisk(MediumType mediumType) {
String instanceName = vmName + "_" + i;
String clonedDisk = System.getProperty("test." + provider + ".clonedDisk");
String instanceClonedDisk = clonedDisk.split("\\.")[0] + "." +clonedDisk.split("\\.")[1];
clonedDiskPath = workingDir + File.separator + instanceClonedDisk;
IMachine newVM = manager.getVBox().createMachine(settingsFile, instanceName, osTypeId, vmId, forceOverwrite);
manager.getVBox().registerMachine(newVM);
// use template disk in multiattach mode
IMedium clonedHd = manager.getVBox().openMedium(originalDiskPath, DeviceType.HardDisk, AccessMode.ReadOnly, forceOverwrite);
System.out.println("cloned HD state: " + clonedHd.getState());
/*
An image in multiattach mode can be attached to more than one virtual machine at the same time,
even if these machines are running simultaneously. For each virtual machine to which such an image is attached, a differencing image
is created. As a result, data that is written to such a virtual disk by one machine is not
seen by the other machines to which the image is attached; each machine creates its own write history of the multiattach image.
*/
while(clonedHd.getState().equals(MediumState.NOT_CREATED)) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
clonedHd.setType(mediumType);
return clonedHd;
}
ISession session = manager.getSessionObject();
IMachine machine = manager.getVBox().findMachine(instanceName);
machine.lockMachine(session, LockType.Write);
IMachine mutable = session.getMachine();
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
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();
}
}
// disk
mutable.addStorageController(controller, StorageBus.IDE);
mutable.attachDevice(controller, 0, 0, DeviceType.HardDisk, clonedHd);
@Test(dependsOnMethods = "testStartVirtualMachines")
public void testSshLogin() {
String ipAddress = null;
for (int i = 1; i < numberOfVirtualMachine +1; i++) {
String instanceName = vmName + "_" + i;
IMachine machine = manager.getVBox().findMachine(instanceName);
System.out.println("\nLaunch VM named " + machine.getName() + " ...");
launchVMProcess(machine, manager.getSessionObject());
// network
String hostInterface = null;
String command = "vboxmanage list bridgedifs";
try {
Process child = Runtime.getRuntime().exec(command);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(child.getInputStream()));
String line = "";
boolean found = false;
while(ipAddress==null || ipAddress.equals("")){
try {
ipAddress = machine.getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("VM " + instanceName + " started with IP " + ipAddress);
IPSocket socket = new IPSocket(ipAddress, 22);
System.out.println("Check SSH for " + instanceName + " ...");
checkSSH(socket);
}
}
while ((line = bufferedReader.readLine()) != null && !found) {
@Test(dependsOnMethods = "testSshLogin")
public void testStopVirtualMachine() {
for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
String instanceName = vmName + "_" + i;
IMachine machine = manager.getVBox().findMachine(instanceName);
try {
ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
while(!machine.getSessionState().equals(SessionState.Unlocked)){
try {
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
assertEquals(machine.getState(), MachineState.PoweredOff);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (line.split(":")[0].contains("Name")) {
hostInterface = line.split(":")[1];
}
if (line.split(":")[0].contains("Status") && line.split(":")[1].contains("Up")) {
System.out.println("bridge: " + hostInterface.trim());
found = true;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO: lookup translations for 4.1 for the below
// mutable.getNetworkAdapter(new Long(0)).attachToBridgedInterface();
// mutable.getNetworkAdapter(new
// Long(0)).setHostInterface(hostInterface.trim());
mutable.getNetworkAdapter(new Long(0)).setEnabled(true);
mutable.saveSettings();
session.unlockMachine();
}
/**
* @param instanceName
* @return
*/
private IMedium cloneDisk(MediumType mediumType) {
String clonedDisk = System.getProperty("test." + provider + ".clonedDisk");
String instanceClonedDisk = clonedDisk.split("\\.")[0] + "." + clonedDisk.split("\\.")[1];
clonedDiskPath = workingDir + File.separator + instanceClonedDisk;
// use template disk in multiattach mode
IMedium clonedHd = manager.getVBox().openMedium(originalDiskPath, DeviceType.HardDisk, AccessMode.ReadOnly,
forceOverwrite);
System.out.println("cloned HD state: " + clonedHd.getState());
/*
* An image in multiattach mode can be attached to more than one virtual
* machine at the same time, even if these machines are running
* simultaneously. For each virtual machine to which such an image is
* attached, a differencing image is created. As a result, data that is
* written to such a virtual disk by one machine is not seen by the other
* machines to which the image is attached; each machine creates its own
* write history of the multiattach image.
*/
while (clonedHd.getState().equals(MediumState.NOT_CREATED)) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
clonedHd.setType(mediumType);
return clonedHd;
}
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
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 = "testStartVirtualMachines")
public void testSshLogin() {
String ipAddress = null;
for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
String instanceName = vmName + "_" + i;
IMachine machine = manager.getVBox().findMachine(instanceName);
System.out.println("\nLaunch VM named " + machine.getName() + " ...");
launchVMProcess(machine, manager.getSessionObject());
while (ipAddress == null || ipAddress.equals("")) {
try {
ipAddress = machine.getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("VM " + instanceName + " started with IP " + ipAddress);
IPSocket socket = new IPSocket(ipAddress, 22);
System.out.println("Check SSH for " + instanceName + " ...");
checkSSH(socket);
}
}
@Test(dependsOnMethods = "testSshLogin")
public void testStopVirtualMachine() {
for (int i = 1; i < numberOfVirtualMachine + 1; i++) {
String instanceName = vmName + "_" + i;
IMachine machine = manager.getVBox().findMachine(instanceName);
try {
ISession machineSession = manager.openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try {
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
assertEquals(machine.getState(), MachineState.PoweredOff);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@ -1,3 +1,21 @@
/**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.settings;
import java.util.Collections;