formatted most changed classes to comply with jclouds formatting guildelines

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

View File

@ -44,49 +44,50 @@ import org.jclouds.PropertiesBuilder;
*/
public class VirtualBoxPropertiesBuilder extends PropertiesBuilder {
public VirtualBoxPropertiesBuilder() {
super();
}
public VirtualBoxPropertiesBuilder() {
super();
}
public VirtualBoxPropertiesBuilder(Properties properties) {
super(properties);
}
public VirtualBoxPropertiesBuilder(Properties properties) {
super(properties);
}
@Override
protected Properties defaultProperties() {
Properties properties = super.defaultProperties();
properties.put(PROPERTY_ENDPOINT, "http://localhost:18083/");
// later version not in maven, yet
properties.put(PROPERTY_API_VERSION, "4.1.4");
properties.put(PROPERTY_BUILD_VERSION, "4.1.8r75467");
properties.put(PROPERTY_IDENTITY, "administrator");
properties.put(PROPERTY_CREDENTIAL, "12345");
@Override
protected Properties defaultProperties() {
Properties properties = super.defaultProperties();
properties.put(PROPERTY_ENDPOINT, "http://localhost:18083/");
// later version not in maven, yet
properties.put(PROPERTY_API_VERSION, "4.1.4");
properties.put(PROPERTY_IMAGE_LOGIN_USER, "toor:password");
properties.put(PROPERTY_IMAGE_AUTHENTICATE_SUDO, "true");
properties.put(PROPERTY_BUILD_VERSION, "4.1.8r75467");
properties.put(PROPERTY_IDENTITY, "administrator");
properties.put(PROPERTY_CREDENTIAL, "12345");
properties.put(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, "<Esc><Esc><Enter> "
+ "/install/vmlinuz noapic preseed/url=PRECONFIGURATION_URL "
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + "HOSTNAME "
+ "fb=false debconf/frontend=noninteractive "
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
+ "initrd=/install/initrd.gz -- <Enter>");
properties.put(PROPERTY_IMAGE_LOGIN_USER, "toor:password");
properties.put(PROPERTY_IMAGE_AUTHENTICATE_SUDO, "true");
properties.put(
VIRTUALBOX_WORKINGDIR,
System.getProperty("user.home") + File.separator
+ System.getProperty("test.virtualbox.workingDir", ".jclouds-vbox"));
properties.put(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, "<Esc><Esc><Enter> "
+ "/install/vmlinuz noapic preseed/url=PRECONFIGURATION_URL "
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + "HOSTNAME "
+ "fb=false debconf/frontend=noninteractive "
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
+ "initrd=/install/initrd.gz -- <Enter>");
// allow to set the descriptor as a sysprop but default to just setting a default file path. The configured supplier
// must be able to handle the chosen option.
properties.put(
VIRTUALBOX_IMAGES_DESCRIPTOR,
System.getProperty("test.virtualbox.image.descriptor.yaml", VIRTUALBOX_DEFAULT_DIR + File.separator
+ "images.yaml"));
properties.put(
VIRTUALBOX_WORKINGDIR,
System.getProperty("user.home") + File.separator
+ System.getProperty("test.virtualbox.workingDir", ".jclouds-vbox"));
properties.put(VIRTUALBOX_PRECONFIGURATION_URL, "http://10.0.2.2:8080/src/test/resources/preseed.cfg");
// allow to set the descriptor as a sysprop but default to just setting a default file path.
// The configured supplier
// must be able to handle the chosen option.
properties.put(
VIRTUALBOX_IMAGES_DESCRIPTOR,
System.getProperty("test.virtualbox.image.descriptor.yaml", VIRTUALBOX_DEFAULT_DIR + File.separator
+ "images.yaml"));
return properties;
}
properties.put(VIRTUALBOX_PRECONFIGURATION_URL, "http://10.0.2.2:8080/src/test/resources/preseed.cfg");
return properties;
}
}

View File

