mirror of https://github.com/apache/jclouds.git
refactored config handling in virtualbox and cleaned up classes
This commit is contained in:
parent
f390f314ee
commit
b2a9313c85
|
@ -40,8 +40,8 @@
|
|||
<test.virtualbox.identity>administrator</test.virtualbox.identity>
|
||||
<test.virtualbox.credential>12345</test.virtualbox.credential>
|
||||
<test.virtualbox.image-id>ubuntu-11.04-server-i386</test.virtualbox.image-id>
|
||||
<test.virtualbox.image.login-user></test.virtualbox.image.login-user>
|
||||
<test.virtualbox.image.authenticate-sudo></test.virtualbox.image.authenticate-sudo>
|
||||
<test.virtualbox.image.login-user>toor:password</test.virtualbox.image.login-user>
|
||||
<test.virtualbox.image.authenticate-sudo>true</test.virtualbox.image.authenticate-sudo>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -0,0 +1,39 @@
|
|||
/**
|
||||
* Licensed to jclouds, Inc. (jclouds) under one or more
|
||||
* contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. jclouds licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.jclouds.virtualbox;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.inject.Qualifier;
|
||||
|
||||
/**
|
||||
* Relating to a preseed or KickStart source
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*
|
||||
*/
|
||||
@Retention(value = RetentionPolicy.RUNTIME)
|
||||
@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
|
||||
@Qualifier
|
||||
public @interface Preconfiguration {
|
||||
|
||||
}
|
|
@ -24,8 +24,8 @@ import java.util.Properties;
|
|||
|
||||
import org.jclouds.compute.StandaloneComputeServiceContextBuilder;
|
||||
import org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.inject.Module;
|
||||
|
||||
/**
|
||||
|
@ -33,10 +33,11 @@ import com.google.inject.Module;
|
|||
*
|
||||
* @author Mattias Holmqvist, Andrea Turli
|
||||
*/
|
||||
public class VirtualBoxContextBuilder extends StandaloneComputeServiceContextBuilder<VirtualBoxManager> {
|
||||
@SuppressWarnings("unchecked")
|
||||
public class VirtualBoxContextBuilder extends StandaloneComputeServiceContextBuilder<Supplier> {
|
||||
|
||||
public VirtualBoxContextBuilder(Properties properties) {
|
||||
super(VirtualBoxManager.class, properties);
|
||||
super(Supplier.class, properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -29,8 +29,8 @@ import java.io.File;
|
|||
import java.util.Properties;
|
||||
|
||||
import org.jclouds.PropertiesBuilder;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
||||
import static org.jclouds.compute.reference.ComputeServiceConstants.*;
|
||||
import static org.jclouds.virtualbox.config.VirtualBoxConstants.*;
|
||||
|
||||
/**
|
||||
* Builds properties for VirtualBox integration.
|
||||
|
@ -56,27 +56,28 @@ public class VirtualBoxPropertiesBuilder extends PropertiesBuilder {
|
|||
properties.put(PROPERTY_BUILD_VERSION, "4.1.8r75467");
|
||||
properties.put(PROPERTY_IDENTITY, "administrator");
|
||||
properties.put(PROPERTY_CREDENTIAL, "12345");
|
||||
properties.put(ComputeServiceConstants.PROPERTY_IMAGE_ID, "ubuntu-11.04-server-i386");
|
||||
properties.put(VirtualBoxConstants.VIRTUALBOX_PRESEED_URL, "http://dl.dropbox.com/u/693111/preseed.cfg");
|
||||
properties.put(VirtualBoxConstants.VIRTUALBOX_SNAPSHOT_DESCRIPTION, "jclouds-virtualbox-snaphot");
|
||||
properties.put(VirtualBoxConstants.VIRTUALBOX_HOSTNAME, "jclouds-virtualbox-kickstart-admin");
|
||||
properties
|
||||
.put(VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE,
|
||||
"<Esc><Esc><Enter> "
|
||||
+ "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg "
|
||||
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us "
|
||||
+ "hostname="
|
||||
+ properties.get(VirtualBoxConstants.VIRTUALBOX_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(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR, System.getProperty("user.home") + File.separator
|
||||
+ System.getProperty("test.virtualbox.workingDir", "jclouds-virtualbox-test"));
|
||||
properties.put(PROPERTY_IMAGE_ID, "ubuntu-11.04-server-i386");
|
||||
properties.put(PROPERTY_IMAGE_LOGIN_USER, "toor:password");
|
||||
properties.put(PROPERTY_IMAGE_AUTHENTICATE_SUDO, "true");
|
||||
|
||||
properties.put(VIRTUALBOX_ISO_URL, "http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso");
|
||||
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(VIRTUALBOX_WORKINGDIR, System.getProperty("user.home") + File.separator
|
||||
+ System.getProperty("test.virtualbox.workingDir", "jclouds-virtualbox-test"));
|
||||
|
||||
properties.put(VIRTUALBOX_PRECONFIGURATION_URL, "http://10.0.2.2:8080/src/test/resources/preseed.cfg");
|
||||
|
||||
|
||||
|
||||
properties.put(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080");
|
||||
|
||||
return properties;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -24,8 +24,6 @@ import static com.google.common.collect.Iterables.filter;
|
|||
import static com.google.common.collect.Iterables.transform;
|
||||
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceAdapter;
|
||||
|
@ -43,7 +41,9 @@ import org.virtualbox_4_1.VirtualBoxManager;
|
|||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.common.base.Throwables;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.inject.Singleton;
|
||||
|
||||
/**
|
||||
|
@ -56,12 +56,12 @@ import com.google.inject.Singleton;
|
|||
@Singleton
|
||||
public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IMachine, IMachine, Image, Location> {
|
||||
|
||||
private final VirtualBoxManager manager;
|
||||
private final Supplier<VirtualBoxManager> manager;
|
||||
private final JustProvider justProvider;
|
||||
private Function<IMachine, Image> iMachineToImage;
|
||||
private final Function<IMachine, Image> iMachineToImage;
|
||||
|
||||
@Inject
|
||||
public VirtualBoxComputeServiceAdapter(VirtualBoxManager manager, JustProvider justProvider,
|
||||
public VirtualBoxComputeServiceAdapter(Supplier<VirtualBoxManager> manager, JustProvider justProvider,
|
||||
Function<IMachine, Image> iMachineToImage) {
|
||||
this.iMachineToImage = iMachineToImage;
|
||||
this.manager = checkNotNull(manager, "manager");
|
||||
|
@ -76,24 +76,35 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IM
|
|||
|
||||
@Override
|
||||
public Iterable<IMachine> listNodes() {
|
||||
return Collections.emptyList();
|
||||
return Iterables.filter(manager.get().getVBox().getMachines(), new Predicate<IMachine>() {
|
||||
|
||||
@Override
|
||||
public boolean apply(IMachine arg0) {
|
||||
return !arg0.getName().startsWith(VIRTUALBOX_IMAGE_PREFIX);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<IMachine> listHardwareProfiles() {
|
||||
return manager.getVBox().getMachines();
|
||||
return imageMachines();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<Image> listImages() {
|
||||
return transform(imageMachines(), iMachineToImage);
|
||||
}
|
||||
|
||||
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.getVBox().getMachines(), imagePredicate);
|
||||
return transform(imageMachines, iMachineToImage);
|
||||
final Iterable<IMachine> imageMachines = filter(manager.get().getVBox().getMachines(), imagePredicate);
|
||||
return imageMachines;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
@ -104,29 +115,29 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IM
|
|||
|
||||
@Override
|
||||
public IMachine getNode(String vmName) {
|
||||
return manager.getVBox().findMachine(vmName);
|
||||
return manager.get().getVBox().findMachine(vmName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroyNode(String vmName) {
|
||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
||||
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||
powerDownMachine(machine);
|
||||
machine.unregister(CleanupMode.Full);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rebootNode(String vmName) {
|
||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
||||
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||
powerDownMachine(machine);
|
||||
launchVMProcess(machine, manager.getSessionObject());
|
||||
launchVMProcess(machine, manager.get().getSessionObject());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resumeNode(String vmName) {
|
||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
||||
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||
ISession machineSession;
|
||||
try {
|
||||
machineSession = manager.openMachineSession(machine);
|
||||
machineSession = manager.get().openMachineSession(machine);
|
||||
machineSession.getConsole().resume();
|
||||
machineSession.unlockMachine();
|
||||
} catch (Exception e) {
|
||||
|
@ -136,10 +147,10 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IM
|
|||
|
||||
@Override
|
||||
public void suspendNode(String vmName) {
|
||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
||||
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||
ISession machineSession;
|
||||
try {
|
||||
machineSession = manager.openMachineSession(machine);
|
||||
machineSession = manager.get().openMachineSession(machine);
|
||||
machineSession.getConsole().pause();
|
||||
machineSession.unlockMachine();
|
||||
} catch (Exception e) {
|
||||
|
@ -161,7 +172,7 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IM
|
|||
|
||||
private void powerDownMachine(IMachine machine) {
|
||||
try {
|
||||
ISession machineSession = manager.openMachineSession(machine);
|
||||
ISession machineSession = manager.get().openMachineSession(machine);
|
||||
IProgress progress = machineSession.getConsole().powerDown();
|
||||
progress.waitForCompletion(-1);
|
||||
machineSession.unlockMachine();
|
||||
|
|
|
@ -19,13 +19,16 @@
|
|||
|
||||
package org.jclouds.virtualbox.config;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.Constants;
|
||||
import org.jclouds.byon.Node;
|
||||
import org.jclouds.byon.functions.NodeToNodeMetadata;
|
||||
import org.jclouds.byon.suppliers.SupplyFromProviderURIOrNodesProperty;
|
||||
import org.jclouds.compute.ComputeServiceAdapter;
|
||||
import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
|
||||
import org.jclouds.compute.domain.Hardware;
|
||||
|
@ -34,21 +37,33 @@ import org.jclouds.compute.domain.NodeMetadata;
|
|||
import org.jclouds.compute.domain.NodeState;
|
||||
import org.jclouds.compute.domain.OsFamily;
|
||||
import org.jclouds.compute.domain.TemplateBuilder;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
|
||||
import org.jclouds.domain.Location;
|
||||
import org.jclouds.functions.IdentityFunction;
|
||||
import org.jclouds.location.Provider;
|
||||
import org.jclouds.location.suppliers.OnlyLocationOrFirstZone;
|
||||
import org.jclouds.predicates.RetryablePredicate;
|
||||
import org.jclouds.ssh.SshClient;
|
||||
import org.jclouds.virtualbox.Preconfiguration;
|
||||
import org.jclouds.virtualbox.compute.VirtualBoxComputeServiceAdapter;
|
||||
import org.jclouds.virtualbox.domain.ExecutionType;
|
||||
import org.jclouds.virtualbox.functions.IMachineToHardware;
|
||||
import org.jclouds.virtualbox.functions.IMachineToImage;
|
||||
import org.jclouds.virtualbox.functions.IMachineToNodeMetadata;
|
||||
import org.jclouds.virtualbox.functions.IMachineToSshClient;
|
||||
import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning;
|
||||
import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning;
|
||||
import org.jclouds.virtualbox.predicates.SshResponds;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
import org.virtualbox_4_1.MachineState;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Functions;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.inject.Injector;
|
||||
import com.google.inject.Provides;
|
||||
|
@ -57,24 +72,15 @@ import com.google.inject.TypeLiteral;
|
|||
/**
|
||||
* @author Mattias Holmqvist, Andrea Turli
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public class VirtualBoxComputeServiceContextModule extends
|
||||
ComputeServiceAdapterContextModule<VirtualBoxManager, VirtualBoxManager, IMachine, IMachine, Image, Location> {
|
||||
ComputeServiceAdapterContextModule<Supplier, Supplier, IMachine, IMachine, Image, Location> {
|
||||
|
||||
public VirtualBoxComputeServiceContextModule() {
|
||||
super(VirtualBoxManager.class, VirtualBoxManager.class);
|
||||
super(Supplier.class, Supplier.class);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
protected VirtualBoxManager createInstance(@Provider URI endpoint,
|
||||
@Named(Constants.PROPERTY_IDENTITY) String identity, @Named(Constants.PROPERTY_CREDENTIAL) String credential) {
|
||||
|
||||
VirtualBoxManager manager = VirtualBoxManager.createInstance("");
|
||||
manager.connect(endpoint.toASCIIString(), identity, credential);
|
||||
return manager;
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@SuppressWarnings( { "unchecked", "rawtypes" })
|
||||
@Override
|
||||
protected void configure() {
|
||||
super.configure();
|
||||
|
@ -92,6 +98,53 @@ public class VirtualBoxComputeServiceContextModule extends
|
|||
}).to(IMachineToImage.class);
|
||||
bind(new TypeLiteral<Supplier<Location>>() {
|
||||
}).to(OnlyLocationOrFirstZone.class);
|
||||
|
||||
// for byon
|
||||
bind(new TypeLiteral<Function<URI, InputStream>>() {
|
||||
}).to(SupplyFromProviderURIOrNodesProperty.class);
|
||||
|
||||
bind(new TypeLiteral<Function<IMachine, SshClient>>() {
|
||||
}).to(IMachineToSshClient.class);
|
||||
|
||||
bind(ExecutionType.class).toInstance(ExecutionType.HEADLESS);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@Preconfiguration
|
||||
protected Supplier<URI> preconfiguration(javax.inject.Provider<StartJettyIfNotAlreadyRunning> lazyGet) {
|
||||
return lazyGet.get();
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
protected Function<Supplier<NodeMetadata>, VirtualBoxManager> provideVBox(Supplier<NodeMetadata> host) {
|
||||
return new Function<Supplier<NodeMetadata>, VirtualBoxManager>(){
|
||||
|
||||
@Override
|
||||
public VirtualBoxManager apply(Supplier<NodeMetadata> arg0) {
|
||||
return VirtualBoxManager.createInstance(arg0.get().getId());
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
protected Supplier defaultClient(Supplier<VirtualBoxManager> in) {
|
||||
return in;
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
protected Supplier<VirtualBoxManager> vbox(javax.inject.Provider<StartVBoxIfNotAlreadyRunning> lazyGet) {
|
||||
return lazyGet.get();
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
protected Predicate<SshClient> sshResponds(SshResponds sshResponds, Timeouts timeouts) {
|
||||
return new RetryablePredicate<SshClient>(sshResponds, timeouts.nodeRunning);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -99,26 +152,37 @@ public class VirtualBoxComputeServiceContextModule extends
|
|||
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>() {
|
||||
|
||||
@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)
|
||||
.<MachineState, NodeState> builder().put(MachineState.Running, NodeState.RUNNING).put(
|
||||
MachineState.PoweredOff, NodeState.SUSPENDED)
|
||||
.put(MachineState.DeletingSnapshot, NodeState.PENDING).put(MachineState.DeletingSnapshotOnline,
|
||||
NodeState.PENDING).put(MachineState.DeletingSnapshotPaused, NodeState.PENDING).put(
|
||||
MachineState.FaultTolerantSyncing, NodeState.PENDING).put(MachineState.LiveSnapshotting,
|
||||
NodeState.PENDING).put(MachineState.SettingUp, NodeState.PENDING).put(MachineState.Starting,
|
||||
NodeState.PENDING).put(MachineState.Stopping, NodeState.PENDING).put(MachineState.Restoring,
|
||||
NodeState.PENDING)
|
||||
// TODO What to map these states to?
|
||||
.put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING).put(
|
||||
MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING)
|
||||
.put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING).put(
|
||||
MachineState.TeleportingPausedVM, NodeState.PENDING)
|
||||
|
||||
.put(MachineState.Aborted, NodeState.ERROR).put(MachineState.Stuck, NodeState.ERROR)
|
||||
.put(MachineState.Aborted, NodeState.ERROR).put(MachineState.Stuck, NodeState.ERROR)
|
||||
|
||||
.put(MachineState.Null, NodeState.UNRECOGNIZED).build();
|
||||
.put(MachineState.Null, NodeState.UNRECOGNIZED).build();
|
||||
|
||||
}
|
||||
|
|
|
@ -27,19 +27,15 @@ package org.jclouds.virtualbox.config;
|
|||
*/
|
||||
public interface VirtualBoxConstants {
|
||||
|
||||
public static final String VIRTUALBOX_IMAGE_PREFIX = "jclouds-image-";
|
||||
public static final String VIRTUALBOX_IMAGE_PREFIX = "jclouds#image#";
|
||||
|
||||
public static final String VIRTUALBOX_PRESEED_URL = "jclouds.virtualbox.preseedurl";
|
||||
|
||||
public static final String VIRTUALBOX_SNAPSHOT_DESCRIPTION = "jclouds.virtualbox.snapshotDescription";
|
||||
public static final String VIRTUALBOX_PRECONFIGURATION_URL = "jclouds.virtualbox.preconfigurationurl";
|
||||
|
||||
public static final String VIRTUALBOX_INSTALLATION_KEY_SEQUENCE = "jclouds.virtualbox.installationkeysequence";
|
||||
|
||||
public static final String VIRTUALBOX_HOSTNAME = "jclouds.virtualbox.hostname";
|
||||
|
||||
public static final String VIRTUALBOX_WORKINGDIR = "jclouds.virtualbox.workingdir";
|
||||
|
||||
public static final String VIRTUALBOX_ISOFILE = "jclouds.virtualbox.isofile";
|
||||
public static final String VIRTUALBOX_ISO_URL = "jclouds.virtualbox.isourl";
|
||||
|
||||
public static final String VIRTUALBOX_MACHINE_GROUP = "jclouds.virtualbox.machinegroup";
|
||||
|
||||
|
@ -51,10 +47,6 @@ public interface VirtualBoxConstants {
|
|||
|
||||
public static final String VIRTUALBOX_HOST_ID = "jclouds.virtualbox.hostid";
|
||||
|
||||
public static final String VIRTUALBOX_JETTY_PORT = "jclouds.virtualbox.jetty.port";
|
||||
|
||||
public static final String VIRTUALBOX_JETTY_BASE_RESOURCE = "jclouds.virtualbox.jetty.baseresource";
|
||||
|
||||
public static final String VIRTUALBOX_WEBSERVER_IDENTITY = "jclouds.virtualbox.webserver.identity";
|
||||
|
||||
public static final String VIRTUALBOX_WEBSERVER_CREDENTIAL = "jclouds.virtualbox.webserver.credential";
|
||||
|
|
|
@ -50,11 +50,25 @@ public class NatAdapter {
|
|||
|
||||
private Set<RedirectRule> redirectRules = Sets.newLinkedHashSet();
|
||||
|
||||
/**
|
||||
* @param host incoming address
|
||||
* @param hostPort
|
||||
* @param guest guest address or empty string for all addresses
|
||||
* @param guestPort
|
||||
* @return
|
||||
*/
|
||||
public Builder tcpRedirectRule(String host, int hostPort, String guest, int guestPort) {
|
||||
redirectRules.add(new RedirectRule(NATProtocol.TCP, host, hostPort, guest, guestPort));
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param host incoming address
|
||||
* @param hostPort
|
||||
* @param guest guest address or empty string for all addresses
|
||||
* @param guestPort
|
||||
* @return
|
||||
*/
|
||||
public Builder udpRedirectRule(String host, int hostPort, String guest, int guestPort) {
|
||||
redirectRules.add(new RedirectRule(NATProtocol.UDP, host, hostPort, guest, guestPort));
|
||||
return this;
|
||||
|
|
|
@ -34,7 +34,15 @@ public class RedirectRule {
|
|||
private final int hostPort;
|
||||
private final String guest;
|
||||
private final int guestPort;
|
||||
|
||||
|
||||
/**
|
||||
* @param protocol
|
||||
* @param host incoming address
|
||||
* @param hostPort
|
||||
* @param guest guest address or empty string for all addresses
|
||||
* @param guestPort
|
||||
* @return
|
||||
*/
|
||||
public RedirectRule(NATProtocol protocol, String host, int hostPort, String guest, int guestPort) {
|
||||
checkNotNull(protocol);
|
||||
checkNotNull(host);
|
||||
|
|
|
@ -23,7 +23,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
|
|||
|
||||
import org.jclouds.virtualbox.domain.StorageController;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
import org.virtualbox_4_1.StorageBus;
|
||||
import org.virtualbox_4_1.VBoxException;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
|
|
|
@ -39,6 +39,7 @@ import org.virtualbox_4_1.VBoxException;
|
|||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
/**
|
||||
|
@ -53,13 +54,13 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
|
|||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private final VirtualBoxManager manager;
|
||||
private final Supplier<VirtualBoxManager> manager;
|
||||
private final String workingDir;
|
||||
private final VmSpec vmSpec;
|
||||
private final boolean isLinkedClone;
|
||||
|
||||
@Inject
|
||||
public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(VirtualBoxManager manager,
|
||||
public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(Supplier<VirtualBoxManager> manager,
|
||||
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, VmSpec vmSpec, boolean isLinkedClone) {
|
||||
this.manager = manager;
|
||||
this.workingDir = workingDir;
|
||||
|
@ -70,7 +71,7 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
|
|||
@Override
|
||||
public IMachine apply(@Nullable IMachine master) {
|
||||
try {
|
||||
manager.getVBox().findMachine(vmSpec.getVmName());
|
||||
manager.get().getVBox().findMachine(vmSpec.getVmName());
|
||||
throw new IllegalStateException("Machine " + vmSpec.getVmName() + " is already registered.");
|
||||
} catch (VBoxException e) {
|
||||
if (machineNotFoundException(e))
|
||||
|
@ -85,8 +86,8 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
|
|||
}
|
||||
|
||||
private IMachine cloneMachine(VmSpec vmSpec, IMachine master) {
|
||||
String settingsFile = manager.getVBox().composeMachineFilename(vmSpec.getVmName(), workingDir);
|
||||
IMachine clonedMachine = manager.getVBox().createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(),
|
||||
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)
|
||||
|
@ -103,7 +104,7 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
|
|||
logger.debug("clone done");
|
||||
|
||||
// registering
|
||||
manager.getVBox().registerMachine(clonedMachine);
|
||||
manager.get().getVBox().registerMachine(clonedMachine);
|
||||
return clonedMachine;
|
||||
}
|
||||
|
||||
|
|
|
@ -19,133 +19,102 @@
|
|||
|
||||
package org.jclouds.virtualbox.functions;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
|
||||
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;
|
||||
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE;
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.applyForMachine;
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApply;
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.lockSessionOnMachineAndApply;
|
||||
import static org.virtualbox_4_1.LockType.Shared;
|
||||
import static org.virtualbox_4_1.LockType.Write;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.net.URI;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.compute.domain.ExecResponse;
|
||||
import org.jclouds.compute.options.RunScriptOptions;
|
||||
import org.jclouds.compute.callables.RunScriptOnNode;
|
||||
import org.jclouds.compute.callables.RunScriptOnNode.Factory;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.config.ValueOfConfigurationKeyOrNull;
|
||||
import org.jclouds.logging.Logger;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.ssh.SshException;
|
||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
||||
import org.jclouds.virtualbox.domain.DeviceDetails;
|
||||
import org.jclouds.scriptbuilder.domain.Statements;
|
||||
import org.jclouds.ssh.SshClient;
|
||||
import org.jclouds.virtualbox.Preconfiguration;
|
||||
import org.jclouds.virtualbox.domain.ExecutionType;
|
||||
import org.jclouds.virtualbox.domain.HardDisk;
|
||||
import org.jclouds.virtualbox.domain.IsoImage;
|
||||
import org.jclouds.virtualbox.domain.NatAdapter;
|
||||
import org.jclouds.virtualbox.domain.StorageController;
|
||||
import org.jclouds.virtualbox.domain.VmSpec;
|
||||
import org.jclouds.virtualbox.settings.KeyboardScancodes;
|
||||
import org.virtualbox_4_1.AccessMode;
|
||||
import org.virtualbox_4_1.DeviceType;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
import org.virtualbox_4_1.IMedium;
|
||||
import org.virtualbox_4_1.IProgress;
|
||||
import org.virtualbox_4_1.ISession;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
@Singleton
|
||||
public class CreateAndInstallVm implements Function<VmSpec, IMachine> {
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private final VirtualBoxManager manager;
|
||||
private final Supplier<VirtualBoxManager> manager;
|
||||
private final CreateAndRegisterMachineFromIsoIfNotAlreadyExists createAndRegisterMachineFromIsoIfNotAlreadyExists;
|
||||
private String guestId;
|
||||
private final ComputeServiceContext context;
|
||||
private final String hostId;
|
||||
private final Predicate<IPSocket> socketTester;
|
||||
private final String webServerHost;
|
||||
private final int webServerPort;
|
||||
private final ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull;
|
||||
|
||||
private final Supplier<URI> preconfiguration;
|
||||
private final Predicate<SshClient> sshResponds;
|
||||
private final ExecutionType executionType;
|
||||
|
||||
private final Factory scriptRunner;
|
||||
private final Supplier<NodeMetadata> host;
|
||||
|
||||
private final Function<IMachine, SshClient> sshClientForIMachine;
|
||||
|
||||
@Inject
|
||||
public CreateAndInstallVm(VirtualBoxManager manager,
|
||||
public CreateAndInstallVm(Supplier<VirtualBoxManager> manager,
|
||||
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
|
||||
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, String guestId,
|
||||
ComputeServiceContext context, String hostId, Predicate<IPSocket> socketTester, String webServerHost,
|
||||
int webServerPort, ExecutionType executionType) {
|
||||
ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull, Predicate<SshClient> sshResponds,
|
||||
Function<IMachine, SshClient> sshClientForIMachine, Supplier<NodeMetadata> host,
|
||||
RunScriptOnNode.Factory scriptRunner, @Preconfiguration Supplier<URI> preconfiguration,
|
||||
ExecutionType executionType) {
|
||||
this.manager = manager;
|
||||
this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
|
||||
this.guestId = guestId;
|
||||
this.context = context;
|
||||
this.hostId = hostId;
|
||||
this.socketTester = socketTester;
|
||||
this.webServerHost = webServerHost;
|
||||
this.webServerPort = webServerPort;
|
||||
this.valueOfConfigurationKeyOrNull = valueOfConfigurationKeyOrNull;
|
||||
this.sshResponds = sshResponds;
|
||||
this.sshClientForIMachine = sshClientForIMachine;
|
||||
this.scriptRunner = scriptRunner;
|
||||
this.host = host;
|
||||
this.preconfiguration = preconfiguration;
|
||||
this.executionType = executionType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IMachine apply(VmSpec vmSpec) {
|
||||
|
||||
ensureWebServerIsRunning();
|
||||
|
||||
final IMachine vm =createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(vmSpec);
|
||||
|
||||
String vmName = vmSpec.getVmName();
|
||||
|
||||
// Change RAM
|
||||
ensureMachineHasMemory(vmName, vmSpec.getMemory());
|
||||
// note this may not be reachable, as this likely uses the 10.2.2 address
|
||||
URI preconfigurationUri = preconfiguration.get();
|
||||
String keySequence = valueOfConfigurationKeyOrNull.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace(
|
||||
"PRECONFIGURATION_URL", preconfigurationUri.toASCIIString()).replace("HOSTNAME", vmName);
|
||||
|
||||
Set<StorageController> controllers = vmSpec.getControllers();
|
||||
if (controllers.isEmpty()) {
|
||||
throw new IllegalStateException(missingIDEControllersMessage(vmSpec));
|
||||
}
|
||||
StorageController controller = controllers.iterator().next();
|
||||
ensureMachineHasIDEControllerNamed(vmName, controller);
|
||||
setupHardDisksForController(vmName, controller);
|
||||
setupDvdsForController(vmSpec, vmName, controller);
|
||||
|
||||
// NAT
|
||||
Map<Long, NatAdapter> natNetworkAdapters = vmSpec.getNatNetworkAdapters();
|
||||
for (Map.Entry<Long, NatAdapter> natAdapterAndSlot : natNetworkAdapters.entrySet()) {
|
||||
long slotId = natAdapterAndSlot.getKey();
|
||||
NatAdapter natAdapter = natAdapterAndSlot.getValue();
|
||||
ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter);
|
||||
}
|
||||
final IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(vmSpec);
|
||||
|
||||
// Launch machine and wait for it to come online
|
||||
ensureMachineIsLaunched(vmName);
|
||||
|
||||
final String installKeySequence = System.getProperty(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, defaultInstallSequence(vmName));
|
||||
sendKeyboardSequence(installKeySequence, vmName);
|
||||
sendKeyboardSequence(keySequence, vmName);
|
||||
|
||||
boolean sshDeamonIsRunning = false;
|
||||
while (!sshDeamonIsRunning) {
|
||||
try {
|
||||
if (runScriptOnNode(guestId, "id", wrapInInitScript(false).runAsRoot(false)).getExitCode() == 0) {
|
||||
logger.debug("Got response from ssh daemon.");
|
||||
sshDeamonIsRunning = true;
|
||||
}
|
||||
} catch (SshException e) {
|
||||
logger.debug("No response from ssh daemon...");
|
||||
}
|
||||
}
|
||||
SshClient client = sshClientForIMachine.apply(vm);
|
||||
|
||||
logger.debug("Installation of image complete. Powering down...");
|
||||
lockSessionOnMachineAndApply(manager, Shared, vmName, new Function<ISession, Void>() {
|
||||
logger.debug(">> awaiting installation to finish node(%s)", vmName);
|
||||
checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", vmName);
|
||||
|
||||
logger.debug("<< installation of image complete. Powering down node(%s)", vmName);
|
||||
lockSessionOnMachineAndApply(manager.get(), Shared, vmName, new Function<ISession, Void>() {
|
||||
|
||||
@Override
|
||||
public Void apply(ISession session) {
|
||||
|
@ -158,70 +127,8 @@ public class CreateAndInstallVm implements Function<VmSpec, IMachine> {
|
|||
return vm;
|
||||
}
|
||||
|
||||
private void setupDvdsForController(VmSpec vmSpecification, String vmName, StorageController controller) {
|
||||
Set<IsoImage> dvds = controller.getIsoImages();
|
||||
for (IsoImage dvd : dvds) {
|
||||
String dvdSource = dvd.getSourcePath();
|
||||
final IMedium dvdMedium = manager.getVBox().openMedium(dvdSource, DeviceType.DVD,
|
||||
AccessMode.ReadOnly, vmSpecification.isForceOverwrite());
|
||||
ensureMachineDevicesAttached(vmName, dvdMedium, dvd.getDeviceDetails(), controller.getName());
|
||||
}
|
||||
}
|
||||
|
||||
private void setupHardDisksForController(String vmName, StorageController controller) {
|
||||
Set<HardDisk> hardDisks = controller.getHardDisks();
|
||||
for (HardDisk hardDisk : hardDisks) {
|
||||
String sourcePath = hardDisk.getDiskPath();
|
||||
if (new File(sourcePath).exists()) {
|
||||
boolean deleted = new File(sourcePath).delete();
|
||||
if (!deleted) {
|
||||
logger.error(String.format("File %s could not be deleted.", sourcePath));
|
||||
}
|
||||
}
|
||||
IMedium medium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||
ensureMachineDevicesAttached(vmName, medium, hardDisk.getDeviceDetails(), controller.getName());
|
||||
}
|
||||
}
|
||||
|
||||
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", vmSpecification);
|
||||
}
|
||||
|
||||
private void ensureWebServerIsRunning() {
|
||||
final IPSocket webServerSocket = new IPSocket(webServerHost, webServerPort);
|
||||
if (!socketTester.apply(webServerSocket)) {
|
||||
throw new IllegalStateException(String.format("Web server is not running on host %s:%s which is needed to serve preseed.cfg.", webServerHost, webServerPort));
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureMachineIsLaunched(String vmName) {
|
||||
applyForMachine(manager, vmName, new LaunchMachineIfNotAlreadyRunning(manager, executionType, ""));
|
||||
}
|
||||
|
||||
private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails, String controllerName) {
|
||||
lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium, controllerName));
|
||||
}
|
||||
|
||||
private void ensureMachineHasMemory(String vmName, final long memorySize) {
|
||||
lockMachineAndApply(manager, Write, vmName, new ApplyMemoryToMachine(memorySize));
|
||||
}
|
||||
|
||||
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, NatAdapter natAdapter) {
|
||||
lockMachineAndApply(manager, Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
|
||||
}
|
||||
|
||||
public void ensureMachineHasIDEControllerNamed(String vmName, StorageController storageController) {
|
||||
lockMachineAndApply(manager, Write, checkNotNull(vmName, "vmName"),
|
||||
new AddIDEControllerIfNotExists(checkNotNull(storageController, "storageController")));
|
||||
}
|
||||
|
||||
private String defaultInstallSequence(String vmName) {
|
||||
return "<Esc><Esc><Enter> "
|
||||
+ "/install/vmlinuz noapic preseed/url=http://10.0.2.2:" + webServerPort + "/src/test/resources/preseed.cfg "
|
||||
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " "
|
||||
+ "fb=false debconf/frontend=noninteractive "
|
||||
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
|
||||
+ "initrd=/install/initrd.gz -- <Enter>";
|
||||
private void ensureMachineIsLaunched(String vmName) {
|
||||
applyForMachine(manager.get(), vmName, new LaunchMachineIfNotAlreadyRunning(manager.get(), executionType, ""));
|
||||
}
|
||||
|
||||
private void sendKeyboardSequence(String keyboardSequence, String vmName) {
|
||||
|
@ -239,7 +146,7 @@ public class CreateAndInstallVm implements Function<VmSpec, IMachine> {
|
|||
|
||||
private void runScriptIfWordEndsWith(StringBuilder sb, String word, String key) {
|
||||
if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get(key))) {
|
||||
runScriptOnNode(hostId, sb.toString(), runAsRoot(false).wrapInInitScript(false));
|
||||
scriptRunner.create(host.get(), Statements.exec(sb.toString()), runAsRoot(false).wrapInInitScript(false)).init().call();
|
||||
sb.delete(0, sb.length() - 1);
|
||||
}
|
||||
}
|
||||
|
@ -267,9 +174,4 @@ public class CreateAndInstallVm implements Function<VmSpec, IMachine> {
|
|||
|
||||
return keycodes.toString();
|
||||
}
|
||||
|
||||
protected ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) {
|
||||
return context.getComputeService().runScriptOnNode(nodeId, command, options);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -29,7 +29,9 @@ import java.util.Set;
|
|||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.logging.Logger;
|
||||
|
@ -49,20 +51,23 @@ import org.virtualbox_4_1.VBoxException;
|
|||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Supplier;
|
||||
|
||||
/**
|
||||
* @author Mattias Holmqvist
|
||||
*/
|
||||
@Singleton
|
||||
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<VmSpec, IMachine> {
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private final VirtualBoxManager manager;
|
||||
private final Supplier<VirtualBoxManager> manager;
|
||||
private final String workingDir;
|
||||
|
||||
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(VirtualBoxManager manager,
|
||||
@Inject
|
||||
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Supplier<VirtualBoxManager> manager,
|
||||
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir) {
|
||||
this.manager = manager;
|
||||
this.workingDir = workingDir;
|
||||
|
@ -70,7 +75,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
|||
|
||||
@Override
|
||||
public IMachine apply(@Nullable VmSpec launchSpecification) {
|
||||
final IVirtualBox vBox = manager.getVBox();
|
||||
final IVirtualBox vBox = manager.get().getVBox();
|
||||
String vmName = launchSpecification.getVmName();
|
||||
try {
|
||||
vBox.findMachine(vmName);
|
||||
|
@ -92,8 +97,12 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
|||
|
||||
IMachine newMachine = vBox.createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(),
|
||||
vmSpec.getVmId(), vmSpec.isForceOverwrite());
|
||||
manager.getVBox().registerMachine(newMachine);
|
||||
manager.get().getVBox().registerMachine(newMachine);
|
||||
ensureConfiguration(vmSpec);
|
||||
return newMachine;
|
||||
}
|
||||
|
||||
private void ensureConfiguration(VmSpec vmSpec) {
|
||||
String vmName = vmSpec.getVmName();
|
||||
|
||||
// Change RAM
|
||||
|
@ -115,14 +124,13 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
|||
NatAdapter natAdapter = natAdapterAndSlot.getValue();
|
||||
ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter);
|
||||
}
|
||||
return newMachine;
|
||||
}
|
||||
|
||||
private void setupDvdsForController(VmSpec vmSpecification, String vmName, StorageController controller) {
|
||||
Set<IsoImage> dvds = controller.getIsoImages();
|
||||
for (IsoImage dvd : dvds) {
|
||||
String dvdSource = dvd.getSourcePath();
|
||||
final IMedium dvdMedium = manager.getVBox().openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly,
|
||||
final IMedium dvdMedium = manager.get().getVBox().openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly,
|
||||
vmSpecification.isForceOverwrite());
|
||||
ensureMachineDevicesAttached(vmName, dvdMedium, dvd.getDeviceDetails(), controller.getName());
|
||||
}
|
||||
|
@ -130,7 +138,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
|||
|
||||
private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails,
|
||||
String controllerName) {
|
||||
lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium,
|
||||
lockMachineAndApply(manager.get(), Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium,
|
||||
controllerName));
|
||||
}
|
||||
|
||||
|
@ -157,15 +165,16 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
|||
}
|
||||
|
||||
private void ensureMachineHasMemory(String vmName, final long memorySize) {
|
||||
lockMachineAndApply(manager, Write, vmName, new ApplyMemoryToMachine(memorySize));
|
||||
lockMachineAndApply(manager.get(), Write, vmName, new ApplyMemoryToMachine(memorySize));
|
||||
}
|
||||
|
||||
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, NatAdapter natAdapter) {
|
||||
lockMachineAndApply(manager, Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
|
||||
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId,
|
||||
NatAdapter natAdapter) {
|
||||
lockMachineAndApply(manager.get(), Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
|
||||
}
|
||||
|
||||
public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) {
|
||||
lockMachineAndApply(manager, Write, checkNotNull(vmName, "vmName"), new AddIDEControllerIfNotExists(checkNotNull(
|
||||
lockMachineAndApply(manager.get(), Write, checkNotNull(vmName, "vmName"), new AddIDEControllerIfNotExists(checkNotNull(
|
||||
storageController, "storageController")));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -26,6 +26,8 @@ import java.util.regex.Matcher;
|
|||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.virtualbox.domain.HardDisk;
|
||||
import org.virtualbox_4_1.DeviceType;
|
||||
|
@ -39,32 +41,36 @@ import org.virtualbox_4_1.VirtualBoxManager;
|
|||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
/**
|
||||
* @author Mattias Holmqvist
|
||||
*/
|
||||
@Singleton
|
||||
public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMedium> {
|
||||
|
||||
private final VirtualBoxManager manager;
|
||||
private boolean overwriteIfExists;
|
||||
private final Supplier<VirtualBoxManager> manager;
|
||||
private final boolean overwriteIfExists;
|
||||
|
||||
public CreateMediumIfNotAlreadyExists(VirtualBoxManager manager, boolean overwriteIfExists) {
|
||||
@Inject
|
||||
public CreateMediumIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, boolean overwriteIfExists) {
|
||||
this.manager = manager;
|
||||
this.overwriteIfExists = overwriteIfExists;
|
||||
}
|
||||
|
||||
public static final Pattern ATTACHED_PATTERN = Pattern.compile(".*is still attached.*: ([-0-9a-f]+) .*");
|
||||
|
||||
@Override
|
||||
public IMedium apply(@Nullable HardDisk hardDisk) {
|
||||
IVirtualBox vBox = manager.getVBox();
|
||||
IVirtualBox vBox = manager.get().getVBox();
|
||||
try {
|
||||
String diskPath = hardDisk.getDiskPath();
|
||||
final IMedium medium = vBox.findMedium(diskPath, DeviceType.HardDisk);
|
||||
if (overwriteIfExists) {
|
||||
try {
|
||||
deleteMediumAndBlockUntilComplete(medium);
|
||||
} catch (VBoxException e){
|
||||
} catch (VBoxException e) {
|
||||
onAlreadyAttachedExceptionDetachOrPropagate(vBox, medium, e);
|
||||
}
|
||||
return createNewMedium(vBox, hardDisk);
|
||||
|
@ -83,12 +89,13 @@ public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMediu
|
|||
if (matcher.find()) {
|
||||
String machineId = matcher.group(1);
|
||||
IMachine immutableMachine = vBox.findMachine(machineId);
|
||||
IMediumAttachment mediumAttachment = Iterables.find(immutableMachine.getMediumAttachments(), new Predicate<IMediumAttachment>(){
|
||||
public boolean apply(IMediumAttachment in){
|
||||
return in.getMedium().getId().equals(medium.getId());
|
||||
}
|
||||
});
|
||||
lockMachineAndApply(manager, Write, immutableMachine.getName(), new DetachDistroMediumFromMachine(
|
||||
IMediumAttachment mediumAttachment = Iterables.find(immutableMachine.getMediumAttachments(),
|
||||
new Predicate<IMediumAttachment>() {
|
||||
public boolean apply(IMediumAttachment in) {
|
||||
return in.getMedium().getId().equals(medium.getId());
|
||||
}
|
||||
});
|
||||
lockMachineAndApply(manager.get(), Write, immutableMachine.getName(), new DetachDistroMediumFromMachine(
|
||||
mediumAttachment.getController(), mediumAttachment.getPort(), mediumAttachment.getDevice()));
|
||||
deleteMediumAndBlockUntilComplete(medium);
|
||||
} else {
|
||||
|
@ -96,11 +103,11 @@ public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMediu
|
|||
}
|
||||
}
|
||||
|
||||
void deleteMediumAndBlockUntilComplete(IMedium medium){
|
||||
void deleteMediumAndBlockUntilComplete(IMedium medium) {
|
||||
final IProgress progress = medium.deleteStorage();
|
||||
progress.waitForCompletion(-1);
|
||||
}
|
||||
|
||||
|
||||
private IMedium createNewMedium(IVirtualBox vBox, HardDisk hardDisk) {
|
||||
IMedium medium = vBox.createHardDisk(hardDisk.getDiskFormat(), hardDisk.getDiskPath());
|
||||
createBaseStorage(medium);
|
||||
|
@ -115,7 +122,7 @@ public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMediu
|
|||
try {
|
||||
long size = 4L * 1024L * 1024L * 1024L - 4L;
|
||||
IProgress storageCreation = hardDisk.createBaseStorage(size,
|
||||
(long) org.virtualbox_4_1.jaxws.MediumVariant.STANDARD.ordinal());
|
||||
(long) org.virtualbox_4_1.jaxws.MediumVariant.STANDARD.ordinal());
|
||||
storageCreation.waitForCompletion(-1);
|
||||
} catch (VBoxException e) {
|
||||
if (fileNotFoundException(e)) {
|
||||
|
@ -137,7 +144,7 @@ public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMediu
|
|||
|
||||
private boolean storageAlreadyExists(VBoxException e) {
|
||||
return e.getMessage().contains("VirtualBox error: Storage for the medium ")
|
||||
&& e.getMessage().contains("is already created");
|
||||
&& e.getMessage().contains("is already created");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -30,13 +30,14 @@ import org.virtualbox_4_1.IMachine;
|
|||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Supplier;
|
||||
|
||||
public class IMachineToHardware implements Function<IMachine, Hardware> {
|
||||
|
||||
private VirtualBoxManager virtualBoxManager;
|
||||
private Supplier<VirtualBoxManager> virtualBoxManager;
|
||||
|
||||
@Inject
|
||||
public IMachineToHardware(VirtualBoxManager virtualBoxManager) {
|
||||
public IMachineToHardware(Supplier<VirtualBoxManager> virtualBoxManager) {
|
||||
this.virtualBoxManager = virtualBoxManager;
|
||||
}
|
||||
|
||||
|
@ -44,7 +45,7 @@ public class IMachineToHardware implements Function<IMachine, Hardware> {
|
|||
public Hardware apply(@Nullable IMachine vm) {
|
||||
String osTypeId = vm.getOSTypeId();
|
||||
|
||||
IGuestOSType guestOSType = virtualBoxManager.getVBox().getGuestOSType(osTypeId);
|
||||
IGuestOSType guestOSType = virtualBoxManager.get().getVBox().getGuestOSType(osTypeId);
|
||||
Boolean is64Bit = guestOSType.getIs64Bit();
|
||||
HardwareBuilder hardwareBuilder = new HardwareBuilder();
|
||||
hardwareBuilder.ids(vm.getId());
|
||||
|
|
|
@ -38,15 +38,16 @@ import org.virtualbox_4_1.IMachine;
|
|||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Supplier;
|
||||
|
||||
@Singleton
|
||||
public class IMachineToImage implements Function<IMachine, Image> {
|
||||
|
||||
private final VirtualBoxManager virtualboxManager;
|
||||
private final Supplier<VirtualBoxManager> virtualboxManager;
|
||||
private final Map<OsFamily, Map<String, String>> osVersionMap;
|
||||
|
||||
@Inject
|
||||
public IMachineToImage(VirtualBoxManager virtualboxManager, Map<OsFamily, Map<String, String>> osVersionMap) {
|
||||
public IMachineToImage(Supplier<VirtualBoxManager> virtualboxManager, Map<OsFamily, Map<String, String>> osVersionMap) {
|
||||
this.virtualboxManager = checkNotNull(virtualboxManager, "virtualboxManager");
|
||||
this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap");
|
||||
}
|
||||
|
@ -56,7 +57,7 @@ public class IMachineToImage implements Function<IMachine, Image> {
|
|||
if (from == null)
|
||||
return null;
|
||||
|
||||
IGuestOSType guestOSType = virtualboxManager.getVBox().getGuestOSType(from.getOSTypeId());
|
||||
IGuestOSType guestOSType = virtualboxManager.get().getVBox().getGuestOSType(from.getOSTypeId());
|
||||
OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription());
|
||||
String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), osVersionMap);
|
||||
OperatingSystem os = OperatingSystem.builder().description(guestOSType.getDescription()).family(family)
|
||||
|
|
|
@ -33,7 +33,6 @@ import org.jclouds.compute.domain.NodeMetadataBuilder;
|
|||
import org.jclouds.compute.domain.NodeState;
|
||||
import org.jclouds.compute.domain.Processor;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.domain.LocationBuilder;
|
||||
import org.jclouds.domain.LocationScope;
|
||||
import org.jclouds.javax.annotation.Nullable;
|
||||
|
@ -43,6 +42,9 @@ import org.virtualbox_4_1.INetworkAdapter;
|
|||
import org.virtualbox_4_1.MachineState;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata> {
|
||||
|
||||
|
@ -54,8 +56,7 @@ public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata>
|
|||
public NodeMetadata apply(@Nullable IMachine vm) {
|
||||
|
||||
NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder();
|
||||
String s = vm.getName();
|
||||
nodeMetadataBuilder.name(s);
|
||||
nodeMetadataBuilder.name(vm.getName()).ids(vm.getName());
|
||||
|
||||
// TODO Set up location properly
|
||||
LocationBuilder locationBuilder = new LocationBuilder();
|
||||
|
@ -79,7 +80,7 @@ public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata>
|
|||
hardwareBuilder.is64Bit(false);
|
||||
|
||||
nodeMetadataBuilder.hostname(vm.getName());
|
||||
nodeMetadataBuilder.loginPort(18083);
|
||||
|
||||
|
||||
MachineState vmState = vm.getState();
|
||||
NodeState nodeState = machineToNodeState.get(vmState);
|
||||
|
@ -91,14 +92,21 @@ public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata>
|
|||
|
||||
INetworkAdapter networkAdapter = vm.getNetworkAdapter(0l);
|
||||
if (networkAdapter != null) {
|
||||
String bridgedInterface = networkAdapter.getBridgedInterface();
|
||||
System.out.println("Interface: " + bridgedInterface);
|
||||
nodeMetadataBuilder.privateAddresses(ImmutableSet.of(networkAdapter.getNatDriver().getHostIP()));
|
||||
for (String nameProtocolnumberAddressInboudportGuestTargetport : networkAdapter.getNatDriver().getRedirects()){
|
||||
Iterable<String> stuff = Splitter.on(',').split(nameProtocolnumberAddressInboudportGuestTargetport);
|
||||
String protocolNumber = Iterables.get(stuff, 1);
|
||||
String hostAddress= Iterables.get(stuff, 2);
|
||||
String inboundPort= Iterables.get(stuff, 3);
|
||||
String targetPort= Iterables.get(stuff, 5);
|
||||
if ("1".equals(protocolNumber) && "22".equals(targetPort))
|
||||
nodeMetadataBuilder.privateAddresses(ImmutableSet.of(hostAddress)).loginPort(Integer.parseInt(inboundPort));
|
||||
}
|
||||
}
|
||||
|
||||
// nodeMetadataBuilder.imageId("");
|
||||
// nodeMetadataBuilder.group("");
|
||||
|
||||
nodeMetadataBuilder.id(vm.getId());
|
||||
return nodeMetadataBuilder.build();
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,66 @@
|
|||
/**
|
||||
* Licensed to jclouds, Inc. (jclouds) under one or more
|
||||
* contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. jclouds licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.jclouds.virtualbox.functions;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkState;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.domain.LoginCredentials;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.ssh.SshClient;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
import org.virtualbox_4_1.INetworkAdapter;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
@Singleton
|
||||
public class IMachineToSshClient implements Function<IMachine, SshClient> {
|
||||
private final SshClient.Factory sshClientFactory;
|
||||
|
||||
@Inject
|
||||
public IMachineToSshClient(SshClient.Factory sshClientFactory) {
|
||||
this.sshClientFactory = sshClientFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SshClient apply(final IMachine vm) {
|
||||
INetworkAdapter networkAdapter = vm.getNetworkAdapter(0l);
|
||||
SshClient client = null;
|
||||
checkState(networkAdapter != null);
|
||||
for (String nameProtocolnumberAddressInboudportGuestTargetport : networkAdapter.getNatDriver().getRedirects()) {
|
||||
Iterable<String> stuff = Splitter.on(',').split(nameProtocolnumberAddressInboudportGuestTargetport);
|
||||
String protocolNumber = Iterables.get(stuff, 1);
|
||||
String hostAddress = Iterables.get(stuff, 2);
|
||||
String inboundPort = Iterables.get(stuff, 3);
|
||||
String targetPort = Iterables.get(stuff, 5);
|
||||
// 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());
|
||||
}
|
||||
|
||||
}
|
||||
return client;
|
||||
}
|
||||
}
|
|
@ -31,9 +31,12 @@ import java.util.regex.Pattern;
|
|||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.compute.callables.RunScriptOnNode.Factory;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.logging.Logger;
|
||||
import org.jclouds.scriptbuilder.domain.Statement;
|
||||
import org.jclouds.scriptbuilder.domain.Statements;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
|
@ -47,27 +50,25 @@ import com.google.inject.name.Named;
|
|||
/**
|
||||
* @author Andrea Turli
|
||||
*/
|
||||
public class RetrieveActiveBridgedInterfaces implements Function<String, List<String>> {
|
||||
public class RetrieveActiveBridgedInterfaces implements Function<NodeMetadata, List<String>> {
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private ComputeServiceContext context;
|
||||
private final Factory runScriptOnNodeFactory;
|
||||
|
||||
@Inject
|
||||
public RetrieveActiveBridgedInterfaces(ComputeServiceContext context) {
|
||||
this.context = context;
|
||||
public RetrieveActiveBridgedInterfaces(Factory runScriptOnNodeFactory) {
|
||||
this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, "runScriptOnNodeFactory");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> apply(String hostId) {
|
||||
public List<String> apply(NodeMetadata host) {
|
||||
// Bridged Network
|
||||
String command = "vboxmanage list bridgedifs";
|
||||
String bridgedIfBlocks = context
|
||||
.getComputeService()
|
||||
.runScriptOnNode(hostId, command,
|
||||
runAsRoot(false).wrapInInitScript(false)).getOutput();
|
||||
Statement command = Statements.exec("vboxmanage list bridgedifs");
|
||||
String bridgedIfBlocks = runScriptOnNodeFactory.create(host, command, runAsRoot(false).wrapInInitScript(false))
|
||||
.init().call().getOutput();
|
||||
|
||||
List<String> bridgedInterfaces = retrieveBridgedInterfaceNames(bridgedIfBlocks);
|
||||
checkNotNull(bridgedInterfaces);
|
||||
|
@ -125,9 +126,8 @@ public class RetrieveActiveBridgedInterfaces implements Function<String, List<St
|
|||
@Override
|
||||
public boolean apply(String bridgedInterfaceName) {
|
||||
try {
|
||||
return (bridgedInterfaceName.startsWith(networkInterface
|
||||
.getDisplayName()) && networkInterface.isUp() && !networkInterface
|
||||
.isLoopback());
|
||||
return (bridgedInterfaceName.startsWith(networkInterface.getDisplayName()) && networkInterface.isUp() && !networkInterface
|
||||
.isLoopback());
|
||||
} catch (SocketException e) {
|
||||
logger.error(e, "Problem in listing network interfaces.");
|
||||
propagate(e);
|
||||
|
|
|
@ -32,6 +32,7 @@ import org.virtualbox_4_1.ISnapshot;
|
|||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.common.base.Throwables;
|
||||
|
||||
/**
|
||||
|
@ -44,12 +45,12 @@ public class TakeSnapshotIfNotAlreadyAttached implements Function<IMachine, ISna
|
|||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private VirtualBoxManager manager;
|
||||
private Supplier<VirtualBoxManager> manager;
|
||||
private String snapshotName;
|
||||
private String snapshotDesc;
|
||||
|
||||
|
||||
public TakeSnapshotIfNotAlreadyAttached(VirtualBoxManager manager, String snapshotName, String snapshotDesc) {
|
||||
public TakeSnapshotIfNotAlreadyAttached(Supplier<VirtualBoxManager> manager, String snapshotName, String snapshotDesc) {
|
||||
this.manager = manager;
|
||||
this.snapshotName = snapshotName;
|
||||
this.snapshotDesc = snapshotDesc;
|
||||
|
@ -61,7 +62,7 @@ public class TakeSnapshotIfNotAlreadyAttached implements Function<IMachine, ISna
|
|||
ISession session = null;
|
||||
if(machine.getCurrentSnapshot() == null ) {
|
||||
try {
|
||||
session = manager.openMachineSession(machine);
|
||||
session = manager.get().openMachineSession(machine);
|
||||
IProgress progress = session.getConsole().takeSnapshot(snapshotName, snapshotDesc);
|
||||
if (progress.getCompleted())
|
||||
logger.debug("Snapshot %s (description: %s) taken from %s", snapshotName, snapshotDesc, machine.getName());
|
||||
|
|
|
@ -35,11 +35,10 @@ import javax.annotation.Resource;
|
|||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.javax.annotation.Nullable;
|
||||
import org.jclouds.logging.Logger;
|
||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
||||
import org.jclouds.rest.HttpClient;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
|
||||
|
@ -52,26 +51,22 @@ public class FileDownloadFromURI implements Function<URI, File> {
|
|||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private final ComputeServiceContext context;
|
||||
private final HttpClient client;
|
||||
private final String workingDir;
|
||||
private final String isoFile;
|
||||
|
||||
@Inject
|
||||
public FileDownloadFromURI(final ComputeServiceContext context,
|
||||
@Named(VIRTUALBOX_WORKINGDIR) final String workingDir,
|
||||
@Named(VirtualBoxConstants.VIRTUALBOX_ISOFILE) final String isoFile) {
|
||||
this.context = context;
|
||||
public FileDownloadFromURI(HttpClient client, @Named(VIRTUALBOX_WORKINGDIR) String workingDir) {
|
||||
this.client = client;
|
||||
this.workingDir = workingDir;
|
||||
this.isoFile = isoFile;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File apply(@Nullable URI input) {
|
||||
|
||||
final File file = new File(workingDir, isoFile);
|
||||
final File file = new File(workingDir, new File(input.getPath()).getName());
|
||||
|
||||
if (!file.exists()) {
|
||||
final InputStream inputStream = context.utils().http().get(input);
|
||||
final InputStream inputStream = client.get(input);
|
||||
checkNotNull(inputStream, "%s not found", input);
|
||||
try {
|
||||
copy(inputStream, new FileOutputStream(file));
|
||||
|
|
|
@ -21,6 +21,10 @@ package org.jclouds.virtualbox.functions.admin;
|
|||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
|
@ -31,51 +35,51 @@ import org.eclipse.jetty.server.handler.DefaultHandler;
|
|||
import org.eclipse.jetty.server.handler.HandlerList;
|
||||
import org.eclipse.jetty.server.handler.ResourceHandler;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.javax.annotation.Nullable;
|
||||
import org.jclouds.logging.Logger;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.predicates.InetSocketAddressConnect;
|
||||
import org.jclouds.virtualbox.Preconfiguration;
|
||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.inject.Singleton;
|
||||
|
||||
/**
|
||||
* @author Andrea Turli
|
||||
*/
|
||||
public class StartJettyIfNotAlreadyRunning implements Function<String, Server> {
|
||||
@Preconfiguration
|
||||
@Singleton
|
||||
public class StartJettyIfNotAlreadyRunning implements Supplier<URI> {
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private final URI preconfigurationUrl;
|
||||
private final Server jetty;
|
||||
private final int port;
|
||||
|
||||
public StartJettyIfNotAlreadyRunning(Server jetty, @Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) int port) {
|
||||
this.jetty = checkNotNull(jetty, "jetty");
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
// TODO: getting an instance of the Server object should really be done in
|
||||
// Guice, so inside a *Module class, perhaps as a @Provides method
|
||||
@Inject
|
||||
public StartJettyIfNotAlreadyRunning(@Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) int port) {
|
||||
this(ServerJetty.getInstance().getServer(), port);
|
||||
public StartJettyIfNotAlreadyRunning(
|
||||
@Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
|
||||
this(new Server(URI.create(preconfigurationUrl).getPort()), preconfigurationUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Server apply(@Nullable String baseResource) {
|
||||
if (!jetty.getState().equals(Server.STARTED)
|
||||
// TODO code smell = hard coding addresses or ports!!
|
||||
&& !new InetSocketAddressConnect().apply(new IPSocket("localhost", port))) {
|
||||
public StartJettyIfNotAlreadyRunning(Server jetty,
|
||||
@Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
|
||||
this.preconfigurationUrl = URI.create(checkNotNull(preconfigurationUrl, "preconfigurationUrl"));
|
||||
this.jetty = jetty;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void start() {
|
||||
|
||||
if (jetty.getState().equals(Server.STARTED)) {
|
||||
logger.debug("not starting jetty, as existing host is serving %s", preconfigurationUrl);
|
||||
} else {
|
||||
logger.debug(">> starting jetty to serve %s", preconfigurationUrl);
|
||||
ResourceHandler resource_handler = new ResourceHandler();
|
||||
resource_handler.setDirectoriesListed(true);
|
||||
resource_handler.setWelcomeFiles(new String[] { "index.html" });
|
||||
|
||||
resource_handler.setResourceBase(baseResource);
|
||||
logger.info("serving " + resource_handler.getBaseResource());
|
||||
|
||||
resource_handler.setResourceBase("");
|
||||
HandlerList handlers = new HandlerList();
|
||||
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
|
||||
jetty.setHandler(handlers);
|
||||
|
@ -83,34 +87,23 @@ public class StartJettyIfNotAlreadyRunning implements Function<String, Server> {
|
|||
try {
|
||||
jetty.start();
|
||||
} catch (Exception e) {
|
||||
logger.error(e, "Server jetty could not be started at this %s", baseResource);
|
||||
logger.error(e, "Server jetty could not be started for %s", preconfigurationUrl);
|
||||
}
|
||||
return jetty;
|
||||
} else {
|
||||
logger.debug("Server jetty serving %s already running. Skipping start", baseResource);
|
||||
return jetty;
|
||||
logger.debug("<< serving %s", resource_handler.getBaseResource());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Singleton
|
||||
private static class ServerJetty {
|
||||
private static ServerJetty instance;
|
||||
private Server server;
|
||||
private String port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080");
|
||||
|
||||
private ServerJetty() {
|
||||
this.server = new Server(Integer.parseInt(port));
|
||||
@PreDestroy()
|
||||
public void stop() {
|
||||
try {
|
||||
jetty.stop();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
public static ServerJetty getInstance() {
|
||||
if (instance == null)
|
||||
instance = new ServerJetty();
|
||||
return instance;
|
||||
}
|
||||
|
||||
public Server getServer() {
|
||||
return server;
|
||||
}
|
||||
@Override
|
||||
public URI get() {
|
||||
return preconfigurationUrl;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -25,68 +25,84 @@ import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
|
|||
|
||||
import java.net.URI;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.ComputeService;
|
||||
import org.jclouds.compute.callables.RunScriptOnNode.Factory;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.predicates.RetryIfSocketNotYetOpen;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.location.Provider;
|
||||
import org.jclouds.logging.Logger;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.rest.annotations.Credential;
|
||||
import org.jclouds.rest.annotations.Identity;
|
||||
import org.jclouds.scriptbuilder.domain.Statements;
|
||||
import org.virtualbox_4_1.SessionState;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Supplier;
|
||||
|
||||
public class StartVBoxIfNotAlreadyRunning implements Function<URI, VirtualBoxManager> {
|
||||
@Singleton
|
||||
public class StartVBoxIfNotAlreadyRunning implements Supplier<VirtualBoxManager> {
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private final ComputeService compute;
|
||||
private final VirtualBoxManager manager;
|
||||
private final Predicate<IPSocket> socketTester;
|
||||
private final String hostId;
|
||||
private final Credentials credentials;
|
||||
private final Factory runScriptOnNodeFactory;
|
||||
private final RetryIfSocketNotYetOpen socketTester;
|
||||
private final Supplier<NodeMetadata> host;
|
||||
private final URI provider;
|
||||
private final String identity;
|
||||
private final String credential;
|
||||
private final Function<Supplier<NodeMetadata>, VirtualBoxManager> managerForNode;
|
||||
private transient VirtualBoxManager manager;
|
||||
|
||||
public StartVBoxIfNotAlreadyRunning(ComputeService compute, VirtualBoxManager manager,
|
||||
Predicate<IPSocket> socketTester, String hostId, Credentials credentials) {
|
||||
this.compute = checkNotNull(compute, "compute");
|
||||
this.manager = checkNotNull(manager, "manager");
|
||||
// the functions and suppliers here are to ensure we don't do heavy i/o in injection
|
||||
@Inject
|
||||
public StartVBoxIfNotAlreadyRunning(Function<Supplier<NodeMetadata>, VirtualBoxManager> managerForNode,
|
||||
Factory runScriptOnNodeFactory, RetryIfSocketNotYetOpen socketTester, Supplier<NodeMetadata> host,
|
||||
@Provider URI provider, @Identity String identity, @Credential String credential) {
|
||||
this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, "runScriptOnNodeFactory");
|
||||
this.socketTester = checkNotNull(socketTester, "socketTester");
|
||||
this.hostId = checkNotNull(hostId, "hostId");
|
||||
this.credentials = checkNotNull(credentials, "credentials");
|
||||
this.host = checkNotNull(host, "host");
|
||||
this.provider = checkNotNull(provider, "endpoint to virtualbox websrvd is needed");
|
||||
this.identity = checkNotNull(identity, "identity");
|
||||
this.credential = checkNotNull(credential, "credential");
|
||||
this.managerForNode = checkNotNull(managerForNode, "managerForNode");
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void start() {
|
||||
if (!socketTester.apply(new IPSocket(provider.getHost(), provider.getPort()))) {
|
||||
logger.debug("disabling password access");
|
||||
runScriptOnNodeFactory.create(host.get(), Statements.exec("VBoxManage setproperty websrvauthlibrary null"),
|
||||
runAsRoot(false).wrapInInitScript(false)).init().call();
|
||||
logger.debug(">> starting vboxwebsrv");
|
||||
String vboxwebsrv = "vboxwebsrv -t 10000 -v -b";
|
||||
if (host.get().getOperatingSystem() != null
|
||||
&& host.get().getOperatingSystem().getDescription().equals("Mac OS X"))
|
||||
vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " + vboxwebsrv;
|
||||
|
||||
runScriptOnNodeFactory.create(host.get(), Statements.exec(vboxwebsrv),
|
||||
runAsRoot(false).wrapInInitScript(false).blockOnComplete(false).nameTask("vboxwebsrv")).init().call();
|
||||
}
|
||||
manager = managerForNode.apply(host);
|
||||
manager.connect(provider.toASCIIString(), identity, credential);
|
||||
if (logger.isDebugEnabled())
|
||||
if (manager.getSessionObject().getState() == SessionState.Unlocked)
|
||||
logger.warn("manager is not in unlocked state " + manager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VirtualBoxManager apply(URI endpoint) {
|
||||
checkState(compute.getNodeMetadata(hostId) != null, "compute service %s cannot locate node with id %s", compute,
|
||||
hostId);
|
||||
checkNotNull(endpoint, "endpoint to virtualbox websrvd is needed");
|
||||
|
||||
if (socketTester.apply(new IPSocket(endpoint.getHost(), endpoint.getPort()))) {
|
||||
manager.connect(endpoint.toASCIIString(), credentials.identity, credentials.credential);
|
||||
return manager;
|
||||
}
|
||||
|
||||
logger.debug("disabling password access");
|
||||
compute.runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null", runAsRoot(false)
|
||||
.wrapInInitScript(false));
|
||||
logger.debug("starting vboxwebsrv");
|
||||
String vboxwebsrv = "vboxwebsrv -t 10000 -v -b";
|
||||
if (isOSX(hostId))
|
||||
vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " + vboxwebsrv;
|
||||
|
||||
compute.runScriptOnNode(hostId, vboxwebsrv, runAsRoot(false).wrapInInitScript(false).blockOnComplete(false)
|
||||
.nameTask("vboxwebsrv"));
|
||||
|
||||
manager.connect(endpoint.toASCIIString(), credentials.identity, credentials.credential);
|
||||
public VirtualBoxManager get() {
|
||||
checkState(manager != null, "start not called");
|
||||
return manager;
|
||||
}
|
||||
|
||||
private boolean isOSX(String hostId) {
|
||||
return compute.getNodeMetadata(hostId).getOperatingSystem().getDescription().equals("Mac OS X");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -28,6 +28,7 @@ import java.util.List;
|
|||
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.logging.Logger;
|
||||
|
@ -45,8 +46,8 @@ import com.google.common.base.Predicate;
|
|||
import com.google.common.base.Throwables;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class UnregisterMachineIfExistsAndDeleteItsMedia implements
|
||||
Function<IMachine, Void> {
|
||||
@Singleton
|
||||
public class UnregisterMachineIfExistsAndDeleteItsMedia implements Function<IMachine, Void> {
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
|
@ -66,18 +67,16 @@ public class UnregisterMachineIfExistsAndDeleteItsMedia implements
|
|||
} catch (VBoxException e) {
|
||||
ErrorCode errorCode = ErrorCode.valueOf(e);
|
||||
switch (errorCode) {
|
||||
case VBOX_E_OBJECT_NOT_FOUND:
|
||||
logger.debug("Machine %s does not exists, cannot unregister",
|
||||
vmSpec.getVmName());
|
||||
break;
|
||||
default:
|
||||
throw e;
|
||||
case VBOX_E_OBJECT_NOT_FOUND:
|
||||
logger.debug("Machine %s does not exists, cannot unregister", vmSpec.getVmName());
|
||||
break;
|
||||
default:
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
List<IMedium> filteredMediaToBeDeleted = Lists.newArrayList(transform(
|
||||
filter(mediaToBeDeleted, new AutoDeleteHardDiskPredicate(vmSpec)),
|
||||
new DeleteChildrenOfMedium()));
|
||||
List<IMedium> filteredMediaToBeDeleted = Lists.newArrayList(transform(filter(mediaToBeDeleted,
|
||||
new AutoDeleteHardDiskPredicate(vmSpec)), new DeleteChildrenOfMedium()));
|
||||
|
||||
checkNotNull(filteredMediaToBeDeleted);
|
||||
if (!filteredMediaToBeDeleted.isEmpty()) {
|
||||
|
@ -85,8 +84,7 @@ public class UnregisterMachineIfExistsAndDeleteItsMedia implements
|
|||
IProgress deletion = machine.delete(filteredMediaToBeDeleted);
|
||||
deletion.waitForCompletion(-1);
|
||||
} catch (Exception e) {
|
||||
logger.error(e, "Problem in deleting the media attached to %s",
|
||||
machine.getName());
|
||||
logger.error(e, "Problem in deleting the media attached to %s", machine.getName());
|
||||
Throwables.propagate(e);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,7 +21,9 @@ package org.jclouds.virtualbox.predicates;
|
|||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.logging.Logger;
|
||||
|
@ -33,20 +35,23 @@ import org.virtualbox_4_1.IStorageController;
|
|||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Supplier;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Andrea Turli
|
||||
*/
|
||||
@Singleton
|
||||
public class IsLinkedClone implements Predicate<IMachine> {
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
private VirtualBoxManager manager;
|
||||
private final Supplier<VirtualBoxManager> manager;
|
||||
|
||||
public IsLinkedClone(VirtualBoxManager manager) {
|
||||
@Inject
|
||||
public IsLinkedClone(Supplier<VirtualBoxManager> manager) {
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
|
@ -64,7 +69,7 @@ public class IsLinkedClone implements Predicate<IMachine> {
|
|||
// more than one machine is attached to this hd
|
||||
for (IMedium child : iMedium.getParent().getChildren()) {
|
||||
for (String machineId : child.getMachineIds()) {
|
||||
IMachine iMachine = manager.getVBox().findMachine(
|
||||
IMachine iMachine = manager.get().getVBox().findMachine(
|
||||
machineId);
|
||||
if (!iMachine.getName().equals(machine.getName())) {
|
||||
logger.debug("Machine %s is a linked clone",
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
/**
|
||||
* Licensed to jclouds, Inc. (jclouds) under one or more
|
||||
* contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. jclouds licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.jclouds.virtualbox.predicates;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import org.jclouds.logging.Logger;
|
||||
import org.jclouds.ssh.SshClient;
|
||||
import org.jclouds.ssh.SshException;
|
||||
|
||||
import com.google.common.base.Predicate;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
public class SshResponds implements Predicate<SshClient> {
|
||||
@Resource
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
@Override
|
||||
public boolean apply(SshClient client) {
|
||||
|
||||
try {
|
||||
client.connect();
|
||||
if (client.exec("id").getExitCode() == 0) {
|
||||
return true;
|
||||
}
|
||||
} catch (SshException e) {
|
||||
logger.trace("No response from ssh daemon connecting to %s: %s", client, e.getMessage());
|
||||
} finally {
|
||||
client.disconnect();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -19,13 +19,19 @@
|
|||
|
||||
package org.jclouds.virtualbox.util;
|
||||
|
||||
import static org.jclouds.scriptbuilder.domain.Statements.call;
|
||||
import static org.jclouds.scriptbuilder.domain.Statements.findPid;
|
||||
import static org.jclouds.scriptbuilder.domain.Statements.kill;
|
||||
import static org.jclouds.scriptbuilder.domain.Statements.newStatementList;
|
||||
|
||||
import org.jclouds.scriptbuilder.domain.Statement;
|
||||
import org.jclouds.util.Throwables2;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
import org.virtualbox_4_1.ISession;
|
||||
import org.virtualbox_4_1.LockType;
|
||||
import org.virtualbox_4_1.SessionState;
|
||||
import org.virtualbox_4_1.VBoxException;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
import org.virtualbox_4_1.jaxws.SessionState;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
|
||||
|
@ -132,33 +138,42 @@ public class MachineUtils {
|
|||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 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/>
|
||||
*
|
||||
* @param manager the VirtualBoxManager
|
||||
* @param machineId the id of the machine
|
||||
* @param function the function to execute
|
||||
*
|
||||
*<h3>Note!</h3> Currently, this can only unlock the machine, if the lock was created in the
|
||||
* current session.
|
||||
*
|
||||
* @param manager
|
||||
* the VirtualBoxManager
|
||||
* @param machineId
|
||||
* the id of the machine
|
||||
* @param function
|
||||
* the function to execute
|
||||
* @return the result from applying the function to the machine.
|
||||
*/
|
||||
public static <T> T unlockMachineAndApply(VirtualBoxManager manager, final String machineId,
|
||||
final Function<IMachine, T> function) {
|
||||
final Function<IMachine, T> function) {
|
||||
try {
|
||||
ISession session = manager.getSessionObject();
|
||||
IMachine immutableMachine = manager.getVBox().findMachine(machineId);
|
||||
if(immutableMachine.getSessionState().equals(SessionState.LOCKED))
|
||||
SessionState state = immutableMachine.getSessionState();
|
||||
if (state.equals(SessionState.Locked))
|
||||
session.unlockMachine();
|
||||
|
||||
//TODO: wire this in
|
||||
Statement kill = newStatementList(call("default"), findPid(machineId), kill());
|
||||
|
||||
return function.apply(immutableMachine);
|
||||
|
||||
|
||||
} catch (VBoxException e) {
|
||||
throw new RuntimeException(String.format("error applying %s to %s: %s", function, machineId,
|
||||
e.getMessage()), e);
|
||||
throw new RuntimeException(String.format("error applying %s to %s: %s", function, machineId, e.getMessage()),
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Unlocks the machine and executes the given function, if the machine is registered.
|
||||
* Since the machine is unlocked it is possible to delete the machine.
|
||||
|
|
|
@ -19,35 +19,40 @@
|
|||
|
||||
package org.jclouds.virtualbox;
|
||||
|
||||
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.jclouds.Constants;
|
||||
import org.jclouds.byon.Node;
|
||||
import org.jclouds.byon.config.CacheNodeStoreModule;
|
||||
import org.jclouds.compute.BaseVersionedServiceLiveTest;
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.compute.ComputeServiceContextFactory;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.domain.OsFamily;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.config.ValueOfConfigurationKeyOrNull;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
|
||||
import org.jclouds.predicates.InetSocketAddressConnect;
|
||||
import org.jclouds.sshj.config.SshjSshClientModule;
|
||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
||||
import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning;
|
||||
import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning;
|
||||
import org.jclouds.virtualbox.domain.VmSpec;
|
||||
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.virtualbox_4_1.SessionState;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.base.Supplier;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.inject.Key;
|
||||
import com.google.inject.Module;
|
||||
import com.google.inject.TypeLiteral;
|
||||
|
||||
/**
|
||||
* Tests behavior of {@code VirtualBoxClient}
|
||||
|
@ -59,19 +64,21 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
|
|||
public BaseVirtualBoxClientLiveTest() {
|
||||
provider = "virtualbox";
|
||||
}
|
||||
|
||||
|
||||
protected ComputeServiceContext context;
|
||||
protected VirtualBoxManager manager;
|
||||
protected Server jetty;
|
||||
protected Supplier<VirtualBoxManager> manager;
|
||||
protected Supplier<URI> preconfigurationUri;
|
||||
protected String hostVersion;
|
||||
protected String operatingSystemIso;
|
||||
protected String guestAdditionsIso;
|
||||
protected String adminDisk;
|
||||
protected String workingDir;
|
||||
|
||||
protected Supplier<NodeMetadata> host;
|
||||
|
||||
@Override
|
||||
protected void setupCredentials() {
|
||||
// default behavior is to bomb when no user is configured, but we know the default user of vbox
|
||||
// default behavior is to bomb when no user is configured, but we know the default user of
|
||||
// vbox
|
||||
ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults();
|
||||
super.setupCredentials();
|
||||
}
|
||||
|
@ -87,44 +94,48 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
|
|||
public void setupClient() {
|
||||
setupCredentials();
|
||||
Properties overrides = setupProperties();
|
||||
context = new ComputeServiceContextFactory().createContext(provider, identity, credential,
|
||||
ImmutableSet.<Module> of(new Log4JLoggingModule(), new SshjSshClientModule()), overrides);
|
||||
Function<String, String> configProperties = context.utils().injector().getInstance(ValueOfConfigurationKeyOrNull.class);
|
||||
|
||||
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 Log4JLoggingModule(), new SshjSshClientModule(), hostModule), overrides);
|
||||
Function<String, String> configProperties = context.utils().injector().getInstance(
|
||||
ValueOfConfigurationKeyOrNull.class);
|
||||
imageId = configProperties.apply(ComputeServiceConstants.PROPERTY_IMAGE_ID);
|
||||
workingDir = configProperties.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
|
||||
host = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<NodeMetadata>>(){}));
|
||||
|
||||
// this will eagerly startup Jetty, note the impl will shut itself down
|
||||
preconfigurationUri = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<URI>>() {
|
||||
}, Preconfiguration.class));
|
||||
// this will eagerly startup Jetty, note the impl will shut itself down
|
||||
preconfigurationUri.get();
|
||||
|
||||
jetty = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource);
|
||||
startVboxIfNotAlreadyRunning();
|
||||
manager = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<VirtualBoxManager>>() {
|
||||
}));
|
||||
// this will eagerly startup vbox
|
||||
manager.get();
|
||||
|
||||
hostVersion = Iterables.get(Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0);
|
||||
adminDisk = workingDir + "/testadmin.vdi";
|
||||
operatingSystemIso = String.format("%s/%s.iso", workingDir, imageId);
|
||||
guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", workingDir, hostVersion);
|
||||
|
||||
}
|
||||
|
||||
protected void undoVm(VmSpec vmSpecification) {
|
||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager.get(), vmSpecification.getVmName(),
|
||||
new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
|
||||
}
|
||||
|
||||
@AfterClass(groups = "live")
|
||||
protected void tearDown() throws Exception {
|
||||
if (context != null)
|
||||
context.close();
|
||||
if (jetty != null)
|
||||
jetty.stop();
|
||||
// TODO: should we stop the vbox manager?
|
||||
}
|
||||
|
||||
private String basebaseResource = ".";
|
||||
// TODO: I'd not use 8080, maybe something like 28080
|
||||
// also update pom.xml so that this passes through
|
||||
private int port = Integer.parseInt(System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"));
|
||||
|
||||
protected void startVboxIfNotAlreadyRunning() {
|
||||
Credentials localhostCredentials = new Credentials("toor", "password");
|
||||
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest("hostId", "localhost", "guestId",
|
||||
"localhost", localhostCredentials);
|
||||
|
||||
manager = new StartVBoxIfNotAlreadyRunning(localHostContext.getComputeService(),
|
||||
VirtualBoxManager.createInstance("hostId"), new InetSocketAddressConnect(), "hostId", localhostCredentials)
|
||||
.apply(context.getProviderSpecificContext().getEndpoint());
|
||||
|
||||
assert manager.getSessionObject().getState() == SessionState.Unlocked : "manager needs to be in unlocked state or all tests will fail!!: "
|
||||
+ manager;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -22,55 +22,31 @@ package org.jclouds.virtualbox.compute;
|
|||
import static org.testng.Assert.assertEquals;
|
||||
import static org.testng.Assert.assertFalse;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;
|
||||
import org.jclouds.compute.config.BaseComputeServiceContextModule;
|
||||
import org.jclouds.compute.domain.ExecResponse;
|
||||
import org.jclouds.compute.domain.Image;
|
||||
import org.jclouds.compute.domain.OsFamily;
|
||||
import org.jclouds.compute.domain.Template;
|
||||
import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.json.Json;
|
||||
import org.jclouds.json.config.GsonModule;
|
||||
import org.jclouds.location.suppliers.JustProvider;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.ssh.SshClient;
|
||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||
import org.jclouds.virtualbox.functions.IMachineToImage;
|
||||
import org.testng.annotations.Test;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.inject.Guice;
|
||||
|
||||
@Test(groups = "live", singleThreaded = true, testName = "VirtualBoxComputeServiceAdapterLiveTest")
|
||||
public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||
|
||||
private VirtualBoxComputeServiceAdapter adapter;
|
||||
private NodeAndInitialCredentials<IMachine> machine;
|
||||
private final Map<OsFamily, Map<String, String>> osVersionMap = new BaseComputeServiceContextModule() {
|
||||
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
|
||||
.getInstance(Json.class));
|
||||
|
||||
@Override
|
||||
public void setupClient() {
|
||||
super.setupClient();
|
||||
final VirtualBoxManager manager = getManager();
|
||||
Function<IMachine, Image> iMachineToImage = new IMachineToImage(manager, osVersionMap);
|
||||
adapter = new VirtualBoxComputeServiceAdapter(manager, new JustProvider(provider, URI.create(endpoint),
|
||||
ImmutableSet.<String> of()), iMachineToImage);
|
||||
}
|
||||
|
||||
protected VirtualBoxManager getManager() {
|
||||
return (VirtualBoxManager) context.getProviderSpecificContext().getApi();
|
||||
adapter = context.utils().injector().getInstance(VirtualBoxComputeServiceAdapter.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -46,6 +46,7 @@ import org.virtualbox_4_1.IVirtualBox;
|
|||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.google.common.collect.Iterators;
|
||||
import com.google.inject.Guice;
|
||||
|
||||
|
@ -83,8 +84,8 @@ public class VirtualBoxComputeServiceAdapterTest {
|
|||
|
||||
replay(manager, justProvider, vBox, clonedMachine, imageMachine, osType);
|
||||
|
||||
Function<IMachine, Image> iMachineToImage = new IMachineToImage(manager, osMap);
|
||||
VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(manager, justProvider,
|
||||
Function<IMachine, Image> iMachineToImage = new IMachineToImage(Suppliers.ofInstance(manager), osMap);
|
||||
VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(Suppliers.ofInstance(manager), justProvider,
|
||||
iMachineToImage);
|
||||
|
||||
Iterator<Image> iterator = adapter.listImages().iterator();
|
||||
|
|
|
@ -1,93 +0,0 @@
|
|||
/**
|
||||
* Licensed to jclouds, Inc. (jclouds) under one or more
|
||||
* contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. jclouds licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.jclouds.virtualbox.experiment;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Map;
|
||||
|
||||
import org.jclouds.byon.Node;
|
||||
import org.jclouds.byon.config.CacheNodeStoreModule;
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.compute.ComputeServiceContextFactory;
|
||||
import org.jclouds.compute.domain.OsFamily;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.encryption.bouncycastle.config.BouncyCastleCryptoModule;
|
||||
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
|
||||
import org.jclouds.sshj.config.SshjSshClientModule;
|
||||
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.inject.Module;
|
||||
|
||||
public class TestUtils {
|
||||
|
||||
public static ComputeServiceContext computeServiceForLocalhostAndGuest() throws IOException {
|
||||
|
||||
Node 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(privateKeyFile()).build();
|
||||
Node guest = Node.builder().id("guest").name("new guest").hostname("localhost").loginPort(2222)
|
||||
.osFamily(OsFamily.UBUNTU.toString()).osDescription("ubuntu/11.04").osVersion(System.getProperty("11.04"))
|
||||
.group("guest").username("toor").sudoPassword("password").credential("password").build();
|
||||
|
||||
final Map<String, Node> nodeMap = ImmutableMap.<String, Node> builder().put("host", host).put("guest", guest)
|
||||
.build();
|
||||
return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet.<Module> of(
|
||||
new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(),
|
||||
new CacheNodeStoreModule(nodeMap)));
|
||||
}
|
||||
|
||||
public static ComputeServiceContext computeServiceForLocalhostAndGuest(String hostId, String hostname,
|
||||
String guestId, String guestHostname, Credentials guestLogin) {
|
||||
|
||||
Node host = Node.builder().id(hostId).name("host installing virtualbox").hostname(hostname)
|
||||
.osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name"))
|
||||
.osVersion(System.getProperty("os.version")).group("ssh").username(System.getProperty("user.name"))
|
||||
.credentialUrl(privateKeyFile()).build();
|
||||
Node guest = Node.builder().id(guestId).name("new guest").hostname(guestHostname).loginPort(2222)
|
||||
.osFamily(OsFamily.UBUNTU.toString()).osDescription("ubuntu/11.04").osVersion(System.getProperty("11.04"))
|
||||
.group("jclouds-linux-image").username(guestLogin.identity).sudoPassword(guestLogin.credential)
|
||||
.credential(guestLogin.credential).build();
|
||||
|
||||
final Map<String, Node> nodeMap = ImmutableMap.<String, Node> builder().put(hostId, host).put(guestId, guest)
|
||||
.build();
|
||||
return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet.<Module> of(
|
||||
new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(),
|
||||
new CacheNodeStoreModule(nodeMap)));
|
||||
}
|
||||
|
||||
private static URI privateKeyFile() {
|
||||
try {
|
||||
return new URI("file://" + System.getProperty("user.home") + "/.ssh/id_rsa");
|
||||
} catch (URISyntaxException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static ComputeServiceContext computeServiceForVirtualBox(LoadingCache<String, Node> cache) {
|
||||
return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet.<Module> of(
|
||||
new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(),
|
||||
new CacheNodeStoreModule(cache)));
|
||||
}
|
||||
}
|
|
@ -52,7 +52,6 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest {
|
|||
|
||||
String controllerName = "IDE Controller";
|
||||
String diskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
|
||||
String diskName = "admin";
|
||||
String diskFormat = "vdi";
|
||||
int controllerPort = 0;
|
||||
int deviceSlot = 1;
|
||||
|
|
|
@ -51,12 +51,12 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
|
|||
networkAdapter.setAttachmentType(NAT);
|
||||
expect(networkAdapter.getNatDriver()).andReturn(natEngine);
|
||||
|
||||
natEngine.addRedirect("TCP@127.0.0.1:2222->guest:22", TCP, "127.0.0.1", 2222, "guest", 22);
|
||||
natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1", 2222, "", 22);
|
||||
networkAdapter.setEnabled(true);
|
||||
machine.saveSettings();
|
||||
|
||||
replay(machine, networkAdapter, natEngine);
|
||||
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "guest", 22).build();
|
||||
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
|
||||
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
|
||||
|
||||
verify(machine, networkAdapter, natEngine);
|
||||
|
@ -73,7 +73,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
|
|||
networkAdapter.setAttachmentType(NAT);
|
||||
expect(networkAdapter.getNatDriver()).andReturn(natEngine);
|
||||
|
||||
natEngine.addRedirect("TCP@127.0.0.1:2222->guest:22", TCP, "127.0.0.1", 2222, "guest", 22);
|
||||
natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1", 2222, "", 22);
|
||||
expectLastCall().andThrow(
|
||||
new VBoxException(null, "VirtualBox error: A NAT rule of this name already exists (0x80070057)"));
|
||||
|
||||
|
@ -81,7 +81,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
|
|||
machine.saveSettings();
|
||||
|
||||
replay(machine, networkAdapter, natEngine);
|
||||
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "guest", 22).build();
|
||||
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
|
||||
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
|
||||
|
||||
verify(machine, networkAdapter, natEngine);
|
||||
|
@ -102,7 +102,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
|
|||
|
||||
replay(machine, networkAdapter, natEngine);
|
||||
|
||||
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "guest", 22).build();
|
||||
NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build();
|
||||
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
|
||||
|
||||
verify(machine, networkAdapter, natEngine);
|
||||
|
|
|
@ -19,95 +19,83 @@
|
|||
|
||||
package org.jclouds.virtualbox.functions;
|
||||
|
||||
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||
import org.jclouds.virtualbox.domain.HardDisk;
|
||||
import org.jclouds.virtualbox.domain.StorageController;
|
||||
import org.jclouds.virtualbox.domain.VmSpec;
|
||||
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
|
||||
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.ISession;
|
||||
import org.virtualbox_4_1.StorageBus;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.CaseFormat;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
|
||||
/**
|
||||
* @author Andrea Turli
|
||||
*/
|
||||
@Test(groups = "live", singleThreaded = true, testName = "CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
|
||||
public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
|
||||
BaseVirtualBoxClientLiveTest {
|
||||
public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||
|
||||
private static final boolean IS_LINKED_CLONE = true;
|
||||
private String vmId = "jclouds-image-iso-1";
|
||||
private String osTypeId = "";
|
||||
private String guestId = "guest";
|
||||
private String hostId = "host";
|
||||
|
||||
private String vmName = "jclouds-virtualbox-clone-test";
|
||||
private String cloneName = vmName + "_clone";
|
||||
private VmSpec clonedVmSpec;
|
||||
private VmSpec sourceVmSpec;
|
||||
|
||||
private String ideControllerName = "IDE Controller";
|
||||
private CleanupMode mode = CleanupMode.Full;
|
||||
|
||||
@Override
|
||||
@BeforeClass(groups = "live")
|
||||
public void setupClient() {
|
||||
setupCredentials();
|
||||
String sourceName = "jclouds#image#"
|
||||
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName());
|
||||
String cloneName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName());
|
||||
|
||||
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE)
|
||||
.attachISO(0, 0, operatingSystemIso).attachHardDisk(
|
||||
HardDisk.builder().diskpath(adminDisk).controllerPort(0).deviceSlot(1).build()).attachISO(1, 1,
|
||||
guestAdditionsIso).build();
|
||||
|
||||
sourceVmSpec = VmSpec.builder().id(sourceName).name(sourceName).osTypeId("").memoryMB(512).cleanUpMode(
|
||||
CleanupMode.Full).controller(ideController).forceOverwrite(true).build();
|
||||
|
||||
clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(512).cleanUpMode(mode)
|
||||
.forceOverwrite(true).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloneMachineFromAnotherMachine() throws Exception {
|
||||
VirtualBoxManager manager = (VirtualBoxManager) context
|
||||
.getProviderSpecificContext().getApi();
|
||||
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(
|
||||
hostId, "localhost", guestId, "localhost", new Credentials("toor",
|
||||
"password"));
|
||||
try {
|
||||
IMachine source = getSourceNode();
|
||||
|
||||
IMachine master = getMasterNode(manager, localHostContext);
|
||||
if (source.getCurrentSnapshot() != null) {
|
||||
ISession session = manager.get().openMachineSession(source);
|
||||
session.getConsole().deleteSnapshot(source.getCurrentSnapshot().getId());
|
||||
session.unlockMachine();
|
||||
}
|
||||
|
||||
if (master.getCurrentSnapshot() != null) {
|
||||
ISession session = manager.openMachineSession(master);
|
||||
session.getConsole().deleteSnapshot(
|
||||
master.getCurrentSnapshot().getId());
|
||||
session.unlockMachine();
|
||||
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, clonedVmSpec,
|
||||
IS_LINKED_CLONE).apply(source);
|
||||
assertEquals(clone.getName(), clonedVmSpec.getVmName());
|
||||
} finally {
|
||||
for (VmSpec spec : ImmutableSet.of(clonedVmSpec, sourceVmSpec))
|
||||
undoVm(spec);
|
||||
}
|
||||
|
||||
clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(512)
|
||||
.cleanUpMode(mode)
|
||||
.forceOverwrite(true).build();
|
||||
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(
|
||||
manager, workingDir, clonedVmSpec, IS_LINKED_CLONE).apply(master);
|
||||
assertEquals(clone.getName(), clonedVmSpec.getVmName());
|
||||
for (VmSpec spec : ImmutableSet.of(clonedVmSpec, new IMachineToVmSpec().apply(master)))
|
||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, spec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(spec));
|
||||
|
||||
}
|
||||
|
||||
private IMachine getMasterNode(VirtualBoxManager manager,
|
||||
ComputeServiceContext localHostContext) {
|
||||
private IMachine getSourceNode() {
|
||||
try {
|
||||
StorageController ideController = StorageController
|
||||
.builder()
|
||||
.name(ideControllerName)
|
||||
.bus(StorageBus.IDE)
|
||||
.attachISO(0, 0, operatingSystemIso)
|
||||
.attachHardDisk(
|
||||
HardDisk.builder().diskpath(adminDisk)
|
||||
.controllerPort(0).deviceSlot(1).build())
|
||||
.attachISO(1, 1, guestAdditionsIso)
|
||||
.build();
|
||||
VmSpec vmSpec = VmSpec.builder().id(vmId).name(vmName)
|
||||
.osTypeId(osTypeId).memoryMB(512).cleanUpMode(CleanupMode.Full)
|
||||
.controller(ideController).forceOverwrite(true).build();
|
||||
return new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir).apply(vmSpec);
|
||||
|
||||
return context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(
|
||||
sourceVmSpec);
|
||||
} catch (IllegalStateException e) {
|
||||
// already created
|
||||
return manager.getVBox().findMachine(vmName);
|
||||
return manager.get().getVBox().findMachine(sourceVmSpec.getVmId());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -22,44 +22,32 @@ package org.jclouds.virtualbox.functions;
|
|||
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 org.jclouds.virtualbox.domain.ExecutionType.HEADLESS;
|
||||
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApplyOrReturnNullIfNotRegistered;
|
||||
import static org.testng.Assert.assertTrue;
|
||||
import static org.virtualbox_4_1.LockType.Write;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.compute.config.BaseComputeServiceContextModule;
|
||||
import org.jclouds.compute.domain.Image;
|
||||
import org.jclouds.compute.domain.OsFamily;
|
||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.json.Json;
|
||||
import org.jclouds.json.config.GsonModule;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.predicates.InetSocketAddressConnect;
|
||||
import org.jclouds.predicates.RetryablePredicate;
|
||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||
import org.jclouds.virtualbox.domain.HardDisk;
|
||||
import org.jclouds.virtualbox.domain.NatAdapter;
|
||||
import org.jclouds.virtualbox.domain.StorageController;
|
||||
import org.jclouds.virtualbox.domain.VmSpec;
|
||||
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
|
||||
import org.testng.annotations.AfterClass;
|
||||
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.StorageBus;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.inject.Guice;
|
||||
|
||||
/**
|
||||
|
@ -72,43 +60,31 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
|
|||
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
|
||||
.getInstance(Json.class));
|
||||
|
||||
private String vmId = "jclouds-image-iso-1";
|
||||
private String osTypeId = "";
|
||||
private String ideControllerName = "IDE Controller";
|
||||
private String guestId = "guest";
|
||||
private String hostId = "host";
|
||||
private String vmName = "jclouds-image-virtualbox-iso-to-machine-test";
|
||||
private StorageController ideController;
|
||||
private VmSpec vmSpecification;
|
||||
|
||||
@Override
|
||||
@BeforeClass(groups = "live")
|
||||
public void setupClient() {
|
||||
super.setupClient();
|
||||
String vmName = "jclouds-image-virtualbox-iso-to-machine-test";
|
||||
|
||||
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true)
|
||||
.controllerPort(0).deviceSlot(1).build();
|
||||
ideController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE)
|
||||
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(vmId).name(vmName).memoryMB(512).osTypeId(osTypeId)
|
||||
vmSpecification = VmSpec.builder().id("jclouds-image-iso-1").name(vmName).memoryMB(512).osTypeId("")
|
||||
.controller(ideController)
|
||||
.forceOverwrite(true)
|
||||
.cleanUpMode(CleanupMode.Full)
|
||||
.natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build()).build();
|
||||
lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, vmName, new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification));
|
||||
undoVm(vmSpecification);
|
||||
}
|
||||
|
||||
public void testCreateImageMachineFromIso() throws Exception {
|
||||
|
||||
VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
|
||||
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(hostId, "localhost", guestId,
|
||||
"localhost", new Credentials("toor", "password"));
|
||||
Predicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS);
|
||||
|
||||
IMachine imageMachine = new CreateAndInstallVm(manager, new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(
|
||||
manager, workingDir), workingDir, guestId, localHostContext, hostId, socketTester, "127.0.0.1", 8080,
|
||||
HEADLESS).apply(vmSpecification);
|
||||
IMachine imageMachine = context.utils().injector().getInstance(CreateAndInstallVm.class).apply(vmSpecification);
|
||||
|
||||
IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
|
||||
Image newImage = iMachineToImage.apply(imageMachine);
|
||||
|
@ -128,5 +104,10 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
|
|||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
@AfterClass(groups = "live")
|
||||
protected void tearDown() throws Exception {
|
||||
undoVm(vmSpecification);
|
||||
super.tearDown();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,7 +19,6 @@
|
|||
|
||||
package org.jclouds.virtualbox.functions;
|
||||
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
import static org.testng.Assert.fail;
|
||||
|
||||
|
@ -28,7 +27,6 @@ import org.jclouds.virtualbox.domain.ErrorCode;
|
|||
import org.jclouds.virtualbox.domain.HardDisk;
|
||||
import org.jclouds.virtualbox.domain.StorageController;
|
||||
import org.jclouds.virtualbox.domain.VmSpec;
|
||||
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
|
||||
import org.testng.annotations.Test;
|
||||
import org.virtualbox_4_1.CleanupMode;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
|
@ -39,8 +37,7 @@ import org.virtualbox_4_1.VBoxException;
|
|||
* @author Mattias Holmqvist
|
||||
*/
|
||||
@Test(groups = "live", singleThreaded = true, testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
|
||||
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
|
||||
BaseVirtualBoxClientLiveTest {
|
||||
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||
|
||||
private String ideControllerName;
|
||||
private CleanupMode mode;
|
||||
|
@ -51,50 +48,48 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
|
|||
super.setupClient();
|
||||
ideControllerName = "IDE Controller";
|
||||
mode = CleanupMode.Full;
|
||||
ideController = StorageController
|
||||
.builder()
|
||||
.name(ideControllerName)
|
||||
.bus(StorageBus.IDE)
|
||||
.attachISO(0, 0, operatingSystemIso)
|
||||
.attachHardDisk(
|
||||
HardDisk.builder().diskpath(adminDisk)
|
||||
.controllerPort(0).deviceSlot(1).build())
|
||||
.attachISO(1, 1, guestAdditionsIso)
|
||||
.build();
|
||||
ideController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE).attachISO(0, 0,
|
||||
operatingSystemIso).attachHardDisk(
|
||||
HardDisk.builder().diskpath(adminDisk).controllerPort(0).deviceSlot(1).build()).attachISO(1, 1,
|
||||
guestAdditionsIso).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateNewMachine() throws Exception {
|
||||
String vmName = "jclouds-test-create-1-node";
|
||||
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName)
|
||||
.memoryMB(512).controller(ideController).cleanUpMode(mode)
|
||||
.osTypeId("Debian").forceOverwrite(true).build();
|
||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification));
|
||||
IMachine debianNode = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(
|
||||
manager, workingDir).apply(launchSpecification);
|
||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
||||
assertEquals(debianNode.getName(), machine.getName());
|
||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification));
|
||||
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).controller(ideController)
|
||||
.cleanUpMode(mode).osTypeId("Debian").forceOverwrite(true).build();
|
||||
undoVm(launchSpecification);
|
||||
try {
|
||||
IMachine debianNode = context.utils().injector().getInstance(
|
||||
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(launchSpecification);
|
||||
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||
assertEquals(debianNode.getName(), machine.getName());
|
||||
} finally {
|
||||
undoVm(launchSpecification);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateNewMachineWithBadOsType() throws Exception {
|
||||
String vmName = "jclouds-test-create-2-node";
|
||||
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName)
|
||||
.memoryMB(512).controller(ideController).cleanUpMode(mode)
|
||||
.osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build();
|
||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification));
|
||||
//new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification).apply(manager.getVBox().findMachine(vmName));
|
||||
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).controller(ideController)
|
||||
.cleanUpMode(mode).osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build();
|
||||
|
||||
undoVm(launchSpecification);
|
||||
try {
|
||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir)
|
||||
.apply(launchSpecification);
|
||||
context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(
|
||||
launchSpecification);
|
||||
fail();
|
||||
} catch (VBoxException e) {
|
||||
ErrorCode errorCode = ErrorCode.valueOf(e);
|
||||
// According to the documentation VBOX_E_OBJECT_NOT_FOUND
|
||||
// if osTypeId is not found.
|
||||
assertEquals(errorCode, ErrorCode.VBOX_E_OBJECT_NOT_FOUND);
|
||||
} finally {
|
||||
undoVm(launchSpecification);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -39,6 +39,8 @@ import org.virtualbox_4_1.LockType;
|
|||
import org.virtualbox_4_1.VBoxException;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
|
||||
/**
|
||||
* @author Mattias Holmqvist
|
||||
*/
|
||||
|
@ -86,7 +88,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
|
|||
|
||||
replay(manager, createdMachine, vBox, session);
|
||||
|
||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, "/tmp/workingDir").apply(launchSpecification);
|
||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(launchSpecification);
|
||||
|
||||
verify(manager, createdMachine, vBox, session);
|
||||
}
|
||||
|
@ -107,7 +109,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
|
|||
|
||||
VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").memoryMB(1024).cleanUpMode(
|
||||
CleanupMode.Full).build();
|
||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, "/tmp/workingDir").apply(launchSpecification);
|
||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(launchSpecification);
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = VBoxException.class)
|
||||
|
@ -129,7 +131,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
|
|||
|
||||
VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full)
|
||||
.memoryMB(1024).build();
|
||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, "/tmp/workingDir").apply(launchSpecification);
|
||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(launchSpecification);
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -44,9 +44,12 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
|
|||
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-1.vdi";
|
||||
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
|
||||
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||
manager.getVBox().findMedium(path, DeviceType.HardDisk);
|
||||
assertFileCanBeDeleted(path);
|
||||
deleteMediumAndBlockUntilComplete(iMedium);
|
||||
manager.get().getVBox().findMedium(path, DeviceType.HardDisk);
|
||||
try {
|
||||
assertFileCanBeDeleted(path);
|
||||
} finally {
|
||||
deleteMediumAndBlockUntilComplete(iMedium);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -68,9 +71,12 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
|
|||
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
|
||||
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||
iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||
manager.getVBox().findMedium(path, DeviceType.HardDisk);
|
||||
assertFileCanBeDeleted(path);
|
||||
deleteMediumAndBlockUntilComplete(iMedium);
|
||||
manager.get().getVBox().findMedium(path, DeviceType.HardDisk);
|
||||
try {
|
||||
assertFileCanBeDeleted(path);
|
||||
} finally {
|
||||
deleteMediumAndBlockUntilComplete(iMedium);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -79,10 +85,10 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
|
|||
boolean mediumDeleted = file.delete();
|
||||
assertTrue(mediumDeleted);
|
||||
}
|
||||
|
||||
void deleteMediumAndBlockUntilComplete(IMedium medium){
|
||||
|
||||
void deleteMediumAndBlockUntilComplete(IMedium medium) {
|
||||
final IProgress progress = medium.deleteStorage();
|
||||
progress.waitForCompletion(-1);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -42,6 +42,7 @@ import org.virtualbox_4_1.LockType;
|
|||
import org.virtualbox_4_1.VBoxException;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
/**
|
||||
|
@ -51,14 +52,11 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
|||
|
||||
private String adminDiskPath;
|
||||
private String diskFormat;
|
||||
private String diskName;
|
||||
|
||||
|
||||
@BeforeMethod
|
||||
public void setUp() throws Exception {
|
||||
adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
|
||||
diskFormat = "vdi";
|
||||
diskName = "diskName";
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -87,7 +85,7 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
|||
|
||||
replay(manager, machine, vBox, medium);
|
||||
|
||||
new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
|
||||
|
||||
verify(machine, vBox);
|
||||
|
||||
|
@ -113,14 +111,15 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
|||
|
||||
replay(manager, machine, vBox, medium, newHardDisk, progress);
|
||||
|
||||
IMedium newDisk = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||
IMedium newDisk = new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
|
||||
|
||||
verify(machine, vBox, medium);
|
||||
assertNotSame(newDisk, medium);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwriteAndStillAttachedDetachesOldThing() throws Exception {
|
||||
public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwriteAndStillAttachedDetachesOldThing()
|
||||
throws Exception {
|
||||
HardDisk hardDisk = createTestHardDisk();
|
||||
|
||||
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
|
||||
|
@ -133,7 +132,6 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
|||
|
||||
expect(manager.getVBox()).andReturn(vBox).anyTimes();
|
||||
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(medium);
|
||||
|
||||
|
||||
String oldMachineId = "a1e03931-29f3-4370-ada3-9547b1009212";
|
||||
String oldMachineName = "oldMachine";
|
||||
|
@ -178,11 +176,11 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
|||
expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(newHardDisk);
|
||||
expect(newHardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress);
|
||||
|
||||
replay(manager,oldMachine, oldAttachment,oldMedium, detachSession, machine, vBox, medium, newHardDisk, progress);
|
||||
replay(manager, oldMachine, oldAttachment, oldMedium, detachSession, machine, vBox, medium, newHardDisk, progress);
|
||||
|
||||
IMedium newDisk = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||
IMedium newDisk = new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
|
||||
|
||||
verify(machine,oldMachine,oldAttachment, detachSession, oldMedium, vBox, medium);
|
||||
verify(machine, oldMachine, oldAttachment, detachSession, oldMedium, vBox, medium);
|
||||
assertNotSame(newDisk, medium);
|
||||
}
|
||||
|
||||
|
@ -202,7 +200,7 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
|||
|
||||
replay(manager, machine, vBox, medium, newHardDisk, progress);
|
||||
|
||||
new CreateMediumIfNotAlreadyExists(manager, false).apply(hardDisk);
|
||||
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), false).apply(hardDisk);
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = VBoxException.class)
|
||||
|
@ -227,7 +225,7 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
|||
|
||||
replay(manager, machine, vBox, medium);
|
||||
|
||||
new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
|
||||
}
|
||||
|
||||
private HardDisk createTestHardDisk() {
|
||||
|
|
|
@ -33,6 +33,8 @@ import org.virtualbox_4_1.IMachine;
|
|||
import org.virtualbox_4_1.IVirtualBox;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
|
||||
@Test(groups = "unit")
|
||||
public class IMachineToHardwareTest {
|
||||
|
||||
|
@ -57,7 +59,7 @@ public class IMachineToHardwareTest {
|
|||
|
||||
replay(vbm, vBox, vm, guestOsType);
|
||||
|
||||
Hardware hardware = new IMachineToHardware(vbm).apply(vm);
|
||||
Hardware hardware = new IMachineToHardware(Suppliers.ofInstance(vbm)).apply(vm);
|
||||
|
||||
assertEquals(hardware.getId(), machineId);
|
||||
assertEquals(hardware.getProviderId(), machineId);
|
||||
|
|
|
@ -40,6 +40,7 @@ import org.virtualbox_4_1.IMachine;
|
|||
import org.virtualbox_4_1.IVirtualBox;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.google.inject.Guice;
|
||||
|
||||
@Test(groups = "unit")
|
||||
|
@ -67,7 +68,7 @@ public class IMachineToImageTest {
|
|||
|
||||
replay(vbm, vBox, vm, guestOsType);
|
||||
|
||||
IMachineToImage fn = new IMachineToImage(vbm, map);
|
||||
IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map);
|
||||
|
||||
Image image = fn.apply(vm);
|
||||
|
||||
|
@ -98,7 +99,7 @@ public class IMachineToImageTest {
|
|||
|
||||
replay(vbm, vBox, vm, guestOsType);
|
||||
|
||||
IMachineToImage fn = new IMachineToImage(vbm, map);
|
||||
IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map);
|
||||
|
||||
Image image = fn.apply(vm);
|
||||
|
||||
|
@ -129,7 +130,9 @@ public class IMachineToImageTest {
|
|||
|
||||
replay(vbm, vBox, vm, guestOsType);
|
||||
|
||||
Image image = new IMachineToImage(vbm, map).apply(vm);
|
||||
IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map);
|
||||
|
||||
Image image = fn.apply(vm);
|
||||
|
||||
assertEquals(image.getOperatingSystem().getDescription(), "SomeOtherOs 2.04");
|
||||
assertEquals(image.getOperatingSystem().getVersion(), "");
|
||||
|
|
|
@ -31,6 +31,7 @@ import org.testng.annotations.Test;
|
|||
import org.virtualbox_4_1.MachineState;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
|
||||
public class IMachineToNodeMetadataTest {
|
||||
|
@ -47,7 +48,7 @@ public class IMachineToNodeMetadataTest {
|
|||
|
||||
VirtualBox virtualBox = new VirtualBox();
|
||||
IMachineToNodeMetadata parser = new IMachineToNodeMetadata();
|
||||
IMachineToHardware hwParser = new IMachineToHardware(manager);
|
||||
IMachineToHardware hwParser = new IMachineToHardware(Suppliers.ofInstance(manager));
|
||||
|
||||
// hwParser.apply()
|
||||
|
||||
|
|
|
@ -19,15 +19,12 @@
|
|||
|
||||
package org.jclouds.virtualbox.functions;
|
||||
|
||||
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
|
||||
import static org.jclouds.virtualbox.functions.RetrieveActiveBridgedInterfaces.retrieveBridgedInterfaceNames;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
import static org.testng.Assert.assertFalse;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
|
@ -38,48 +35,31 @@ import com.google.common.collect.ImmutableList;
|
|||
*/
|
||||
@Test(groups = "live", singleThreaded = true, testName = "RetrieveActiveBridgedInterfacesLiveTest")
|
||||
public class RetrieveActiveBridgedInterfacesLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||
|
||||
public static final String TEST1 = "Name: eth0\n"
|
||||
+ "GUID: 30687465-0000-4000-8000-00261834d0cb\n"
|
||||
+ "Dhcp: Disabled\n"
|
||||
+ "IPAddress: 209.x.x.x\n"
|
||||
+ "NetworkMask: 255.255.255.0\n"
|
||||
+ "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n"
|
||||
+ "IPV6NetworkMaskPrefixLength: 64\n"
|
||||
+ "HardwareAddress: 00:26:18:34:d0:cb\n"
|
||||
+ "MediumType: Ethernet\n"
|
||||
+ "Status: Up\n"
|
||||
+ "VBoxNetworkName: HostInterfaceNetworking-eth0\n"
|
||||
+ "\n"
|
||||
+ "Name: vbox0\n"
|
||||
+ "GUID: 786f6276-0030-4000-8000-5a3ded993fed\n"
|
||||
+ "Dhcp: Disabled\n"
|
||||
+ "IPAddress: 192.168.56.1\n"
|
||||
+ "NetworkMask: 255.255.255.0\n"
|
||||
+ "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n"
|
||||
+ "IPV6NetworkMaskPrefixLength: 0\n"
|
||||
+ "HardwareAddress: 5a:3d:ed:99:3f:ed\n"
|
||||
+ "MediumType: Ethernet\n"
|
||||
+ "Status: Down\n"
|
||||
+ "VBoxNetworkName: HostInterfaceNetworking-vbox0\n";
|
||||
|
||||
public static final List<String> expectedBridgedInterfaces = ImmutableList.of("eth0", "vbox0");
|
||||
|
||||
private String guestId = "guest";
|
||||
private String hostId = "host";
|
||||
public static final String TEST1 = "Name: eth0\n"
|
||||
+ "GUID: 30687465-0000-4000-8000-00261834d0cb\n" + "Dhcp: Disabled\n"
|
||||
+ "IPAddress: 209.x.x.x\n" + "NetworkMask: 255.255.255.0\n"
|
||||
+ "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n" + "IPV6NetworkMaskPrefixLength: 64\n"
|
||||
+ "HardwareAddress: 00:26:18:34:d0:cb\n" + "MediumType: Ethernet\n" + "Status: Up\n"
|
||||
+ "VBoxNetworkName: HostInterfaceNetworking-eth0\n" + "\n" + "Name: vbox0\n"
|
||||
+ "GUID: 786f6276-0030-4000-8000-5a3ded993fed\n" + "Dhcp: Disabled\n"
|
||||
+ "IPAddress: 192.168.56.1\n" + "NetworkMask: 255.255.255.0\n"
|
||||
+ "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n" + "IPV6NetworkMaskPrefixLength: 0\n"
|
||||
+ "HardwareAddress: 5a:3d:ed:99:3f:ed\n" + "MediumType: Ethernet\n" + "Status: Down\n"
|
||||
+ "VBoxNetworkName: HostInterfaceNetworking-vbox0\n";
|
||||
|
||||
public static final List<String> expectedBridgedInterfaces = ImmutableList.of("eth0", "vbox0");
|
||||
|
||||
@Test
|
||||
public void retrieveBridgedInterfaceNamesTest() {
|
||||
List<String> activeBridgedInterfaceNames = retrieveBridgedInterfaceNames(TEST1);
|
||||
assertEquals(activeBridgedInterfaceNames, expectedBridgedInterfaces);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void retrieveAvailableBridgedInterfaceInfoTest() {
|
||||
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(
|
||||
hostId, "localhost", guestId, "localhost", new Credentials("toor",
|
||||
"password"));
|
||||
List<String> bridgedInterface = new RetrieveActiveBridgedInterfaces(localHostContext).apply(hostId);
|
||||
List<String> bridgedInterface = context.utils().injector().getInstance(RetrieveActiveBridgedInterfaces.class)
|
||||
.apply(host.get());
|
||||
assertFalse(bridgedInterface.isEmpty());
|
||||
}
|
||||
|
||||
|
|
|
@ -33,6 +33,8 @@ import org.virtualbox_4_1.ISnapshot;
|
|||
import org.virtualbox_4_1.IVirtualBox;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
|
||||
/**
|
||||
* @author Andrea Turli
|
||||
*/
|
||||
|
@ -64,7 +66,7 @@ public class TakeSnapshotIfNotAlreadyAttachedTest {
|
|||
session.unlockMachine();
|
||||
replay(manager, machine, vBox, session, console, progress);
|
||||
|
||||
new TakeSnapshotIfNotAlreadyAttached(manager, snapshotName, snapshotDesc)
|
||||
new TakeSnapshotIfNotAlreadyAttached(Suppliers.ofInstance(manager), snapshotName, snapshotDesc)
|
||||
.apply(machine);
|
||||
|
||||
verify(machine);
|
||||
|
@ -94,7 +96,7 @@ public class TakeSnapshotIfNotAlreadyAttachedTest {
|
|||
session.unlockMachine();
|
||||
replay(manager, machine, vBox, session, console, progress);
|
||||
|
||||
new TakeSnapshotIfNotAlreadyAttached(manager, snapshotName, snapshotDesc)
|
||||
new TakeSnapshotIfNotAlreadyAttached(Suppliers.ofInstance(manager), snapshotName, snapshotDesc)
|
||||
.apply(machine);
|
||||
|
||||
verify(machine);
|
||||
|
|
|
@ -25,29 +25,34 @@ import static org.easymock.classextension.EasyMock.replay;
|
|||
import static org.easymock.classextension.EasyMock.verify;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
/**
|
||||
* @author Andrea Turli
|
||||
* @author Andrea Turli, Adrian Cole
|
||||
*/
|
||||
@Test(groups = "unit", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningTest")
|
||||
public class StartJettyIfNotAlreadyRunningTest {
|
||||
|
||||
private String basebaseResource = ".";
|
||||
private int port = 8080;
|
||||
|
||||
@Test
|
||||
public void testLaunchJettyServerWhenAlreadyRunningDoesntLaunchAgain() {
|
||||
Server jetty = createMock(Server.class);
|
||||
|
||||
String preconfigurationUrl = "http://foo:8080";
|
||||
|
||||
expect(jetty.getState()).andReturn(Server.STARTED);
|
||||
replay(jetty);
|
||||
|
||||
assertEquals(new StartJettyIfNotAlreadyRunning(jetty, port).apply(basebaseResource), jetty);
|
||||
StartJettyIfNotAlreadyRunning starter = new StartJettyIfNotAlreadyRunning(jetty, preconfigurationUrl);
|
||||
starter.start();
|
||||
|
||||
assertEquals(starter.get(), URI.create(preconfigurationUrl));
|
||||
verify(jetty);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testLaunchJettyServerWhenNotRunningStartsJettyOnCorrectHostPortAndBasedir() {
|
||||
// TODO: all yours!
|
||||
|
|
|
@ -19,147 +19,92 @@
|
|||
|
||||
package org.jclouds.virtualbox.functions.admin;
|
||||
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Module;
|
||||
import org.jclouds.compute.ComputeService;
|
||||
import org.jclouds.compute.ComputeServiceContextFactory;
|
||||
import org.jclouds.compute.domain.ExecResponse;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.domain.LoginCredentials;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.ssh.ConfiguresSshClient;
|
||||
import org.jclouds.ssh.SshClient;
|
||||
import org.testng.annotations.Test;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.classextension.EasyMock.createMock;
|
||||
import static org.easymock.classextension.EasyMock.replay;
|
||||
import static org.easymock.classextension.EasyMock.verify;
|
||||
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.classextension.EasyMock.*;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
import org.jclouds.compute.callables.RunScriptOnNode;
|
||||
import org.jclouds.compute.callables.RunScriptOnNode.Factory;
|
||||
import org.jclouds.compute.domain.ExecResponse;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.domain.NodeMetadataBuilder;
|
||||
import org.jclouds.compute.domain.NodeState;
|
||||
import org.jclouds.compute.domain.OperatingSystem;
|
||||
import org.jclouds.compute.predicates.RetryIfSocketNotYetOpen;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.scriptbuilder.domain.Statements;
|
||||
import org.testng.annotations.Test;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Functions;
|
||||
import com.google.common.base.Suppliers;
|
||||
|
||||
@Test(groups = "unit", singleThreaded = true, testName = "StartVBoxIfNotAlreadyRunningTest")
|
||||
public class StartVBoxIfNotAlreadyRunningTest {
|
||||
|
||||
@Test(expectedExceptions = IllegalStateException.class)
|
||||
public void testStartVboxThrowsIllegalStateExceptionIfTheNodeIdConfiguredIsntAround() throws Exception {
|
||||
|
||||
ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar")
|
||||
.getComputeService();
|
||||
|
||||
VirtualBoxManager manager = createMock(VirtualBoxManager.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
Predicate<IPSocket> socketTester = createMock(Predicate.class);
|
||||
String hostId = "hostId";
|
||||
URI endpointUri = URI.create("http://localhost:18083/");
|
||||
Credentials localhostCredentials = new Credentials("toor", "password");
|
||||
|
||||
manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential);
|
||||
|
||||
replay(socketTester);
|
||||
replay(manager);
|
||||
|
||||
new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials).apply(endpointUri);
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testStartVboxConnectsToManagerWhenPortAlreadyListening() throws Exception {
|
||||
|
||||
ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar")
|
||||
.getComputeService();
|
||||
|
||||
// TODO: possibly better to use a defined name as opposed to an id, since
|
||||
// most compute services the id is not predictable.
|
||||
NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup("foo", 1));
|
||||
String hostId = node.getId();
|
||||
|
||||
VirtualBoxManager manager = createMock(VirtualBoxManager.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
Predicate<IPSocket> socketTester = createMock(Predicate.class);
|
||||
URI endpointUri = URI.create("http://localhost:18083/");
|
||||
Credentials localhostCredentials = new Credentials("toor", "password");
|
||||
Factory runScriptOnNodeFactory = createMock(Factory.class);
|
||||
RetryIfSocketNotYetOpen client = createMock(RetryIfSocketNotYetOpen.class);
|
||||
NodeMetadata host = new NodeMetadataBuilder().id("host").state(NodeState.RUNNING).build();
|
||||
URI provider = URI.create("http://localhost:18083/");
|
||||
String identity = "adminstrator";
|
||||
String credential = "12345";
|
||||
|
||||
expect(socketTester.apply(new IPSocket(endpointUri.getHost(), endpointUri.getPort()))).andReturn(true);
|
||||
manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential);
|
||||
expect(client.apply(new IPSocket(provider.getHost(), provider.getPort()))).andReturn(true);
|
||||
|
||||
replay(socketTester);
|
||||
replay(manager);
|
||||
manager.connect(provider.toASCIIString(), identity, credential);
|
||||
|
||||
assertEquals(
|
||||
new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials)
|
||||
.apply(endpointUri),
|
||||
manager);
|
||||
replay(manager, runScriptOnNodeFactory, client);
|
||||
|
||||
verify(socketTester);
|
||||
verify(manager);
|
||||
}
|
||||
new StartVBoxIfNotAlreadyRunning((Function) Functions.constant(manager), runScriptOnNodeFactory, client,
|
||||
Suppliers.ofInstance(host), provider, identity, credential).start();
|
||||
|
||||
@ConfiguresSshClient
|
||||
static class StartingVBoxWhenNotRunningModule extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
SshClient.Factory factory = createMock(SshClient.Factory.class);
|
||||
SshClient client = createMock(SshClient.class);
|
||||
// NOTE we may want to switch to a node supplier so that we can predict
|
||||
// these values. Right now, it is node 2 since the above test made node
|
||||
// 1.
|
||||
IPSocket expectedSshSockectFor2ndCreatedNode = new IPSocket("144.175.1.2", 22);
|
||||
LoginCredentials loginCredentials = new LoginCredentials("root", "password2", null, false);
|
||||
expect(factory.create(expectedSshSockectFor2ndCreatedNode, loginCredentials)).andReturn(
|
||||
client).times(2);
|
||||
|
||||
expect(client.getUsername()).andReturn(loginCredentials.identity).times(2);
|
||||
expect(client.getHostAddress()).andReturn(expectedSshSockectFor2ndCreatedNode.getAddress()).times(2);
|
||||
|
||||
client.disconnect();
|
||||
client.connect();
|
||||
expect(client.exec("VBoxManage setproperty websrvauthlibrary null\n")).andReturn(new ExecResponse("", "", 0));
|
||||
|
||||
client.disconnect();
|
||||
client.connect();
|
||||
expect(client.exec("vboxwebsrv -t 10000 -v -b\n")).andReturn(new ExecResponse("", "", 0));
|
||||
|
||||
replay(factory);
|
||||
replay(client);
|
||||
bind(SshClient.Factory.class).toInstance(factory);
|
||||
|
||||
}
|
||||
verify(manager, runScriptOnNodeFactory, client);
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testStartVboxDisablesPasswordAccessOnWebsrvauthlibraryStartsVboxwebsrvInBackgroundAndConnectsManagerWhenPortIsNotListening()
|
||||
throws Exception {
|
||||
ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar",
|
||||
ImmutableSet.<Module> of(new StartingVBoxWhenNotRunningModule())).getComputeService();
|
||||
NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup("foo", 1));
|
||||
String hostId = node.getId();
|
||||
|
||||
throws Exception {
|
||||
VirtualBoxManager manager = createMock(VirtualBoxManager.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
Predicate<IPSocket> socketTester = createMock(Predicate.class);
|
||||
Credentials localhostCredentials = new Credentials("toor", "password");
|
||||
URI endpointUri = URI.create("http://localhost:18083/");
|
||||
Factory runScriptOnNodeFactory = createMock(Factory.class);
|
||||
RetryIfSocketNotYetOpen client = createMock(RetryIfSocketNotYetOpen.class);
|
||||
RunScriptOnNode runScriptOnNode = createMock(RunScriptOnNode.class);
|
||||
NodeMetadata host = new NodeMetadataBuilder().id("host").state(NodeState.RUNNING).operatingSystem(
|
||||
OperatingSystem.builder().description("unix").build()).build();
|
||||
URI provider = URI.create("http://localhost:18083/");
|
||||
String identity = "adminstrator";
|
||||
String credential = "12345";
|
||||
|
||||
expect(socketTester.apply(new IPSocket(endpointUri.getHost(), endpointUri.getPort()))).andReturn(false);
|
||||
expect(client.apply(new IPSocket(provider.getHost(), provider.getPort()))).andReturn(false);
|
||||
expect(
|
||||
runScriptOnNodeFactory.create(host, Statements.exec("VBoxManage setproperty websrvauthlibrary null"),
|
||||
runAsRoot(false).wrapInInitScript(false))).andReturn(runScriptOnNode);
|
||||
expect(runScriptOnNode.init()).andReturn(runScriptOnNode);
|
||||
expect(runScriptOnNode.call()).andReturn(new ExecResponse("", "", 0));
|
||||
|
||||
expect(
|
||||
runScriptOnNodeFactory.create(host, Statements.exec("vboxwebsrv -t 10000 -v -b"), runAsRoot(false)
|
||||
.wrapInInitScript(false).blockOnComplete(false).nameTask("vboxwebsrv"))).andReturn(
|
||||
runScriptOnNode);
|
||||
expect(runScriptOnNode.init()).andReturn(runScriptOnNode);
|
||||
expect(runScriptOnNode.call()).andReturn(new ExecResponse("", "", 0));
|
||||
|
||||
manager.connect(provider.toASCIIString(), identity, credential);
|
||||
|
||||
manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential);
|
||||
replay(manager, runScriptOnNodeFactory, runScriptOnNode, client);
|
||||
new StartVBoxIfNotAlreadyRunning((Function) Functions.constant(manager), runScriptOnNodeFactory, client,
|
||||
Suppliers.ofInstance(host), provider, identity, credential).start();
|
||||
verify(manager, runScriptOnNodeFactory, runScriptOnNode, client);
|
||||
|
||||
replay(socketTester);
|
||||
replay(manager);
|
||||
|
||||
assertEquals(
|
||||
new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials)
|
||||
.apply(endpointUri),
|
||||
manager);
|
||||
|
||||
verify(socketTester);
|
||||
verify(manager);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -19,10 +19,8 @@
|
|||
|
||||
package org.jclouds.virtualbox.predicates;
|
||||
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApplyOrReturnNullIfNotRegistered;
|
||||
import static org.testng.Assert.assertFalse;
|
||||
import static org.testng.Assert.assertTrue;
|
||||
import static org.virtualbox_4_1.LockType.Write;
|
||||
|
||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||
import org.jclouds.virtualbox.domain.HardDisk;
|
||||
|
@ -30,14 +28,13 @@ import org.jclouds.virtualbox.domain.StorageController;
|
|||
import org.jclouds.virtualbox.domain.VmSpec;
|
||||
import org.jclouds.virtualbox.functions.CloneAndRegisterMachineFromIMachineIfNotAlreadyExists;
|
||||
import org.jclouds.virtualbox.functions.CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
|
||||
import org.jclouds.virtualbox.functions.IMachineToVmSpec;
|
||||
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
|
||||
import org.testng.annotations.AfterMethod;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.BeforeMethod;
|
||||
import org.testng.annotations.Test;
|
||||
import org.virtualbox_4_1.CleanupMode;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
import org.virtualbox_4_1.StorageBus;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
|
||||
|
@ -78,29 +75,28 @@ public class IsLinkedClonesLiveTest extends BaseVirtualBoxClientLiveTest {
|
|||
@Test
|
||||
public void testLinkedClone() {
|
||||
|
||||
VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
|
||||
lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, masterSpec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(masterSpec));
|
||||
|
||||
IMachine master = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir).apply(masterSpec);
|
||||
IMachine master = context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
|
||||
.apply(masterSpec);
|
||||
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec,
|
||||
IS_LINKED_CLONE).apply(master);
|
||||
|
||||
assertTrue(new IsLinkedClone(manager).apply(clone));
|
||||
for (VmSpec spec : ImmutableSet.of(new IMachineToVmSpec().apply(clone), masterSpec))
|
||||
lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, spec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(spec));
|
||||
}
|
||||
|
||||
public void testFullClone() {
|
||||
|
||||
VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
|
||||
lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, masterSpec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(masterSpec));
|
||||
|
||||
IMachine master = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir).apply(masterSpec);
|
||||
IMachine master = context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
|
||||
.apply(masterSpec);
|
||||
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec,
|
||||
!IS_LINKED_CLONE).apply(master);
|
||||
|
||||
assertFalse(new IsLinkedClone(manager).apply(clone));
|
||||
for (VmSpec spec : ImmutableSet.of(new IMachineToVmSpec().apply(clone), masterSpec))
|
||||
lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, spec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(spec));
|
||||
|
||||
}
|
||||
|
||||
@BeforeMethod
|
||||
@AfterMethod
|
||||
void cleanUpVms() {
|
||||
for (VmSpec spec : ImmutableSet.of(cloneSpec, masterSpec))
|
||||
this.undoVm(spec);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,92 +0,0 @@
|
|||
package org.jclouds.virtualbox.predicates;
|
||||
|
||||
import static org.jclouds.virtualbox.domain.ExecutionType.HEADLESS;
|
||||
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.applyForMachine;
|
||||
import static org.jclouds.virtualbox.util.MachineUtils.lockSessionOnMachineAndApply;
|
||||
import static org.testng.Assert.assertTrue;
|
||||
import static org.virtualbox_4_1.LockType.Shared;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.net.IPSocket;
|
||||
import org.jclouds.predicates.InetSocketAddressConnect;
|
||||
import org.jclouds.predicates.RetryablePredicate;
|
||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||
import org.jclouds.virtualbox.domain.ExecutionType;
|
||||
import org.jclouds.virtualbox.domain.HardDisk;
|
||||
import org.jclouds.virtualbox.domain.StorageController;
|
||||
import org.jclouds.virtualbox.domain.VmSpec;
|
||||
import org.jclouds.virtualbox.functions.CreateAndInstallVm;
|
||||
import org.jclouds.virtualbox.functions.CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
|
||||
import org.jclouds.virtualbox.functions.LaunchMachineIfNotAlreadyRunning;
|
||||
import org.testng.annotations.Test;
|
||||
import org.virtualbox_4_1.IMachine;
|
||||
import org.virtualbox_4_1.IProgress;
|
||||
import org.virtualbox_4_1.ISession;
|
||||
import org.virtualbox_4_1.StorageBus;
|
||||
import org.virtualbox_4_1.VirtualBoxManager;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
|
||||
@Test(groups = "live", singleThreaded = true, testName = "SshAvailableLiveTest")
|
||||
public class SshAvailableLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||
|
||||
private String guestId = "guest";
|
||||
private String hostId = "host";
|
||||
|
||||
private String vmName = "jclouds-image-virtualbox-iso-to-machine-sshtest";
|
||||
|
||||
@Test
|
||||
public void testSshDaemonIsRunning() {
|
||||
VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
|
||||
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(hostId, "localhost", guestId,
|
||||
"localhost", new Credentials("toor", "password"));
|
||||
|
||||
getNodeWithSshDaemonRunning(manager, localHostContext);
|
||||
ensureMachineIsLaunched(vmName);
|
||||
RetryablePredicate<String> predicate = new RetryablePredicate<String>(new SshAvailable(localHostContext), 5, 1,
|
||||
TimeUnit.SECONDS);
|
||||
assertTrue(predicate.apply(guestId));
|
||||
|
||||
lockSessionOnMachineAndApply(manager, Shared, vmName, new Function<ISession, Void>() {
|
||||
|
||||
@Override
|
||||
public Void apply(ISession session) {
|
||||
IProgress powerDownProgress = session.getConsole().powerDown();
|
||||
powerDownProgress.waitForCompletion(-1);
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
private IMachine getNodeWithSshDaemonRunning(VirtualBoxManager manager, ComputeServiceContext localHostContext) {
|
||||
try {
|
||||
Predicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 10, 1,
|
||||
TimeUnit.SECONDS);
|
||||
String vmId = "jclouds-image-iso-2";
|
||||
|
||||
StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE)
|
||||
.attachISO(0, 0, operatingSystemIso).attachHardDisk(
|
||||
HardDisk.builder().diskpath(adminDisk).controllerPort(0).deviceSlot(1).build()).build();
|
||||
VmSpec vmSpecification = VmSpec.builder().id(vmId).name(vmName).osTypeId("").memoryMB(512).controller(
|
||||
ideController).forceOverwrite(true).build();
|
||||
|
||||
return new CreateAndInstallVm(manager, new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager,
|
||||
workingDir), guestId, vmId, localHostContext, hostId, socketTester, "127.0.0.1", 8080, HEADLESS)
|
||||
.apply(vmSpecification);
|
||||
} catch (IllegalStateException e) {
|
||||
// already created
|
||||
return manager.getVBox().findMachine(vmName);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureMachineIsLaunched(String vmName) {
|
||||
applyForMachine(manager, vmName, new LaunchMachineIfNotAlreadyRunning(manager, ExecutionType.GUI, ""));
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue