formatted most changed classes to comply with jclouds formatting guildelines

This commit is contained in:
David Ribeiro Alves 2012-03-05 17:03:15 +00:00
parent c08cbc89f4
commit fa26fe34f9
24 changed files with 1190 additions and 1281 deletions

View File

@ -78,7 +78,8 @@ public class VirtualBoxPropertiesBuilder extends PropertiesBuilder {
System.getProperty("user.home") + File.separator System.getProperty("user.home") + File.separator
+ System.getProperty("test.virtualbox.workingDir", ".jclouds-vbox")); + System.getProperty("test.virtualbox.workingDir", ".jclouds-vbox"));
// allow to set the descriptor as a sysprop but default to just setting a default file path. The configured supplier // allow to set the descriptor as a sysprop but default to just setting a default file path.
// The configured supplier
// must be able to handle the chosen option. // must be able to handle the chosen option.
properties.put( properties.put(
VIRTUALBOX_IMAGES_DESCRIPTOR, VIRTUALBOX_IMAGES_DESCRIPTOR,

View File

@ -53,8 +53,8 @@ import com.google.common.collect.Iterables;
import com.google.inject.Singleton; import com.google.inject.Singleton;
/** /**
* Defines the connection between the {@link org.virtualbox_4_1.VirtualBoxManager} implementation and the jclouds * Defines the connection between the {@link org.virtualbox_4_1.VirtualBoxManager} implementation
* {@link org.jclouds.compute.ComputeService} * and the jclouds {@link org.jclouds.compute.ComputeService}
* *
* @author Mattias Holmqvist, Andrea Turli * @author Mattias Holmqvist, Andrea Turli
*/ */

View File

@ -175,8 +175,10 @@ public class VirtualBoxComputeServiceContextModule extends
"host", "host",
Node.builder().id("host").name("host installing virtualbox").hostname("localhost") Node.builder().id("host").name("host installing virtualbox").hostname("localhost")
.osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name")) .osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name"))
.osVersion(System.getProperty("os.version")).group("ssh").username(System.getProperty("user.name")) .osVersion(System.getProperty("os.version")).group("ssh")
.credentialUrl(URI.create("file://" + System.getProperty("user.home") + "/.ssh/id_rsa")).build())); .username(System.getProperty("user.name"))
.credentialUrl(URI.create("file://" + System.getProperty("user.home") + "/.ssh/id_rsa"))
.build()));
return new ComputeServiceContextFactory().createContext(provider, identity, credential, return new ComputeServiceContextFactory().createContext(provider, identity, credential,
ImmutableSet.<Module> of(new SLF4JLoggingModule(), new SshjSshClientModule(), hostModule)); ImmutableSet.<Module> of(new SLF4JLoggingModule(), new SshjSshClientModule(), hostModule));
} }
@ -243,45 +245,24 @@ public class VirtualBoxComputeServiceContextModule extends
@VisibleForTesting @VisibleForTesting
public static final Map<MachineState, NodeState> machineToNodeState = ImmutableMap public static final Map<MachineState, NodeState> machineToNodeState = ImmutableMap
.<MachineState, NodeState> builder() .<MachineState, NodeState> builder().put(MachineState.Running, NodeState.RUNNING)
.put(MachineState.Running, NodeState.RUNNING) .put(MachineState.PoweredOff, NodeState.SUSPENDED)
.put(MachineState.PoweredOff, .put(MachineState.DeletingSnapshot, NodeState.PENDING)
NodeState.SUSPENDED) .put(MachineState.DeletingSnapshotOnline, NodeState.PENDING)
.put(MachineState.DeletingSnapshot, .put(MachineState.DeletingSnapshotPaused, NodeState.PENDING)
NodeState.PENDING) .put(MachineState.FaultTolerantSyncing, NodeState.PENDING)
.put(MachineState.DeletingSnapshotOnline, .put(MachineState.LiveSnapshotting, NodeState.PENDING)
NodeState.PENDING) .put(MachineState.SettingUp, NodeState.PENDING)
.put(MachineState.DeletingSnapshotPaused,
NodeState.PENDING)
.put(MachineState.FaultTolerantSyncing,
NodeState.PENDING)
.put(MachineState.LiveSnapshotting,
NodeState.PENDING)
.put(MachineState.SettingUp,
NodeState.PENDING)
.put(MachineState.Starting, NodeState.PENDING) .put(MachineState.Starting, NodeState.PENDING)
.put(MachineState.Stopping, NodeState.PENDING) .put(MachineState.Stopping, NodeState.PENDING)
.put(MachineState.Restoring, .put(MachineState.Restoring, NodeState.PENDING)
NodeState.PENDING)
// TODO What to map these states to? // TODO What to map these states to?
.put(MachineState.FirstOnline, .put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING)
NodeState.PENDING) .put(MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING)
.put(MachineState.FirstTransient, .put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING)
NodeState.PENDING) .put(MachineState.TeleportingPausedVM, NodeState.PENDING).put(MachineState.Aborted, NodeState.ERROR)
.put(MachineState.LastOnline,
NodeState.PENDING)
.put(MachineState.LastTransient,
NodeState.PENDING)
.put(MachineState.Teleported,
NodeState.PENDING)
.put(MachineState.TeleportingIn,
NodeState.PENDING)
.put(MachineState.TeleportingPausedVM,
NodeState.PENDING)
.put(MachineState.Aborted, NodeState.ERROR)
.put(MachineState.Stuck, NodeState.ERROR) .put(MachineState.Stuck, NodeState.ERROR)
.put(MachineState.Null, .put(MachineState.Null, NodeState.UNRECOGNIZED).build();
NodeState.UNRECOGNIZED).build();
} }