@ -53,147 +53,147 @@ import com.google.common.collect.Iterables;
import com.google.inject.Singleton;
/**
* Defines the connection between the {@link org.virtualbox_4_1.VirtualBoxManager} implementation and the jclouds
* {@link org.jclouds.compute.ComputeService}
* Defines the connection between the {@link org.virtualbox_4_1.VirtualBoxManager} implementation
* and the jclouds {@link org.jclouds.compute.ComputeService}
*
* @author Mattias Holmqvist, Andrea Turli
*/
@Singleton
public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IMachine, IMachine, Image, Location> {
private final Supplier<VirtualBoxManager> manager;
private final Map<Image, YamlImage> images;
private final LoadingCache<Image, Master> mastersLoader;
private final Function<NodeSpec, NodeAndInitialCredentials<IMachine>> cloneCreator;
private final Supplier<VirtualBoxManager> manager;
private final Map<Image, YamlImage> images;
private final LoadingCache<Image, Master> mastersLoader;
private final Function<NodeSpec, NodeAndInitialCredentials<IMachine>> cloneCreator;
@Inject
public VirtualBoxComputeServiceAdapter(Supplier<VirtualBoxManager> manager,
Supplier<Map<Image, YamlImage>> imagesMapper, LoadingCache<Image, Master> mastersLoader,
Function<NodeSpec, NodeAndInitialCredentials<IMachine>> cloneCreator) {
this.manager = checkNotNull(manager, "manager");
this.images = imagesMapper.get();
this.mastersLoader = mastersLoader;
this.cloneCreator = cloneCreator;
}
@Inject
public VirtualBoxComputeServiceAdapter(Supplier<VirtualBoxManager> manager,
Supplier<Map<Image, YamlImage>> imagesMapper, LoadingCache<Image, Master> mastersLoader,
Function<NodeSpec, NodeAndInitialCredentials<IMachine>> cloneCreator) {
this.manager = checkNotNull(manager, "manager");
this.images = imagesMapper.get();
this.mastersLoader = mastersLoader;
this.cloneCreator = cloneCreator;
}
@Override
public NodeAndInitialCredentials<IMachine> createNodeWithGroupEncodedIntoName(String tag, String name,
Template template) {
try {
Master master = mastersLoader.get(template.getImage());
NodeSpec nodeSpec = NodeSpec.builder().master(master).name(name).tag(tag).template(template).build();
return cloneCreator.apply(nodeSpec);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Iterable<IMachine> listNodes() {
return Iterables.filter(manager.get().getVBox().getMachines(), new Predicate<IMachine>() {
@Override
public boolean apply(IMachine arg0) {
return !arg0.getName().startsWith(VIRTUALBOX_NODE_PREFIX);
@Override
public NodeAndInitialCredentials<IMachine> createNodeWithGroupEncodedIntoName(String tag, String name,
Template template) {
try {
Master master = mastersLoader.get(template.getImage());
NodeSpec nodeSpec = NodeSpec.builder().master(master).name(name).tag(tag).template(template).build();
return cloneCreator.apply(nodeSpec);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
}
@Override
public Iterable<IMachine> listHardwareProfiles() {
return imageMachines();
}
@Override
public Iterable<IMachine> listNodes() {
return Iterables.filter(manager.get().getVBox().getMachines(), new Predicate<IMachine>() {
@Override
public boolean apply(IMachine arg0) {
return !arg0.getName().startsWith(VIRTUALBOX_NODE_PREFIX);
}
});
}
@Override
public Iterable<Image> listImages() {
return images.keySet();
}
@Override
public Iterable<IMachine> listHardwareProfiles() {
return imageMachines();
}
private Iterable<IMachine> imageMachines() {
final Predicate<? super IMachine> imagePredicate = new Predicate<IMachine>() {
@Override
public boolean apply(@Nullable IMachine iMachine) {
return iMachine.getName().startsWith(VIRTUALBOX_IMAGE_PREFIX);
@Override
public Iterable<Image> listImages() {
return images.keySet();
}
private Iterable<IMachine> imageMachines() {
final Predicate<? super IMachine> imagePredicate = new Predicate<IMachine>() {
@Override
public boolean apply(@Nullable IMachine iMachine) {
return iMachine.getName().startsWith(VIRTUALBOX_IMAGE_PREFIX);
}
};
final Iterable<IMachine> imageMachines = filter(manager.get().getVBox().getMachines(), imagePredicate);
return imageMachines;
}
@Override
public Iterable<Location> listLocations() {
// Not using the adapter to determine locations
return ImmutableSet.<Location> of();
}
@Override
public IMachine getNode(String vmName) {
return manager.get().getVBox().findMachine(vmName);
}
@Override
public void destroyNode(String vmName) {
IMachine machine = manager.get().getVBox().findMachine(vmName);
powerDownMachine(machine);
machine.unregister(CleanupMode.Full);
}
@Override
public void rebootNode(String vmName) {
IMachine machine = manager.get().getVBox().findMachine(vmName);
powerDownMachine(machine);
launchVMProcess(machine, manager.get().getSessionObject());
}
@Override
public void resumeNode(String vmName) {
IMachine machine = manager.get().getVBox().findMachine(vmName);
ISession machineSession;
try {
machineSession = manager.get().openMachineSession(machine);
machineSession.getConsole().resume();
machineSession.unlockMachine();
} catch (Exception e) {
throw Throwables.propagate(e);
}
};
final Iterable<IMachine> imageMachines = filter(manager.get().getVBox().getMachines(), imagePredicate);
return imageMachines;
}
}
@Override
public Iterable<Location> listLocations() {
// Not using the adapter to determine locations
return ImmutableSet.<Location> of();
}
@Override
public IMachine getNode(String vmName) {
return manager.get().getVBox().findMachine(vmName);
}
@Override
public void destroyNode(String vmName) {
IMachine machine = manager.get().getVBox().findMachine(vmName);
powerDownMachine(machine);
machine.unregister(CleanupMode.Full);
}
@Override
public void rebootNode(String vmName) {
IMachine machine = manager.get().getVBox().findMachine(vmName);
powerDownMachine(machine);
launchVMProcess(machine, manager.get().getSessionObject());
}
@Override
public void resumeNode(String vmName) {
IMachine machine = manager.get().getVBox().findMachine(vmName);
ISession machineSession;
try {
machineSession = manager.get().openMachineSession(machine);
machineSession.getConsole().resume();
machineSession.unlockMachine();
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
@Override
public void suspendNode(String vmName) {
IMachine machine = manager.get().getVBox().findMachine(vmName);
ISession machineSession;
try {
machineSession = manager.get().openMachineSession(machine);
machineSession.getConsole().pause();
machineSession.unlockMachine();
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
session.unlockMachine();
}
private void powerDownMachine(IMachine machine) {
try {
ISession machineSession = manager.get().openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try {
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
}
@Override
public void suspendNode(String vmName) {
IMachine machine = manager.get().getVBox().findMachine(vmName);
ISession machineSession;
try {
machineSession = manager.get().openMachineSession(machine);
machineSession.getConsole().pause();
machineSession.unlockMachine();
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
private void launchVMProcess(IMachine machine, ISession session) {
IProgress prog = machine.launchVMProcess(session, "gui", "");
prog.waitForCompletion(-1);
session.unlockMachine();
}
private void powerDownMachine(IMachine machine) {
try {
ISession machineSession = manager.get().openMachineSession(machine);
IProgress progress = machineSession.getConsole().powerDown();
progress.waitForCompletion(-1);
machineSession.unlockMachine();
while (!machine.getSessionState().equals(SessionState.Unlocked)) {
try {
System.out.println("waiting for unlocking session - session state: " + machine.getSessionState());
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}

View File

@ -103,185 +103,166 @@ import com.google.inject.TypeLiteral;
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
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);
}
public VirtualBoxComputeServiceContextModule() {
super(Supplier.class, Supplier.class);
}
@Override
protected void configure() {
super.configure();
bind(new TypeLiteral<ComputeServiceAdapter<IMachine, IMachine, Image, Location>>() {
}).to(VirtualBoxComputeServiceAdapter.class);
bind(new TypeLiteral<Function<IMachine, NodeMetadata>>() {
}).to(IMachineToNodeMetadata.class);
bind(new TypeLiteral<Function<Location, Location>>() {
}).to((Class) IdentityFunction.class);
bind(new TypeLiteral<Function<Image, Image>>() {
}).to((Class) IdentityFunction.class);
bind(new TypeLiteral<Function<IMachine, Hardware>>() {
}).to(IMachineToHardware.class);
bind(new TypeLiteral<Function<IMachine, Image>>() {
}).to(IMachineToImage.class);
bind(new TypeLiteral<CacheLoader<IsoSpec, URI>>() {
}).to((Class) StartJettyIfNotAlreadyRunning.class);
bind(new TypeLiteral<Supplier<VirtualBoxManager>>() {
}).to((Class) StartVBoxIfNotAlreadyRunning.class);
// the yaml config to image mapper
bind(new TypeLiteral<Supplier<Map<Image, YamlImage>>>() {
}).to((Class) ImagesToYamlImagesFromYamlDescriptor.class);
// the yaml config provider
bind(new TypeLiteral<Supplier<String>>() {
}).to((Class) YamlImagesFromFileConfig.class);
// the master machines cache
bind(new TypeLiteral<LoadingCache<Image, Master>>() {
}).to((Class) MastersCache.class);
// the master creating function
bind(new TypeLiteral<Function<MasterSpec, IMachine>>() {
}).to((Class) CreateAndInstallVm.class);
// the machine cloning function
bind(new TypeLiteral<Function<NodeSpec, NodeAndInitialCredentials<IMachine>>>() {
}).to((Class) NodeCreator.class);
bind(new TypeLiteral<Function<CloneSpec, IMachine>>() {
}).to((Class) CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.class);
@Override
protected void configure() {
super.configure();
bind(new TypeLiteral<ComputeServiceAdapter<IMachine, IMachine, Image, Location>>() {
}).to(VirtualBoxComputeServiceAdapter.class);
bind(new TypeLiteral<Function<IMachine, NodeMetadata>>() {
}).to(IMachineToNodeMetadata.class);
bind(new TypeLiteral<Function<Location, Location>>() {
}).to((Class) IdentityFunction.class);
bind(new TypeLiteral<Function<Image, Image>>() {
}).to((Class) IdentityFunction.class);
bind(new TypeLiteral<Function<IMachine, Hardware>>() {
}).to(IMachineToHardware.class);
bind(new TypeLiteral<Function<IMachine, Image>>() {
}).to(IMachineToImage.class);
bind(new TypeLiteral<CacheLoader<IsoSpec, URI>>() {
}).to((Class) StartJettyIfNotAlreadyRunning.class);
bind(new TypeLiteral<Supplier<VirtualBoxManager>>() {
}).to((Class) StartVBoxIfNotAlreadyRunning.class);
// the yaml config to image mapper
bind(new TypeLiteral<Supplier<Map<Image, YamlImage>>>() {
}).to((Class) ImagesToYamlImagesFromYamlDescriptor.class);
// the yaml config provider
bind(new TypeLiteral<Supplier<String>>() {
}).to((Class) YamlImagesFromFileConfig.class);
// the master machines cache
bind(new TypeLiteral<LoadingCache<Image, Master>>() {
}).to((Class) MastersCache.class);
// the master creating function
bind(new TypeLiteral<Function<MasterSpec, IMachine>>() {
}).to((Class) CreateAndInstallVm.class);
// the machine cloning function
bind(new TypeLiteral<Function<NodeSpec, NodeAndInitialCredentials<IMachine>>>() {
}).to((Class) NodeCreator.class);
bind(new TypeLiteral<Function<CloneSpec, IMachine>>() {
}).to((Class) CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.class);
// for byon
bind(new TypeLiteral<Function<URI, InputStream>>() {
}).to(SupplyFromProviderURIOrNodesProperty.class);
// for byon
bind(new TypeLiteral<Function<URI, InputStream>>() {
}).to(SupplyFromProviderURIOrNodesProperty.class);
bind(new TypeLiteral<Function<IMachine, SshClient>>() {
}).to(IMachineToSshClient.class);
bind(new TypeLiteral<Function<IMachine, SshClient>>() {
}).to(IMachineToSshClient.class);
bind(ExecutionType.class).toInstance(ExecutionType.GUI);
bind(LockType.class).toInstance(LockType.Write);
}
bind(ExecutionType.class).toInstance(ExecutionType.GUI);
bind(LockType.class).toInstance(LockType.Write);
}
@Provides
@Singleton
@Preconfiguration
protected LoadingCache<IsoSpec, URI> preconfiguration(CacheLoader<IsoSpec, URI> cacheLoader) {
return CacheBuilder.newBuilder().build(cacheLoader);
}
@Provides
@Singleton
@Preconfiguration
protected LoadingCache<IsoSpec, URI> preconfiguration(CacheLoader<IsoSpec, URI> cacheLoader) {
return CacheBuilder.newBuilder().build(cacheLoader);
}
@Provides
@Host
@Singleton
protected ComputeServiceContext provideHostController() {
String provider = "byon";
String identity = "";
String credential = "";
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()));
return new ComputeServiceContextFactory().createContext(provider, identity, credential,
ImmutableSet.<Module> of(new SLF4JLoggingModule(), new SshjSshClientModule(), hostModule));
}
@Provides
@Host
@Singleton
protected ComputeServiceContext provideHostController() {
String provider = "byon";
String identity = "";
String credential = "";
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()));
return new ComputeServiceContextFactory().createContext(provider, identity, credential,
ImmutableSet.<Module> of(new SLF4JLoggingModule(), new SshjSshClientModule(), hostModule));
}
@Provides
@Singleton
protected Server providesJettyServer(@Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
return new Server(URI.create(preconfigurationUrl).getPort());
}
@Provides
@Singleton
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>() {
@Provides
@Singleton
protected Function<Supplier<NodeMetadata>, VirtualBoxManager> provideVBox() {
return new Function<Supplier<NodeMetadata>, VirtualBoxManager>() {
@Override
public VirtualBoxManager apply(Supplier<NodeMetadata> nodeSupplier) {
return VirtualBoxManager.createInstance(nodeSupplier.get().getId());
}
@Override
public VirtualBoxManager apply(Supplier<NodeMetadata> nodeSupplier) {
return VirtualBoxManager.createInstance(nodeSupplier.get().getId());
}
@Override
public String toString() {
return "createInstanceByNodeId()";
}
@Override
public String toString() {
return "createInstanceByNodeId()";
}
};
}
};
}
@Provides
@Singleton
protected Supplier defaultClient(Supplier<VirtualBoxManager> in) {
return in;
}
@Provides
@Singleton
protected Supplier defaultClient(Supplier<VirtualBoxManager> in) {
return in;
}
@Provides
@Singleton
protected Predicate<SshClient> sshResponds(SshResponds sshResponds, Timeouts timeouts) {
return new RetryablePredicate<SshClient>(sshResponds, timeouts.nodeRunning);
}
@Provides
@Singleton
protected Predicate<SshClient> sshResponds(SshResponds sshResponds, Timeouts timeouts) {
return new RetryablePredicate<SshClient>(sshResponds, timeouts.nodeRunning);
}
@Override
protected Supplier provideHardware(ComputeServiceAdapter<IMachine, IMachine, Image, Location> adapter,
Function<IMachine, Hardware> transformer) {
return Suppliers.ofInstance(Collections.singleton(new HardwareBuilder().id("").build()));
}
@Override
protected Supplier provideHardware(ComputeServiceAdapter<IMachine, IMachine, Image, Location> adapter,
Function<IMachine, Hardware> transformer) {
return Suppliers.ofInstance(Collections.singleton(new HardwareBuilder().id("").build()));
}
@Override
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
return template.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04");
}
@Override
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
return template.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04");
}
@Provides
@Singleton
protected Supplier<NodeMetadata> host(Supplier<LoadingCache<String, Node>> nodes, NodeToNodeMetadata converter)
throws ExecutionException {
return Suppliers.compose(Functions.compose(converter, new Function<LoadingCache<String, Node>, Node>() {
@Provides
@Singleton
protected Supplier<NodeMetadata> host(Supplier<LoadingCache<String, Node>> nodes, NodeToNodeMetadata converter)
throws ExecutionException {
return Suppliers.compose(Functions.compose(converter, new Function<LoadingCache<String, Node>, Node>() {
@Override
public Node apply(LoadingCache<String, Node> arg0) {
return arg0.apply("host");
}
}), nodes);
}
@Override
public Node apply(LoadingCache<String, Node> arg0) {
return arg0.apply("host");
}
}), nodes);
}
@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)
.put(MachineState.Aborted, NodeState.ERROR)
.put(MachineState.Stuck, NodeState.ERROR)
@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).put(MachineState.Aborted, NodeState.ERROR)
.put(MachineState.Stuck, NodeState.ERROR)
.put(MachineState.Null,
NodeState.UNRECOGNIZED).build();
.put(MachineState.Null, NodeState.UNRECOGNIZED).build();
}

View File

@ -30,7 +30,7 @@ import java.io.File;
public interface VirtualBoxConstants {
public static final String VIRTUALBOX_IMAGE_PREFIX = "jclouds-image-";
public static final String VIRTUALBOX_NODE_PREFIX = "jclouds-node-";
public static final String VIRTUALBOX_PRECONFIGURATION_URL = "jclouds.virtualbox.preconfigurationurl";
@ -38,7 +38,7 @@ public interface VirtualBoxConstants {
public static final String VIRTUALBOX_INSTALLATION_KEY_SEQUENCE = "jclouds.virtualbox.installationkeysequence";
public static final String VIRTUALBOX_WORKINGDIR = "jclouds.virtualbox.workingdir";
public static final String VIRTUALBOX_IMAGES_DESCRIPTOR = "jclouds.virtualbox.image.descriptor.yaml";
public static final String VIRTUALBOX_MACHINE_GROUP = "jclouds.virtualbox.machinegroup";
@ -54,10 +54,10 @@ public interface VirtualBoxConstants {
public static final String VIRTUALBOX_WEBSERVER_IDENTITY = "jclouds.virtualbox.webserver.identity";
public static final String VIRTUALBOX_WEBSERVER_CREDENTIAL = "jclouds.virtualbox.webserver.credential";
public static final String VIRTUALBOX_DEFAULT_DIR = System.getProperty("user.home")
+ File.separator +".jclouds-vbox";
public static final String VIRTUALBOX_DEFAULT_DIR = System.getProperty("user.home") + File.separator
+ ".jclouds-vbox";
public static final String VIRTUALBOX_PROVIDER = "virtualbox";
}

View File

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

View File

@ -23,45 +23,45 @@ import org.virtualbox_4_1.IMachine;
public class Master {
private final IMachine machine;
private final MasterSpec spec;
public static Builder builder() {
return new Builder();
}
public static class Builder {
private IMachine machine;
private MasterSpec spec;
public Builder machine(IMachine machine){
this.machine = machine;
return this;
}
public Builder spec(MasterSpec spec){
this.spec = spec;
return this;
}
public Master build(){
return new Master(machine,spec);
}
}
private final IMachine machine;
private final MasterSpec spec;
private Master(IMachine machine, MasterSpec spec) {
super();
this.machine = machine;
this.spec = spec;
}
public IMachine getMachine() {
return machine;
}
public MasterSpec getSpec() {
return spec;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private IMachine machine;
private MasterSpec spec;
public Builder machine(IMachine machine) {
this.machine = machine;
return this;
}
public Builder spec(MasterSpec spec) {
this.spec = spec;
return this;
}
public Master build() {
return new Master(machine, spec);
}
}
private Master(IMachine machine, MasterSpec spec) {
super();
this.machine = machine;
this.spec = spec;
}
public IMachine getMachine() {
return machine;
}
public MasterSpec getSpec() {
return spec;
}
}

View File

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

View File

@ -23,70 +23,70 @@ import org.jclouds.compute.domain.Template;
public class NodeSpec {
private final Master master;
private final String name;
private final String tag;
private final Template template;
private final Master master;
private final String name;
private final String tag;
private final Template template;
public static Builder builder() {
return new Builder();
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
public static class Builder {
private Master master;
private String name;
private String tag;
private Template template;
private Master master;
private String name;
private String tag;
private Template template;
public Builder master(Master master) {
public Builder master(Master master) {
this.master = master;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder tag(String tag) {
this.tag = tag;
return this;
}
public Builder template(Template template) {
this.template = template;
return this;
}
public NodeSpec build() {
return new NodeSpec(master, name, tag, template);
}
}
private NodeSpec(Master master, String name, String tag, Template template) {
super();
this.master = master;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder tag(String tag) {
this.tag = tag;
return this;
}
public Builder template(Template template) {
this.template = template;
return this;
}
}
public NodeSpec build() {
return new NodeSpec(master, name, tag, template);
}
public Master getMaster() {
return master;
}
}
public String getName() {
return name;
}
private NodeSpec(Master master, String name, String tag, Template template) {
super();
this.master = master;
this.name = name;
this.tag = tag;
this.template = template;
}
public String getTag() {
return tag;
}
public Master getMaster() {
return master;
}
public String getName() {
return name;
}
public String getTag() {
return tag;
}
public Template getTemplate() {
return template;
}
public Template getTemplate() {
return template;
}
}

View File

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

View File

@ -139,10 +139,10 @@ public class YamlImage {
OsFamily family = parseOsFamilyOrUnrecognized(arg0.os_family);
OperatingSystem operatingSystem = OperatingSystem.builder().description(arg0.os_description).family(family)
.version(arg0.os_version).is64Bit(arg0.os_64bit).build();
.version(arg0.os_version).is64Bit(arg0.os_64bit).build();
return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description)
.operatingSystem(operatingSystem).build();
.operatingSystem(operatingSystem).build();
}
};

View File

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

View File

@ -61,118 +61,120 @@ import com.google.inject.Inject;
@Singleton
public class CreateAndInstallVm implements Function<MasterSpec, IMachine> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Supplier<VirtualBoxManager> manager;
private final CreateAndRegisterMachineFromIsoIfNotAlreadyExists createAndRegisterMachineFromIsoIfNotAlreadyExists;
private final GuestAdditionsInstaller guestAdditionsInstaller;
private final Predicate<SshClient> sshResponds;
private final ExecutionType executionType;
private LoadingCache<IsoSpec, URI> preConfiguration;
private final Function<IMachine, SshClient> sshClientForIMachine;
private final MachineUtils machineUtils;
private final IMachineToNodeMetadata imachineToNodeMetadata;
private final Supplier<VirtualBoxManager> manager;
private final CreateAndRegisterMachineFromIsoIfNotAlreadyExists createAndRegisterMachineFromIsoIfNotAlreadyExists;
private final GuestAdditionsInstaller guestAdditionsInstaller;
private final Predicate<SshClient> sshResponds;
private final ExecutionType executionType;
private LoadingCache<IsoSpec, URI> preConfiguration;
private final Function<IMachine, SshClient> sshClientForIMachine;
private final MachineUtils machineUtils;
private final IMachineToNodeMetadata imachineToNodeMetadata;
@Inject
public CreateAndInstallVm(Supplier<VirtualBoxManager> manager,
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
GuestAdditionsInstaller guestAdditionsInstaller, IMachineToNodeMetadata imachineToNodeMetadata,
Predicate<SshClient> sshResponds, Function<IMachine, SshClient> sshClientForIMachine,
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;
this.guestAdditionsInstaller = guestAdditionsInstaller;
this.imachineToNodeMetadata = imachineToNodeMetadata;
}
@Inject
public CreateAndInstallVm(Supplier<VirtualBoxManager> manager,
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
GuestAdditionsInstaller guestAdditionsInstaller, IMachineToNodeMetadata imachineToNodeMetadata,
Predicate<SshClient> sshResponds, Function<IMachine, SshClient> sshClientForIMachine,
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;
this.guestAdditionsInstaller = guestAdditionsInstaller;
this.imachineToNodeMetadata = imachineToNodeMetadata;
}
@Override
public IMachine apply(MasterSpec masterSpec) {
@Override
public IMachine apply(MasterSpec masterSpec) {
VmSpec vmSpec = masterSpec.getVmSpec();
IsoSpec isoSpec = masterSpec.getIsoSpec();
String vmName = vmSpec.getVmName();
IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(masterSpec);
VmSpec vmSpec = masterSpec.getVmSpec();
IsoSpec isoSpec = masterSpec.getIsoSpec();
String vmName = vmSpec.getVmName();
// Launch machine and wait for it to come online
ensureMachineIsLaunched(vmName);
IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(masterSpec);
URI uri = preConfiguration.getUnchecked(isoSpec);
String installationKeySequence = isoSpec.getInstallationKeySequence().replace("PRECONFIGURATION_URL",
uri.toASCIIString());
// Launch machine and wait for it to come online
ensureMachineIsLaunched(vmName);
configureOsInstallationWithKeyboardSequence(vmName, installationKeySequence);
SshClient client = sshClientForIMachine.apply(vm);
logger.debug(">> awaiting installation to finish node(%s)", vmName);
URI uri = preConfiguration.getUnchecked(isoSpec);
String installationKeySequence = isoSpec.getInstallationKeySequence().replace("PRECONFIGURATION_URL",
uri.toASCIIString());
checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", vmName);
configureOsInstallationWithKeyboardSequence(vmName, installationKeySequence);
SshClient client = sshClientForIMachine.apply(vm);
logger.debug(">> awaiting installation to finish node(%s)", vmName);
logger.debug(">> awaiting installation of guest additions on vm: %s", vmName);
checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", vmName);
checkState(guestAdditionsInstaller.apply(vm));
logger.debug(">> awaiting installation of guest additions on vm: %s", vmName);
logger.debug(">> awaiting post-installation actions on vm: %s", vmName);
checkState(guestAdditionsInstaller.apply(vm));
NodeMetadata vmMetadata = imachineToNodeMetadata.apply(vm);
ListenableFuture<ExecResponse> execFuture = machineUtils.runScriptOnNode(vmMetadata, call("cleanupUdevIfNeeded"),
RunScriptOptions.NONE);
ExecResponse execResponse = Futures.getUnchecked(execFuture);
checkState(execResponse.getExitCode() == 0);
logger.debug(">> awaiting post-installation actions on vm: %s", vmName);
logger.debug("<< installation of image complete. Powering down node(%s)", vmName);
ensureMachineHasPowerDown(vmName);
return vm;
}
NodeMetadata vmMetadata = imachineToNodeMetadata.apply(vm);
ListenableFuture<ExecResponse> execFuture = machineUtils.runScriptOnNode(vmMetadata, call("cleanupUdevIfNeeded"),
RunScriptOptions.NONE);
ExecResponse execResponse = Futures.getUnchecked(execFuture);
checkState(execResponse.getExitCode() == 0);
private void configureOsInstallationWithKeyboardSequence(String vmName, String installationKeySequence) {
Iterable<List<Integer>> scancodelist = transform(Splitter.on(" ").split(installationKeySequence),
new StringToKeyCode());
logger.debug("<< installation of image complete. Powering down node(%s)", vmName);
for (List<Integer> scancodes : scancodelist) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new SendScancodes(scancodes));
}
}
ensureMachineHasPowerDown(vmName);
return vm;
}
/**
* ensureMachineHasPowerDown needs to have this delay just to ensure that the machine is completely powered off
*
* @param vmName
*/
private void ensureMachineHasPowerDown(String vmName) {
while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.POWERED_OFF)) {
try {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() {
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
});
} catch (RuntimeException e) {
// sometimes the machine might be powered of between the while test and the call to lockSessionOnMachineAndApply
if (e.getMessage().contains("Invalid machine state: PoweredOff")){
return;
} else if(e.getMessage().contains("VirtualBox error: The object is not ready")){
continue;
} else {
throw e;
}
private void configureOsInstallationWithKeyboardSequence(String vmName, String installationKeySequence) {
Iterable<List<Integer>> scancodelist = transform(Splitter.on(" ").split(installationKeySequence),
new StringToKeyCode());
for (List<Integer> scancodes : scancodelist) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new SendScancodes(scancodes));
}
}
}
}
private void ensureMachineIsLaunched(String vmName) {
machineUtils.applyForMachine(vmName, new LaunchMachineIfNotAlreadyRunning(manager.get(), executionType, ""));
}
/**
* ensureMachineHasPowerDown needs to have this delay just to ensure that the machine is
* completely powered off
*
* @param vmName
*/
private void ensureMachineHasPowerDown(String vmName) {
while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.POWERED_OFF)) {
try {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() {
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
});
} catch (RuntimeException e) {
// sometimes the machine might be powered of between the while test and the call to
// lockSessionOnMachineAndApply
if (e.getMessage().contains("Invalid machine state: PoweredOff")) {
return;
} else if (e.getMessage().contains("VirtualBox error: The object is not ready")) {
continue;
} else {
throw e;
}
}
}
}
private void ensureMachineIsLaunched(String vmName) {
machineUtils.applyForMachine(vmName, new LaunchMachineIfNotAlreadyRunning(manager.get(), executionType, ""));
}
}

