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; package org.jclouds.virtualbox.config;
import java.io.InputStream; import com.google.common.annotations.VisibleForTesting;
import java.net.URI; import com.google.common.base.*;
import java.util.Map; import com.google.common.cache.CacheBuilder;
import java.util.concurrent.ExecutionException; import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import javax.inject.Singleton; 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.Node;
import org.jclouds.byon.functions.NodeToNodeMetadata; import org.jclouds.byon.functions.NodeToNodeMetadata;
import org.jclouds.byon.suppliers.SupplyFromProviderURIOrNodesProperty; import org.jclouds.byon.suppliers.SupplyFromProviderURIOrNodesProperty;
import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.config.ComputeServiceAdapterContextModule; import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.*;
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.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.functions.IdentityFunction; import org.jclouds.functions.IdentityFunction;
@ -46,6 +44,7 @@ import org.jclouds.ssh.SshClient;
import org.jclouds.virtualbox.Preconfiguration; import org.jclouds.virtualbox.Preconfiguration;
import org.jclouds.virtualbox.compute.VirtualBoxComputeServiceAdapter; import org.jclouds.virtualbox.compute.VirtualBoxComputeServiceAdapter;
import org.jclouds.virtualbox.domain.ExecutionType; import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.functions.IMachineToHardware; import org.jclouds.virtualbox.functions.IMachineToHardware;
import org.jclouds.virtualbox.functions.IMachineToImage; import org.jclouds.virtualbox.functions.IMachineToImage;
import org.jclouds.virtualbox.functions.IMachineToNodeMetadata; 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.MachineState;
import org.virtualbox_4_1.VirtualBoxManager; import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.annotations.VisibleForTesting; import javax.inject.Named;
import com.google.common.base.Function; import javax.inject.Singleton;
import com.google.common.base.Functions; import java.io.InputStream;
import com.google.common.base.Predicate; import java.net.URI;
import com.google.common.base.Supplier; import java.util.Map;
import com.google.common.base.Suppliers; import java.util.concurrent.ExecutionException;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
/** /**
* @author Mattias Holmqvist, Andrea Turli * @author Mattias Holmqvist, Andrea Turli
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class VirtualBoxComputeServiceContextModule extends public class VirtualBoxComputeServiceContextModule extends
ComputeServiceAdapterContextModule<Supplier, Supplier, IMachine, IMachine, Image, Location> { ComputeServiceAdapterContextModule<Supplier, Supplier, IMachine, IMachine, Image, Location> {
public VirtualBoxComputeServiceContextModule() { public VirtualBoxComputeServiceContextModule() {
super(Supplier.class, Supplier.class); super(Supplier.class, Supplier.class);
} }
@SuppressWarnings( { "unchecked", "rawtypes" }) @SuppressWarnings({"unchecked", "rawtypes"})
@Override @Override
protected void configure() { protected void configure() {
super.configure(); super.configure();
@ -99,7 +95,10 @@ public class VirtualBoxComputeServiceContextModule extends
}).to(IMachineToImage.class); }).to(IMachineToImage.class);
bind(new TypeLiteral<Supplier<Location>>() { bind(new TypeLiteral<Supplier<Location>>() {
}).to(OnlyLocationOrFirstZone.class); }).to(OnlyLocationOrFirstZone.class);
bind(new TypeLiteral<CacheLoader<IsoSpec, URI>>() {
}).to((Class) StartJettyIfNotAlreadyRunning.class);
bind(new TypeLiteral<Supplier<VirtualBoxManager>>() {
}).to((Class) StartVBoxIfNotAlreadyRunning.class);
// for byon // for byon
bind(new TypeLiteral<Function<URI, InputStream>>() { bind(new TypeLiteral<Function<URI, InputStream>>() {
}).to(SupplyFromProviderURIOrNodesProperty.class); }).to(SupplyFromProviderURIOrNodesProperty.class);
@ -115,20 +114,32 @@ public class VirtualBoxComputeServiceContextModule extends
@Provides @Provides
@Singleton @Singleton
@Preconfiguration @Preconfiguration
protected Supplier<URI> preconfiguration(javax.inject.Provider<StartJettyIfNotAlreadyRunning> lazyGet) { protected LoadingCache<IsoSpec, URI> preconfiguration(CacheLoader<IsoSpec, URI> cacheLoader) {
return lazyGet.get(); return CacheBuilder.newBuilder().build(cacheLoader);
} }
@Provides @Provides
@Singleton @Singleton
protected Function<Supplier<NodeMetadata>, VirtualBoxManager> provideVBox(Supplier<NodeMetadata> host) { protected Server providesJettyServer(@Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
return new Function<Supplier<NodeMetadata>, VirtualBoxManager>(){ return new Server(URI.create(preconfigurationUrl).getPort());
}
@Provides
@Singleton
protected Function<Supplier<NodeMetadata>, VirtualBoxManager> provideVBox() {
return new Function<Supplier<NodeMetadata>, VirtualBoxManager>() {
@Override @Override
public VirtualBoxManager apply(Supplier<NodeMetadata> arg0) { public VirtualBoxManager apply(Supplier<NodeMetadata> nodeSupplier) {
return VirtualBoxManager.createInstance(arg0.get().getId()); return VirtualBoxManager.createInstance(nodeSupplier.get().getId());
} }
@Override
public String toString() {
return "createInstanceByNodeId()";
}
}; };
} }
@ -138,12 +149,6 @@ public class VirtualBoxComputeServiceContextModule extends
return in; return in;
} }
@Provides
@Singleton
protected Supplier<VirtualBoxManager> vbox(javax.inject.Provider<StartVBoxIfNotAlreadyRunning> lazyGet) {
return lazyGet.get();
}
@Provides @Provides
@Singleton @Singleton
protected Predicate<SshClient> sshResponds(SshResponds sshResponds, Timeouts timeouts) { protected Predicate<SshClient> sshResponds(SshResponds sshResponds, Timeouts timeouts) {
@ -158,7 +163,7 @@ public class VirtualBoxComputeServiceContextModule extends
@Provides @Provides
@Singleton @Singleton
protected Supplier<NodeMetadata> host(Supplier<LoadingCache<String, Node>> nodes, NodeToNodeMetadata converter) 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>() { return Suppliers.compose(Functions.compose(converter, new Function<LoadingCache<String, Node>, Node>() {
@Override @Override
@ -170,22 +175,22 @@ 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().put(MachineState.Running, NodeState.RUNNING).put( .<MachineState, NodeState>builder().put(MachineState.Running, NodeState.RUNNING).put(
MachineState.PoweredOff, NodeState.SUSPENDED) MachineState.PoweredOff, NodeState.SUSPENDED)
.put(MachineState.DeletingSnapshot, NodeState.PENDING).put(MachineState.DeletingSnapshotOnline, .put(MachineState.DeletingSnapshot, NodeState.PENDING).put(MachineState.DeletingSnapshotOnline,
NodeState.PENDING).put(MachineState.DeletingSnapshotPaused, NodeState.PENDING).put( NodeState.PENDING).put(MachineState.DeletingSnapshotPaused, NodeState.PENDING).put(
MachineState.FaultTolerantSyncing, NodeState.PENDING).put(MachineState.LiveSnapshotting, MachineState.FaultTolerantSyncing, NodeState.PENDING).put(MachineState.LiveSnapshotting,
NodeState.PENDING).put(MachineState.SettingUp, NodeState.PENDING).put(MachineState.Starting, NodeState.PENDING).put(MachineState.SettingUp, NodeState.PENDING).put(MachineState.Starting,
NodeState.PENDING).put(MachineState.Stopping, NodeState.PENDING).put(MachineState.Restoring, NodeState.PENDING).put(MachineState.Stopping, NodeState.PENDING).put(MachineState.Restoring,
NodeState.PENDING) NodeState.PENDING)
// TODO What to map these states to? // TODO What to map these states to?
.put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING).put( .put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING).put(
MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING) MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING)
.put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING).put( .put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING).put(
MachineState.TeleportingPausedVM, NodeState.PENDING) 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.Objects;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.cache.CacheLoader;
import org.jclouds.virtualbox.Preconfiguration; import org.jclouds.virtualbox.Preconfiguration;
import java.net.URI; import java.net.URI;
@ -34,15 +35,10 @@ public class IsoSpec {
private final String installationKeySequence; private final String installationKeySequence;
private final String sourcePath; private final String sourcePath;
private final Supplier<URI> preConfigurationUri;
public IsoSpec(String sourcePath, String installationKeySequence, @Preconfiguration Supplier<URI> preConfigurationUri) { public IsoSpec(String sourcePath, String installationKeySequence) {
checkNotNull(sourcePath, "sourcePath"); this.sourcePath = checkNotNull(sourcePath, "sourcePath");
checkNotNull(installationKeySequence, "installationKeySequence"); this.installationKeySequence = checkNotNull(installationKeySequence, "installationKeySequence");
checkNotNull(preConfigurationUri, "preConfigurationUri");
this.sourcePath = sourcePath;
this.installationKeySequence = installationKeySequence;
this.preConfigurationUri = preConfigurationUri;
} }
public static Builder builder() { public static Builder builder() {
@ -60,11 +56,6 @@ public class IsoSpec {
return this; return this;
} }
public Builder preConfiguration(Supplier<URI> preConfigurationUri) {
this.preConfigurationUri = preConfigurationUri;
return this;
}
public Builder sourcePath(String sourcePath) { public Builder sourcePath(String sourcePath) {
this.sourcePath = sourcePath; this.sourcePath = sourcePath;
return this; return this;
@ -72,7 +63,7 @@ public class IsoSpec {
public IsoSpec build() { public IsoSpec build() {
return new IsoSpec(sourcePath, installationSequence, preConfigurationUri); return new IsoSpec(sourcePath, installationSequence);
} }
} }
@ -80,10 +71,6 @@ public class IsoSpec {
return installationKeySequence; return installationKeySequence;
} }
public Supplier<URI> getPreConfigurationUri() {
return preConfigurationUri;
}
public String getSourcePath() { public String getSourcePath() {
return sourcePath; return sourcePath;
} }
@ -94,15 +81,14 @@ public class IsoSpec {
if (o instanceof VmSpec) { if (o instanceof VmSpec) {
IsoSpec other = (IsoSpec) o; IsoSpec other = (IsoSpec) o;
return Objects.equal(sourcePath, other.sourcePath) && return Objects.equal(sourcePath, other.sourcePath) &&
Objects.equal(installationKeySequence, other.installationKeySequence) && Objects.equal(installationKeySequence, other.installationKeySequence);
Objects.equal(preConfigurationUri, other.preConfigurationUri);
} }
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(sourcePath, installationKeySequence, preConfigurationUri); return Objects.hashCode(sourcePath, installationKeySequence);
} }
@Override @Override
@ -110,7 +96,6 @@ public class IsoSpec {
return "IsoSpec{" + return "IsoSpec{" +
"sourcePath='" + sourcePath + '\'' + "sourcePath='" + sourcePath + '\'' +
"installationKeySequence='" + installationKeySequence + '\'' + "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 * A complete specification of a "master" node, including the ISO, networking setup
* and the physical machine specification. * and the physical machine specification.
*/ */
public class IMachineSpec { public class MasterSpec {
private VmSpec vmSpec; private VmSpec vmSpec;
private IsoSpec isoSpec; private IsoSpec isoSpec;
@ -58,13 +58,13 @@ public class IMachineSpec {
return this; return this;
} }
public IMachineSpec build() { public MasterSpec build() {
return new IMachineSpec(vmSpec, isoSpec, networkSpec); 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(vmSpec, "vmSpec");
checkNotNull(isoSpec, "isoSpec"); checkNotNull(isoSpec, "isoSpec");
checkNotNull(networkSpec, "networkSpec"); checkNotNull(networkSpec, "networkSpec");
@ -89,7 +89,7 @@ public class IMachineSpec {
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) {
IMachineSpec other = (IMachineSpec) 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);

View File

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

View File

@ -40,18 +40,14 @@ public class VmSpec {
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) {
checkNotNull(vmId, "vmId"); this.vmId = checkNotNull(vmId, "vmId");
checkNotNull(vmName, "vmName"); this.vmName = checkNotNull(vmName, "vmName");
this.osTypeId = checkNotNull(osTypeId, "osTypeId");
checkArgument(memory > 0, "memory must be > 0"); 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.memory = memory;
this.controllers = controllers; this.controllers = checkNotNull(controllers, "controllers");
this.cleanupMode = checkNotNull(cleanupMode, "cleanupMode");
this.forceOverwrite = forceOverwrite; this.forceOverwrite = forceOverwrite;
this.cleanupMode = cleanupMode;
} }
public static Builder builder() { public static Builder builder() {

View File

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

View File

@ -19,46 +19,31 @@
package org.jclouds.virtualbox.functions; package org.jclouds.virtualbox.functions;
import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import java.io.File; import org.jclouds.compute.reference.ComputeServiceConstants;
import java.util.Map; import org.jclouds.logging.Logger;
import java.util.Set; 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.Nullable;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import java.io.File;
import java.util.Map;
import java.util.Set;
import org.jclouds.compute.reference.ComputeServiceConstants; import static com.google.common.base.Preconditions.checkNotNull;
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;
/** /**
* @author Mattias Holmqvist * @author Mattias Holmqvist
*/ */
@Singleton @Singleton
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<IMachineSpec, IMachine> { public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<MasterSpec, IMachine> {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
@ -78,7 +63,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
} }
@Override @Override
public IMachine apply(@Nullable IMachineSpec launchSpecification) { public IMachine apply(@Nullable MasterSpec launchSpecification) {
final IVirtualBox vBox = manager.get().getVBox(); final IVirtualBox vBox = manager.get().getVBox();
String vmName = launchSpecification.getVmSpec().getVmName(); String vmName = launchSpecification.getVmSpec().getVmName();
String vmId = launchSpecification.getVmSpec().getVmId(); 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 {"); 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(); VmSpec vmSpec = machineSpec.getVmSpec();
String settingsFile = vBox.composeMachineFilename(vmSpec.getVmName(), workingDir); String settingsFile = vBox.composeMachineFilename(vmSpec.getVmName(), workingDir);
@ -110,7 +95,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
return newMachine; return newMachine;
} }
private void ensureConfiguration(IMachineSpec machineSpec) { private void ensureConfiguration(MasterSpec machineSpec) {
VmSpec vmSpec = machineSpec.getVmSpec(); VmSpec vmSpec = machineSpec.getVmSpec();
NetworkSpec networkSpec = machineSpec.getNetworkSpec(); NetworkSpec networkSpec = machineSpec.getNetworkSpec();
String vmName = vmSpec.getVmName(); String vmName = vmSpec.getVmName();
@ -149,7 +134,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
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, medium,
controllerName)); controllerName));
} }
private String missingIDEControllersMessage(VmSpec vmSpecification) { private String missingIDEControllersMessage(VmSpec vmSpecification) {
@ -178,13 +163,12 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
machineUtils.writeLockMachineAndApply(vmName, new ApplyMemoryToMachine(memorySize)); machineUtils.writeLockMachineAndApply(vmName, new ApplyMemoryToMachine(memorySize));
} }
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, NatAdapter natAdapter) {
NatAdapter natAdapter) {
machineUtils.writeLockMachineAndApply(vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter)); machineUtils.writeLockMachineAndApply(vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
} }
public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) { public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) {
machineUtils.writeLockMachineAndApply(vmName, new AddIDEControllerIfNotExists(checkNotNull( 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)), client = sshClientFactory.create(new IPSocket(hostAddress, Integer.parseInt(inboundPort)),
LoginCredentials.builder().user("toor").password("password").authenticateSudo(true).build()); LoginCredentials.builder().user("toor").password("password").authenticateSudo(true).build());
} }
} }
return client; return client;
} }