View File

@ -55,8 +55,8 @@ public interface VirtualBoxConstants {
public static final String VIRTUALBOX_WEBSERVER_CREDENTIAL = "jclouds.virtualbox.webserver.credential"; public static final String VIRTUALBOX_WEBSERVER_CREDENTIAL = "jclouds.virtualbox.webserver.credential";
public static final String VIRTUALBOX_DEFAULT_DIR = System.getProperty("user.home") public static final String VIRTUALBOX_DEFAULT_DIR = System.getProperty("user.home") + File.separator
+ File.separator +".jclouds-vbox"; + ".jclouds-vbox";
public static final String VIRTUALBOX_PROVIDER = "virtualbox"; public static final String VIRTUALBOX_PROVIDER = "virtualbox";

View File

@ -26,8 +26,8 @@ import org.virtualbox_4_1.IMachine;
import com.google.common.base.Objects; import com.google.common.base.Objects;
/** /**
* A complete specification of a "clone" node with networking setup * A complete specification of a "clone" node with networking setup and the physical machine
* and the physical machine specification. * specification.
*/ */
public class CloneSpec { public class CloneSpec {
@ -57,18 +57,18 @@ public class CloneSpec {
return this; return this;
} }
public Builder master(IMachine master){ public Builder master(IMachine master) {
this.master = master; this.master = master;
return this; return this;
} }
public Builder linked(boolean isLinked){ public Builder linked(boolean isLinked) {
this.isLinked = isLinked; this.isLinked = isLinked;
return this; return this;
} }
public CloneSpec build() { public CloneSpec build() {
return new CloneSpec(vmSpec, networkSpec, master ,isLinked); return new CloneSpec(vmSpec, networkSpec, master, isLinked);
} }
} }
@ -101,25 +101,22 @@ public class CloneSpec {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
return true;
if (o instanceof VmSpec) { if (o instanceof VmSpec) {
CloneSpec other = (CloneSpec) o; CloneSpec other = (CloneSpec) o;
return Objects.equal(vmSpec, other.vmSpec) && return Objects.equal(vmSpec, other.vmSpec) && Objects.equal(networkSpec, other.networkSpec);
Objects.equal(networkSpec, other.networkSpec);
} }
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(vmSpec,networkSpec); return Objects.hashCode(vmSpec, networkSpec);
} }
@Override @Override
public String toString() { public String toString() {
return "IMachineSpec{" + return "IMachineSpec{" + "vmSpec= " + vmSpec + ", networkSpec= " + networkSpec + '}';
"vmSpec= " + vmSpec +
", networkSpec= " + networkSpec +
'}';
} }
} }

View File

@ -34,18 +34,18 @@ public class Master {
private IMachine machine; private IMachine machine;
private MasterSpec spec; private MasterSpec spec;
public Builder machine(IMachine machine){ public Builder machine(IMachine machine) {
this.machine = machine; this.machine = machine;
return this; return this;
} }
public Builder spec(MasterSpec spec){ public Builder spec(MasterSpec spec) {
this.spec = spec; this.spec = spec;
return this; return this;
} }
public Master build(){ public Master build() {
return new Master(machine,spec); return new Master(machine, spec);
} }
} }

View File

@ -24,8 +24,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects; import com.google.common.base.Objects;
/** /**
* A complete specification of a "master" node, including the ISO, networking setup * A complete specification of a "master" node, including the ISO, networking setup and the physical
* and the physical machine specification. * machine specification.
*/ */
public class MasterSpec { public class MasterSpec {
@ -87,27 +87,23 @@ public class MasterSpec {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
return true;
if (o instanceof VmSpec) { if (o instanceof VmSpec) {
MasterSpec other = (MasterSpec) o; MasterSpec other = (MasterSpec) o;
return Objects.equal(vmSpec, other.vmSpec) && return Objects.equal(vmSpec, other.vmSpec) && Objects.equal(isoSpec, other.isoSpec)
Objects.equal(isoSpec, other.isoSpec) && && Objects.equal(networkSpec, other.networkSpec);
Objects.equal(networkSpec, other.networkSpec);
} }
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(vmSpec,isoSpec,networkSpec); return Objects.hashCode(vmSpec, isoSpec, networkSpec);
} }
@Override @Override
public String toString() { public String toString() {
return "IMachineSpec{" + return "IMachineSpec{" + "vmSpec=" + vmSpec + ", isoSpec=" + isoSpec + ", networkSpec=" + networkSpec + '}';
"vmSpec=" + vmSpec +
", isoSpec=" + isoSpec +
", networkSpec=" + networkSpec +
'}';
} }
} }

View File