View File

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

View File

@ -61,10 +61,10 @@ public class IMachineToImage implements Function<IMachine, Image> {
OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription());
String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), osVersionMap);
OperatingSystem os = OperatingSystem.builder().description(guestOSType.getDescription()).family(family)
.version(version).is64Bit(guestOSType.getIs64Bit()).build();
.version(version).is64Bit(guestOSType.getIs64Bit()).build();
return new ImageBuilder().id("" + from.getId()).name(from.getName()).description(from.getDescription())
.operatingSystem(os).build();
return new ImageBuilder().id("" + from.getId()).name(from.getName()).description(from.getDescription())
.operatingSystem(os).build();
}
}

View File

@ -39,11 +39,11 @@ import com.google.inject.Inject;
@Singleton
public class IMachineToSshClient implements Function<IMachine, SshClient> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final SshClient.Factory sshClientFactory;
@Inject
@ -53,8 +53,8 @@ public class IMachineToSshClient implements Function<IMachine, SshClient> {
@Override
public SshClient apply(final IMachine vm) {
INetworkAdapter networkAdapter = vm.getNetworkAdapter(0L);
INetworkAdapter networkAdapter = vm.getNetworkAdapter(0L);
SshClient client = null;
checkNotNull(networkAdapter);
for (String nameProtocolnumberAddressInboudportGuestTargetport : networkAdapter.getNatDriver().getRedirects()) {
@ -66,8 +66,8 @@ public class IMachineToSshClient implements Function<IMachine, SshClient> {
// TODO: we need a way to align the default login credentials from the iso with the
// vmspec
if ("1".equals(protocolNumber) && "22".equals(targetPort)) {
client = sshClientFactory.create(new IPSocket(hostAddress, Integer.parseInt(inboundPort)),
LoginCredentials.builder().user("toor").password("password").authenticateSudo(true).build());
client = sshClientFactory.create(new IPSocket(hostAddress, Integer.parseInt(inboundPort)), LoginCredentials
.builder().user("toor").password("password").authenticateSudo(true).build());
}
}
checkNotNull(client);

View File

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

View File

@ -69,121 +69,120 @@ import com.google.common.collect.Maps;
*/
public class MastersCache extends AbstractLoadingCache<Image, Master> {
private final Map<String, Master> masters = Maps.newHashMap();
private final Function<MasterSpec, IMachine> masterCreatorAndInstaller;
private final Map<String, YamlImage> imageMapping;
private final String workingDir;
private final String adminDisk;
private final String guestAdditionsIso;
private final String installationKeySequence;
private final String isosDir;
private Supplier<VirtualBoxManager> manager;
private final Map<String, Master> masters = Maps.newHashMap();
private final Function<MasterSpec, IMachine> masterCreatorAndInstaller;
private final Map<String, YamlImage> imageMapping;
private final String workingDir;
private final String adminDisk;
private final String guestAdditionsIso;
private final String installationKeySequence;
private final String isosDir;
private Supplier<VirtualBoxManager> manager;
@Inject
public MastersCache(@Named(Constants.PROPERTY_BUILD_VERSION) String version,
@Named(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) String installationKeySequence,
@Named(VIRTUALBOX_WORKINGDIR) String workingDir, Function<MasterSpec, IMachine> masterLoader,
Supplier<Map<Image, YamlImage>> yamlMapper, Supplier<VirtualBoxManager> manager) {
checkNotNull(version, "version");
checkNotNull(installationKeySequence, "installationKeySequence");
checkNotNull(manager, "vboxmanager");
this.manager = manager;
this.masterCreatorAndInstaller = masterLoader;
this.installationKeySequence = installationKeySequence;
this.workingDir = workingDir == null ? VIRTUALBOX_DEFAULT_DIR : workingDir;
File wdFile = new File(this.workingDir);
if (!wdFile.exists()) {
wdFile.mkdirs();
}
this.isosDir = wdFile.getAbsolutePath() + File.separator + "isos";
this.adminDisk = workingDir + "/testadmin.vdi";
this.imageMapping = Maps.newLinkedHashMap();
for (Entry<Image, YamlImage> entry : yamlMapper.get().entrySet()) {
this.imageMapping.put(entry.getKey().getId(), entry.getValue());
}
this.guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", isosDir,
Iterables.get(Splitter.on('r').split(version), 0));
checkState(new File(guestAdditionsIso).exists(), "guest additions iso does not exist at: " + guestAdditionsIso);
}
@Override
public Master get(Image key) throws ExecutionException {
// check if we have loaded this machine before
if (masters.containsKey(key.getId())) {
return masters.get(key);
}
// the yaml image
YamlImage yamlImage = imageMapping.get(key.getId());
checkNotNull(yamlImage, "could not find yaml image for image: " + key);
// check if the iso is here, download if not
String localIsoUrl = getFilePathOrDownload(yamlImage.iso);
String vmName = VIRTUALBOX_IMAGE_PREFIX + yamlImage.id;
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, localIsoUrl).attachHardDisk(hardDisk).attachISO(1, 1, guestAdditionsIso).build();
VmSpec vmSpecification = VmSpec.builder().id(yamlImage.id).name(vmName).memoryMB(512).osTypeId("")
.controller(ideController).forceOverwrite(true).cleanUpMode(CleanupMode.Full).build();
NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter)
.build();
NetworkSpec networkSpec = NetworkSpec.builder().addNIC(0L, networkInterfaceCard).build();
MasterSpec masterSpec = MasterSpec
.builder()
.vm(vmSpecification)
.iso(
IsoSpec.builder().sourcePath(localIsoUrl)
.installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName())).build())
.network(networkSpec).build();
IMachine masterMachine;
// try and find a master machine in vbox
try {
masterMachine = manager.get().getVBox().findMachine(vmName);
} catch (VBoxException e) {
if (machineNotFoundException(e)) {
// create the master machine if it can't be found
masterMachine = masterCreatorAndInstaller.apply(masterSpec);
@Inject
public MastersCache(@Named(Constants.PROPERTY_BUILD_VERSION) String version,
@Named(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) String installationKeySequence,
@Named(VIRTUALBOX_WORKINGDIR) String workingDir, Function<MasterSpec, IMachine> masterLoader,
Supplier<Map<Image, YamlImage>> yamlMapper, Supplier<VirtualBoxManager> manager) {
checkNotNull(version, "version");
checkNotNull(installationKeySequence, "installationKeySequence");
checkNotNull(manager, "vboxmanager");
this.manager = manager;
this.masterCreatorAndInstaller = masterLoader;
this.installationKeySequence = installationKeySequence;
this.workingDir = workingDir == null ? VIRTUALBOX_DEFAULT_DIR : workingDir;
File wdFile = new File(this.workingDir);
if (!wdFile.exists()) {
wdFile.mkdirs();
}
else {
throw e;
this.isosDir = wdFile.getAbsolutePath() + File.separator + "isos";
this.adminDisk = workingDir + "/testadmin.vdi";
this.imageMapping = Maps.newLinkedHashMap();
for (Entry<Image, YamlImage> entry : yamlMapper.get().entrySet()) {
this.imageMapping.put(entry.getKey().getId(), entry.getValue());
}
this.guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", isosDir,
Iterables.get(Splitter.on('r').split(version), 0));
checkState(new File(guestAdditionsIso).exists(), "guest additions iso does not exist at: " + guestAdditionsIso);
}
Master master = Master.builder().machine(masterMachine).spec(masterSpec).build();
@Override
public Master get(Image key) throws ExecutionException {
// check if we have loaded this machine before
if (masters.containsKey(key.getId())) {
return masters.get(key);
}
masters.put(key.getId(), master);
// the yaml image
YamlImage yamlImage = imageMapping.get(key.getId());
return master;
}
checkNotNull(yamlImage, "could not find yaml image for image: " + key);
private String getFilePathOrDownload(String httpUrl) throws ExecutionException {
// TODO validation
String fileName = httpUrl.substring(httpUrl.lastIndexOf('/') + 1, httpUrl.length());
File localFile = new File(isosDir, fileName);
// TODO download. for now just expect the file to be there
checkState(localFile.exists(), "iso file has not been downloaded: " + fileName);
return localFile.getAbsolutePath();
}
// check if the iso is here, download if not
String localIsoUrl = getFilePathOrDownload(yamlImage.iso);
@Override
public Master getIfPresent(Image key) {
if (masters.containsKey(key.getId())) {
return masters.get(key.getId());
}
return null;
}
String vmName = VIRTUALBOX_IMAGE_PREFIX + yamlImage.id;
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, localIsoUrl).attachHardDisk(hardDisk).attachISO(1, 1, guestAdditionsIso).build();
VmSpec vmSpecification = VmSpec.builder().id(yamlImage.id).name(vmName).memoryMB(512).osTypeId("")
.controller(ideController).forceOverwrite(true).cleanUpMode(CleanupMode.Full).build();
NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter)
.build();
NetworkSpec networkSpec = NetworkSpec.builder().addNIC(0L, networkInterfaceCard).build();
MasterSpec masterSpec = MasterSpec
.builder()
.vm(vmSpecification)
.iso(IsoSpec.builder().sourcePath(localIsoUrl)
.installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName()))
.build()).network(networkSpec).build();
IMachine masterMachine;
// try and find a master machine in vbox
try {
masterMachine = manager.get().getVBox().findMachine(vmName);
} catch (VBoxException e) {
if (machineNotFoundException(e)) {
// create the master machine if it can't be found
masterMachine = masterCreatorAndInstaller.apply(masterSpec);
} else {
throw e;
}
}
Master master = Master.builder().machine(masterMachine).spec(masterSpec).build();
masters.put(key.getId(), master);
return master;
}
private String getFilePathOrDownload(String httpUrl) throws ExecutionException {
// TODO validation
String fileName = httpUrl.substring(httpUrl.lastIndexOf('/') + 1, httpUrl.length());
File localFile = new File(isosDir, fileName);
// TODO download. for now just expect the file to be there
checkState(localFile.exists(), "iso file has not been downloaded: " + fileName);
return localFile.getAbsolutePath();
}
@Override
public Master getIfPresent(Image key) {
if (masters.containsKey(key.getId())) {
return masters.get(key.getId());
}
return null;
}
}