View File

@ -19,16 +19,8 @@
package org.jclouds.virtualbox.functions.admin; package org.jclouds.virtualbox.functions.admin;
import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.cache.CacheLoader;
import com.google.inject.Singleton;
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 org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler; 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.eclipse.jetty.server.handler.ResourceHandler;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.virtualbox.Preconfiguration; import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.config.VirtualBoxConstants;
import com.google.common.base.Supplier; import javax.annotation.PostConstruct;
import com.google.inject.Singleton; 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 * @author Andrea Turli
*/ */
@Preconfiguration
@Singleton @Singleton
public class StartJettyIfNotAlreadyRunning implements Supplier<URI> { public class StartJettyIfNotAlreadyRunning extends CacheLoader<IsoSpec, URI> {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private Server jetty;
private final URI preconfigurationUrl; private final String preconfigurationUrl;
private final Server jetty;
@Inject @Inject
public StartJettyIfNotAlreadyRunning( public StartJettyIfNotAlreadyRunning(@Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl, Server jetty) {
@Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) { this.preconfigurationUrl = 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"));
this.jetty = jetty; this.jetty = jetty;
} }
@PostConstruct @Override
public void start() { 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)) { if (jetty.getState().equals(Server.STARTED)) {
logger.debug("not starting jetty, as existing host is serving %s", preconfigurationUrl); logger.debug("not starting jetty, as existing host is serving %s", preconfigurationUrl);
} else { } else {
logger.debug(">> starting jetty to serve %s", preconfigurationUrl); logger.debug(">> starting jetty to serve %s", preconfigurationUrl);
ResourceHandler resource_handler = new ResourceHandler(); ResourceHandler resourceHandler = new ResourceHandler();
resource_handler.setDirectoriesListed(true); resourceHandler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "index.html" }); resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resource_handler.setResourceBase(""); resourceHandler.setResourceBase("");
HandlerList handlers = new HandlerList(); HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() }); handlers.setHandlers(new Handler[]{resourceHandler, new DefaultHandler()});
jetty.setHandler(handlers); jetty.setHandler(handlers);
try { try {
@ -89,7 +88,7 @@ public class StartJettyIfNotAlreadyRunning implements Supplier<URI> {
} catch (Exception e) { } catch (Exception e) {
logger.error(e, "Server jetty could not be started for %s", preconfigurationUrl); 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 { try {
jetty.stop(); jetty.stop();
} catch (Exception e) { } 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; package org.jclouds.virtualbox.util;
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; import com.google.common.base.Function;
import static org.jclouds.scriptbuilder.domain.Statements.call; import com.google.common.base.Supplier;
import static org.jclouds.scriptbuilder.domain.Statements.findPid; import com.google.inject.Inject;
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 org.jclouds.compute.callables.RunScriptOnNode; import org.jclouds.compute.callables.RunScriptOnNode;
import org.jclouds.compute.callables.RunScriptOnNode.Factory; import org.jclouds.compute.callables.RunScriptOnNode.Factory;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
@ -36,20 +29,18 @@ import org.jclouds.logging.Logger;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.util.Throwables2; import org.jclouds.util.Throwables2;
import org.jclouds.virtualbox.functions.MutableMachine; import org.jclouds.virtualbox.functions.MutableMachine;
import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.*;
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 com.google.common.base.Function; import javax.annotation.Resource;
import com.google.common.base.Supplier; import javax.inject.Named;
import com.google.inject.Inject; 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. * Utilities for executing functions on a VirtualBox machine.
* *
* @author Adrian Cole, Mattias Holmqvist, Andrea Turli * @author Adrian Cole, Mattias Holmqvist, Andrea Turli
*/ */
@ -78,28 +69,26 @@ public class MachineUtils {
* perform some modifications to the IMachine. * perform some modifications to the IMachine.
* <p/> * <p/>
* Unlocks the machine before returning. * Unlocks the machine before returning.
* *
* @param machineId * @param machineId the id of the machine
* the id of the machine * @param function the function to execute
* @param function
* the function to execute
* @return the result from applying the function to the machine. * @return the result from applying the function to the machine.
*/ */
public <T> T writeLockMachineAndApply(final String machineId, final Function<IMachine, T> function) { public <T> T writeLockMachineAndApply(final String machineId, final Function<IMachine, T> function) {
return lockSessionOnMachineAndApply(machineId, LockType.Write, return lockSessionOnMachineAndApply(machineId, LockType.Write,
new Function<ISession, T>() { new Function<ISession, T>() {
@Override @Override
public T apply(ISession session) { public T apply(ISession session) {
return function.apply(session.getMachine()); return function.apply(session.getMachine());
} }
@Override @Override
public String toString() { public String toString() {
return function.toString(); return function.toString();
} }
}); });
} }
/** /**
@ -108,13 +97,10 @@ public class MachineUtils {
* modifications to the IMachine. * modifications to the IMachine.
* <p/> * <p/>
* Unlocks the machine before returning. * Unlocks the machine before returning.
* *
* @param type * @param type the kind of lock to use when initially locking the machine.
* the kind of lock to use when initially locking the machine. * @param machineId the id of the machine
* @param machineId * @param function the function to execute
* the id of the machine
* @param function
* the function to execute
* @return the result from applying the function to the session. * @return the result from applying the function to the session.
*/ */
public <T> T lockSessionOnMachineAndApply(String machineId, LockType type, Function<ISession, T> function) { public <T> T lockSessionOnMachineAndApply(String machineId, LockType type, Function<ISession, T> function) {
@ -127,8 +113,8 @@ public class MachineUtils {
} }
} catch (VBoxException e) { } catch (VBoxException e) {
throw new RuntimeException(String.format( throw new RuntimeException(String.format(
"error applying %s to %s with %s lock: %s", function, machineId, "error applying %s to %s with %s lock: %s", function, machineId,
type, e.getMessage()), e); type, e.getMessage()), e);
} }
} }
@ -140,10 +126,10 @@ public class MachineUtils {
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"), Statement kill = newStatementList(call("default"),
findPid(immutableMachine.getSessionPid().toString()), kill()); findPid(immutableMachine.getSessionPid().toString()), kill());
scriptRunner scriptRunner
.create(host.get(), kill, .create(host.get(), kill,
runAsRoot(false).wrapInInitScript(false)).init().call(); 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 * matching the given id. Since the machine is unlocked it is possible to
* delete the IMachine. * delete the IMachine.
* <p/> * <p/>
* * <p/>
* <h3>Note!</h3> Currently, this can only unlock the machine, if the lock * <h3>Note!</h3> Currently, this can only unlock the machine, if the lock
* was created in the current session. * was created in the current session.
* *
* @param machineId * @param machineId the id of the machine
* the id of the machine * @param function the function to execute
* @param function
* the function to execute
* @return the result from applying the function to the machine. * @return the result from applying the function to the machine.
*/ */
public <T> T unlockMachineAndApply(final String machineId, final Function<IMachine, T> function) { public <T> T unlockMachineAndApply(final String machineId, final Function<IMachine, T> function) {
try { try {
unlockMachine(machineId); unlockMachine(machineId);
IMachine immutableMachine = manager.get().getVBox().findMachine(machineId); IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
return function.apply(immutableMachine); return function.apply(immutableMachine);
} catch (VBoxException e) { } catch (VBoxException e) {
throw new RuntimeException(String.format( throw new RuntimeException(String.format(
"error applying %s to %s: %s", function, machineId, "error applying %s to %s: %s", function, machineId,
e.getMessage()), e); e.getMessage()), e);
} }
} }
@ -182,29 +165,26 @@ public class MachineUtils {
* registered. Since the machine is unlocked it is possible to delete the * registered. Since the machine is unlocked it is possible to delete the
* machine. * machine.
* <p/> * <p/>
* *
* @param machineId * @param machineId the id of the machine
* the id of the machine * @param function the function to execute
* @param function
* the function to execute
* @return the result from applying the function to the session. * @return the result from applying the function to the session.
*/ */
public <T> T unlockMachineAndApplyOrReturnNullIfNotRegistered(String machineId, public <T> T unlockMachineAndApplyOrReturnNullIfNotRegistered(String machineId,
Function<IMachine, T> function) { Function<IMachine, T> function) {
try { try {
return unlockMachineAndApply(machineId, function); return unlockMachineAndApply(machineId, function);
} catch (RuntimeException e) { } catch (RuntimeException e) {
VBoxException vbex = Throwables2.getFirstThrowableOfType(e, VBoxException vbex = Throwables2.getFirstThrowableOfType(e,
VBoxException.class); VBoxException.class);
if (vbex != null if (vbex != null
&& vbex.getMessage().indexOf("not find a registered") == -1) && vbex.getMessage().indexOf("not find a registered") == -1)
throw e; throw e;
return null; return null;
} }
} }
/** /**
*
* @param machineId * @param machineId
* @param function * @param function
* @return * @return
@ -223,5 +203,5 @@ public class MachineUtils {
} }
}.apply(immutableMachine); }.apply(immutableMachine);
} }
} }

View File

@ -19,9 +19,16 @@
package org.jclouds.virtualbox; package org.jclouds.virtualbox;
import java.net.URI; import com.google.common.base.Function;
import java.util.Properties; 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.Constants;
import org.jclouds.byon.Node; import org.jclouds.byon.Node;
import org.jclouds.byon.config.CacheNodeStoreModule; 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.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.virtualbox.config.VirtualBoxConstants; import org.jclouds.virtualbox.config.VirtualBoxConstants;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia; import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
import org.jclouds.virtualbox.util.MachineUtils; import org.jclouds.virtualbox.util.MachineUtils;
@ -43,19 +51,12 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.virtualbox_4_1.VirtualBoxManager; import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Function; import java.net.URI;
import com.google.common.base.Splitter; import java.util.Properties;
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;
/** /**
* Tests behavior of {@code VirtualBoxClient} * Tests behavior of {@code VirtualBoxClient}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "live", singleThreaded = true, testName = "BaseVirtualBoxClientLiveTest") @Test(groups = "live", singleThreaded = true, testName = "BaseVirtualBoxClientLiveTest")
@ -67,7 +68,7 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
protected ComputeServiceContext context; protected ComputeServiceContext context;
protected Supplier<VirtualBoxManager> manager; protected Supplier<VirtualBoxManager> manager;
protected MachineUtils machineUtils; protected MachineUtils machineUtils;
protected Supplier<URI> preconfigurationUri; protected LoadingCache<IsoSpec, URI> preconfigurationUri;
protected String hostVersion; protected String hostVersion;
protected String operatingSystemIso; protected String operatingSystemIso;
protected String guestAdditionsIso; protected String guestAdditionsIso;
@ -86,10 +87,10 @@ 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));
} }
@BeforeClass(groups = "live") @BeforeClass(groups = "live")
@ -98,65 +99,61 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
Properties overrides = setupProperties(); Properties overrides = setupProperties();
CacheNodeStoreModule hostModule = new CacheNodeStoreModule( CacheNodeStoreModule hostModule = new CacheNodeStoreModule(
ImmutableMap.of( ImmutableMap.of(
"host", "host",
Node.builder() Node.builder()
.id("host") .id("host")
.name("host installing virtualbox") .name("host installing virtualbox")
.hostname("localhost") .hostname("localhost")
.osFamily(OsFamily.LINUX.toString()) .osFamily(OsFamily.LINUX.toString())
.osDescription(System.getProperty("os.name")) .osDescription(System.getProperty("os.name"))
.osVersion(System.getProperty("os.version")) .osVersion(System.getProperty("os.version"))
.group("ssh") .group("ssh")
.username(System.getProperty("user.name")) .username(System.getProperty("user.name"))
.credentialUrl( .credentialUrl(
URI.create("file://" URI.create("file://"
+ System.getProperty("user.home") + System.getProperty("user.home")
+ "/.ssh/id_rsa")).build())); + "/.ssh/id_rsa")).build()));
context = new ComputeServiceContextFactory().createContext(provider, context = new ComputeServiceContextFactory().createContext(provider,
identity, credential, ImmutableSet.<Module> of( identity, credential, ImmutableSet.<Module>of(
new SLF4JLoggingModule(), new SshjSshClientModule(), new SLF4JLoggingModule(), new SshjSshClientModule(),
hostModule), overrides); hostModule), overrides);
Function<String, String> configProperties = context.utils().injector() Function<String, String> configProperties = context.utils().injector()
.getInstance(ValueOfConfigurationKeyOrNull.class); .getInstance(ValueOfConfigurationKeyOrNull.class);
imageId = configProperties imageId = configProperties
.apply(ComputeServiceConstants.PROPERTY_IMAGE_ID); .apply(ComputeServiceConstants.PROPERTY_IMAGE_ID);
workingDir = configProperties workingDir = configProperties
.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR); .apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
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() preconfigurationUri = context.utils().injector().getInstance(Key.get(new TypeLiteral<LoadingCache<IsoSpec, URI>>() {
.getInstance(Key.get(new TypeLiteral<Supplier<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
preconfigurationUri.get();
manager = context manager = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<VirtualBoxManager>>() {
.utils() }));
.injector()
.getInstance(Key.get(new TypeLiteral<Supplier<VirtualBoxManager>>() {}));
// this will eagerly startup vbox // this will eagerly startup vbox
manager.get(); manager.get();
machineUtils = context.utils().injector().getInstance(MachineUtils.class); machineUtils = context.utils().injector().getInstance(MachineUtils.class);
hostVersion = Iterables.get( hostVersion = Iterables.get(
Splitter.on('r').split( Splitter.on('r').split(
context.getProviderSpecificContext().getBuildVersion()), 0); context.getProviderSpecificContext().getBuildVersion()), 0);
adminDisk = workingDir + "/testadmin.vdi"; adminDisk = workingDir + "/testadmin.vdi";
operatingSystemIso = String.format("%s/%s.iso", workingDir, imageId); operatingSystemIso = String.format("%s/%s.iso", workingDir, imageId);
guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso",
workingDir, hostVersion); workingDir, 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));
} }
@AfterClass(groups = "live") @AfterClass(groups = "live")

View File

@ -49,7 +49,7 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
private static final boolean IS_LINKED_CLONE = true; private static final boolean IS_LINKED_CLONE = true;
private VmSpec clonedVmSpec; private VmSpec clonedVmSpec;
private IMachineSpec sourceMachineSpec; private MasterSpec sourceMachineSpec;
private CleanupMode mode = CleanupMode.Full; private CleanupMode mode = CleanupMode.Full;
@ -87,12 +87,10 @@ public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
.sourcePath(operatingSystemIso) .sourcePath(operatingSystemIso)
.installationScript( .installationScript(
configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME", sourceVmSpec.getVmName())) .replace("HOSTNAME", sourceVmSpec.getVmName())).build();
.preConfiguration(preconfigurationUri).build();
NetworkSpec networkSpec = NetworkSpec.builder().build(); NetworkSpec networkSpec = NetworkSpec.builder().build();
sourceMachineSpec = IMachineSpec.builder().iso(isoSpec).vm(sourceVmSpec) sourceMachineSpec = MasterSpec.builder().iso(isoSpec).vm(sourceVmSpec).network(networkSpec).build();
.network(networkSpec).build();
clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName) clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName)
.memoryMB(512).cleanUpMode(mode).forceOverwrite(true).build(); .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() + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName()); .getSimpleName());
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk) HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true)
.autoDelete(true).controllerPort(0).deviceSlot(1).build(); .controllerPort(0).deviceSlot(1).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)
.attachISO(0, 0, operatingSystemIso).attachHardDisk(hardDisk) .attachHardDisk(hardDisk)
.attachISO(1, 1, guestAdditionsIso).build(); .attachISO(1, 1, guestAdditionsIso).build();
vmSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512) vmSpecification = VmSpec.builder().id("jclouds#image#create-and-install-vm-test").name(vmName).memoryMB(512).osTypeId("")
.osTypeId("").controller(ideController).forceOverwrite(true) .controller(ideController)
.cleanUpMode(CleanupMode.Full).build(); .forceOverwrite(true)
undoVm(vmSpecification); .cleanUpMode(CleanupMode.Full).build();
} }
public void testCreateImageMachineFromIso() throws Exception { public void testCreateImageMachineFromIso() throws Exception {
@ -87,27 +87,17 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
Function<String, String> configProperties = injector Function<String, String> configProperties = injector
.getInstance(ValueOfConfigurationKeyOrNull.class); .getInstance(ValueOfConfigurationKeyOrNull.class);
IMachineSpec machineSpec = IMachineSpec MasterSpec masterSpec = MasterSpec.builder().vm(vmSpecification)
.builder() .iso(IsoSpec.builder()
.vm(vmSpecification) .sourcePath(operatingSystemIso)
.iso(IsoSpec .installationScript(configProperties
.builder() .apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.sourcePath(operatingSystemIso) .replace("HOSTNAME", vmSpecification.getVmName()))
.installationScript( .build())
configProperties.apply( .network(NetworkSpec.builder()
VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace( .natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build())
"HOSTNAME", vmSpecification.getVmName())) .build()).build();
.preConfiguration(preconfigurationUri).build()) IMachine imageMachine = injector.getInstance(CreateAndInstallVm.class).apply(masterSpec);
.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);
IMachineToImage iMachineToImage = new IMachineToImage(manager, map); IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
Image newImage = iMachineToImage.apply(imageMachine); Image newImage = iMachineToImage.apply(imageMachine);

View File

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

View File

@ -18,6 +18,17 @@
*/ */
package org.jclouds.virtualbox.functions; 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.anyBoolean;
import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect; 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.replay;
import static org.easymock.classextension.EasyMock.verify; 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 * @author Mattias Holmqvist
*/ */
@Test(groups = "unit", testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest") @Test(groups = "unit", testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest")
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest { public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
@Test(enabled=false) @Test(enabled = false)
public void testCreateAndSetMemoryWhenNotAlreadyExists() throws Exception { public void testCreateAndSetMemoryWhenNotAlreadyExists() throws Exception {
MachineUtils machineUtils = createMock(MachineUtils.class); MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createMock(VirtualBoxManager.class); VirtualBoxManager manager = createMock(VirtualBoxManager.class);
IVirtualBox vBox = createMock(IVirtualBox.class); IVirtualBox vBox = createMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class); LoadingCache<IsoSpec, URI> preconfiguration = createNiceMock(LoadingCache.class);
String vmName = "jclouds-image-my-ubuntu-image"; String vmName = "jclouds-image-my-ubuntu-image";
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE).build(); 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( VmSpec vmSpec = VmSpec.builder().id(vmName).name(vmName).osTypeId("").memoryMB(1024).controller(ideController).cleanUpMode(
CleanupMode.Full).build(); CleanupMode.Full).build();
IMachineSpec machineSpec = IMachineSpec.builder() MasterSpec machineSpec = MasterSpec.builder()
.iso(IsoSpec.builder().sourcePath("some.iso").installationScript("").preConfiguration(preconfiguration).build()) .iso(IsoSpec.builder().sourcePath("some.iso").installationScript("").build())
.vm(vmSpec) .vm(vmSpec)
.network(NetworkSpec.builder().build()).build(); .network(NetworkSpec.builder().build()).build();
IMachine createdMachine = createMock(IMachine.class); IMachine createdMachine = createMock(IMachine.class);
ISession session = createMock(ISession.class); ISession session = createMock(ISession.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.composeMachineFilename(vmName, "/tmp/workingDir")).andReturn("settingsFile"); expect(vBox.composeMachineFilename(vmName, "/tmp/workingDir")).andReturn("settingsFile");
StringBuilder errorMessageBuilder = new StringBuilder(); StringBuilder errorMessageBuilder = new StringBuilder();
errorMessageBuilder.append("VirtualBox error: Could not find a registered machine with UUID {"); errorMessageBuilder.append("VirtualBox error: Could not find a registered machine with UUID {");
errorMessageBuilder.append("'jclouds-image-virtualbox-iso-to-machine-test'} (0x80BB0001)"); errorMessageBuilder.append("'jclouds-image-virtualbox-iso-to-machine-test'} (0x80BB0001)");
String errorMessage = errorMessageBuilder.toString(); String errorMessage = errorMessageBuilder.toString();
VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage); 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( expect(vBox.createMachine(anyString(), eq(vmName), anyString(), anyString(), anyBoolean())).andReturn(
createdMachine).anyTimes(); createdMachine).anyTimes();
vBox.registerMachine(createdMachine); vBox.registerMachine(createdMachine);
expect(vBox.findMachine(vmName)).andReturn(createdMachine).anyTimes(); expect(vBox.findMachine(vmName)).andReturn(createdMachine).anyTimes();
expect(manager.getSessionObject()).andReturn(session); expect(manager.getSessionObject()).andReturn(session);
expect(session.getMachine()).andReturn(createdMachine); expect(session.getMachine()).andReturn(createdMachine);
createdMachine.lockMachine(session, LockType.Write); createdMachine.lockMachine(session, LockType.Write);
createdMachine.setMemorySize(1024l); createdMachine.setMemorySize(1024l);
createdMachine.saveSettings(); createdMachine.saveSettings();
session.unlockMachine(); session.unlockMachine();
//TODO: this mock test is not finished. //TODO: this mock test is not finished.
replay(manager, createdMachine, vBox, session); 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) @Test(expectedExceptions = IllegalStateException.class)
public void testFailIfMachineIsAlreadyRegistered() throws Exception { public void testFailIfMachineIsAlreadyRegistered() throws Exception {
MachineUtils machineUtils = createMock(MachineUtils.class); MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class); IVirtualBox vBox = createNiceMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class); Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
String vmName = "jclouds-image-my-ubuntu-image"; String vmName = "jclouds-image-my-ubuntu-image";
IMachine registeredMachine = createMock(IMachine.class); IMachine registeredMachine = createMock(IMachine.class);
expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(manager.getVBox()).andReturn(vBox).anyTimes();
expect(vBox.findMachine(vmName)).andReturn(registeredMachine).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( VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).osTypeId("").memoryMB(1024).cleanUpMode(
CleanupMode.Full).build(); CleanupMode.Full).build();
IMachineSpec machineSpec = IMachineSpec.builder() MasterSpec machineSpec = MasterSpec.builder()
.iso(IsoSpec.builder() .iso(IsoSpec.builder()
.sourcePath("some.iso") .sourcePath("some.iso")
.installationScript("dostuff") .installationScript("dostuff").build())
.preConfiguration(preconfiguration).build()) .vm(launchSpecification)
.vm(launchSpecification) .network(NetworkSpec.builder().build()).build();
.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); }
}
@Test(expectedExceptions = VBoxException.class) @Test(expectedExceptions = VBoxException.class)
public void testFailIfOtherVBoxExceptionIsThrown() throws Exception { public void testFailIfOtherVBoxExceptionIsThrown() throws Exception {
MachineUtils machineUtils = createMock(MachineUtils.class); MachineUtils machineUtils = createMock(MachineUtils.class);
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
IVirtualBox vBox = createNiceMock(IVirtualBox.class); IVirtualBox vBox = createNiceMock(IVirtualBox.class);
Supplier<URI> preconfiguration = createNiceMock(Supplier.class); Supplier<URI> preconfiguration = createNiceMock(Supplier.class);
String vmName = "jclouds-image-my-ubuntu-image"; String vmName = "jclouds-image-my-ubuntu-image";
String errorMessage = "VirtualBox error: Soem other VBox error"; String errorMessage = "VirtualBox error: Soem other VBox error";
VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage); VBoxException vBoxException = new VBoxException(createNiceMock(Throwable.class), errorMessage);
expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(manager.getVBox()).andReturn(vBox).anyTimes();
vBox.findMachine(vmName); vBox.findMachine(vmName);
expectLastCall().andThrow(vBoxException); expectLastCall().andThrow(vBoxException);
replay(manager, vBox, machineUtils); replay(manager, vBox, machineUtils);
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full) VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full)
.memoryMB(1024).build(); .memoryMB(1024).build();
IMachineSpec machineSpec = IMachineSpec.builder() MasterSpec machineSpec = MasterSpec.builder()
.iso(IsoSpec.builder() .iso(IsoSpec.builder()
.sourcePath("some.iso") .sourcePath("some.iso")
.installationScript("dostuff") .installationScript("dostuff").build())
.preConfiguration(preconfiguration).build()) .vm(launchSpecification)
.vm(launchSpecification) .network(NetworkSpec.builder().build()).build();
.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() { private String anyString() {
return EasyMock.<String>anyObject(); 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 String PATH_TO_HD = "/path/to/hd";
private static final StorageBus CONTROLLER_BUS = StorageBus.IDE; private static final StorageBus CONTROLLER_BUS = StorageBus.IDE;
private static final long MEMORY_SIZE = 512L; 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 VM_NAME = "test";
private static final String CONTROLLER_NAME = "IDE Controller"; private static final String CONTROLLER_NAME = "IDE Controller";
private static final String VM_ID = "test"; private static final String VM_ID = "test";
@ -54,12 +55,10 @@ public class IMachineToVmSpecTest {
public void testConvert() throws Exception { public void testConvert() throws Exception {
VirtualBoxManager vbm = createNiceMock(VirtualBoxManager.class); VirtualBoxManager vbm = createNiceMock(VirtualBoxManager.class);
IStorageController iStorageController = createNiceMock(IStorageController.class); IStorageController iStorageController = createNiceMock(IStorageController.class);
IMediumAttachment iMediumAttachment = createNiceMock(IMediumAttachment.class);
IMediumAttachment iMediumAttachment = createNiceMock(IMediumAttachment.class);
IMedium hd = createNiceMock(IMedium.class); IMedium hd = createNiceMock(IMedium.class);
IMedium dvd = createNiceMock(IMedium.class); IMedium dvd = createNiceMock(IMedium.class);
IMachine vm = createNiceMock(IMachine.class); IMachine vm = createNiceMock(IMachine.class);
expect(vm.getStorageControllers()).andReturn(Lists.newArrayList(iStorageController)).anyTimes(); 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(vm.getMediumAttachmentsOfController(CONTROLLER_NAME)).andReturn(Lists.newArrayList(iMediumAttachment)).anyTimes();
expect(iMediumAttachment.getPort()).andReturn(0).once(); expect(iMediumAttachment.getPort()).andReturn(0).once();
expect(iMediumAttachment.getDevice()).andReturn(0).once(); expect(iMediumAttachment.getDevice()).andReturn(0).once();
expect(iMediumAttachment.getMedium()).andReturn(hd); expect(iMediumAttachment.getMedium()).andReturn(hd);
expect(hd.getDeviceType()).andReturn(DeviceType.HardDisk).once(); expect(hd.getDeviceType()).andReturn(DeviceType.HardDisk).once();
expect(hd.getLocation()).andReturn(PATH_TO_HD).once(); expect(hd.getLocation()).andReturn(PATH_TO_HD).once();
expect(iMediumAttachment.getMedium()).andReturn(dvd); expect(iMediumAttachment.getMedium()).andReturn(dvd);
expect(dvd.getDeviceType()).andReturn(DeviceType.DVD).once(); expect(dvd.getDeviceType()).andReturn(DeviceType.DVD).once();
expect(dvd.getLocation()).andReturn(PATH_TO_DVD).once(); expect(dvd.getLocation()).andReturn(PATH_TO_DVD).once();
expect(vm.getName()).andReturn(VM_NAME).anyTimes(); expect(vm.getName()).andReturn(VM_NAME).anyTimes();
expect(vm.getId()).andReturn(VM_ID).anyTimes(); expect(vm.getId()).andReturn(VM_ID).anyTimes();
expect(vm.getOSTypeId()).andReturn(OS_TYPE_ID).anyTimes();
expect(vm.getMemorySize()).andReturn(MEMORY_SIZE).anyTimes(); expect(vm.getMemorySize()).andReturn(MEMORY_SIZE).anyTimes();
replay(vbm, iStorageController, iMediumAttachment, hd, dvd, vm); replay(vbm, iStorageController, iMediumAttachment, hd, dvd, vm);
VmSpec vmSpec = new IMachineToVmSpec().apply(vm); VmSpec vmSpec = new IMachineToVmSpec().apply(vm);
assertEquals(vmSpec.getVmName(), VM_NAME); assertEquals(vmSpec.getVmName(), VM_NAME);
assertEquals(vmSpec.getVmId(), VM_ID); assertEquals(vmSpec.getVmId(), VM_ID);
assertEquals(vmSpec.getMemory(), MEMORY_SIZE); assertEquals(vmSpec.getMemory(), MEMORY_SIZE);
@ -92,10 +92,10 @@ public class IMachineToVmSpecTest {
assertEquals(controller.getName(), CONTROLLER_NAME); assertEquals(controller.getName(), CONTROLLER_NAME);
assertEquals(controller.getBus(), CONTROLLER_BUS); assertEquals(controller.getBus(), CONTROLLER_BUS);
for (HardDisk hardDisk : controller.getHardDisks()) { for (HardDisk hardDisk : controller.getHardDisks()) {
assertEquals(hardDisk.getDiskPath(), PATH_TO_HD); assertEquals(hardDisk.getDiskPath(), PATH_TO_HD);
} }
for (IsoImage iso : controller.getIsoImages()) { 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; package org.jclouds.virtualbox.functions.admin;
import static org.easymock.EasyMock.expect; import org.eclipse.jetty.server.Server;
import static org.easymock.classextension.EasyMock.createMock; import org.jclouds.virtualbox.domain.IsoSpec;
import static org.easymock.classextension.EasyMock.replay; import org.testng.annotations.Test;
import static org.easymock.classextension.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import java.net.URI; import java.net.URI;
import org.eclipse.jetty.server.Server; import static org.easymock.EasyMock.expect;
import org.testng.annotations.Test; import static org.easymock.classextension.EasyMock.*;
import static org.testng.Assert.assertEquals;
/** /**
* @author Andrea Turli, Adrian Cole * @author Andrea Turli, Adrian Cole
@ -36,23 +35,24 @@ import org.testng.annotations.Test;
@Test(groups = "unit", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningTest") @Test(groups = "unit", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningTest")
public class StartJettyIfNotAlreadyRunningTest { public class StartJettyIfNotAlreadyRunningTest {
@Test @Test
public void testLaunchJettyServerWhenAlreadyRunningDoesntLaunchAgain() { public void testLoadStartsJettyServer() throws Exception {
Server jetty = createMock(Server.class); Server jetty = createMock(Server.class);
String preconfigurationUrl = "http://foo:8080"; String preconfigurationUrl = "http://foo:8080";
expect(jetty.getState()).andReturn(Server.STARTED); expect(jetty.getState()).andReturn(Server.STARTED);
replay(jetty); replay(jetty);
StartJettyIfNotAlreadyRunning starter = new StartJettyIfNotAlreadyRunning(jetty, preconfigurationUrl); StartJettyIfNotAlreadyRunning starter = new StartJettyIfNotAlreadyRunning(preconfigurationUrl, jetty);
starter.start();
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); verify(jetty);
} }
@Test @Test
public void testLaunchJettyServerWhenNotRunningStartsJettyOnCorrectHostPortAndBasedir() { public void testLaunchJettyServerWhenNotRunningStartsJettyOnCorrectHostPortAndBasedir() {
// TODO: all yours! // TODO: all yours!

View File

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