@ -42,7 +42,8 @@ public class VmSpec {
private final Set<StorageController> controllers; private final Set<StorageController> controllers;
private final CleanupMode cleanupMode; private final CleanupMode cleanupMode;
public VmSpec(String vmId, String vmName, String osTypeId, long memory, boolean forceOverwrite, Set<StorageController> controllers, CleanupMode cleanupMode) { public VmSpec(String vmId, String vmName, String osTypeId, long memory, boolean forceOverwrite,
Set<StorageController> controllers, CleanupMode cleanupMode) {
this.vmId = checkNotNull(vmId, "vmId"); this.vmId = checkNotNull(vmId, "vmId");
this.vmName = checkNotNull(vmName, "vmName"); this.vmName = checkNotNull(vmName, "vmName");
this.osTypeId = checkNotNull(osTypeId, "osTypeId"); this.osTypeId = checkNotNull(osTypeId, "osTypeId");
@ -141,16 +142,14 @@ public class VmSpec {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
return true;
if (o instanceof VmSpec) { if (o instanceof VmSpec) {
VmSpec other = (VmSpec) o; VmSpec other = (VmSpec) o;
return Objects.equal(vmId, other.vmId) && return Objects.equal(vmId, other.vmId) && Objects.equal(vmName, other.vmName)
Objects.equal(vmName, other.vmName) && && Objects.equal(osTypeId, other.osTypeId) && Objects.equal(memory, other.memory)
Objects.equal(osTypeId, other.osTypeId) && && Objects.equal(forceOverwrite, other.forceOverwrite)
Objects.equal(memory, other.memory) && && Objects.equal(controllers, other.controllers) && Objects.equal(cleanupMode, other.cleanupMode);
Objects.equal(forceOverwrite, other.forceOverwrite) &&
Objects.equal(controllers, other.controllers) &&
Objects.equal(cleanupMode, other.cleanupMode);
} }
return false; return false;
} }
@ -162,14 +161,8 @@ public class VmSpec {
@Override @Override
public String toString() { public String toString() {
return "VmSpecification{" + return "VmSpecification{" + "vmName='" + vmName + '\'' + ", osTypeId='" + osTypeId + '\'' + ", memory='" + memory
"vmName='" + vmName + '\'' + + '\'' + ", vmId='" + vmId + '\'' + ", forceOverwrite=" + forceOverwrite + ", controllers="
", osTypeId='" + osTypeId + '\'' + + controllers + ", cleanupMode=" + cleanupMode + '}';
", memory='" + memory + '\'' +
", vmId='" + vmId + '\'' +
", forceOverwrite=" + forceOverwrite +
", controllers=" + controllers +
", cleanupMode=" + cleanupMode +
'}';
} }
} }

View File

@ -46,13 +46,12 @@ import com.google.common.base.Supplier;
import com.google.inject.Inject; import com.google.inject.Inject;
/** /**
* CloneAndRegisterMachineFromIMachineIfNotAlreadyExists will take care of the * CloneAndRegisterMachineFromIMachineIfNotAlreadyExists will take care of the followings: - cloning
* followings: - cloning the master - register the clone machine - * the master - register the clone machine -
* *
* @author Andrea Turli * @author Andrea Turli
*/ */
public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Function<CloneSpec, IMachine> {
Function<CloneSpec, IMachine> {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
@ -63,10 +62,8 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements
private final MachineUtils machineUtils; private final MachineUtils machineUtils;
@Inject @Inject
public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists( public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(Supplier<VirtualBoxManager> manager,
Supplier<VirtualBoxManager> manager, @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, MachineUtils machineUtils) {
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir,
MachineUtils machineUtils) {
this.manager = manager; this.manager = manager;
this.workingDir = workingDir; this.workingDir = workingDir;
this.machineUtils = machineUtils; this.machineUtils = machineUtils;
@ -77,8 +74,7 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements
VmSpec vmSpec = cloneSpec.getVmSpec(); VmSpec vmSpec = cloneSpec.getVmSpec();
try { try {
manager.get().getVBox().findMachine(vmSpec.getVmName()); manager.get().getVBox().findMachine(vmSpec.getVmName());
throw new IllegalStateException("Machine " + vmSpec.getVmName() throw new IllegalStateException("Machine " + vmSpec.getVmName() + " is already registered.");
+ " is already registered.");
} catch (VBoxException e) { } catch (VBoxException e) {
if (machineNotFoundException(e)) if (machineNotFoundException(e))
return cloneMachine(cloneSpec); return cloneMachine(cloneSpec);
@ -88,10 +84,8 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements
} }
private boolean machineNotFoundException(VBoxException e) { private boolean machineNotFoundException(VBoxException e) {
return e.getMessage().contains( return e.getMessage().contains("VirtualBox error: Could not find a registered machine named ")
"VirtualBox error: Could not find a registered machine named ") || e.getMessage().contains("Could not find a registered machine with UUID {");
|| e.getMessage().contains(
"Could not find a registered machine with UUID {");
} }
private IMachine cloneMachine(CloneSpec cloneSpec) { private IMachine cloneMachine(CloneSpec cloneSpec) {
@ -99,25 +93,22 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements
NetworkSpec networkSpec = cloneSpec.getNetworkSpec(); NetworkSpec networkSpec = cloneSpec.getNetworkSpec();
boolean isLinkedClone = cloneSpec.isLinked(); boolean isLinkedClone = cloneSpec.isLinked();
IMachine master = cloneSpec.getMaster(); IMachine master = cloneSpec.getMaster();
String settingsFile = manager.get().getVBox() String settingsFile = manager.get().getVBox().composeMachineFilename(vmSpec.getVmName(), workingDir);
.composeMachineFilename(vmSpec.getVmName(), workingDir);
IMachine clonedMachine = manager IMachine clonedMachine = manager
.get() .get()
.getVBox() .getVBox()
.createMachine(settingsFile, vmSpec.getVmName(), .createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(), vmSpec.getVmId(),
vmSpec.getOsTypeId(), vmSpec.getVmId(),
vmSpec.isForceOverwrite()); vmSpec.isForceOverwrite());
List<CloneOptions> options = new ArrayList<CloneOptions>(); List<CloneOptions> options = new ArrayList<CloneOptions>();
if (isLinkedClone) if (isLinkedClone)
options.add(CloneOptions.Link); options.add(CloneOptions.Link);
// TODO snapshot name // TODO snapshot name
ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached( ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached(manager, "snapshotName", "snapshotDesc")
manager, "snapshotName", "snapshotDesc").apply(master); .apply(master);
// clone // clone
IProgress progress = currentSnapshot.getMachine().cloneTo( IProgress progress = currentSnapshot.getMachine().cloneTo(clonedMachine, CloneMode.MachineState, options);
clonedMachine, CloneMode.MachineState, options);
progress.waitForCompletion(-1); progress.waitForCompletion(-1);
logger.debug("clone done"); logger.debug("clone done");

View File

@ -143,7 +143,8 @@ public class CreateAndInstallVm implements Function<MasterSpec, IMachine> {
} }
/** /**
* ensureMachineHasPowerDown needs to have this delay just to ensure that the machine is completely powered off * ensureMachineHasPowerDown needs to have this delay just to ensure that the machine is
* completely powered off
* *
* @param vmName * @param vmName
*/ */
@ -159,10 +160,11 @@ public class CreateAndInstallVm implements Function<MasterSpec, IMachine> {
} }
}); });
} catch (RuntimeException e) { } catch (RuntimeException e) {
// sometimes the machine might be powered of between the while test and the call to lockSessionOnMachineAndApply // sometimes the machine might be powered of between the while test and the call to
if (e.getMessage().contains("Invalid machine state: PoweredOff")){ // lockSessionOnMachineAndApply
if (e.getMessage().contains("Invalid machine state: PoweredOff")) {
return; return;
} else if(e.getMessage().contains("VirtualBox error: The object is not ready")){ } else if (e.getMessage().contains("VirtualBox error: The object is not ready")) {
continue; continue;
} else { } else {
throw e; throw e;

View File

@ -70,8 +70,8 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
private final String workingDir; private final String workingDir;
@Inject @Inject
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, MachineUtils machineUtils, public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Supplier<VirtualBoxManager> manager,
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir) { MachineUtils machineUtils, @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir) {
this.manager = manager; this.manager = manager;
this.machineUtils = machineUtils; this.machineUtils = machineUtils;
this.workingDir = workingDir; this.workingDir = workingDir;
@ -132,22 +132,21 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
Set<IsoImage> dvds = controller.getIsoImages(); Set<IsoImage> dvds = controller.getIsoImages();
for (IsoImage dvd : dvds) { for (IsoImage dvd : dvds) {
String dvdSource = dvd.getSourcePath(); String dvdSource = dvd.getSourcePath();
final IMedium dvdMedium = manager.get().getVBox().openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly, final IMedium dvdMedium = manager.get().getVBox()
vmSpecification.isForceOverwrite()); .openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly, vmSpecification.isForceOverwrite());
ensureMachineDevicesAttached(vmName, dvdMedium, dvd.getDeviceDetails(), controller.getName()); ensureMachineDevicesAttached(vmName, dvdMedium, dvd.getDeviceDetails(), controller.getName());
} }
} }
private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails, private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails,
String controllerName) { String controllerName) {
machineUtils.writeLockMachineAndApply(vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium, machineUtils.writeLockMachineAndApply(vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails,
controllerName)); medium, controllerName));
} }
private String missingIDEControllersMessage(VmSpec vmSpecification) { private String missingIDEControllersMessage(VmSpec vmSpecification) {
return String return String
.format( .format("First controller is not an IDE controller. Please verify that the VM spec is a correct master node: %s",
"First controller is not an IDE controller. Please verify that the VM spec is a correct master node: %s",
vmSpecification); vmSpecification);
} }
@ -171,7 +170,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
} }
public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) { public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) {
machineUtils.writeLockMachineAndApply(vmName, new AddIDEControllerIfNotExists(checkNotNull( machineUtils.writeLockMachineAndApply(vmName,
storageController, "storageController"))); new AddIDEControllerIfNotExists(checkNotNull(storageController, "storageController")));
} }
} }