View File

@ -48,57 +48,58 @@ import com.google.common.base.Supplier;
@Singleton
public class NodeCreator implements Function<NodeSpec, NodeAndInitialCredentials<IMachine>> {
private final Supplier<VirtualBoxManager> manager;
private final Function<CloneSpec, IMachine> cloner;
private final Supplier<VirtualBoxManager> manager;
private final Function<CloneSpec, IMachine> cloner;
@Inject
public NodeCreator(Supplier<VirtualBoxManager> manager, Function<CloneSpec, IMachine> cloner, MachineUtils machineUtils) {
this.manager = manager;
this.cloner = cloner;
}
@Inject
public NodeCreator(Supplier<VirtualBoxManager> manager, Function<CloneSpec, IMachine> cloner,
MachineUtils machineUtils) {
this.manager = manager;
this.cloner = cloner;
}
@Override
public NodeAndInitialCredentials<IMachine> apply(NodeSpec nodeSpec) {
@Override
public NodeAndInitialCredentials<IMachine> apply(NodeSpec nodeSpec) {
Master master = nodeSpec.getMaster();
Master master = nodeSpec.getMaster();
if (master.getMachine().getCurrentSnapshot() != null) {
ISession session;
try {
session = manager.get().openMachineSession(master.getMachine());
} catch (Exception e) {
throw new RuntimeException("error opening vbox machine session: " + e.getMessage(), e);
if (master.getMachine().getCurrentSnapshot() != null) {
ISession session;
try {
session = manager.get().openMachineSession(master.getMachine());
} catch (Exception e) {
throw new RuntimeException("error opening vbox machine session: " + e.getMessage(), e);
}
session.getConsole().deleteSnapshot(master.getMachine().getCurrentSnapshot().getId());
session.unlockMachine();
}
session.getConsole().deleteSnapshot(master.getMachine().getCurrentSnapshot().getId());
session.unlockMachine();
}
String masterNameWithoutPrefix = master.getSpec().getVmSpec().getVmName().replace(VIRTUALBOX_IMAGE_PREFIX, "");
String masterNameWithoutPrefix = master.getSpec().getVmSpec().getVmName().replace(VIRTUALBOX_IMAGE_PREFIX, "");
String cloneName = VIRTUALBOX_NODE_PREFIX + masterNameWithoutPrefix + "-" + nodeSpec.getTag() + "-"
+ nodeSpec.getName();
String cloneName = VIRTUALBOX_NODE_PREFIX + masterNameWithoutPrefix + "-" + nodeSpec.getTag() + "-"
+ nodeSpec.getName();
VmSpec cloneVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(512).cleanUpMode(CleanupMode.Full)
.forceOverwrite(true).build();
VmSpec cloneVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(512).cleanUpMode(CleanupMode.Full)
.forceOverwrite(true).build();
NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter)
.build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter)
.build();
NetworkSpec networkSpec = NetworkSpec.builder().addNIC(0L, networkInterfaceCard).build();
NetworkSpec networkSpec = NetworkSpec.builder().addNIC(0L, networkInterfaceCard).build();
CloneSpec cloneSpec = CloneSpec.builder().linked(true).master(master.getMachine()).network(networkSpec)
.vm(cloneVmSpec).build();
CloneSpec cloneSpec = CloneSpec.builder().linked(true).master(master.getMachine()).network(networkSpec)
.vm(cloneVmSpec).build();
IMachine cloned = cloner.apply(cloneSpec);
IMachine cloned = cloner.apply(cloneSpec);
new LaunchMachineIfNotAlreadyRunning(manager.get(), ExecutionType.GUI, "").apply(cloned);
new LaunchMachineIfNotAlreadyRunning(manager.get(), ExecutionType.GUI, "").apply(cloned);
// TODO get credentials from somewhere else (they are also HC in IMachineToSshClient)
NodeAndInitialCredentials<IMachine> nodeAndInitialCredentials = new NodeAndInitialCredentials<IMachine>(cloned,
cloneName, LoginCredentials.builder().user("toor").password("password").authenticateSudo(true).build());
// TODO get credentials from somewhere else (they are also HC in IMachineToSshClient)
NodeAndInitialCredentials<IMachine> nodeAndInitialCredentials = new NodeAndInitialCredentials<IMachine>(cloned,
cloneName, LoginCredentials.builder().user("toor").password("password").authenticateSudo(true).build());
return nodeAndInitialCredentials;
}
return nodeAndInitialCredentials;
}
}

