Replaced Supplier with LoadingCache for @Preconfiguration. Also removed preconfiguration from IsoSpec.

This commit is contained in:
Mattias Holmqvist 2012-01-19 23:03:51 +01:00
parent 55975af60d
commit f9a6e642c0
18 changed files with 413 additions and 501 deletions

View File

@ -19,24 +19,22 @@
package org.jclouds.virtualbox.config;
import java.io.InputStream;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.inject.Singleton;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.*;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
import org.eclipse.jetty.server.Server;
import org.jclouds.byon.Node;
import org.jclouds.byon.functions.NodeToNodeMetadata;
import org.jclouds.byon.suppliers.SupplyFromProviderURIOrNodesProperty;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.*;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.domain.Location;
import org.jclouds.functions.IdentityFunction;
@ -46,6 +44,7 @@ import org.jclouds.ssh.SshClient;
import org.jclouds.virtualbox.Preconfiguration;
import org.jclouds.virtualbox.compute.VirtualBoxComputeServiceAdapter;
import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.functions.IMachineToHardware;
import org.jclouds.virtualbox.functions.IMachineToImage;
import org.jclouds.virtualbox.functions.IMachineToNodeMetadata;
@ -58,30 +57,27 @@ import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.MachineState;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.InputStream;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL;
/**
* @author Mattias Holmqvist, Andrea Turli
*/
@SuppressWarnings("unchecked")
public class VirtualBoxComputeServiceContextModule extends
ComputeServiceAdapterContextModule<Supplier, Supplier, IMachine, IMachine, Image, Location> {
ComputeServiceAdapterContextModule<Supplier, Supplier, IMachine, IMachine, Image, Location> {
public VirtualBoxComputeServiceContextModule() {
super(Supplier.class, Supplier.class);
}
@SuppressWarnings( { "unchecked", "rawtypes" })
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
protected void configure() {
super.configure();
@ -99,7 +95,10 @@ public class VirtualBoxComputeServiceContextModule extends
}).to(IMachineToImage.class);
bind(new TypeLiteral<Supplier<Location>>() {
}).to(OnlyLocationOrFirstZone.class);
bind(new TypeLiteral<CacheLoader<IsoSpec, URI>>() {
}).to((Class) StartJettyIfNotAlreadyRunning.class);
bind(new TypeLiteral<Supplier<VirtualBoxManager>>() {
}).to((Class) StartVBoxIfNotAlreadyRunning.class);
// for byon
bind(new TypeLiteral<Function<URI, InputStream>>() {
}).to(SupplyFromProviderURIOrNodesProperty.class);
@ -115,20 +114,32 @@ public class VirtualBoxComputeServiceContextModule extends
@Provides
@Singleton
@Preconfiguration
protected Supplier<URI> preconfiguration(javax.inject.Provider<StartJettyIfNotAlreadyRunning> lazyGet) {
return lazyGet.get();
protected LoadingCache<IsoSpec, URI> preconfiguration(CacheLoader<IsoSpec, URI> cacheLoader) {
return CacheBuilder.newBuilder().build(cacheLoader);
}
@Provides
@Singleton
protected Function<Supplier<NodeMetadata>, VirtualBoxManager> provideVBox(Supplier<NodeMetadata> host) {
return new Function<Supplier<NodeMetadata>, VirtualBoxManager>(){
protected Server providesJettyServer(@Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
return new Server(URI.create(preconfigurationUrl).getPort());
}
@Provides
@Singleton
protected Function<Supplier<NodeMetadata>, VirtualBoxManager> provideVBox() {
return new Function<Supplier<NodeMetadata>, VirtualBoxManager>() {
@Override
public VirtualBoxManager apply(Supplier<NodeMetadata> arg0) {
return VirtualBoxManager.createInstance(arg0.get().getId());
public VirtualBoxManager apply(Supplier<NodeMetadata> nodeSupplier) {
return VirtualBoxManager.createInstance(nodeSupplier.get().getId());
}
@Override
public String toString() {
return "createInstanceByNodeId()";
}
};
}
@ -138,12 +149,6 @@ public class VirtualBoxComputeServiceContextModule extends
return in;
}
@Provides
@Singleton
protected Supplier<VirtualBoxManager> vbox(javax.inject.Provider<StartVBoxIfNotAlreadyRunning> lazyGet) {
return lazyGet.get();
}
@Provides
@Singleton
protected Predicate<SshClient> sshResponds(SshResponds sshResponds, Timeouts timeouts) {
@ -158,7 +163,7 @@ public class VirtualBoxComputeServiceContextModule extends
@Provides
@Singleton
protected Supplier<NodeMetadata> host(Supplier<LoadingCache<String, Node>> nodes, NodeToNodeMetadata converter)
throws ExecutionException {
throws ExecutionException {
return Suppliers.compose(Functions.compose(converter, new Function<LoadingCache<String, Node>, Node>() {
@Override
@ -170,22 +175,22 @@ public class VirtualBoxComputeServiceContextModule extends
@VisibleForTesting
public static final Map<MachineState, NodeState> machineToNodeState = ImmutableMap
.<MachineState, NodeState> builder().put(MachineState.Running, NodeState.RUNNING).put(
MachineState.PoweredOff, NodeState.SUSPENDED)
.put(MachineState.DeletingSnapshot, NodeState.PENDING).put(MachineState.DeletingSnapshotOnline,
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.Stopping, NodeState.PENDING).put(MachineState.Restoring,
NodeState.PENDING)
// TODO What to map these states to?
.put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING).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)
.<MachineState, NodeState>builder().put(MachineState.Running, NodeState.RUNNING).put(
MachineState.PoweredOff, NodeState.SUSPENDED)
.put(MachineState.DeletingSnapshot, NodeState.PENDING).put(MachineState.DeletingSnapshotOnline,
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.Stopping, NodeState.PENDING).put(MachineState.Restoring,
NodeState.PENDING)
// TODO What to map these states to?
.put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING).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.Aborted, NodeState.ERROR).put(MachineState.Stuck, NodeState.ERROR)
.put(MachineState.Null, NodeState.UNRECOGNIZED).build();
.put(MachineState.Null, NodeState.UNRECOGNIZED).build();
}

View File

@ -21,6 +21,7 @@ package org.jclouds.virtualbox.domain;
import com.google.common.base.Objects;
import com.google.common.base.Supplier;
import com.google.common.cache.CacheLoader;
import org.jclouds.virtualbox.Preconfiguration;
import java.net.URI;
@ -34,15 +35,10 @@ public class IsoSpec {
private final String installationKeySequence;
private final String sourcePath;
private final Supplier<URI> preConfigurationUri;
public IsoSpec(String sourcePath, String installationKeySequence, @Preconfiguration Supplier<URI> preConfigurationUri) {
checkNotNull(sourcePath, "sourcePath");
checkNotNull(installationKeySequence, "installationKeySequence");
checkNotNull(preConfigurationUri, "preConfigurationUri");
this.sourcePath = sourcePath;
this.installationKeySequence = installationKeySequence;
this.preConfigurationUri = preConfigurationUri;
public IsoSpec(String sourcePath, String installationKeySequence) {
this.sourcePath = checkNotNull(sourcePath, "sourcePath");
this.installationKeySequence = checkNotNull(installationKeySequence, "installationKeySequence");
}
public static Builder builder() {
@ -60,11 +56,6 @@ public class IsoSpec {
return this;
}
public Builder preConfiguration(Supplier<URI> preConfigurationUri) {
this.preConfigurationUri = preConfigurationUri;
return this;
}
public Builder sourcePath(String sourcePath) {
this.sourcePath = sourcePath;
return this;
@ -72,7 +63,7 @@ public class IsoSpec {
public IsoSpec build() {
return new IsoSpec(sourcePath, installationSequence, preConfigurationUri);
return new IsoSpec(sourcePath, installationSequence);
}
}
@ -80,10 +71,6 @@ public class IsoSpec {
return installationKeySequence;
}
public Supplier<URI> getPreConfigurationUri() {
return preConfigurationUri;
}
public String getSourcePath() {
return sourcePath;
}
@ -94,15 +81,14 @@ public class IsoSpec {
if (o instanceof VmSpec) {
IsoSpec other = (IsoSpec) o;
return Objects.equal(sourcePath, other.sourcePath) &&
Objects.equal(installationKeySequence, other.installationKeySequence) &&
Objects.equal(preConfigurationUri, other.preConfigurationUri);
Objects.equal(installationKeySequence, other.installationKeySequence);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(sourcePath, installationKeySequence, preConfigurationUri);
return Objects.hashCode(sourcePath, installationKeySequence);
}
@Override
@ -110,7 +96,6 @@ public class IsoSpec {
return "IsoSpec{" +
"sourcePath='" + sourcePath + '\'' +
"installationKeySequence='" + installationKeySequence + '\'' +
", preConfigurationUri=" + preConfigurationUri +
'}';
}
}

View File

@ -27,7 +27,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
* A complete specification of a "master" node, including the ISO, networking setup
* and the physical machine specification.
*/
public class IMachineSpec {
public class MasterSpec {
private VmSpec vmSpec;
private IsoSpec isoSpec;
@ -58,13 +58,13 @@ public class IMachineSpec {
return this;
}
public IMachineSpec build() {
return new IMachineSpec(vmSpec, isoSpec, networkSpec);
public MasterSpec build() {
return new MasterSpec(vmSpec, isoSpec, networkSpec);
}
}
public IMachineSpec(VmSpec vmSpec, IsoSpec isoSpec, NetworkSpec networkSpec) {
public MasterSpec(VmSpec vmSpec, IsoSpec isoSpec, NetworkSpec networkSpec) {
checkNotNull(vmSpec, "vmSpec");
checkNotNull(isoSpec, "isoSpec");
checkNotNull(networkSpec, "networkSpec");
@ -89,7 +89,7 @@ public class IMachineSpec {
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof VmSpec) {
IMachineSpec other = (IMachineSpec) o;
MasterSpec other = (MasterSpec) o;
return Objects.equal(vmSpec, other.vmSpec) &&
Objects.equal(isoSpec, other.isoSpec) &&
Objects.equal(networkSpec, other.networkSpec);

View File

@ -35,8 +35,7 @@ public class NetworkSpec {
private final Map<Long, NatAdapter> natNetworkAdapters;
public NetworkSpec(final Map<Long, NatAdapter> natNetworkAdapters) {
checkNotNull(natNetworkAdapters, "natNetworkAdapters");
this.natNetworkAdapters = natNetworkAdapters;
this.natNetworkAdapters = checkNotNull(natNetworkAdapters, "natNetworkAdapters");
}
public static Builder builder() {

View File

@ -40,18 +40,14 @@ public class VmSpec {
private final CleanupMode cleanupMode;
public VmSpec(String vmId, String vmName, String osTypeId, long memory, boolean forceOverwrite, Set<StorageController> controllers, CleanupMode cleanupMode) {
checkNotNull(vmId, "vmId");
checkNotNull(vmName, "vmName");
this.vmId = checkNotNull(vmId, "vmId");
this.vmName = checkNotNull(vmName, "vmName");
this.osTypeId = checkNotNull(osTypeId, "osTypeId");
checkArgument(memory > 0, "memory must be > 0");
checkNotNull(controllers, "controllers");
checkNotNull(cleanupMode, "cleanupMode");
this.vmId = vmId;
this.vmName = vmName;
this.osTypeId = osTypeId;
this.memory = memory;
this.controllers = controllers;
this.controllers = checkNotNull(controllers, "controllers");
this.cleanupMode = checkNotNull(cleanupMode, "cleanupMode");
this.forceOverwrite = forceOverwrite;
this.cleanupMode = cleanupMode;
}
public static Builder builder() {

View File

@ -18,38 +18,34 @@
*/
package org.jclouds.virtualbox.functions;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.transform;
import java.net.URI;
import java.util.List;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.ssh.SshClient;
import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.IMachineSpec;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.IProgress;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.cache.LoadingCache;
import com.google.inject.Inject;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.ssh.SshClient;
import org.jclouds.virtualbox.Preconfiguration;
import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.MasterSpec;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.*;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import java.net.URI;
import java.util.List;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.transform;
@Singleton
public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
public class CreateAndInstallVm implements Function<MasterSpec, IMachine> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
@ -60,6 +56,9 @@ public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
private final Predicate<SshClient> sshResponds;
private final ExecutionType executionType;
private LoadingCache<IsoSpec, URI> preConfiguration;
private final Function<IMachine, SshClient> sshClientForIMachine;
private final MachineUtils machineUtils;
@ -68,29 +67,30 @@ public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
public CreateAndInstallVm(Supplier<VirtualBoxManager> manager,
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
Predicate<SshClient> sshResponds, Function<IMachine, SshClient> sshClientForIMachine,
ExecutionType executionType, MachineUtils machineUtils) {
ExecutionType executionType, MachineUtils machineUtils, @Preconfiguration LoadingCache<IsoSpec, URI> preConfiguration) {
this.manager = manager;
this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
this.sshResponds = sshResponds;
this.sshClientForIMachine = sshClientForIMachine;
this.executionType = executionType;
this.machineUtils = machineUtils;
this.preConfiguration = preConfiguration;
}
@Override
public IMachine apply(IMachineSpec machineSpec) {
VmSpec vmSpec = machineSpec.getVmSpec();
IsoSpec isoSpec = machineSpec.getIsoSpec();
public IMachine apply(MasterSpec masterSpec) {
VmSpec vmSpec = masterSpec.getVmSpec();
IsoSpec isoSpec = masterSpec.getIsoSpec();
String vmName = vmSpec.getVmName();
final IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(machineSpec);
final IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(masterSpec);
// Launch machine and wait for it to come online
ensureMachineIsLaunched(vmName);
URI uri = isoSpec.getPreConfigurationUri().get();
URI uri = preConfiguration.getUnchecked(isoSpec);
String installationKeySequence = isoSpec.getInstallationKeySequence().replace("PRECONFIGURATION_URL",
uri.toASCIIString());
@ -104,9 +104,9 @@ public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
ensureMachineHasPowerDown(vmName);
return vm;
}
private void configureOsInstallationWithKeyboardSequence(String vmName, String installationKeySequence) {
Iterable<List<Integer>> scancodelist =
Iterable<List<Integer>> scancodelist =
transform(Splitter.on(" ").split(installationKeySequence), new StringToKeyCode());
for (List<Integer> scancodes : scancodelist) {
@ -129,4 +129,4 @@ public class CreateAndInstallVm implements Function<IMachineSpec, IMachine> {
machineUtils.applyForMachine(vmName, new LaunchMachineIfNotAlreadyRunning(manager.get(), executionType, ""));
}
}
}

View File

@ -19,46 +19,31 @@
package org.jclouds.virtualbox.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.File;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
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.util.MachineUtils;
import org.virtualbox_4_1.*;
import javax.annotation.Nullable;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.util.Map;
import java.util.Set;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
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;
import org.virtualbox_4_1.IMedium;
import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* @author Mattias Holmqvist
*/
@Singleton
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<IMachineSpec, IMachine> {
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<MasterSpec, IMachine> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
@ -78,7 +63,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
}
@Override
public IMachine apply(@Nullable IMachineSpec launchSpecification) {
public IMachine apply(@Nullable MasterSpec launchSpecification) {
final IVirtualBox vBox = manager.get().getVBox();
String vmName = launchSpecification.getVmSpec().getVmName();
String vmId = launchSpecification.getVmSpec().getVmId();
@ -99,7 +84,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
e.getMessage().contains("Could not find a registered machine with UUID {");
}
private IMachine createMachine(IVirtualBox vBox, IMachineSpec machineSpec) {
private IMachine createMachine(IVirtualBox vBox, MasterSpec machineSpec) {
VmSpec vmSpec = machineSpec.getVmSpec();
String settingsFile = vBox.composeMachineFilename(vmSpec.getVmName(), workingDir);
@ -110,7 +95,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
return newMachine;
}
private void ensureConfiguration(IMachineSpec machineSpec) {
private void ensureConfiguration(MasterSpec machineSpec) {
VmSpec vmSpec = machineSpec.getVmSpec();
NetworkSpec networkSpec = machineSpec.getNetworkSpec();
String vmName = vmSpec.getVmName();
@ -149,7 +134,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails,
String controllerName) {
machineUtils.writeLockMachineAndApply(vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium,
controllerName));
controllerName));
}
private String missingIDEControllersMessage(VmSpec vmSpecification) {
@ -178,13 +163,12 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
machineUtils.writeLockMachineAndApply(vmName, new ApplyMemoryToMachine(memorySize));
}
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId,
NatAdapter natAdapter) {
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, NatAdapter natAdapter) {
machineUtils.writeLockMachineAndApply(vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
}
public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) {
machineUtils.writeLockMachineAndApply(vmName, new AddIDEControllerIfNotExists(checkNotNull(
storageController, "storageController")));
storageController, "storageController")));
}
}

View File

@ -59,7 +59,6 @@ public class IMachineToSshClient implements Function<IMachine, SshClient> {
client = sshClientFactory.create(new IPSocket(hostAddress, Integer.parseInt(inboundPort)),
LoginCredentials.builder().user("toor").password("password").authenticateSudo(true).build());
}
}
return client;
}

View File

@ -19,16 +19,8 @@
package org.jclouds.virtualbox.functions.admin;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import com.google.common.cache.CacheLoader;
import com.google.inject.Singleton;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
@ -36,52 +28,59 @@ import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.virtualbox.Preconfiguration;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.IsoSpec;
import com.google.common.base.Supplier;
import com.google.inject.Singleton;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import java.net.URI;
import static com.google.common.base.Throwables.propagate;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL;
/**
* @author Andrea Turli
*/
@Preconfiguration
@Singleton
public class StartJettyIfNotAlreadyRunning implements Supplier<URI> {
public class StartJettyIfNotAlreadyRunning extends CacheLoader<IsoSpec, URI> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final URI preconfigurationUrl;
private final Server jetty;
private Server jetty;
private final String preconfigurationUrl;
@Inject
public StartJettyIfNotAlreadyRunning(
@Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
this(new Server(URI.create(preconfigurationUrl).getPort()), preconfigurationUrl);
}
public StartJettyIfNotAlreadyRunning(Server jetty,
@Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
this.preconfigurationUrl = URI.create(checkNotNull(preconfigurationUrl, "preconfigurationUrl"));
public StartJettyIfNotAlreadyRunning(@Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl, Server jetty) {
this.preconfigurationUrl = preconfigurationUrl;
this.jetty = jetty;
}
@PostConstruct
public void start() {
@Override
public URI load(IsoSpec isoSpec) throws Exception {
try {
start();
} catch (Exception e) {
logger.error("Could not connect to host providing ISO " + isoSpec, e);
propagate(e);
}
return URI.create(preconfigurationUrl);
}
private void start() {
if (jetty.getState().equals(Server.STARTED)) {
logger.debug("not starting jetty, as existing host is serving %s", preconfigurationUrl);
} else {
logger.debug(">> starting jetty to serve %s", preconfigurationUrl);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "index.html" });
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resource_handler.setResourceBase("");
resourceHandler.setResourceBase("");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
handlers.setHandlers(new Handler[]{resourceHandler, new DefaultHandler()});
jetty.setHandler(handlers);
try {
@ -89,7 +88,7 @@ public class StartJettyIfNotAlreadyRunning implements Supplier<URI> {
} catch (Exception e) {
logger.error(e, "Server jetty could not be started for %s", preconfigurationUrl);
}
logger.debug("<< serving %s", resource_handler.getBaseResource());
logger.debug("<< serving %s", resourceHandler.getBaseResource());
}
}
@ -99,11 +98,8 @@ public class StartJettyIfNotAlreadyRunning implements Supplier<URI> {
try {
jetty.stop();
} catch (Exception e) {
logger.error("Could not stop jetty.", e);
}
}
@Override
public URI get() {
return preconfigurationUrl;
}
}

View File

@ -18,16 +18,9 @@
*/
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 javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import com.google.common.base.Function;
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;
@ -36,20 +29,18 @@ import org.jclouds.logging.Logger;
import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.util.Throwables2;
import org.jclouds.virtualbox.functions.MutableMachine;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.SessionState;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
import org.virtualbox_4_1.*;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.inject.Inject;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
import static org.jclouds.scriptbuilder.domain.Statements.*;
/**
* Utilities for executing functions on a VirtualBox machine.
*
*
* @author Adrian Cole, Mattias Holmqvist, Andrea Turli
*/
@ -78,28 +69,26 @@ public class MachineUtils {
* perform some modifications to the IMachine.
* <p/>
* Unlocks the machine before returning.
*
* @param machineId
* the id of the machine
* @param function
* the function to execute
*
* @param machineId the id of the machine
* @param function the function to execute
* @return the result from applying the function to the machine.
*/
public <T> T writeLockMachineAndApply(final String machineId, final Function<IMachine, T> function) {
return lockSessionOnMachineAndApply(machineId, LockType.Write,
new Function<ISession, T>() {
return lockSessionOnMachineAndApply(machineId, LockType.Write,
new Function<ISession, T>() {
@Override
public T apply(ISession session) {
return function.apply(session.getMachine());
}
@Override
public T apply(ISession session) {
return function.apply(session.getMachine());
}
@Override
public String toString() {
return function.toString();
}
@Override
public String toString() {
return function.toString();
}
});
});
}
/**
@ -108,13 +97,10 @@ public class MachineUtils {
* modifications to the IMachine.
* <p/>
* Unlocks the machine before returning.
*
* @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
*
* @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 <T> T lockSessionOnMachineAndApply(String machineId, LockType type, Function<ISession, T> function) {
@ -127,8 +113,8 @@ public class MachineUtils {
}
} catch (VBoxException e) {
throw new RuntimeException(String.format(
"error applying %s to %s with %s lock: %s", function, machineId,
type, e.getMessage()), e);
"error applying %s to %s with %s lock: %s", function, machineId,
type, e.getMessage()), e);
}
}
@ -140,10 +126,10 @@ public class MachineUtils {
IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
if (immutableMachine.getSessionState().equals(SessionState.Locked)) {
Statement kill = newStatementList(call("default"),
findPid(immutableMachine.getSessionPid().toString()), kill());
findPid(immutableMachine.getSessionPid().toString()), kill());
scriptRunner
.create(host.get(), kill,
runAsRoot(false).wrapInInitScript(false)).init().call();
.create(host.get(), kill,
runAsRoot(false).wrapInInitScript(false)).init().call();
}
}
@ -152,28 +138,25 @@ public class MachineUtils {
* matching the given id. Since the machine is unlocked it is possible to
* delete the IMachine.
* <p/>
*
* <p/>
* <h3>Note!</h3> Currently, this can only unlock the machine, if the lock
* was created in the current session.
*
* @param machineId
* the id of the machine
* @param function
* the function to execute
*
* @param machineId the id of the machine
* @param function the function to execute
* @return the result from applying the function to the machine.
*/
public <T> T unlockMachineAndApply(final String machineId, final Function<IMachine, T> function) {
try {
unlockMachine(machineId);
IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
return function.apply(immutableMachine);
} catch (VBoxException e) {
throw new RuntimeException(String.format(
"error applying %s to %s: %s", function, machineId,
e.getMessage()), e);
"error applying %s to %s: %s", function, machineId,
e.getMessage()), e);
}
}
@ -182,29 +165,26 @@ public class MachineUtils {
* registered. Since the machine is unlocked it is possible to delete the
* machine.
* <p/>
*
* @param machineId
* the id of the machine
* @param function
* the function to execute
*
* @param machineId the id of the machine
* @param function the function to execute
* @return the result from applying the function to the session.
*/
public <T> T unlockMachineAndApplyOrReturnNullIfNotRegistered(String machineId,
Function<IMachine, T> function) {
Function<IMachine, T> function) {
try {
return unlockMachineAndApply(machineId, function);
} catch (RuntimeException e) {
VBoxException vbex = Throwables2.getFirstThrowableOfType(e,
VBoxException.class);
VBoxException.class);
if (vbex != null
&& vbex.getMessage().indexOf("not find a registered") == -1)
&& vbex.getMessage().indexOf("not find a registered") == -1)
throw e;
return null;
}
}
/**
*
* @param machineId
* @param function
* @return
@ -223,5 +203,5 @@ public class MachineUtils {
}
}.apply(immutableMachine);
}
}

View File

@ -19,9 +19,16 @@
package org.jclouds.virtualbox;
import java.net.URI;
import java.util.Properties;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import org.jclouds.Constants;
import org.jclouds.byon.Node;
import org.jclouds.byon.config.CacheNodeStoreModule;
@ -35,6 +42,7 @@ import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
import org.jclouds.virtualbox.util.MachineUtils;
@ -43,19 +51,12 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import java.net.URI;
import java.util.Properties;
/**
* Tests behavior of {@code VirtualBoxClient}
*
*
* @author Adrian Cole
*/
@Test(groups = "live", singleThreaded = true, testName = "BaseVirtualBoxClientLiveTest")
@ -67,7 +68,7 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
protected ComputeServiceContext context;
protected Supplier<VirtualBoxManager> manager;
protected MachineUtils machineUtils;
protected Supplier<URI> preconfigurationUri;
protected LoadingCache<IsoSpec, URI> preconfigurationUri;
protected String hostVersion;
protected String operatingSystemIso;
protected String guestAdditionsIso;
@ -86,10 +87,10 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
protected void ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults() {
Properties defaultVBoxProperties = new VirtualBoxPropertiesBuilder()
.build();
.build();
if (!System.getProperties().containsKey("test." + provider + ".identity"))
System.setProperty("test." + provider + ".identity",
defaultVBoxProperties.getProperty(Constants.PROPERTY_IDENTITY));
defaultVBoxProperties.getProperty(Constants.PROPERTY_IDENTITY));
}
@BeforeClass(groups = "live")
@ -98,65 +99,61 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
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()));
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);
identity, credential, ImmutableSet.<Module>of(
new SLF4JLoggingModule(), new SshjSshClientModule(),
hostModule), overrides);
Function<String, String> configProperties = context.utils().injector()
.getInstance(ValueOfConfigurationKeyOrNull.class);
.getInstance(ValueOfConfigurationKeyOrNull.class);
imageId = configProperties
.apply(ComputeServiceConstants.PROPERTY_IMAGE_ID);
.apply(ComputeServiceConstants.PROPERTY_IMAGE_ID);
workingDir = configProperties
.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
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
preconfigurationUri = context.utils().injector()
.getInstance(Key.get(new TypeLiteral<Supplier<URI>>() {
}, Preconfiguration.class));
preconfigurationUri = context.utils().injector().getInstance(Key.get(new TypeLiteral<LoadingCache<IsoSpec, 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();
machineUtils = context.utils().injector().getInstance(MachineUtils.class);
hostVersion = Iterables.get(
Splitter.on('r').split(
context.getProviderSpecificContext().getBuildVersion()), 0);
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);
workingDir, hostVersion);
}
protected void undoVm(VmSpec vmSpecification) {
machineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered(
vmSpecification.getVmId(),
new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
vmSpecification.getVmId(),
new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
}
@AfterClass(groups = "live")

View File

@ -49,7 +49,7 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
private static final boolean IS_LINKED_CLONE = true;
private VmSpec clonedVmSpec;
private IMachineSpec sourceMachineSpec;
private MasterSpec sourceMachineSpec;
private CleanupMode mode = CleanupMode.Full;
@ -87,12 +87,10 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
.sourcePath(operatingSystemIso)
.installationScript(
configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME", sourceVmSpec.getVmName()))
.preConfiguration(preconfigurationUri).build();
.replace("HOSTNAME", sourceVmSpec.getVmName())).build();
NetworkSpec networkSpec = NetworkSpec.builder().build();
sourceMachineSpec = IMachineSpec.builder().iso(isoSpec).vm(sourceVmSpec)
.network(networkSpec).build();
sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec).network(networkSpec).build();
clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName)
.memoryMB(512).cleanUpMode(mode).forceOverwrite(true).build();

View File

@ -70,16 +70,16 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName());
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk)
.autoDelete(true).controllerPort(0).deviceSlot(1).build();
StorageController ideController = StorageController.builder()
.name("IDE Controller").bus(StorageBus.IDE)
.attachISO(0, 0, operatingSystemIso).attachHardDisk(hardDisk)
.attachISO(1, 1, guestAdditionsIso).build();
vmSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512)
.osTypeId("").controller(ideController).forceOverwrite(true)
.cleanUpMode(CleanupMode.Full).build();
undoVm(vmSpecification);
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true)
.controllerPort(0).deviceSlot(1).build();
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE)
.attachISO(0, 0, operatingSystemIso)
.attachHardDisk(hardDisk)
.attachISO(1, 1, guestAdditionsIso).build();
vmSpecification = VmSpec.builder().id("jclouds#image#create-and-install-vm-test").name(vmName).memoryMB(512).osTypeId("")
.controller(ideController)
.forceOverwrite(true)
.cleanUpMode(CleanupMode.Full).build();
}
public void testCreateImageMachineFromIso() throws Exception {
@ -87,27 +87,17 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
Function<String, String> configProperties = injector
.getInstance(ValueOfConfigurationKeyOrNull.class);
IMachineSpec machineSpec = IMachineSpec
.builder()
.vm(vmSpecification)
.iso(IsoSpec
.builder()
.sourcePath(operatingSystemIso)
.installationScript(
configProperties.apply(
VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace(
"HOSTNAME", vmSpecification.getVmName()))
.preConfiguration(preconfigurationUri).build())
.network(
NetworkSpec
.builder()
.natNetworkAdapter(
0,
NatAdapter.builder()
.tcpRedirectRule("127.0.0.1", 2222, "", 22)
.build()).build()).build();
IMachine imageMachine = injector.getInstance(CreateAndInstallVm.class)
.apply(machineSpec);
MasterSpec masterSpec = MasterSpec.builder().vm(vmSpecification)
.iso(IsoSpec.builder()
.sourcePath(operatingSystemIso)
.installationScript(configProperties
.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME", vmSpecification.getVmName()))
.build())
.network(NetworkSpec.builder()
.natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build())
.build()).build();
IMachine imageMachine = injector.getInstance(CreateAndInstallVm.class).apply(masterSpec);
IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
Image newImage = iMachineToImage.apply(imageMachine);

View File

@ -66,11 +66,10 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends B
.cleanUpMode(mode)
.osTypeId("Debian")
.forceOverwrite(true).build();
IMachineSpec machineSpec = IMachineSpec.builder()
MasterSpec machineSpec = MasterSpec.builder()
.iso(IsoSpec.builder()
.sourcePath(operatingSystemIso)
.installationScript("")
.preConfiguration(preconfigurationUri)
.build())
.vm(vmSpec)
.network(NetworkSpec.builder().build()).build();
@ -97,10 +96,9 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends B
IsoSpec isoSpec = IsoSpec.builder()
.sourcePath(operatingSystemIso)
.installationScript("")
.preConfiguration(preconfigurationUri)
.build();
NetworkSpec networkSpec = NetworkSpec.builder().build();
IMachineSpec machineSpec = IMachineSpec.builder()
MasterSpec machineSpec = MasterSpec.builder()
.iso(isoSpec)
.vm(vmSpec)
.network(networkSpec).build();

View File

@ -18,6 +18,17 @@
*/
package org.jclouds.virtualbox.functions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.LoadingCache;
import org.easymock.EasyMock;
import org.jclouds.virtualbox.domain.*;
import org.jclouds.virtualbox.util.MachineUtils;
import org.testng.annotations.Test;
import org.virtualbox_4_1.*;
import java.net.URI;
import static org.easymock.EasyMock.anyBoolean;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
@ -27,150 +38,125 @@ import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import java.net.URI;
import org.easymock.EasyMock;
import org.jclouds.virtualbox.domain.HardDisk;
import org.jclouds.virtualbox.domain.IMachineSpec;
import org.jclouds.virtualbox.domain.IsoSpec;
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.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.ISession;
import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.VBoxException;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
/**
* @author Mattias Holmqvist
*/
@Test(groups = "unit", testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest")
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
@Test(enabled=false)
public void testCreateAndSetMemoryWhenNotAlreadyExists() throws Exception {
@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);
String vmName = "jclouds-image-my-ubuntu-image";
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE).build();
VmSpec vmSpec = VmSpec.builder().id(vmName).name(vmName).osTypeId("").memoryMB(1024).controller(ideController).cleanUpMode(
CleanupMode.Full).build();
IMachineSpec machineSpec = IMachineSpec.builder()
.iso(IsoSpec.builder().sourcePath("some.iso").installationScript("").preConfiguration(preconfiguration).build())
.vm(vmSpec)
.network(NetworkSpec.builder().build()).build();
IMachine createdMachine = createMock(IMachine.class);
ISession session = createMock(ISession.class);
MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createMock(VirtualBoxManager.class);
IVirtualBox vBox = createMock(IVirtualBox.class);
LoadingCache<IsoSpec, URI> preconfiguration = createNiceMock(LoadingCache.class);
String vmName = "jclouds-image-my-ubuntu-image";
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE).build();
VmSpec vmSpec = VmSpec.builder().id(vmName).name(vmName).osTypeId("").memoryMB(1024).controller(ideController).cleanUpMode(
CleanupMode.Full).build();
MasterSpec machineSpec = MasterSpec.builder()
.iso(IsoSpec.builder().sourcePath("some.iso").installationScript("").build())
.vm(vmSpec)
.network(NetworkSpec.builder().build()).build();
IMachine createdMachine = createMock(IMachine.class);
ISession session = createMock(ISession.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.composeMachineFilename(vmName, "/tmp/workingDir")).andReturn("settingsFile");
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.composeMachineFilename(vmName, "/tmp/workingDir")).andReturn("settingsFile");
StringBuilder errorMessageBuilder = new StringBuilder();
errorMessageBuilder.append("VirtualBox error: Could not find a registered machine with UUID {");
errorMessageBuilder.append("'jclouds-image-virtualbox-iso-to-machine-test'} (0x80BB0001)");
String errorMessage = errorMessageBuilder.toString();
VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
StringBuilder errorMessageBuilder = new StringBuilder();
errorMessageBuilder.append("VirtualBox error: Could not find a registered machine with UUID {");
errorMessageBuilder.append("'jclouds-image-virtualbox-iso-to-machine-test'} (0x80BB0001)");
String errorMessage = errorMessageBuilder.toString();
VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(vBox.findMachine(vmName)).andThrow(vBoxException);
expect(vBox.findMachine(vmName)).andThrow(vBoxException);
expect(vBox.createMachine(anyString(), eq(vmName), anyString(), anyString(), anyBoolean())).andReturn(
createdMachine).anyTimes();
vBox.registerMachine(createdMachine);
expect(vBox.createMachine(anyString(), eq(vmName), anyString(), anyString(), anyBoolean())).andReturn(
createdMachine).anyTimes();
vBox.registerMachine(createdMachine);
expect(vBox.findMachine(vmName)).andReturn(createdMachine).anyTimes();
expect(manager.getSessionObject()).andReturn(session);
expect(session.getMachine()).andReturn(createdMachine);
createdMachine.lockMachine(session, LockType.Write);
createdMachine.setMemorySize(1024l);
createdMachine.saveSettings();
session.unlockMachine();
expect(vBox.findMachine(vmName)).andReturn(createdMachine).anyTimes();
expect(manager.getSessionObject()).andReturn(session);
expect(session.getMachine()).andReturn(createdMachine);
createdMachine.lockMachine(session, LockType.Write);
createdMachine.setMemorySize(1024l);
createdMachine.saveSettings();
session.unlockMachine();
//TODO: this mock test is not finished.
replay(manager, createdMachine, vBox, session);
//TODO: this mock test is not finished.
replay(manager, createdMachine, vBox, session);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
verify(manager, createdMachine, vBox, session);
}
verify(manager, createdMachine, vBox, session);
}
@Test(expectedExceptions = IllegalStateException.class)
public void testFailIfMachineIsAlreadyRegistered() throws Exception {
@Test(expectedExceptions = IllegalStateException.class)
public void testFailIfMachineIsAlreadyRegistered() throws Exception {
MachineUtils machineUtils = createMock(MachineUtils.class);
MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
String vmName = "jclouds-image-my-ubuntu-image";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
String vmName = "jclouds-image-my-ubuntu-image";
IMachine registeredMachine = createMock(IMachine.class);
IMachine registeredMachine = createMock(IMachine.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMachine(vmName)).andReturn(registeredMachine).anyTimes();
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMachine(vmName)).andReturn(registeredMachine).anyTimes();
replay(manager, vBox, machineUtils);
replay(manager, vBox, machineUtils);
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).osTypeId("").memoryMB(1024).cleanUpMode(
CleanupMode.Full).build();
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).osTypeId("").memoryMB(1024).cleanUpMode(
CleanupMode.Full).build();
IMachineSpec machineSpec = IMachineSpec.builder()
.iso(IsoSpec.builder()
.sourcePath("some.iso")
.installationScript("dostuff")
.preConfiguration(preconfiguration).build())
.vm(launchSpecification)
.network(NetworkSpec.builder().build()).build();
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
}
MasterSpec machineSpec = MasterSpec.builder()
.iso(IsoSpec.builder()
.sourcePath("some.iso")
.installationScript("dostuff").build())
.vm(launchSpecification)
.network(NetworkSpec.builder().build()).build();
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
}
@Test(expectedExceptions = VBoxException.class)
public void testFailIfOtherVBoxExceptionIsThrown() throws Exception {
@Test(expectedExceptions = VBoxException.class)
public void testFailIfOtherVBoxExceptionIsThrown() throws Exception {
MachineUtils machineUtils = createMock(MachineUtils.class);
MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
String vmName = "jclouds-image-my-ubuntu-image";
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
String vmName = "jclouds-image-my-ubuntu-image";
String errorMessage = "VirtualBox error: Soem other VBox error";
VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
String errorMessage = "VirtualBox error: Soem other VBox error";
VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(manager.getVBox()).andReturn(vBox).anyTimes();
vBox.findMachine(vmName);
expectLastCall().andThrow(vBoxException);
vBox.findMachine(vmName);
expectLastCall().andThrow(vBoxException);
replay(manager, vBox, machineUtils);
replay(manager, vBox, machineUtils);
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full)
.memoryMB(1024).build();
IMachineSpec machineSpec = IMachineSpec.builder()
.iso(IsoSpec.builder()
.sourcePath("some.iso")
.installationScript("dostuff")
.preConfiguration(preconfiguration).build())
.vm(launchSpecification)
.network(NetworkSpec.builder().build()).build();
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full)
.memoryMB(1024).build();
MasterSpec machineSpec = MasterSpec.builder()
.iso(IsoSpec.builder()
.sourcePath("some.iso")
.installationScript("dostuff").build())
.vm(launchSpecification)
.network(NetworkSpec.builder().build()).build();
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), machineUtils, "/tmp/workingDir").apply(machineSpec);
}
}
private String anyString() {
return EasyMock.<String>anyObject();
}
private String anyString() {
return EasyMock.<String>anyObject();
}
}

