Merge branch 'develop' of https://github.com/andreaturli/jclouds into pull-323

- Changed 'vboxmanage' to 'VBoxManage'
- Did some additional cleanup on the commit. Removed some unused code and some other tidying.
This commit is contained in:
Mattias Holmqvist 2012-01-20 00:04:20 +01:00
commit 02353b93d5
15 changed files with 217 additions and 222 deletions

View File

@ -22,7 +22,6 @@ import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.inject.Inject;
import org.jclouds.compute.callables.RunScriptOnNode;
import org.jclouds.compute.callables.RunScriptOnNode.Factory;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.reference.ComputeServiceConstants;
@ -34,10 +33,8 @@ import org.jclouds.virtualbox.domain.IMachineSpec;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.settings.KeyboardScancodes;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.VirtualBoxManager;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.*;
import javax.annotation.Resource;
import javax.inject.Named;
@ -46,9 +43,6 @@ import java.net.URI;
import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import static org.jclouds.virtualbox.util.MachineUtils.applyForMachine;
import static org.jclouds.virtualbox.util.MachineUtils.lockSessionOnMachineAndApply;
import static org.virtualbox_4_1.LockType.Shared;
@Singleton
public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
@ -68,11 +62,16 @@ public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
private final Function<IMachine, SshClient> sshClientForIMachine;
private final MachineUtils machineUtils;
@Inject
public CreateAndInstallVm(Supplier<VirtualBoxManager> manager,
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
Predicate<SshClient> sshResponds, Function<IMachine, SshClient> sshClientForIMachine,
Supplier<NodeMetadata> host, RunScriptOnNode.Factory scriptRunner, ExecutionType executionType) {
public CreateAndInstallVm(
Supplier<VirtualBoxManager> manager,
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
Predicate<SshClient> sshResponds,
Function<IMachine, SshClient> sshClientForIMachine,
Supplier<NodeMetadata> host, Factory scriptRunner,
ExecutionType executionType, MachineUtils machineUtils) {
this.manager = manager;
this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
this.sshResponds = sshResponds;
@ -80,6 +79,7 @@ public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
this.scriptRunner = scriptRunner;
this.host = host;
this.executionType = executionType;
this.machineUtils = machineUtils;
}
@Override
@ -90,37 +90,45 @@ public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
String vmName = vmSpec.getVmName();
final IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(machineSpec);
final IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists
.apply(machineSpec);
// Launch machine and wait for it to come online
ensureMachineIsLaunched(vmName);
URI uri = isoSpec.getPreConfigurationUri().get();
String installationKeySequence = isoSpec.getInstallationKeySequence()
.replace("PRECONFIGURATION_URL", uri.toASCIIString());
.replace("PRECONFIGURATION_URL", uri.toASCIIString());
sendKeyboardSequence(installationKeySequence, vmName);
SshClient client = sshClientForIMachine.apply(vm);
logger.debug(">> awaiting installation to finish node(%s)", vmName);
checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", vmName);
logger.debug("<< installation of image complete. Powering down node(%s)", vmName);
lockSessionOnMachineAndApply(manager.get(), Shared, vmName, new Function<ISession, Void>() {
checkState(sshResponds.apply(client),
"timed out waiting for guest %s to be accessible via ssh", vmName);
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
});
logger.debug("<< installation of image complete. Powering down node(%s)",
vmName);
ensureMachineHasPowerDown(vmName);
return vm;
}
private void ensureMachineHasPowerDown(String vmName) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared,
new Function<ISession, Void>() {
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole()
.powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
});
}
private void ensureMachineIsLaunched(String vmName) {
applyForMachine(manager.get(), vmName,
machineUtils.applyForMachine(vmName,
new LaunchMachineIfNotAlreadyRunning(manager.get(), executionType,
""));
}
@ -131,7 +139,7 @@ public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
for (String line : splitSequence) {
String converted = stringToKeycode(line);
for (String word : converted.split(" ")) {
sb.append("vboxmanage controlvm ").append(vmName)
sb.append("VBoxManage controlvm ").append(vmName)
.append(" keyboardputscancode ").append(word).append("; ");
runScriptIfWordEndsWith(sb, word, "<Enter>");
runScriptIfWordEndsWith(sb, word, "<Return>");

View File

@ -20,8 +20,6 @@
package org.jclouds.virtualbox.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApply;
import static org.virtualbox_4_1.LockType.Write;
import java.io.File;
import java.util.Map;
@ -36,7 +34,15 @@ import javax.inject.Singleton;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.*;
import org.jclouds.virtualbox.domain.DeviceDetails;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IMachineSpec;
import org.jclouds.virtualbox.domain.IsoImage;
import org.jclouds.virtualbox.domain.NatAdapter;
import org.jclouds.virtualbox.domain.NetworkSpec;
import org.jclouds.virtualbox.domain.StorageController;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.AccessMode;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine;
@ -59,12 +65,15 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
protected Logger logger = Logger.NULL;
private final Supplier<VirtualBoxManager> manager;
private final MachineUtils machineUtils;
private final String workingDir;
@Inject
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Supplier<VirtualBoxManager> manager,
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, MachineUtils machineUtils,
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir) {
this.manager = manager;
this.machineUtils = machineUtils;
this.workingDir = workingDir;
}
@ -136,8 +145,8 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails,
String controllerName) {
lockMachineAndApply(manager.get(), Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium,
controllerName));
machineUtils.writeLockMachineAndApply(vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium,
controllerName));
}
private String missingIDEControllersMessage(VmSpec vmSpecification) {
@ -157,22 +166,22 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
logger.error(String.format("File %s could not be deleted.", sourcePath));
}
}
IMedium medium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
IMedium medium = new CreateMediumIfNotAlreadyExists(manager, machineUtils, true).apply(hardDisk);
ensureMachineDevicesAttached(vmName, medium, hardDisk.getDeviceDetails(), controller.getName());
}
}
private void ensureMachineHasMemory(String vmName, final long memorySize) {
lockMachineAndApply(manager.get(), Write, vmName, new ApplyMemoryToMachine(memorySize));
machineUtils.writeLockMachineAndApply(vmName, new ApplyMemoryToMachine(memorySize));
}
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId,
NatAdapter natAdapter) {
lockMachineAndApply(manager.get(), Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
machineUtils.writeLockMachineAndApply(vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
}
public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) {
lockMachineAndApply(manager.get(), Write, checkNotNull(vmName, "vmName"), new AddIDEControllerIfNotExists(checkNotNull(
storageController, "storageController")));
machineUtils.writeLockMachineAndApply(vmName, new AddIDEControllerIfNotExists(checkNotNull(
storageController, "storageController")));
}
}