View File

@ -43,22 +43,22 @@ import com.google.common.base.Supplier;
*/
public class YamlImagesFromFileConfig implements Supplier<String> {
private String yamlFilePath;
private String yamlFilePath;
@Inject
public YamlImagesFromFileConfig(@Named(VirtualBoxConstants.VIRTUALBOX_IMAGES_DESCRIPTOR) String yamlFilePath) {
this.yamlFilePath = yamlFilePath;
}
@Inject
public YamlImagesFromFileConfig(@Named(VirtualBoxConstants.VIRTUALBOX_IMAGES_DESCRIPTOR) String yamlFilePath) {
this.yamlFilePath = yamlFilePath;
}
@Override
public String get() {
checkNotNull(yamlFilePath, "yaml file path");
File yamlFile = new File(yamlFilePath);
checkState(yamlFile.exists(), "yaml file does not exist at: " + yamlFilePath);
try {
return IOUtils.toString(new FileInputStream(yamlFile));
} catch (IOException e) {
throw new RuntimeException("error reading yaml file");
}
}
@Override
public String get() {
checkNotNull(yamlFilePath, "yaml file path");
File yamlFile = new File(yamlFilePath);
checkState(yamlFile.exists(), "yaml file does not exist at: " + yamlFilePath);
try {
return IOUtils.toString(new FileInputStream(yamlFile));
} catch (IOException e) {
throw new RuntimeException("error reading yaml file");
}
}
}