View File

@ -46,6 +46,7 @@ public class IMachineToVmSpecTest {
private static final String PATH_TO_HD = "/path/to/hd";
private static final StorageBus CONTROLLER_BUS = StorageBus.IDE;
private static final long MEMORY_SIZE = 512L;
private static final String OS_TYPE_ID = "ubuntu";
private static final String VM_NAME = "test";
private static final String CONTROLLER_NAME = "IDE Controller";
private static final String VM_ID = "test";
@ -54,12 +55,10 @@ public class IMachineToVmSpecTest {
public void testConvert() throws Exception {
VirtualBoxManager vbm = createNiceMock(VirtualBoxManager.class);
IStorageController iStorageController = createNiceMock(IStorageController.class);
IMediumAttachment iMediumAttachment = createNiceMock(IMediumAttachment.class);
IStorageController iStorageController = createNiceMock(IStorageController.class);
IMediumAttachment iMediumAttachment = createNiceMock(IMediumAttachment.class);
IMedium hd = createNiceMock(IMedium.class);
IMedium dvd = createNiceMock(IMedium.class);
IMachine vm = createNiceMock(IMachine.class);
expect(vm.getStorageControllers()).andReturn(Lists.newArrayList(iStorageController)).anyTimes();
@ -68,23 +67,24 @@ public class IMachineToVmSpecTest {
expect(vm.getMediumAttachmentsOfController(CONTROLLER_NAME)).andReturn(Lists.newArrayList(iMediumAttachment)).anyTimes();
expect(iMediumAttachment.getPort()).andReturn(0).once();
expect(iMediumAttachment.getDevice()).andReturn(0).once();
expect(iMediumAttachment.getMedium()).andReturn(hd);
expect(hd.getDeviceType()).andReturn(DeviceType.HardDisk).once();
expect(hd.getLocation()).andReturn(PATH_TO_HD).once();
expect(iMediumAttachment.getMedium()).andReturn(dvd);
expect(dvd.getDeviceType()).andReturn(DeviceType.DVD).once();
expect(dvd.getLocation()).andReturn(PATH_TO_DVD).once();
expect(vm.getName()).andReturn(VM_NAME).anyTimes();
expect(vm.getId()).andReturn(VM_ID).anyTimes();
expect(vm.getOSTypeId()).andReturn(OS_TYPE_ID).anyTimes();
expect(vm.getMemorySize()).andReturn(MEMORY_SIZE).anyTimes();
replay(vbm, iStorageController, iMediumAttachment, hd, dvd, vm);
VmSpec vmSpec = new IMachineToVmSpec().apply(vm);
assertEquals(vmSpec.getVmName(), VM_NAME);
assertEquals(vmSpec.getVmId(), VM_ID);
assertEquals(vmSpec.getMemory(), MEMORY_SIZE);
@ -92,10 +92,10 @@ public class IMachineToVmSpecTest {
assertEquals(controller.getName(), CONTROLLER_NAME);
assertEquals(controller.getBus(), CONTROLLER_BUS);
for (HardDisk hardDisk : controller.getHardDisks()) {
assertEquals(hardDisk.getDiskPath(), PATH_TO_HD);
assertEquals(hardDisk.getDiskPath(), PATH_TO_HD);
}
for (IsoImage iso : controller.getIsoImages()) {
assertEquals(iso.getSourcePath(), PATH_TO_DVD);
assertEquals(iso.getSourcePath(), PATH_TO_DVD);
}
}
}

View File

@ -19,16 +19,15 @@
package org.jclouds.virtualbox.functions.admin;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import org.eclipse.jetty.server.Server;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.testng.annotations.Test;
import java.net.URI;
import org.eclipse.jetty.server.Server;
import org.testng.annotations.Test;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.*;
import static org.testng.Assert.assertEquals;
/**
* @author Andrea Turli, Adrian Cole
@ -36,23 +35,24 @@ import org.testng.annotations.Test;
@Test(groups = "unit", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningTest")
public class StartJettyIfNotAlreadyRunningTest {
@Test
public void testLaunchJettyServerWhenAlreadyRunningDoesntLaunchAgain() {
public void testLoadStartsJettyServer() throws Exception {
Server jetty = createMock(Server.class);
String preconfigurationUrl = "http://foo:8080";
expect(jetty.getState()).andReturn(Server.STARTED);
replay(jetty);
StartJettyIfNotAlreadyRunning starter = new StartJettyIfNotAlreadyRunning(jetty, preconfigurationUrl);
starter.start();
StartJettyIfNotAlreadyRunning starter = new StartJettyIfNotAlreadyRunning(preconfigurationUrl, jetty);
assertEquals(starter.get(), URI.create(preconfigurationUrl));
IsoSpec isoSpec = IsoSpec.builder()
.sourcePath("/tmp/myisos/ubuntu.iso")
.installationScript("install").build();
assertEquals(starter.load(isoSpec), URI.create(preconfigurationUrl));
verify(jetty);
}
@Test
public void testLaunchJettyServerWhenNotRunningStartsJettyOnCorrectHostPortAndBasedir() {
// TODO: all yours!

View File

@ -52,7 +52,7 @@ public class IsLinkedClonesLiveTest extends BaseVirtualBoxClientLiveTest {
private String cloneName;
private String vmName;
private StorageController masterStorageController;
private IMachineSpec masterMachineSpec;
private MasterSpec masterMachineSpec;
private VmSpec cloneSpec;
@Override
@ -71,10 +71,9 @@ public class IsLinkedClonesLiveTest extends BaseVirtualBoxClientLiveTest {
operatingSystemIso).attachHardDisk(hardDisk).attachISO(1, 1, guestAdditionsIso).build();
VmSpec masterSpec = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).osTypeId(osTypeId).controller(
masterStorageController).forceOverwrite(true).cleanUpMode(CleanupMode.Full).build();
masterMachineSpec = IMachineSpec.builder()
masterMachineSpec = MasterSpec.builder()
.iso(IsoSpec.builder()
.sourcePath(operatingSystemIso)
.preConfiguration(preconfigurationUri)
.installationScript("").build())
.vm(masterSpec)
.network(NetworkSpec.builder().build()).build();