View File

@ -66,8 +66,8 @@ public class IMachineToSshClient implements Function<IMachine, SshClient> {
// TODO: we need a way to align the default login credentials from the iso with the // TODO: we need a way to align the default login credentials from the iso with the
// vmspec // vmspec
if ("1".equals(protocolNumber) && "22".equals(targetPort)) { if ("1".equals(protocolNumber) && "22".equals(targetPort)) {
client = sshClientFactory.create(new IPSocket(hostAddress, Integer.parseInt(inboundPort)), client = sshClientFactory.create(new IPSocket(hostAddress, Integer.parseInt(inboundPort)), LoginCredentials
LoginCredentials.builder().user("toor").password("password").authenticateSudo(true).build()); .builder().user("toor").password("password").authenticateSudo(true).build());
} }
} }
checkNotNull(client); checkNotNull(client);

View File

@ -58,13 +58,10 @@ public class IMachineToVmSpec implements Function<IMachine, VmSpec> {
// TODO some parameters are predefined cause the IMachine doesn't have the // TODO some parameters are predefined cause the IMachine doesn't have the
// concept i.e.: cleanUpMode // concept i.e.: cleanUpMode
org.jclouds.virtualbox.domain.VmSpec.Builder vmSpecBuilder = VmSpec org.jclouds.virtualbox.domain.VmSpec.Builder vmSpecBuilder = VmSpec.builder();
.builder();
vmSpecBuilder.id(machine.getId()).name(machine.getName()) vmSpecBuilder.id(machine.getId()).name(machine.getName()).memoryMB(machine.getMemorySize().intValue())
.memoryMB(machine.getMemorySize().intValue()) .osTypeId(machine.getOSTypeId()).forceOverwrite(true).cleanUpMode(CleanupMode.Full);
.osTypeId(machine.getOSTypeId()).forceOverwrite(true)
.cleanUpMode(CleanupMode.Full);
for (StorageController storageController : controllers) { for (StorageController storageController : controllers) {
vmSpecBuilder.controller(storageController); vmSpecBuilder.controller(storageController);
@ -76,28 +73,23 @@ public class IMachineToVmSpec implements Function<IMachine, VmSpec> {
private List<StorageController> buildControllers(IMachine machine) { private List<StorageController> buildControllers(IMachine machine) {
List<StorageController> controllers = Lists.newArrayList(); List<StorageController> controllers = Lists.newArrayList();
for (IStorageController iStorageController : machine for (IStorageController iStorageController : machine.getStorageControllers()) {
.getStorageControllers()) {
Builder storageControlleBuiler = StorageController.builder(); Builder storageControlleBuiler = StorageController.builder();
for (IMediumAttachment iMediumAttachment : machine for (IMediumAttachment iMediumAttachment : machine.getMediumAttachmentsOfController(iStorageController
.getMediumAttachmentsOfController(iStorageController.getName())) { .getName())) {
IMedium iMedium = iMediumAttachment.getMedium(); IMedium iMedium = iMediumAttachment.getMedium();
if (iMedium.getDeviceType().equals(DeviceType.HardDisk)) { if (iMedium.getDeviceType().equals(DeviceType.HardDisk)) {
storageControlleBuiler.attachHardDisk(HardDisk.builder() storageControlleBuiler.attachHardDisk(HardDisk.builder().diskpath(iMedium.getLocation())
.diskpath(iMedium.getLocation()).autoDelete(true) .autoDelete(true).controllerPort(iMediumAttachment.getPort())
.controllerPort(iMediumAttachment.getPort()) .deviceSlot(iMediumAttachment.getDevice().intValue()).build());
.deviceSlot(iMediumAttachment.getDevice().intValue())
.build());
} else if (iMedium.getDeviceType().equals(DeviceType.DVD)) { } else if (iMedium.getDeviceType().equals(DeviceType.DVD)) {
storageControlleBuiler.attachISO(iMediumAttachment.getPort(), storageControlleBuiler.attachISO(iMediumAttachment.getPort(), iMediumAttachment.getDevice().intValue(),
iMediumAttachment.getDevice().intValue(),
iMedium.getLocation()); iMedium.getLocation());
} }
} }
controllers.add(storageControlleBuiler controllers.add(storageControlleBuiler.name(iStorageController.getName()).bus(iStorageController.getBus())
.name(iStorageController.getName()) .build());
.bus(iStorageController.getBus()).build());
} }
return controllers; return controllers;
} }

View File

@ -123,7 +123,8 @@ public class MastersCache extends AbstractLoadingCache<Image, Master> {
String vmName = VIRTUALBOX_IMAGE_PREFIX + yamlImage.id; String vmName = VIRTUALBOX_IMAGE_PREFIX + yamlImage.id;
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true).controllerPort(0).deviceSlot(1).build(); HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true).controllerPort(0).deviceSlot(1)
.build();
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE) StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE)
.attachISO(0, 0, localIsoUrl).attachHardDisk(hardDisk).attachISO(1, 1, guestAdditionsIso).build(); .attachISO(0, 0, localIsoUrl).attachHardDisk(hardDisk).attachISO(1, 1, guestAdditionsIso).build();
@ -142,10 +143,9 @@ public class MastersCache extends AbstractLoadingCache<Image, Master> {
MasterSpec masterSpec = MasterSpec MasterSpec masterSpec = MasterSpec
.builder() .builder()
.vm(vmSpecification) .vm(vmSpecification)
.iso( .iso(IsoSpec.builder().sourcePath(localIsoUrl)
IsoSpec.builder().sourcePath(localIsoUrl) .installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName()))
.installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName())).build()) .build()).network(networkSpec).build();
.network(networkSpec).build();
IMachine masterMachine; IMachine masterMachine;
@ -156,8 +156,7 @@ public class MastersCache extends AbstractLoadingCache<Image, Master> {
if (machineNotFoundException(e)) { if (machineNotFoundException(e)) {
// create the master machine if it can't be found // create the master machine if it can't be found
masterMachine = masterCreatorAndInstaller.apply(masterSpec); masterMachine = masterCreatorAndInstaller.apply(masterSpec);
} } else {
else {
throw e; throw e;
} }
} }