View File

@ -43,42 +43,42 @@ import com.google.common.collect.Maps;
@Singleton
public class ImagesToYamlImagesFromYamlDescriptor implements Supplier<Map<Image, YamlImage>> {
private String yamlDescriptor;
private String yamlDescriptor;
@Inject
public ImagesToYamlImagesFromYamlDescriptor(Supplier<String> yamlDescriptorSupplier) {
this.yamlDescriptor = yamlDescriptorSupplier.get();
checkNotNull(yamlDescriptor, "yaml descriptor");
checkState(!yamlDescriptor.equals(""), "yaml descriptor is empty");
}
@Inject
public ImagesToYamlImagesFromYamlDescriptor(Supplier<String> yamlDescriptorSupplier) {
this.yamlDescriptor = yamlDescriptorSupplier.get();
checkNotNull(yamlDescriptor, "yaml descriptor");
checkState(!yamlDescriptor.equals(""), "yaml descriptor is empty");
}
/**
* Type-safe config class for YAML
*
*/
public static class Config {
public List<YamlImage> images;
}
/**
* Type-safe config class for YAML
*
*/
public static class Config {
public List<YamlImage> images;
}
@Override
public Map<Image, YamlImage> get() {
@Override
public Map<Image, YamlImage> get() {
Constructor constructor = new Constructor(Config.class);
Constructor constructor = new Constructor(Config.class);
TypeDescription imageDesc = new TypeDescription(YamlImage.class);
imageDesc.putListPropertyType("images", String.class);
constructor.addTypeDescription(imageDesc);
TypeDescription imageDesc = new TypeDescription(YamlImage.class);
imageDesc.putListPropertyType("images", String.class);
constructor.addTypeDescription(imageDesc);
Yaml yaml = new Yaml(constructor);
Config config = (Config) yaml.load(yamlDescriptor);
checkState(config != null, "missing config: class");
checkState(config.images != null, "missing images: collection");
Yaml yaml = new Yaml(constructor);
Config config = (Config) yaml.load(yamlDescriptor);
checkState(config != null, "missing config: class");
checkState(config.images != null, "missing images: collection");
Map<Image, YamlImage> backingMap = Maps.newLinkedHashMap();
for (YamlImage yamlImage : config.images) {
backingMap.put(YamlImage.toImage.apply(yamlImage), yamlImage);
}
return backingMap;
}
Map<Image, YamlImage> backingMap = Maps.newLinkedHashMap();
for (YamlImage yamlImage : config.images) {
backingMap.put(YamlImage.toImage.apply(yamlImage), yamlImage);
}
return backingMap;
}
}

View File