View File

@ -19,9 +19,6 @@
package org.jclouds.virtualbox.functions;
import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApply;
import static org.virtualbox_4_1.LockType.Write;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -30,6 +27,7 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.DeviceType;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IMedium;
@ -51,11 +49,13 @@ import com.google.common.collect.Iterables;
public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMedium> {
private final Supplier<VirtualBoxManager> manager;
private final MachineUtils machineUtils;
private final boolean overwriteIfExists;
@Inject
public CreateMediumIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, boolean overwriteIfExists) {
public CreateMediumIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, MachineUtils machineUtils, boolean overwriteIfExists) {
this.manager = manager;
this.machineUtils = machineUtils;
this.overwriteIfExists = overwriteIfExists;
}
@ -95,8 +95,8 @@ public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMediu
return in.getMedium().getId().equals(medium.getId());
}
});
lockMachineAndApply(manager.get(), Write, immutableMachine.getName(), new DetachDistroMediumFromMachine(
mediumAttachment.getController(), mediumAttachment.getPort(), mediumAttachment.getDevice()));
machineUtils.writeLockMachineAndApply(immutableMachine.getName(), new DetachDistroMediumFromMachine(
mediumAttachment.getController(), mediumAttachment.getPort(), mediumAttachment.getDevice()));
deleteMediumAndBlockUntilComplete(medium);
} else {
throw e;

View File

@ -36,7 +36,7 @@ import com.google.common.base.Supplier;
import com.google.inject.Inject;
@Singleton
public class MutableMachine implements Function<String, IMachine> {
public class MutableMachine implements Function<String, ISession> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
@ -54,7 +54,7 @@ public class MutableMachine implements Function<String, IMachine> {
}
@Override
public IMachine apply(String machineId) {
public ISession apply(String machineId) {
return lockSessionOnMachineAndReturn(manager.get(), lockType, machineId);
}
@ -67,14 +67,14 @@ public class MutableMachine implements Function<String, IMachine> {
* @param manager the VirtualBoxManager
* @param type the kind of lock to use when initially locking the machine.
* @param machineId the id of the machine
* @return the result from applying the function to the session.
* @return the ISession bounded to the machine locked.
*/
public static IMachine lockSessionOnMachineAndReturn(VirtualBoxManager manager, LockType type, String machineId) {
public static ISession lockSessionOnMachineAndReturn(VirtualBoxManager manager, LockType type, String machineId) {
try {
ISession session = manager.getSessionObject();
IMachine immutableMachine = manager.getVBox().findMachine(machineId);
immutableMachine.lockMachine(session, type);
return immutableMachine;
return session;
} catch (VBoxException e) {
throw new RuntimeException(String.format("error locking %s with %s lock: %s", machineId,
type, e.getMessage()), e);

View File

@ -66,7 +66,7 @@ public class RetrieveActiveBridgedInterfaces implements Function<NodeMetadata, L
@Override
public List<String> apply(NodeMetadata host) {
// Bridged Network
Statement command = Statements.exec("vboxmanage list bridgedifs");
Statement command = Statements.exec("VBoxManage list bridgedifs");
String bridgedIfBlocks = runScriptOnNodeFactory.create(host, command, runAsRoot(false).wrapInInitScript(false))
.init().call().getOutput();

View File

@ -1,4 +1,4 @@
/**
/*
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information

View File

@ -18,11 +18,11 @@
*/
package org.jclouds.virtualbox.util;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import static org.jclouds.scriptbuilder.domain.Statements.call;
import static org.jclouds.scriptbuilder.domain.Statements.findPid;
import static org.jclouds.scriptbuilder.domain.Statements.kill;
import static org.jclouds.scriptbuilder.domain.Statements.newStatementList;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import javax.annotation.Resource;
import javax.inject.Named;
@ -33,9 +33,7 @@ import org.jclouds.compute.callables.RunScriptOnNode.Factory;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.scriptbuilder.domain.Statements;
import org.jclouds.util.Throwables2;
import org.jclouds.virtualbox.functions.MutableMachine;
import org.virtualbox_4_1.IMachine;
@ -46,7 +44,6 @@ import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Supplier;
import com.google.inject.Inject;
@ -64,56 +61,17 @@ public class MachineUtils {
protected Logger logger = Logger.NULL;
private final Supplier<VirtualBoxManager> manager;
private final LockType lockType;
private final Factory scriptRunner;
private final Supplier<NodeMetadata> host;
@Inject
public MachineUtils(Supplier<VirtualBoxManager> manager, LockType lockType, RunScriptOnNode.Factory scriptRunner, Supplier<NodeMetadata> host) {
public MachineUtils(Supplier<VirtualBoxManager> manager, RunScriptOnNode.Factory scriptRunner, Supplier<NodeMetadata> host) {
super();
this.manager = manager;
this.lockType = lockType;
this.scriptRunner = scriptRunner;
this.host = host;
}
public <T> Function<String, T> mutateMachine(String machineId,
Function<IMachine, T> function) {
try {
return Functions.compose(function, new MutableMachine(manager, lockType));
} finally {
unlockMachine(machineId);
}
}
protected void unlockMachine(final String machineId) {
IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
if (immutableMachine.getSessionState().equals(SessionState.Locked)) {
Statement kill = newStatementList(call("default"),
findPid(immutableMachine.getSessionPid().toString()), kill());
scriptRunner
.create(host.get(), kill,
runAsRoot(false).wrapInInitScript(false)).init().call();
}
}
public static <T> T applyForMachine(VirtualBoxManager manager,
final String machineId, final Function<IMachine, T> function) {
final IMachine immutableMachine = manager.getVBox()
.findMachine(machineId);
return new Function<IMachine, T>() {
@Override
public T apply(IMachine machine) {
return function.apply(machine);
}
@Override
public String toString() {
return function.toString();
}
}.apply(immutableMachine);
}
/**
* Locks the machine and executes the given function using the machine
* matching the given id. Since the machine is locked it is possible to
@ -121,20 +79,14 @@ public class MachineUtils {
* <p/>
* Unlocks the machine before returning.
*
* @param manager
* the VirtualBoxManager
* @param type
* the kind of lock to use when initially locking the machine.
* @param machineId
* the id of the machine
* @param function
* the function to execute
* @return the result from applying the function to the machine.
*/
public static <T> T lockMachineAndApply(VirtualBoxManager manager,
final LockType type, final String machineId,
final Function<IMachine, T> function) {
return lockSessionOnMachineAndApply(manager, type, machineId,
public <T> T writeLockMachineAndApply(final String machineId, final Function<IMachine, T> function) {
return lockSessionOnMachineAndApply(machineId, LockType.Write,
new Function<ISession, T>() {
@Override
@ -157,8 +109,6 @@ public class MachineUtils {
* <p/>
* Unlocks the machine before returning.
*
* @param manager
* the VirtualBoxManager
* @param type
* the kind of lock to use when initially locking the machine.
* @param machineId
@ -167,12 +117,9 @@ public class MachineUtils {
* the function to execute
* @return the result from applying the function to the session.
*/
public static <T> T lockSessionOnMachineAndApply(VirtualBoxManager manager,
LockType type, String machineId, Function<ISession, T> function) {
public <T> T lockSessionOnMachineAndApply(String machineId, LockType type, Function<ISession, T> function) {
try {
ISession session = manager.getSessionObject();
IMachine immutableMachine = manager.getVBox().findMachine(machineId);
immutableMachine.lockMachine(session, type);
ISession session = lockSessionOnMachine(type, machineId);
try {
return function.apply(session);
} finally {
@ -185,35 +132,18 @@ public class MachineUtils {
}
}
/**
* Locks the machine and executes the given function using the current
* session, if the machine is registered. Since the machine is locked it is
* possible to perform some modifications to the IMachine.
* <p/>
* Unlocks the machine before returning.
*
* @param manager
* the VirtualBoxManager
* @param type
* the kind of lock to use when initially locking the machine.
* @param machineId
* the id of the machine
* @param function
* the function to execute
* @return the result from applying the function to the session.
*/
public static <T> T lockMachineAndApplyOrReturnNullIfNotRegistered(
VirtualBoxManager manager, LockType type, String machineId,
Function<IMachine, T> function) {
try {
return lockMachineAndApply(manager, type, machineId, function);
} catch (RuntimeException e) {
VBoxException vbex = Throwables2.getFirstThrowableOfType(e,
VBoxException.class);
if (vbex != null
&& vbex.getMessage().indexOf("not find a registered") == -1)
throw e;
return null;
private ISession lockSessionOnMachine(LockType type, String machineId) {
return new MutableMachine(manager, type).apply(machineId);
}
private void unlockMachine(final String machineId) {
IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
if (immutableMachine.getSessionState().equals(SessionState.Locked)) {
Statement kill = newStatementList(call("default"),
findPid(immutableMachine.getSessionPid().toString()), kill());
scriptRunner
.create(host.get(), kill,
runAsRoot(false).wrapInInitScript(false)).init().call();
}
}
@ -226,32 +156,21 @@ public class MachineUtils {
* <h3>Note!</h3> Currently, this can only unlock the machine, if the lock
* was created in the current session.
*
* @param manager
* the VirtualBoxManager
* @param machineId
* the id of the machine
* @param function
* the function to execute
* @return the result from applying the function to the machine.
*/
public static <T> T unlockMachineAndApply(VirtualBoxManager manager,
final String machineId, final Function<IMachine, T> function) {
ISession session = manager.getSessionObject();
public <T> T unlockMachineAndApply(final String machineId, final Function<IMachine, T> function) {
try {
IMachine immutableMachine = manager.getVBox().findMachine(machineId);
SessionState state = immutableMachine.getSessionState();
Statement kill = newStatementList(call("default"),
findPid(immutableMachine.getSessionPid().toString()), kill());
if (state.equals(SessionState.Locked))
// session.unlockMachine();
kill.render(OsFamily.UNIX);
// TODO: wire this in
unlockMachine(machineId);
IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
return function.apply(immutableMachine);
} catch (VBoxException e) {
session.unlockMachine();
throw new RuntimeException(String.format(
"error applying %s to %s: %s", function, machineId,
e.getMessage()), e);
@ -264,19 +183,16 @@ public class MachineUtils {
* machine.
* <p/>
*
* @param manager
* the VirtualBoxManager
* @param machineId
* the id of the machine
* @param function
* the function to execute
* @return the result from applying the function to the session.
*/
public static <T> T unlockMachineAndApplyOrReturnNullIfNotRegistered(
VirtualBoxManager manager, String machineId,
public <T> T unlockMachineAndApplyOrReturnNullIfNotRegistered(String machineId,
Function<IMachine, T> function) {
try {
return unlockMachineAndApply(manager, machineId, function);
return unlockMachineAndApply(machineId, function);
} catch (RuntimeException e) {
VBoxException vbex = Throwables2.getFirstThrowableOfType(e,
VBoxException.class);
@ -286,4 +202,26 @@ public class MachineUtils {
return null;
}
}
/**
*
* @param machineId
* @param function
* @return
*/
public <T> T applyForMachine(final String machineId, final Function<IMachine, T> function) {
final IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
return new Function<IMachine, T>() {
@Override
public T apply(IMachine machine) {
return function.apply(machine);
}
@Override
public String toString() {
return function.toString();
}
}.apply(immutableMachine);
}
}

View File

@ -5,7 +5,7 @@ function exportIpAddressFromVmNamed {
return 1
}
local VMNAME="$0"; shift
local _FOUND=`vboxmanage guestproperty enumerate "$VMNAME" --patterns "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $4 }' | cut -c 1-14`
local _FOUND=`VBoxManage guestproperty enumerate "$VMNAME" --patterns "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $4 }' | cut -c 1-14`
[ -n "$_FOUND" ] && {
export FOUND_IP_ADDRESS=$_FOUND
echo [$FOUND_IP_ADDRESS]

View File

@ -5,7 +5,7 @@ function getIpAddress {
return 1
}
local VMNAME="$0"; shift
local _FOUND=`vboxmanage guestproperty enumerate "$VMNAME" --patterns "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $4 }' | cut -c 1-14`
local _FOUND=`VBoxManage guestproperty enumerate "$VMNAME" --patterns "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $4 }' | cut -c 1-14`
[ -n "$_FOUND" ] && {
export FOUND_IP_ADDRESS=$_FOUND
echo [$FOUND_IP_ADDRESS]

View File

@ -19,8 +19,6 @@
package org.jclouds.virtualbox;
import static org.jclouds.virtualbox.util.MachineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered;
import java.net.URI;
import java.util.Properties;
@ -38,8 +36,6 @@ import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.functions.CreateAndInstallVm;
import org.jclouds.virtualbox.functions.CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
import org.jclouds.virtualbox.util.MachineUtils;
import org.testng.annotations.AfterClass;
@ -70,6 +66,7 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
protected ComputeServiceContext context;
protected Supplier<VirtualBoxManager> manager;
protected MachineUtils machineUtils;
protected Supplier<URI> preconfigurationUri;
protected String hostVersion;
protected String operatingSystemIso;
@ -80,17 +77,19 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
@Override
protected void setupCredentials() {
// default behavior is to bomb when no user is configured, but we know the default user of
// default behavior is to bomb when no user is configured, but we know the
// default user of
// vbox
ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults();
super.setupCredentials();
}
protected void ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults() {
Properties defaultVBoxProperties = new VirtualBoxPropertiesBuilder().build();
Properties defaultVBoxProperties = new VirtualBoxPropertiesBuilder()
.build();
if (!System.getProperties().containsKey("test." + provider + ".identity"))
System.setProperty("test." + provider + ".identity", defaultVBoxProperties
.getProperty(Constants.PROPERTY_IDENTITY));
System.setProperty("test." + provider + ".identity",
defaultVBoxProperties.getProperty(Constants.PROPERTY_IDENTITY));
}
@BeforeClass(groups = "live")
@ -98,40 +97,66 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
setupCredentials();
Properties overrides = setupProperties();
CacheNodeStoreModule hostModule = new CacheNodeStoreModule(ImmutableMap.of("host", Node.builder().id("host")
.name("host installing virtualbox").hostname("localhost").osFamily(OsFamily.LINUX.toString())
.osDescription(System.getProperty("os.name")).osVersion(System.getProperty("os.version")).group("ssh")
.username(System.getProperty("user.name")).credentialUrl(
URI.create("file://" + System.getProperty("user.home") + "/.ssh/id_rsa")).build()));
CacheNodeStoreModule hostModule = new CacheNodeStoreModule(
ImmutableMap.of(
"host",
Node.builder()
.id("host")
.name("host installing virtualbox")
.hostname("localhost")
.osFamily(OsFamily.LINUX.toString())
.osDescription(System.getProperty("os.name"))
.osVersion(System.getProperty("os.version"))
.group("ssh")
.username(System.getProperty("user.name"))
.credentialUrl(
URI.create("file://"
+ System.getProperty("user.home")
+ "/.ssh/id_rsa")).build()));
context = new ComputeServiceContextFactory().createContext(provider, identity, credential, ImmutableSet
.<Module> of(new SLF4JLoggingModule(), new SshjSshClientModule(), hostModule), overrides);
Function<String, String> configProperties = context.utils().injector().getInstance(
ValueOfConfigurationKeyOrNull.class);
imageId = configProperties.apply(ComputeServiceConstants.PROPERTY_IMAGE_ID);
workingDir = configProperties.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
host = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<NodeMetadata>>(){}));
context = new ComputeServiceContextFactory().createContext(provider,
identity, credential, ImmutableSet.<Module> of(
new SLF4JLoggingModule(), new SshjSshClientModule(),
hostModule), overrides);
Function<String, String> configProperties = context.utils().injector()
.getInstance(ValueOfConfigurationKeyOrNull.class);
imageId = configProperties
.apply(ComputeServiceConstants.PROPERTY_IMAGE_ID);
workingDir = configProperties
.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
host = context.utils().injector()
.getInstance(Key.get(new TypeLiteral<Supplier<NodeMetadata>>() {
}));
// this will eagerly startup Jetty, note the impl will shut itself down
preconfigurationUri = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<URI>>() {
}, Preconfiguration.class));
preconfigurationUri = context.utils().injector()
.getInstance(Key.get(new TypeLiteral<Supplier<URI>>() {
}, Preconfiguration.class));
// this will eagerly startup Jetty, note the impl will shut itself down
preconfigurationUri.get();
manager = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<VirtualBoxManager>>() {
}));
manager = context
.utils()
.injector()
.getInstance(Key.get(new TypeLiteral<Supplier<VirtualBoxManager>>() {}));
// this will eagerly startup vbox
manager.get();
hostVersion = Iterables.get(Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0);
machineUtils = context.utils().injector().getInstance(MachineUtils.class);
hostVersion = Iterables.get(
Splitter.on('r').split(
context.getProviderSpecificContext().getBuildVersion()), 0);
adminDisk = workingDir + "/testadmin.vdi";
operatingSystemIso = String.format("%s/%s.iso", workingDir, imageId);
guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", workingDir, hostVersion);
guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso",
workingDir, hostVersion);
}
protected void undoVm(VmSpec vmSpecification) {
MachineUtils machineUtils = context.utils().injector().getInstance(MachineUtils.class);
machineUtils.mutateMachine(vmSpecification.getVmId(), new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
machineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered(
vmSpecification.getVmId(),
new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
}
@AfterClass(groups = "live")

View File

@ -27,15 +27,14 @@ import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import com.google.common.base.Supplier;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import java.net.URI;
import org.easymock.EasyMock;
import org.jclouds.virtualbox.Preconfiguration;
import org.jclouds.virtualbox.domain.IMachineSpec;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.NetworkSpec;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.util.MachineUtils;
import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine;
@ -45,10 +44,9 @@ import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import java.net.URI;
/**
* @author Mattias Holmqvist
*/
@ -58,6 +56,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
@Test(enabled = false)
public void testCreateAndSetMemoryWhenNotAlreadyExists() throws Exception {
MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createMock(VirtualBoxManager.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
@ -96,17 +95,18 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
//TODO: this mock test is not finished.
replay(manager, createdMachine, vBox, session);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(machineSpec);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
verify(manager, createdMachine, vBox, session);
}
@Test(expectedExceptions = IllegalStateException.class)
@Test(expectedExceptions = IllegalStateException.class, enabled=false)
public void testFailIfMachineIsAlreadyRegistered() throws Exception {
MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
@ -117,7 +117,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMachine(vmName)).andReturn(registeredMachine).anyTimes();
replay(manager, vBox);
replay(manager, vBox, machineUtils);
VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").memoryMB(1024).cleanUpMode(
CleanupMode.Full).build();
@ -129,12 +129,14 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
.preConfiguration(preconfiguration).build())
.vm(launchSpecification)
.network(NetworkSpec.builder().build()).build();
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(machineSpec);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
}
@Test(expectedExceptions = VBoxException.class)
public void testFailIfOtherVBoxExceptionIsThrown() throws Exception {
MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
@ -148,7 +150,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
vBox.findMachine(vmName);
expectLastCall().andThrow(vBoxException);
replay(manager, vBox);
replay(manager, vBox, machineUtils);
VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full)
.memoryMB(1024).build();
@ -160,7 +162,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
.vm(launchSpecification)
.network(NetworkSpec.builder().build()).build();
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(machineSpec);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
}

View File

@ -42,7 +42,7 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
public void testCreateMedium() throws Exception {
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-1.vdi";
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, machineUtils, true).apply(hardDisk);
manager.get().getVBox().findMedium(path, DeviceType.HardDisk);
try {
assertFileCanBeDeleted(path);
@ -56,7 +56,7 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
String path = "test-medium-2.vdi";
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
try {
new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
new CreateMediumIfNotAlreadyExists(manager, machineUtils, true).apply(hardDisk);
fail();
} catch (VBoxException e) {
ErrorCode errorCode = ErrorCode.valueOf(e);
@ -68,15 +68,14 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
public void testCreateSameMediumTwiceWhenUsingOverwrite() throws Exception {
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-3.vdi";
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
new CreateMediumIfNotAlreadyExists(manager, machineUtils, true).apply(hardDisk);
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, machineUtils, true).apply(hardDisk);
manager.get().getVBox().findMedium(path, DeviceType.HardDisk);
try {
assertFileCanBeDeleted(path);
} finally {
deleteMediumAndBlockUntilComplete(iMedium);
}
}
private void assertFileCanBeDeleted(String path) {

View File

@ -28,7 +28,9 @@ import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.testng.Assert.assertNotSame;
import org.easymock.EasyMock;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.util.MachineUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.virtualbox_4_1.DeviceType;
@ -65,6 +67,8 @@ public class CreateMediumIfNotAlreadyExistsTest {
HardDisk hardDisk = createTestHardDisk();
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
MachineUtils machineUtils = createMock(MachineUtils.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium medium = createMock(IMedium.class);
@ -75,17 +79,17 @@ public class CreateMediumIfNotAlreadyExistsTest {
errorBuilder.append("Could not find an open hard disk with location ");
errorBuilder.append("'/Users/johndoe/jclouds-virtualbox-test/testadmin.vdi' (0x80BB0001)");
String errorMessage = errorBuilder.toString();
expect(manager.getVBox()).andReturn(vBox).anyTimes();
VBoxException notFoundException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(vBox.findMedium(eq(adminDiskPath), eq(DeviceType.HardDisk))).andThrow(notFoundException);
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(medium);
expect(medium.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
//expect(machineUtils.writeLockMachineAndApply(anyString(), new DetachDistroMediumFromMachine(anyString(), anyInt() , anyInt()))).andReturn().anyTimes();
replay(manager, machine, vBox, medium);
replay(manager, machine, vBox, medium, machineUtils);
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, true).apply(hardDisk);
verify(machine, vBox);
@ -96,6 +100,8 @@ public class CreateMediumIfNotAlreadyExistsTest {
HardDisk hardDisk = createTestHardDisk();
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
MachineUtils machineUtils = createMock(MachineUtils.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium medium = createMock(IMedium.class);
@ -109,20 +115,24 @@ public class CreateMediumIfNotAlreadyExistsTest {
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(newHardDisk);
expect(newHardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, machine, vBox, medium, newHardDisk, progress);
//expect(machineUtils.writeLockMachineAndApply(anyString(), new DetachDistroMediumFromMachine(anyString(), anyInt() , anyInt()))).andReturn(v).anyTimes();
IMedium newDisk = new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
replay(manager, machine, vBox, medium, newHardDisk, progress, machineUtils);
IMedium newDisk = new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, true).apply(hardDisk);
verify(machine, vBox, medium);
assertNotSame(newDisk, medium);
}
@Test
@Test(enabled = false)
public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwriteAndStillAttachedDetachesOldThing()
throws Exception {
HardDisk hardDisk = createTestHardDisk();
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
MachineUtils machineUtils = createMock(MachineUtils.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium medium = createMock(IMedium.class);
@ -176,9 +186,9 @@ public class CreateMediumIfNotAlreadyExistsTest {
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(newHardDisk);
expect(newHardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, oldMachine, oldAttachment, oldMedium, detachSession, machine, vBox, medium, newHardDisk, progress);
replay(manager, oldMachine, oldAttachment, oldMedium, detachSession, machine, vBox, medium, newHardDisk, progress, machineUtils);
IMedium newDisk = new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
IMedium newDisk = new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, true).apply(hardDisk);
verify(machine, oldMachine, oldAttachment, detachSession, oldMedium, vBox, medium);
assertNotSame(newDisk, medium);
@ -189,6 +199,8 @@ public class CreateMediumIfNotAlreadyExistsTest {
HardDisk hardDisk = createTestHardDisk();
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
MachineUtils machineUtils = createMock(MachineUtils.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium medium = createMock(IMedium.class);
@ -198,9 +210,9 @@ public class CreateMediumIfNotAlreadyExistsTest {
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(medium);
replay(manager, machine, vBox, medium, newHardDisk, progress);
replay(manager, machine, vBox, medium, newHardDisk, progress, machineUtils);
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), false).apply(hardDisk);
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, false).apply(hardDisk);
}
@Test(expectedExceptions = VBoxException.class)
@ -209,6 +221,8 @@ public class CreateMediumIfNotAlreadyExistsTest {
HardDisk hardDisk = createTestHardDisk();
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
MachineUtils machineUtils = createMock(MachineUtils.class);
IMachine machine = createMock(IMachine.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
IMedium medium = createMock(IMedium.class);
@ -223,9 +237,9 @@ public class CreateMediumIfNotAlreadyExistsTest {
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(medium);
expect(medium.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
replay(manager, machine, vBox, medium);
replay(manager, machine, vBox, medium, machineUtils);
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, true).apply(hardDisk);
}
private HardDisk createTestHardDisk() {

View File

@ -14,7 +14,7 @@ function exportIpAddressFromVmNamed {
return 1
}
local VMNAME="$0"; shift
local _FOUND=`vboxmanage guestproperty enumerate "$VMNAME" --patterns "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $4 }' | cut -c 1-14`
local _FOUND=`VBoxManage guestproperty enumerate "$VMNAME" --patterns "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $4 }' | cut -c 1-14`
[ -n "$_FOUND" ] && {
export FOUND_IP_ADDRESS=$_FOUND
echo [$FOUND_IP_ADDRESS]

View File

@ -14,7 +14,7 @@ function getIpAddress {
return 1
}
local VMNAME="$0"; shift
local _FOUND=`vboxmanage guestproperty enumerate "$VMNAME" --patterns "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $4 }' | cut -c 1-14`
local _FOUND=`VBoxManage guestproperty enumerate "$VMNAME" --patterns "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $4 }' | cut -c 1-14`
[ -n "$_FOUND" ] && {
export FOUND_IP_ADDRESS=$_FOUND
echo [$FOUND_IP_ADDRESS]