View File

@ -52,7 +52,8 @@ public class NodeCreator implements Function<NodeSpec, NodeAndInitialCredentials
private final Function<CloneSpec, IMachine> cloner; private final Function<CloneSpec, IMachine> cloner;
@Inject @Inject
public NodeCreator(Supplier<VirtualBoxManager> manager, Function<CloneSpec, IMachine> cloner, MachineUtils machineUtils) { public NodeCreator(Supplier<VirtualBoxManager> manager, Function<CloneSpec, IMachine> cloner,
MachineUtils machineUtils) {
this.manager = manager; this.manager = manager;
this.cloner = cloner; this.cloner = cloner;
} }

View File

@ -82,8 +82,8 @@ public class MachineUtils {
} }
/** /**
* Locks the machine and executes the given function using the machine matching the given id. Since the machine is * Locks the machine and executes the given function using the machine matching the given id.
* locked it is possible to perform some modifications to the IMachine. * Since the machine is locked it is possible to perform some modifications to the IMachine.
* <p/> * <p/>
* Unlocks the machine before returning. * Unlocks the machine before returning.
* *
@ -110,8 +110,8 @@ public class MachineUtils {
} }
/** /**
* Locks the machine and executes the given function using the current session. Since the machine is locked it is * Locks the machine and executes the given function using the current session. Since the machine
* possible to perform some modifications to the IMachine. * is locked it is possible to perform some modifications to the IMachine.
* <p/> * <p/>
* Unlocks the machine before returning. * Unlocks the machine before returning.
* *
@ -132,8 +132,8 @@ public class MachineUtils {
session.unlockMachine(); session.unlockMachine();
} }
} catch (VBoxException e) { } catch (VBoxException e) {
throw new RuntimeException(String.format("error applying %s to %s with %s lock: %s", function, machineId, type, throw new RuntimeException(String.format("error applying %s to %s with %s lock: %s", function, machineId,
e.getMessage()), e); type, e.getMessage()), e);
} }
} }
@ -144,17 +144,19 @@ public class MachineUtils {
private void unlockMachine(final String machineId) { private void unlockMachine(final String machineId) {
IMachine immutableMachine = manager.get().getVBox().findMachine(machineId); IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
if (immutableMachine.getSessionState().equals(SessionState.Locked)) { if (immutableMachine.getSessionState().equals(SessionState.Locked)) {
Statement kill = newStatementList(call("default"), findPid(immutableMachine.getSessionPid().toString()), kill()); Statement kill = newStatementList(call("default"), findPid(immutableMachine.getSessionPid().toString()),
kill());
scriptRunner.create(host.get(), kill, runAsRoot(false).wrapInInitScript(false)).init().call(); scriptRunner.create(host.get(), kill, runAsRoot(false).wrapInInitScript(false)).init().call();
} }
} }
/** /**
* Unlocks the machine and executes the given function using the machine matching the given id. Since the machine is * Unlocks the machine and executes the given function using the machine matching the given id.
* unlocked it is possible to delete the IMachine. * Since the machine is unlocked it is possible to delete the IMachine.
* <p/> * <p/>
* <p/> * <p/>
* <h3>Note!</h3> Currently, this can only unlock the machine, if the lock was created in the current session. * <h3>Note!</h3> Currently, this can only unlock the machine, if the lock was created in the
* current session.
* *
* @param machineId * @param machineId
* the id of the machine * the id of the machine
@ -170,13 +172,14 @@ public class MachineUtils {
return function.apply(immutableMachine); return function.apply(immutableMachine);
} catch (VBoxException e) { } catch (VBoxException e) {
throw new RuntimeException(String.format("error applying %s to %s: %s", function, machineId, e.getMessage()), e); throw new RuntimeException(String.format("error applying %s to %s: %s", function, machineId, e.getMessage()),
e);
} }
} }
/** /**
* Unlocks the machine and executes the given function, if the machine is registered. Since the machine is unlocked it * Unlocks the machine and executes the given function, if the machine is registered. Since the
* is possible to delete the machine. * machine is unlocked it is possible to delete the machine.
* <p/> * <p/>
* *
* @param machineId * @param machineId

View File

@ -32,7 +32,6 @@ import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials; import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate; import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;
import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
@ -97,8 +96,7 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
} }
protected void ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults() { protected void ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults() {
Properties defaultVBoxProperties = new VirtualBoxPropertiesBuilder() Properties defaultVBoxProperties = new VirtualBoxPropertiesBuilder().build();
.build();
if (!System.getProperties().containsKey("test." + provider + ".identity")) if (!System.getProperties().containsKey("test." + provider + ".identity"))
System.setProperty("test." + provider + ".identity", System.setProperty("test." + provider + ".identity",
defaultVBoxProperties.getProperty(Constants.PROPERTY_IDENTITY)); defaultVBoxProperties.getProperty(Constants.PROPERTY_IDENTITY));
@ -109,43 +107,32 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
setupCredentials(); setupCredentials();
Properties overrides = new VirtualBoxPropertiesBuilder(setupProperties()).build(); Properties overrides = new VirtualBoxPropertiesBuilder(setupProperties()).build();
CacheNodeStoreModule hostModule = new CacheNodeStoreModule( CacheNodeStoreModule hostModule = new CacheNodeStoreModule(ImmutableMap.of(
ImmutableMap.of(
"host", "host",
Node.builder() Node.builder().id("host").name("host installing virtualbox").hostname("localhost")
.id("host") .osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name"))
.name("host installing virtualbox") .osVersion(System.getProperty("os.version")).group("ssh")
.hostname("localhost")
.osFamily(OsFamily.LINUX.toString())
.osDescription(System.getProperty("os.name"))
.osVersion(System.getProperty("os.version"))
.group("ssh")
.username(System.getProperty("user.name")) .username(System.getProperty("user.name"))
.credentialUrl( .credentialUrl(URI.create("file://" + System.getProperty("user.home") + "/.ssh/id_rsa"))
URI.create("file://" .build()));
+ System.getProperty("user.home")
+ "/.ssh/id_rsa")).build()));
context = new ComputeServiceContextFactory().createContext(provider, context = new ComputeServiceContextFactory().createContext(provider, identity, credential,
identity, credential, ImmutableSet.<Module>of( ImmutableSet.<Module> of(new SLF4JLoggingModule(), new SshjSshClientModule(), hostModule), overrides);
new SLF4JLoggingModule(), new SshjSshClientModule(),
hostModule), overrides);
Function<String, String> configProperties = context.utils().injector() Function<String, String> configProperties = context.utils().injector()
.getInstance(ValueOfConfigurationKeyOrNull.class); .getInstance(ValueOfConfigurationKeyOrNull.class);
imageId = "ubuntu-11.04-server-i386"; imageId = "ubuntu-11.04-server-i386";
workingDir = configProperties workingDir = configProperties.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR); isosDir = workingDir + File.separator + "isos";
isosDir = workingDir+File.separator+"isos";
File isosDirFile = new File(isosDir); File isosDirFile = new File(isosDir);
if(!isosDirFile.exists()){ if (!isosDirFile.exists()) {
isosDirFile.mkdirs(); isosDirFile.mkdirs();
} }
host = context.utils().injector() host = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<NodeMetadata>>() {
.getInstance(Key.get(new TypeLiteral<Supplier<NodeMetadata>>() {
})); }));
// this will eagerly startup Jetty, note the impl will shut itself down // this will eagerly startup Jetty, note the impl will shut itself down
preconfigurationUri = context.utils().injector().getInstance(Key.get(new TypeLiteral<LoadingCache<IsoSpec, URI>>() { preconfigurationUri = context.utils().injector()
.getInstance(Key.get(new TypeLiteral<LoadingCache<IsoSpec, URI>>() {
}, Preconfiguration.class)); }, Preconfiguration.class));
// this will eagerly startup Jetty, note the impl will shut itself down // this will eagerly startup Jetty, note the impl will shut itself down
@ -156,18 +143,14 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
machineUtils = context.utils().injector().getInstance(MachineUtils.class); machineUtils = context.utils().injector().getInstance(MachineUtils.class);
hostVersion = Iterables.get( hostVersion = Iterables.get(Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0);
Splitter.on('r').split(
context.getProviderSpecificContext().getBuildVersion()), 0);
adminDisk = workingDir + "/testadmin.vdi"; adminDisk = workingDir + "/testadmin.vdi";
operatingSystemIso = String.format("%s/%s.iso", isosDir, imageId); operatingSystemIso = String.format("%s/%s.iso", isosDir, imageId);
guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", isosDir, hostVersion);
isosDir, hostVersion);
} }
protected void undoVm(VmSpec vmSpecification) { protected void undoVm(VmSpec vmSpecification) {
machineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered( machineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered(vmSpecification.getVmId(),
vmSpecification.getVmId(),
new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification)); new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
} }
@ -183,10 +166,11 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
} }
}); });
} catch (RuntimeException e) { } catch (RuntimeException e) {
// sometimes the machine might be powered of between the while test and the call to lockSessionOnMachineAndApply // sometimes the machine might be powered of between the while test and the call to
if (e.getMessage().contains("Invalid machine state: PoweredOff")){ // lockSessionOnMachineAndApply
if (e.getMessage().contains("Invalid machine state: PoweredOff")) {
return; return;
} else if(e.getMessage().contains("VirtualBox error: The object is not ready")){ } else if (e.getMessage().contains("VirtualBox error: The object is not ready")) {
continue; continue;
} else { } else {
throw e; throw e;

View File

@ -101,7 +101,7 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien
@Override @Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (machine != null) if (machine != null)
// adapter.destroyNode(machine.getNodeId() + ""); // adapter.destroyNode(machine.getNodeId() + "");
super.tearDown(); super.tearDown();
} }
} }

View File

@ -20,16 +20,12 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.transform;
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertEquals;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.Map; import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -57,18 +53,15 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.NetworkAttachmentType; import org.virtualbox_4_1.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.jaxws.MachineState;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.inject.Guice; import com.google.inject.Guice;
@ -81,8 +74,8 @@ import com.google.inject.Injector;
public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest { public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() { Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.createInjector(new GsonModule()).getInstance(Json.class)); .getInstance(Json.class));
private VmSpec vmSpecification; private VmSpec vmSpecification;
private MasterSpec masterSpec; private MasterSpec masterSpec;
@ -96,31 +89,24 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
public void setupClient() { public void setupClient() {
super.setupClient(); super.setupClient();
this.vmName = VIRTUALBOX_IMAGE_PREFIX this.vmName = VIRTUALBOX_IMAGE_PREFIX
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass() + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName());
.getSimpleName());
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk) HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true).controllerPort(0).deviceSlot(1)
.autoDelete(true).controllerPort(0).deviceSlot(1).build(); .build();
StorageController ideController = StorageController.builder() StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE)
.name("IDE Controller").bus(StorageBus.IDE) .attachISO(0, 0, operatingSystemIso).attachHardDisk(hardDisk).attachISO(1, 1, guestAdditionsIso).build();
.attachISO(0, 0, operatingSystemIso).attachHardDisk(hardDisk) vmSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).osTypeId("").controller(ideController)
.attachISO(1, 1, guestAdditionsIso).build();
vmSpecification = VmSpec.builder().id(vmName).name(vmName)
.memoryMB(512).osTypeId("").controller(ideController)
.forceOverwrite(true).cleanUpMode(CleanupMode.Full).build(); .forceOverwrite(true).cleanUpMode(CleanupMode.Full).build();
injector = context.utils().injector(); injector = context.utils().injector();
Function<String, String> configProperties = injector Function<String, String> configProperties = injector.getInstance(ValueOfConfigurationKeyOrNull.class);
.getInstance(ValueOfConfigurationKeyOrNull.class);
NetworkAdapter networkAdapter = NetworkAdapter.builder() NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT)
.networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); .tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter)
.builder().addNetworkAdapter(networkAdapter).build(); .build();
NetworkSpec networkSpec = NetworkSpec.builder() NetworkSpec networkSpec = NetworkSpec.builder().addNIC(0L, networkInterfaceCard).build();
.addNIC(0L, networkInterfaceCard).build();
masterSpec = MasterSpec masterSpec = MasterSpec
.builder() .builder()
@ -129,11 +115,8 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
.builder() .builder()
.sourcePath(operatingSystemIso) .sourcePath(operatingSystemIso)
.installationScript( .installationScript(
configProperties.apply( configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace("HOSTNAME",
VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) vmSpecification.getVmName())).build()).network(networkSpec).build();
.replace("HOSTNAME",
vmSpecification.getVmName()))
.build()).network(networkSpec).build();
undoVm(vmSpecification); undoVm(vmSpecification);
} }
@ -143,7 +126,7 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
IMachine imageMachine = getVmWithGuestAdditionsInstalled(); IMachine imageMachine = getVmWithGuestAdditionsInstalled();
IMachineToImage iMachineToImage = new IMachineToImage(manager, map); IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
Image newImage = iMachineToImage.apply(imageMachine); Image newImage = iMachineToImage.apply(imageMachine);
assertEquals(vmName,newImage.getName()); assertEquals(vmName, newImage.getName());
} }
@Test @Test
@ -151,33 +134,22 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
try { try {
IMachine machine = getVmWithGuestAdditionsInstalled(); IMachine machine = getVmWithGuestAdditionsInstalled();
machineUtils.applyForMachine(machine.getName(), machineUtils.applyForMachine(machine.getName(), new LaunchMachineIfNotAlreadyRunning(manager.get(),
new LaunchMachineIfNotAlreadyRunning(manager.get(),
ExecutionType.GUI, "")); ExecutionType.GUI, ""));
sshClientForIMachine = injector sshClientForIMachine = injector.getInstance(IMachineToSshClient.class);
.getInstance(IMachineToSshClient.class);
SshClient client = sshClientForIMachine.apply(machine); SshClient client = sshClientForIMachine.apply(machine);
sshResponds = injector.getInstance(SshResponds.class); sshResponds = injector.getInstance(SshResponds.class);
checkState(sshResponds.apply(client), checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh",
"timed out waiting for guest %s to be accessible via ssh",
machine.getName()); machine.getName());
assertTrue(machineUtils.lockSessionOnMachineAndApply( assertTrue(machineUtils.lockSessionOnMachineAndApply(machine.getName(), LockType.Shared,
machine.getName(), LockType.Shared,
new Function<ISession, Boolean>() { new Function<ISession, Boolean>() {
@Override @Override
public Boolean apply(ISession session) { public Boolean apply(ISession session) {
String vboxVersion = Iterables String vboxVersion = Iterables.get(
.get(Splitter Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0);
.on('r') return session.getMachine().getGuestPropertyValue("/VirtualBox/GuestAdd/Version")
.split(context
.getProviderSpecificContext()
.getBuildVersion()), 0);
return session
.getMachine()
.getGuestPropertyValue(
"/VirtualBox/GuestAdd/Version")
.equals(vboxVersion); .equals(vboxVersion);
} }
})); }));
@ -201,12 +173,10 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
private IMachine getVmWithGuestAdditionsInstalled() { private IMachine getVmWithGuestAdditionsInstalled() {
try { try {
Injector injector = context.utils().injector(); Injector injector = context.utils().injector();
return injector.getInstance(CreateAndInstallVm.class).apply( return injector.getInstance(CreateAndInstallVm.class).apply(masterSpec);
masterSpec);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// already created // already created
return manager.get().getVBox() return manager.get().getVBox().findMachine(masterSpec.getVmSpec().getVmId());
.findMachine(masterSpec.getVmSpec().getVmId());
} }
} }