@ -59,165 +59,168 @@ import com.google.inject.Inject;
@Singleton
public class MachineUtils {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Supplier<VirtualBoxManager> manager;
private final Factory scriptRunner;
private final Supplier<NodeMetadata> host;
private final Supplier<VirtualBoxManager> manager;
private final Factory scriptRunner;
private final Supplier<NodeMetadata> host;
@Inject
public MachineUtils(Supplier<VirtualBoxManager> manager, RunScriptOnNode.Factory scriptRunner,
Supplier<NodeMetadata> host) {
super();
this.manager = manager;
this.scriptRunner = scriptRunner;
this.host = host;
}
@Inject
public MachineUtils(Supplier<VirtualBoxManager> manager, RunScriptOnNode.Factory scriptRunner,
Supplier<NodeMetadata> host) {
super();
this.manager = manager;
this.scriptRunner = scriptRunner;
this.host = host;
}
public ListenableFuture<ExecResponse> runScriptOnNode(NodeMetadata metadata, Statement statement,
RunScriptOptions options) {
return scriptRunner.submit(metadata, statement, options);
}
public ListenableFuture<ExecResponse> runScriptOnNode(NodeMetadata metadata, Statement statement,
RunScriptOptions options) {
return scriptRunner.submit(metadata, statement, options);
}
/**
* Locks the machine and executes the given function using the machine matching the given id. Since the machine is
* locked it is possible to 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
* @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>() {
/**
* Locks the machine and executes the given function using the machine matching the given id.
* Since the machine is locked it is possible to 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
* @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>() {
@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();
}
});
}
});
}
/**
* Locks the machine and executes the given function using the current session. Since the machine is locked it is
* possible to perform some 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
* @return the result from applying the function to the session.
*/
public <T> T lockSessionOnMachineAndApply(String machineId, LockType type, Function<ISession, T> function) {
try {
ISession session = lockSessionOnMachine(type, machineId);
/**
* Locks the machine and executes the given function using the current session. Since the machine
* is locked it is possible to perform some 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
* @return the result from applying the function to the session.
*/
public <T> T lockSessionOnMachineAndApply(String machineId, LockType type, Function<ISession, T> function) {
try {
return function.apply(session);
} finally {
session.unlockMachine();
ISession session = lockSessionOnMachine(type, machineId);
try {
return function.apply(session);
} finally {
session.unlockMachine();
}
} catch (VBoxException e) {
throw new RuntimeException(String.format("error applying %s to %s with %s lock: %s", function, machineId,
type, e.getMessage()), e);
}
} catch (VBoxException e) {
throw new RuntimeException(String.format("error applying %s to %s with %s lock: %s", function, machineId, type,
e.getMessage()), e);
}
}
}
private ISession lockSessionOnMachine(LockType type, String machineId) {
return new MutableMachine(manager, type).apply(machineId);
}
private ISession lockSessionOnMachine(LockType type, String machineId) {
return new MutableMachine(manager, type).apply(machineId);
}
private void unlockMachine(final String machineId) {
IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
if (immutableMachine.getSessionState().equals(SessionState.Locked)) {
Statement kill = newStatementList(call("default"), findPid(immutableMachine.getSessionPid().toString()), kill());
scriptRunner.create(host.get(), kill, runAsRoot(false).wrapInInitScript(false)).init().call();
}
}
/**
* Unlocks the machine and executes the given function using the machine 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
* @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);
private void unlockMachine(final String 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);
}
}
/**
* Unlocks the machine and executes the given function, if the machine is 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
* @return the result from applying the function to the session.
*/
public <T> T unlockMachineAndApplyOrReturnNullIfNotRegistered(String machineId, Function<IMachine, T> function) {
try {
return unlockMachineAndApply(machineId, function);
} catch (RuntimeException e) {
VBoxException vbex = Throwables2.getFirstThrowableOfType(e, VBoxException.class);
if (vbex != null && vbex.getMessage().indexOf("not find a registered") == -1)
throw e;
return null;
}
}
/**
* @param machineId
* @param function
* @return
*/
public <T> T applyForMachine(final String machineId, final Function<IMachine, T> function) {
final IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
return new Function<IMachine, T>() {
@Override
public T apply(IMachine machine) {
return function.apply(machine);
if (immutableMachine.getSessionState().equals(SessionState.Locked)) {
Statement kill = newStatementList(call("default"), findPid(immutableMachine.getSessionPid().toString()),
kill());
scriptRunner.create(host.get(), kill, runAsRoot(false).wrapInInitScript(false)).init().call();
}
}
@Override
public String toString() {
return function.toString();
/**
* Unlocks the machine and executes the given function using the machine 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
* @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);
}
}.apply(immutableMachine);
}
}
public static boolean machineNotFoundException(VBoxException e) {
return e.getMessage().contains("VirtualBox error: Could not find a registered machine named ")
|| e.getMessage().contains("Could not find a registered machine with UUID {");
}
/**
* Unlocks the machine and executes the given function, if the machine is 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
* @return the result from applying the function to the session.
*/
public <T> T unlockMachineAndApplyOrReturnNullIfNotRegistered(String machineId, Function<IMachine, T> function) {
try {
return unlockMachineAndApply(machineId, function);
} catch (RuntimeException e) {
VBoxException vbex = Throwables2.getFirstThrowableOfType(e, VBoxException.class);
if (vbex != null && vbex.getMessage().indexOf("not find a registered") == -1)
throw e;
return null;
}
}
/**
* @param machineId
* @param function
* @return
*/
public <T> T applyForMachine(final String machineId, final Function<IMachine, T> function) {
final IMachine immutableMachine = manager.get().getVBox().findMachine(machineId);
return new Function<IMachine, T>() {
@Override
public T apply(IMachine machine) {
return function.apply(machine);
}
@Override
public String toString() {
return function.toString();
}
}.apply(immutableMachine);
}
public static boolean machineNotFoundException(VBoxException e) {
return e.getMessage().contains("VirtualBox error: Could not find a registered machine named ")
|| e.getMessage().contains("Could not find a registered machine with UUID {");
}
}

View File

@ -32,7 +32,6 @@ import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;
import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
@ -64,7 +63,7 @@ import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code VirtualBoxClient}
*
*
* @author Adrian Cole
*/
@Test(groups = "live", singleThreaded = true, testName = "BaseVirtualBoxClientLiveTest")
@ -85,7 +84,7 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
protected String isosDir;
protected Supplier<NodeMetadata> host;
protected static final PrioritizeCredentialsFromTemplate prioritizeCredentialsFromTemplate = new PrioritizeCredentialsFromTemplate(
new DefaultCredentialsFromImageOrOverridingCredentials());
new DefaultCredentialsFromImageOrOverridingCredentials());
@Override
protected void setupCredentials() {
@ -97,11 +96,10 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
}
protected void ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults() {
Properties defaultVBoxProperties = new VirtualBoxPropertiesBuilder()
.build();
Properties defaultVBoxProperties = new VirtualBoxPropertiesBuilder().build();
if (!System.getProperties().containsKey("test." + provider + ".identity"))
System.setProperty("test." + provider + ".identity",
defaultVBoxProperties.getProperty(Constants.PROPERTY_IDENTITY));
defaultVBoxProperties.getProperty(Constants.PROPERTY_IDENTITY));
}
@BeforeClass(groups = "live")
@ -109,44 +107,33 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
setupCredentials();
Properties overrides = new VirtualBoxPropertiesBuilder(setupProperties()).build();
CacheNodeStoreModule hostModule = new CacheNodeStoreModule(
ImmutableMap.of(
"host",
Node.builder()
.id("host")
.name("host installing virtualbox")
.hostname("localhost")
.osFamily(OsFamily.LINUX.toString())
.osDescription(System.getProperty("os.name"))
.osVersion(System.getProperty("os.version"))
.group("ssh")
.username(System.getProperty("user.name"))
.credentialUrl(
URI.create("file://"
+ System.getProperty("user.home")
+ "/.ssh/id_rsa")).build()));
CacheNodeStoreModule hostModule = new CacheNodeStoreModule(ImmutableMap.of(
"host",
Node.builder().id("host").name("host installing virtualbox").hostname("localhost")
.osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name"))
.osVersion(System.getProperty("os.version")).group("ssh")
.username(System.getProperty("user.name"))
.credentialUrl(URI.create("file://" + System.getProperty("user.home") + "/.ssh/id_rsa"))
.build()));
context = new ComputeServiceContextFactory().createContext(provider,
identity, credential, ImmutableSet.<Module>of(
new SLF4JLoggingModule(), new SshjSshClientModule(),
hostModule), overrides);
context = new ComputeServiceContextFactory().createContext(provider, identity, credential,
ImmutableSet.<Module> of(new SLF4JLoggingModule(), new SshjSshClientModule(), hostModule), overrides);
Function<String, String> configProperties = context.utils().injector()
.getInstance(ValueOfConfigurationKeyOrNull.class);
.getInstance(ValueOfConfigurationKeyOrNull.class);
imageId = "ubuntu-11.04-server-i386";
workingDir = configProperties
.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
isosDir = workingDir+File.separator+"isos";
workingDir = configProperties.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
isosDir = workingDir + File.separator + "isos";
File isosDirFile = new File(isosDir);
if(!isosDirFile.exists()){
isosDirFile.mkdirs();
if (!isosDirFile.exists()) {
isosDirFile.mkdirs();
}
host = context.utils().injector()
.getInstance(Key.get(new TypeLiteral<Supplier<NodeMetadata>>() {
}));
host = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<NodeMetadata>>() {
}));
// this will eagerly startup Jetty, note the impl will shut itself down
preconfigurationUri = context.utils().injector().getInstance(Key.get(new TypeLiteral<LoadingCache<IsoSpec, 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
manager = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<VirtualBoxManager>>() {
@ -156,43 +143,40 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
machineUtils = context.utils().injector().getInstance(MachineUtils.class);
hostVersion = Iterables.get(
Splitter.on('r').split(
context.getProviderSpecificContext().getBuildVersion()), 0);
hostVersion = Iterables.get(Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0);
adminDisk = workingDir + "/testadmin.vdi";
operatingSystemIso = String.format("%s/%s.iso", isosDir, imageId);
guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso",
isosDir, hostVersion);
guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", isosDir, hostVersion);
}
protected void undoVm(VmSpec vmSpecification) {
machineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered(
vmSpecification.getVmId(),
new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
machineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered(vmSpecification.getVmId(),
new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
}
protected void ensureMachineHasPowerDown(String vmName) {
while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.POWERED_OFF)) {
try {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() {
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
});
} catch (RuntimeException e) {
// sometimes the machine might be powered of between the while test and the call to lockSessionOnMachineAndApply
if (e.getMessage().contains("Invalid machine state: PoweredOff")){
return;
} else if(e.getMessage().contains("VirtualBox error: The object is not ready")){
continue;
} else {
throw e;
while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.POWERED_OFF)) {
try {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function<ISession, Void>() {
@Override
public Void apply(ISession session) {
IProgress powerDownProgress = session.getConsole().powerDown();
powerDownProgress.waitForCompletion(-1);
return null;
}
});
} catch (RuntimeException e) {
// sometimes the machine might be powered of between the while test and the call to
// lockSessionOnMachineAndApply
if (e.getMessage().contains("Invalid machine state: PoweredOff")) {
return;
} else if (e.getMessage().contains("VirtualBox error: The object is not ready")) {
continue;
} else {
throw e;
}
}
}
}
}
}
@AfterClass(groups = "live")

View File

@ -38,70 +38,70 @@ import com.google.common.collect.Iterables;
@Test(groups = "live", singleThreaded = true, testName = "VirtualBoxComputeServiceAdapterLiveTest")
public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClientLiveTest {
private VirtualBoxComputeServiceAdapter adapter;
private NodeAndInitialCredentials<IMachine> machine;
private VirtualBoxComputeServiceAdapter adapter;
private NodeAndInitialCredentials<IMachine> machine;
@Override
public void setupClient() {
super.setupClient();
adapter = context.utils().injector().getInstance(VirtualBoxComputeServiceAdapter.class);
}
@Override
public void setupClient() {
super.setupClient();
adapter = context.utils().injector().getInstance(VirtualBoxComputeServiceAdapter.class);
}
@Test
public void testCreateNodeWithGroupEncodedIntoNameThenStoreCredentials() {
String group = "foo";
String name = "foo-ef4";
String machineName = VIRTUALBOX_NODE_PREFIX + "myTestId-" + group + "-" + name;
// get the image from
Image image = Iterables.get(adapter.listImages(), 0);
System.out.println(context.getComputeService().templateBuilder());
Template template = context.getComputeService().templateBuilder().fromImage(image).build();
machine = adapter.createNodeWithGroupEncodedIntoName(group, name, template);
assertEquals(machine.getNode().getName(), machineName);
// is there a place for group?
// check other things, like cpu correct, mem correct, image/os is correct
// (as possible)
// TODO: what's the IP address?
// assert
// InetAddresses.isInetAddress(machine.getPrimaryBackendIpAddress()) :
// machine;
doConnectViaSsh(machine.getNode(), prioritizeCredentialsFromTemplate.apply(template, machine.getCredentials()));
}
@Test
public void testCreateNodeWithGroupEncodedIntoNameThenStoreCredentials() {
String group = "foo";
String name = "foo-ef4";
String machineName = VIRTUALBOX_NODE_PREFIX + "myTestId-" + group + "-" + name;
// get the image from
Image image = Iterables.get(adapter.listImages(), 0);
System.out.println(context.getComputeService().templateBuilder());
Template template = context.getComputeService().templateBuilder().fromImage(image).build();
machine = adapter.createNodeWithGroupEncodedIntoName(group, name, template);
assertEquals(machine.getNode().getName(), machineName);
// is there a place for group?
// check other things, like cpu correct, mem correct, image/os is correct
// (as possible)
// TODO: what's the IP address?
// assert
// InetAddresses.isInetAddress(machine.getPrimaryBackendIpAddress()) :
// machine;
doConnectViaSsh(machine.getNode(), prioritizeCredentialsFromTemplate.apply(template, machine.getCredentials()));
}
protected void doConnectViaSsh(IMachine machine, LoginCredentials creds) {
SshClient ssh = context.utils().injector().getInstance(IMachineToSshClient.class).apply(machine);
try {
ssh.connect();
ExecResponse hello = ssh.exec("echo hello");
assertEquals(hello.getOutput().trim(), "hello");
System.err.println(ssh.exec("df -k").getOutput());
System.err.println(ssh.exec("mount").getOutput());
System.err.println(ssh.exec("uname -a").getOutput());
} finally {
if (ssh != null)
ssh.disconnect();
}
}
protected void doConnectViaSsh(IMachine machine, LoginCredentials creds) {
SshClient ssh = context.utils().injector().getInstance(IMachineToSshClient.class).apply(machine);
try {
ssh.connect();
ExecResponse hello = ssh.exec("echo hello");
assertEquals(hello.getOutput().trim(), "hello");
System.err.println(ssh.exec("df -k").getOutput());
System.err.println(ssh.exec("mount").getOutput());
System.err.println(ssh.exec("uname -a").getOutput());
} finally {
if (ssh != null)
ssh.disconnect();
}
}
@Test
public void testListHardwareProfiles() {
Iterable<IMachine> profiles = adapter.listHardwareProfiles();
assertEquals(1, Iterables.size(profiles));
}
@Test
public void testListHardwareProfiles() {
Iterable<IMachine> profiles = adapter.listHardwareProfiles();
assertEquals(1, Iterables.size(profiles));
}
@Test
public void testListImages() {
Iterable<Image> iMageIterable = adapter.listImages();
for (Image image : iMageIterable) {
System.out.println(image);
}
// check state;
}
@Test
public void testListImages() {
Iterable<Image> iMageIterable = adapter.listImages();
for (Image image : iMageIterable) {
System.out.println(image);
}
// check state;
}
@Override
protected void tearDown() throws Exception {
if (machine != null)
// adapter.destroyNode(machine.getNodeId() + "");
super.tearDown();
}
@Override
protected void tearDown() throws Exception {
if (machine != null)
// adapter.destroyNode(machine.getNodeId() + "");
super.tearDown();
}
}

View File

@ -20,16 +20,12 @@
package org.jclouds.virtualbox.functions;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.transform;
import static junit.framework.Assert.assertEquals;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX;
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE;
import static org.testng.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
@ -57,18 +53,15 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.virtualbox_4_1.CleanupMode;
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.NetworkAttachmentType;
import org.virtualbox_4_1.StorageBus;
import org.virtualbox_4_1.jaxws.MachineState;
import com.google.common.base.CaseFormat;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Guice;
@ -80,142 +73,119 @@ import com.google.inject.Injector;
@Test(groups = "live", singleThreaded = true, testName = "CreateAndInstallVmLiveTest")
public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice
.createInjector(new GsonModule()).getInstance(Json.class));
Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.getInstance(Json.class));
private VmSpec vmSpecification;
private MasterSpec masterSpec;
private Injector injector;
private Function<IMachine, SshClient> sshClientForIMachine;
private Predicate<SshClient> sshResponds;
private String vmName;
private VmSpec vmSpecification;
private MasterSpec masterSpec;
private Injector injector;
private Function<IMachine, SshClient> sshClientForIMachine;
private Predicate<SshClient> sshResponds;
private String vmName;
@Override
@BeforeClass(groups = "live")
public void setupClient() {
super.setupClient();
this.vmName = VIRTUALBOX_IMAGE_PREFIX
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass()
.getSimpleName());
@Override
@BeforeClass(groups = "live")
public void setupClient() {
super.setupClient();
this.vmName = VIRTUALBOX_IMAGE_PREFIX
+ 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();
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();
injector = context.utils().injector();
Function<String, String> configProperties = injector
.getInstance(ValueOfConfigurationKeyOrNull.class);
injector = context.utils().injector();
Function<String, String> configProperties = injector.getInstance(ValueOfConfigurationKeyOrNull.class);
NetworkAdapter networkAdapter = NetworkAdapter.builder()
.networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard
.builder().addNetworkAdapter(networkAdapter).build();
NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT)
.tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter)
.build();
NetworkSpec networkSpec = NetworkSpec.builder()
.addNIC(0L, networkInterfaceCard).build();
NetworkSpec networkSpec = NetworkSpec.builder().addNIC(0L, networkInterfaceCard).build();
masterSpec = MasterSpec
.builder()
.vm(vmSpecification)
.iso(IsoSpec
.builder()
.sourcePath(operatingSystemIso)
.installationScript(
configProperties.apply(
VIRTUALBOX_INSTALLATION_KEY_SEQUENCE)
.replace("HOSTNAME",
vmSpecification.getVmName()))
.build()).network(networkSpec).build();
masterSpec = MasterSpec
.builder()
.vm(vmSpecification)
.iso(IsoSpec
.builder()
.sourcePath(operatingSystemIso)
.installationScript(
configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace("HOSTNAME",
vmSpecification.getVmName())).build()).network(networkSpec).build();
undoVm(vmSpecification);
}
undoVm(vmSpecification);
}
@Test
public void testCreateImageMachineFromIso() throws Exception {
IMachine imageMachine = getVmWithGuestAdditionsInstalled();
IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
Image newImage = iMachineToImage.apply(imageMachine);
assertEquals(vmName,newImage.getName());
}
@Test
public void testCreateImageMachineFromIso() throws Exception {
IMachine imageMachine = getVmWithGuestAdditionsInstalled();
IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
Image newImage = iMachineToImage.apply(imageMachine);
assertEquals(vmName, newImage.getName());
}
@Test
public void testGuestAdditionsAreInstalled() throws Exception {
try {
IMachine machine = getVmWithGuestAdditionsInstalled();
@Test
public void testGuestAdditionsAreInstalled() throws Exception {
try {
IMachine machine = getVmWithGuestAdditionsInstalled();
machineUtils.applyForMachine(machine.getName(),
new LaunchMachineIfNotAlreadyRunning(manager.get(),
ExecutionType.GUI, ""));
sshClientForIMachine = injector
.getInstance(IMachineToSshClient.class);
SshClient client = sshClientForIMachine.apply(machine);
machineUtils.applyForMachine(machine.getName(), new LaunchMachineIfNotAlreadyRunning(manager.get(),
ExecutionType.GUI, ""));
sshClientForIMachine = injector.getInstance(IMachineToSshClient.class);
SshClient client = sshClientForIMachine.apply(machine);
sshResponds = injector.getInstance(SshResponds.class);
checkState(sshResponds.apply(client),
"timed out waiting for guest %s to be accessible via ssh",
machine.getName());
sshResponds = injector.getInstance(SshResponds.class);
checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh",
machine.getName());
assertTrue(machineUtils.lockSessionOnMachineAndApply(
machine.getName(), LockType.Shared,
new Function<ISession, Boolean>() {
@Override
public Boolean apply(ISession session) {
String vboxVersion = Iterables
.get(Splitter
.on('r')
.split(context
.getProviderSpecificContext()
.getBuildVersion()), 0);
return session
.getMachine()
.getGuestPropertyValue(
"/VirtualBox/GuestAdd/Version")
.equals(vboxVersion);
}
}));
} finally {
for (VmSpec spec : ImmutableSet.of(vmSpecification)) {
ensureMachineHasPowerDown(spec.getVmName());
}
}
}
assertTrue(machineUtils.lockSessionOnMachineAndApply(machine.getName(), LockType.Shared,
new Function<ISession, Boolean>() {
@Override
public Boolean apply(ISession session) {
String vboxVersion = Iterables.get(
Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0);
return session.getMachine().getGuestPropertyValue("/VirtualBox/GuestAdd/Version")
.equals(vboxVersion);
}
}));
} finally {
for (VmSpec spec : ImmutableSet.of(vmSpecification)) {
ensureMachineHasPowerDown(spec.getVmName());
}
}
}
private Function<Image, String> extractId() {
return new Function<Image, String>() {
private Function<Image, String> extractId() {
return new Function<Image, String>() {
@Override
public String apply(@Nullable Image input) {
return input.getId();
}
};
}
private IMachine getVmWithGuestAdditionsInstalled() {
try {
Injector injector = context.utils().injector();
return injector.getInstance(CreateAndInstallVm.class).apply(
masterSpec);
} catch (IllegalStateException e) {
// already created
return manager.get().getVBox()
.findMachine(masterSpec.getVmSpec().getVmId());
}
}
@Override
public String apply(@Nullable Image input) {
return input.getId();
}
};
}
@Override
@AfterClass(groups = "live")
protected void tearDown() throws Exception {
for (VmSpec spec : ImmutableSet.of(vmSpecification)) {
undoVm(spec);
}
super.tearDown();
}
private IMachine getVmWithGuestAdditionsInstalled() {
try {
Injector injector = context.utils().injector();
return injector.getInstance(CreateAndInstallVm.class).apply(masterSpec);
} catch (IllegalStateException e) {
// already created
return manager.get().getVBox().findMachine(masterSpec.getVmSpec().getVmId());
}
}
@Override
@AfterClass(groups = "live")
protected void tearDown() throws Exception {
for (VmSpec spec : ImmutableSet.of(vmSpecification)) {
undoVm(spec);
}
super.tearDown();
}
}