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.identity>administrator</test.virtualbox.identity>
|
||||||
<test.virtualbox.credential>12345</test.virtualbox.credential>
|
<test.virtualbox.credential>12345</test.virtualbox.credential>
|
||||||
<test.virtualbox.image-id>ubuntu-11.04-server-i386</test.virtualbox.image-id>
|
<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.login-user>toor:password</test.virtualbox.image.login-user>
|
||||||
<test.virtualbox.image.authenticate-sudo></test.virtualbox.image.authenticate-sudo>
|
<test.virtualbox.image.authenticate-sudo>true</test.virtualbox.image.authenticate-sudo>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<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.compute.StandaloneComputeServiceContextBuilder;
|
||||||
import org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule;
|
import org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
|
||||||
|
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
import com.google.inject.Module;
|
import com.google.inject.Module;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -33,10 +33,11 @@ import com.google.inject.Module;
|
||||||
*
|
*
|
||||||
* @author Mattias Holmqvist, Andrea Turli
|
* @author Mattias Holmqvist, Andrea Turli
|
||||||
*/
|
*/
|
||||||
public class VirtualBoxContextBuilder extends StandaloneComputeServiceContextBuilder<VirtualBoxManager> {
|
@SuppressWarnings("unchecked")
|
||||||
|
public class VirtualBoxContextBuilder extends StandaloneComputeServiceContextBuilder<Supplier> {
|
||||||
|
|
||||||
public VirtualBoxContextBuilder(Properties properties) {
|
public VirtualBoxContextBuilder(Properties properties) {
|
||||||
super(VirtualBoxManager.class, properties);
|
super(Supplier.class, properties);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -29,8 +29,8 @@ import java.io.File;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import org.jclouds.PropertiesBuilder;
|
import org.jclouds.PropertiesBuilder;
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import static org.jclouds.compute.reference.ComputeServiceConstants.*;
|
||||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
import static org.jclouds.virtualbox.config.VirtualBoxConstants.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds properties for VirtualBox integration.
|
* 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_BUILD_VERSION, "4.1.8r75467");
|
||||||
properties.put(PROPERTY_IDENTITY, "administrator");
|
properties.put(PROPERTY_IDENTITY, "administrator");
|
||||||
properties.put(PROPERTY_CREDENTIAL, "12345");
|
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(PROPERTY_IMAGE_ID, "ubuntu-11.04-server-i386");
|
||||||
properties.put(VirtualBoxConstants.VIRTUALBOX_SNAPSHOT_DESCRIPTION, "jclouds-virtualbox-snaphot");
|
properties.put(PROPERTY_IMAGE_LOGIN_USER, "toor:password");
|
||||||
properties.put(VirtualBoxConstants.VIRTUALBOX_HOSTNAME, "jclouds-virtualbox-kickstart-admin");
|
properties.put(PROPERTY_IMAGE_AUTHENTICATE_SUDO, "true");
|
||||||
properties
|
|
||||||
.put(VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE,
|
properties.put(VIRTUALBOX_ISO_URL, "http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso");
|
||||||
"<Esc><Esc><Enter> "
|
properties.put(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, "<Esc><Esc><Enter> "
|
||||||
+ "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg "
|
+ "/install/vmlinuz noapic preseed/url=PRECONFIGURATION_URL "
|
||||||
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us "
|
+ "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + "HOSTNAME "
|
||||||
+ "hostname="
|
|
||||||
+ properties.get(VirtualBoxConstants.VIRTUALBOX_HOSTNAME)
|
|
||||||
+ " "
|
|
||||||
+ "fb=false debconf/frontend=noninteractive "
|
+ "fb=false debconf/frontend=noninteractive "
|
||||||
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
|
+ "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false "
|
||||||
+ "initrd=/install/initrd.gz -- <Enter>");
|
+ "initrd=/install/initrd.gz -- <Enter>");
|
||||||
|
|
||||||
properties.put(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR, System.getProperty("user.home") + File.separator
|
properties.put(VIRTUALBOX_WORKINGDIR, System.getProperty("user.home") + File.separator
|
||||||
+ System.getProperty("test.virtualbox.workingDir", "jclouds-virtualbox-test"));
|
+ System.getProperty("test.virtualbox.workingDir", "jclouds-virtualbox-test"));
|
||||||
|
|
||||||
properties.put(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080");
|
properties.put(VIRTUALBOX_PRECONFIGURATION_URL, "http://10.0.2.2:8080/src/test/resources/preseed.cfg");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return properties;
|
return properties;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,8 +24,6 @@ import static com.google.common.collect.Iterables.filter;
|
||||||
import static com.google.common.collect.Iterables.transform;
|
import static com.google.common.collect.Iterables.transform;
|
||||||
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX;
|
import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX;
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
|
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
|
|
||||||
import org.jclouds.compute.ComputeServiceAdapter;
|
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.Function;
|
||||||
import com.google.common.base.Predicate;
|
import com.google.common.base.Predicate;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
import com.google.common.base.Throwables;
|
import com.google.common.base.Throwables;
|
||||||
|
import com.google.common.collect.Iterables;
|
||||||
import com.google.inject.Singleton;
|
import com.google.inject.Singleton;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -56,12 +56,12 @@ import com.google.inject.Singleton;
|
||||||
@Singleton
|
@Singleton
|
||||||
public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IMachine, IMachine, Image, Location> {
|
public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IMachine, IMachine, Image, Location> {
|
||||||
|
|
||||||
private final VirtualBoxManager manager;
|
private final Supplier<VirtualBoxManager> manager;
|
||||||
private final JustProvider justProvider;
|
private final JustProvider justProvider;
|
||||||
private Function<IMachine, Image> iMachineToImage;
|
private final Function<IMachine, Image> iMachineToImage;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public VirtualBoxComputeServiceAdapter(VirtualBoxManager manager, JustProvider justProvider,
|
public VirtualBoxComputeServiceAdapter(Supplier<VirtualBoxManager> manager, JustProvider justProvider,
|
||||||
Function<IMachine, Image> iMachineToImage) {
|
Function<IMachine, Image> iMachineToImage) {
|
||||||
this.iMachineToImage = iMachineToImage;
|
this.iMachineToImage = iMachineToImage;
|
||||||
this.manager = checkNotNull(manager, "manager");
|
this.manager = checkNotNull(manager, "manager");
|
||||||
|
@ -76,24 +76,35 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IM
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Iterable<IMachine> listNodes() {
|
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
|
@Override
|
||||||
public Iterable<IMachine> listHardwareProfiles() {
|
public Iterable<IMachine> listHardwareProfiles() {
|
||||||
return manager.getVBox().getMachines();
|
return imageMachines();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Iterable<Image> listImages() {
|
public Iterable<Image> listImages() {
|
||||||
|
return transform(imageMachines(), iMachineToImage);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Iterable<IMachine> imageMachines() {
|
||||||
final Predicate<? super IMachine> imagePredicate = new Predicate<IMachine>() {
|
final Predicate<? super IMachine> imagePredicate = new Predicate<IMachine>() {
|
||||||
@Override
|
@Override
|
||||||
public boolean apply(@Nullable IMachine iMachine) {
|
public boolean apply(@Nullable IMachine iMachine) {
|
||||||
return iMachine.getName().startsWith(VIRTUALBOX_IMAGE_PREFIX);
|
return iMachine.getName().startsWith(VIRTUALBOX_IMAGE_PREFIX);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
final Iterable<IMachine> imageMachines = filter(manager.getVBox().getMachines(), imagePredicate);
|
final Iterable<IMachine> imageMachines = filter(manager.get().getVBox().getMachines(), imagePredicate);
|
||||||
return transform(imageMachines, iMachineToImage);
|
return imageMachines;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
|
@ -104,29 +115,29 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IM
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public IMachine getNode(String vmName) {
|
public IMachine getNode(String vmName) {
|
||||||
return manager.getVBox().findMachine(vmName);
|
return manager.get().getVBox().findMachine(vmName);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void destroyNode(String vmName) {
|
public void destroyNode(String vmName) {
|
||||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||||
powerDownMachine(machine);
|
powerDownMachine(machine);
|
||||||
machine.unregister(CleanupMode.Full);
|
machine.unregister(CleanupMode.Full);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void rebootNode(String vmName) {
|
public void rebootNode(String vmName) {
|
||||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||||
powerDownMachine(machine);
|
powerDownMachine(machine);
|
||||||
launchVMProcess(machine, manager.getSessionObject());
|
launchVMProcess(machine, manager.get().getSessionObject());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void resumeNode(String vmName) {
|
public void resumeNode(String vmName) {
|
||||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||||
ISession machineSession;
|
ISession machineSession;
|
||||||
try {
|
try {
|
||||||
machineSession = manager.openMachineSession(machine);
|
machineSession = manager.get().openMachineSession(machine);
|
||||||
machineSession.getConsole().resume();
|
machineSession.getConsole().resume();
|
||||||
machineSession.unlockMachine();
|
machineSession.unlockMachine();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
@ -136,10 +147,10 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IM
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void suspendNode(String vmName) {
|
public void suspendNode(String vmName) {
|
||||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||||
ISession machineSession;
|
ISession machineSession;
|
||||||
try {
|
try {
|
||||||
machineSession = manager.openMachineSession(machine);
|
machineSession = manager.get().openMachineSession(machine);
|
||||||
machineSession.getConsole().pause();
|
machineSession.getConsole().pause();
|
||||||
machineSession.unlockMachine();
|
machineSession.unlockMachine();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
@ -161,7 +172,7 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter<IM
|
||||||
|
|
||||||
private void powerDownMachine(IMachine machine) {
|
private void powerDownMachine(IMachine machine) {
|
||||||
try {
|
try {
|
||||||
ISession machineSession = manager.openMachineSession(machine);
|
ISession machineSession = manager.get().openMachineSession(machine);
|
||||||
IProgress progress = machineSession.getConsole().powerDown();
|
IProgress progress = machineSession.getConsole().powerDown();
|
||||||
progress.waitForCompletion(-1);
|
progress.waitForCompletion(-1);
|
||||||
machineSession.unlockMachine();
|
machineSession.unlockMachine();
|
||||||
|
|
|
@ -19,13 +19,16 @@
|
||||||
|
|
||||||
package org.jclouds.virtualbox.config;
|
package org.jclouds.virtualbox.config;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
import javax.inject.Named;
|
|
||||||
import javax.inject.Singleton;
|
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.ComputeServiceAdapter;
|
||||||
import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
|
import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
|
||||||
import org.jclouds.compute.domain.Hardware;
|
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.NodeState;
|
||||||
import org.jclouds.compute.domain.OsFamily;
|
import org.jclouds.compute.domain.OsFamily;
|
||||||
import org.jclouds.compute.domain.TemplateBuilder;
|
import org.jclouds.compute.domain.TemplateBuilder;
|
||||||
|
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
|
||||||
import org.jclouds.domain.Location;
|
import org.jclouds.domain.Location;
|
||||||
import org.jclouds.functions.IdentityFunction;
|
import org.jclouds.functions.IdentityFunction;
|
||||||
import org.jclouds.location.Provider;
|
|
||||||
import org.jclouds.location.suppliers.OnlyLocationOrFirstZone;
|
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.compute.VirtualBoxComputeServiceAdapter;
|
||||||
|
import org.jclouds.virtualbox.domain.ExecutionType;
|
||||||
import org.jclouds.virtualbox.functions.IMachineToHardware;
|
import org.jclouds.virtualbox.functions.IMachineToHardware;
|
||||||
import org.jclouds.virtualbox.functions.IMachineToImage;
|
import org.jclouds.virtualbox.functions.IMachineToImage;
|
||||||
import org.jclouds.virtualbox.functions.IMachineToNodeMetadata;
|
import org.jclouds.virtualbox.functions.IMachineToNodeMetadata;
|
||||||
|
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.IMachine;
|
||||||
import org.virtualbox_4_1.MachineState;
|
import org.virtualbox_4_1.MachineState;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.annotations.VisibleForTesting;
|
import com.google.common.annotations.VisibleForTesting;
|
||||||
import com.google.common.base.Function;
|
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.Supplier;
|
||||||
|
import com.google.common.base.Suppliers;
|
||||||
|
import com.google.common.cache.LoadingCache;
|
||||||
import com.google.common.collect.ImmutableMap;
|
import com.google.common.collect.ImmutableMap;
|
||||||
import com.google.inject.Injector;
|
import com.google.inject.Injector;
|
||||||
import com.google.inject.Provides;
|
import com.google.inject.Provides;
|
||||||
|
@ -57,21 +72,12 @@ import com.google.inject.TypeLiteral;
|
||||||
/**
|
/**
|
||||||
* @author Mattias Holmqvist, Andrea Turli
|
* @author Mattias Holmqvist, Andrea Turli
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
public class VirtualBoxComputeServiceContextModule extends
|
public class VirtualBoxComputeServiceContextModule extends
|
||||||
ComputeServiceAdapterContextModule<VirtualBoxManager, VirtualBoxManager, IMachine, IMachine, Image, Location> {
|
ComputeServiceAdapterContextModule<Supplier, Supplier, IMachine, IMachine, Image, Location> {
|
||||||
|
|
||||||
public VirtualBoxComputeServiceContextModule() {
|
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" })
|
||||||
|
@ -92,6 +98,53 @@ public class VirtualBoxComputeServiceContextModule extends
|
||||||
}).to(IMachineToImage.class);
|
}).to(IMachineToImage.class);
|
||||||
bind(new TypeLiteral<Supplier<Location>>() {
|
bind(new TypeLiteral<Supplier<Location>>() {
|
||||||
}).to(OnlyLocationOrFirstZone.class);
|
}).to(OnlyLocationOrFirstZone.class);
|
||||||
|
|
||||||
|
// 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
|
@Override
|
||||||
|
@ -99,23 +152,34 @@ public class VirtualBoxComputeServiceContextModule extends
|
||||||
return template.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04");
|
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
|
@VisibleForTesting
|
||||||
public static final Map<MachineState, NodeState> machineToNodeState = ImmutableMap
|
public static final Map<MachineState, NodeState> machineToNodeState = ImmutableMap
|
||||||
.<MachineState, NodeState> builder().put(MachineState.Running, NodeState.RUNNING)
|
.<MachineState, NodeState> builder().put(MachineState.Running, NodeState.RUNNING).put(
|
||||||
.put(MachineState.PoweredOff, NodeState.SUSPENDED).put(MachineState.DeletingSnapshot, NodeState.PENDING)
|
MachineState.PoweredOff, NodeState.SUSPENDED)
|
||||||
.put(MachineState.DeletingSnapshotOnline, NodeState.PENDING)
|
.put(MachineState.DeletingSnapshot, NodeState.PENDING).put(MachineState.DeletingSnapshotOnline,
|
||||||
.put(MachineState.DeletingSnapshotPaused, NodeState.PENDING)
|
NodeState.PENDING).put(MachineState.DeletingSnapshotPaused, NodeState.PENDING).put(
|
||||||
.put(MachineState.FaultTolerantSyncing, NodeState.PENDING)
|
MachineState.FaultTolerantSyncing, NodeState.PENDING).put(MachineState.LiveSnapshotting,
|
||||||
.put(MachineState.LiveSnapshotting, NodeState.PENDING)
|
NodeState.PENDING).put(MachineState.SettingUp, NodeState.PENDING).put(MachineState.Starting,
|
||||||
.put(MachineState.SettingUp, NodeState.PENDING)
|
NodeState.PENDING).put(MachineState.Stopping, NodeState.PENDING).put(MachineState.Restoring,
|
||||||
.put(MachineState.Starting, NodeState.PENDING)
|
NodeState.PENDING)
|
||||||
.put(MachineState.Stopping, NodeState.PENDING)
|
|
||||||
.put(MachineState.Restoring, NodeState.PENDING)
|
|
||||||
// TODO What to map these states to?
|
// TODO What to map these states to?
|
||||||
.put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING)
|
.put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING).put(
|
||||||
.put(MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING)
|
MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING)
|
||||||
.put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING)
|
.put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING).put(
|
||||||
.put(MachineState.TeleportingPausedVM, NodeState.PENDING)
|
MachineState.TeleportingPausedVM, NodeState.PENDING)
|
||||||
|
|
||||||
.put(MachineState.Aborted, NodeState.ERROR).put(MachineState.Stuck, NodeState.ERROR)
|
.put(MachineState.Aborted, NodeState.ERROR).put(MachineState.Stuck, NodeState.ERROR)
|
||||||
|
|
||||||
|
|
|
@ -27,19 +27,15 @@ package org.jclouds.virtualbox.config;
|
||||||
*/
|
*/
|
||||||
public interface VirtualBoxConstants {
|
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_PRECONFIGURATION_URL = "jclouds.virtualbox.preconfigurationurl";
|
||||||
|
|
||||||
public static final String VIRTUALBOX_SNAPSHOT_DESCRIPTION = "jclouds.virtualbox.snapshotDescription";
|
|
||||||
|
|
||||||
public static final String VIRTUALBOX_INSTALLATION_KEY_SEQUENCE = "jclouds.virtualbox.installationkeysequence";
|
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_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";
|
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_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_IDENTITY = "jclouds.virtualbox.webserver.identity";
|
||||||
|
|
||||||
public static final String VIRTUALBOX_WEBSERVER_CREDENTIAL = "jclouds.virtualbox.webserver.credential";
|
public static final String VIRTUALBOX_WEBSERVER_CREDENTIAL = "jclouds.virtualbox.webserver.credential";
|
||||||
|
|
|
@ -50,11 +50,25 @@ public class NatAdapter {
|
||||||
|
|
||||||
private Set<RedirectRule> redirectRules = Sets.newLinkedHashSet();
|
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) {
|
public Builder tcpRedirectRule(String host, int hostPort, String guest, int guestPort) {
|
||||||
redirectRules.add(new RedirectRule(NATProtocol.TCP, host, hostPort, guest, guestPort));
|
redirectRules.add(new RedirectRule(NATProtocol.TCP, host, hostPort, guest, guestPort));
|
||||||
return this;
|
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) {
|
public Builder udpRedirectRule(String host, int hostPort, String guest, int guestPort) {
|
||||||
redirectRules.add(new RedirectRule(NATProtocol.UDP, host, hostPort, guest, guestPort));
|
redirectRules.add(new RedirectRule(NATProtocol.UDP, host, hostPort, guest, guestPort));
|
||||||
return this;
|
return this;
|
||||||
|
|
|
@ -35,6 +35,14 @@ public class RedirectRule {
|
||||||
private final String guest;
|
private final String guest;
|
||||||
private final int guestPort;
|
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) {
|
public RedirectRule(NATProtocol protocol, String host, int hostPort, String guest, int guestPort) {
|
||||||
checkNotNull(protocol);
|
checkNotNull(protocol);
|
||||||
checkNotNull(host);
|
checkNotNull(host);
|
||||||
|
|
|
@ -23,7 +23,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
|
||||||
|
|
||||||
import org.jclouds.virtualbox.domain.StorageController;
|
import org.jclouds.virtualbox.domain.StorageController;
|
||||||
import org.virtualbox_4_1.IMachine;
|
import org.virtualbox_4_1.IMachine;
|
||||||
import org.virtualbox_4_1.StorageBus;
|
|
||||||
import org.virtualbox_4_1.VBoxException;
|
import org.virtualbox_4_1.VBoxException;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
|
|
@ -39,6 +39,7 @@ import org.virtualbox_4_1.VBoxException;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
import com.google.inject.Inject;
|
import com.google.inject.Inject;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -53,13 +54,13 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
protected Logger logger = Logger.NULL;
|
||||||
|
|
||||||
private final VirtualBoxManager manager;
|
private final Supplier<VirtualBoxManager> manager;
|
||||||
private final String workingDir;
|
private final String workingDir;
|
||||||
private final VmSpec vmSpec;
|
private final VmSpec vmSpec;
|
||||||
private final boolean isLinkedClone;
|
private final boolean isLinkedClone;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(VirtualBoxManager manager,
|
public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(Supplier<VirtualBoxManager> manager,
|
||||||
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, VmSpec vmSpec, boolean isLinkedClone) {
|
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, VmSpec vmSpec, boolean isLinkedClone) {
|
||||||
this.manager = manager;
|
this.manager = manager;
|
||||||
this.workingDir = workingDir;
|
this.workingDir = workingDir;
|
||||||
|
@ -70,7 +71,7 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
|
||||||
@Override
|
@Override
|
||||||
public IMachine apply(@Nullable IMachine master) {
|
public IMachine apply(@Nullable IMachine master) {
|
||||||
try {
|
try {
|
||||||
manager.getVBox().findMachine(vmSpec.getVmName());
|
manager.get().getVBox().findMachine(vmSpec.getVmName());
|
||||||
throw new IllegalStateException("Machine " + vmSpec.getVmName() + " is already registered.");
|
throw new IllegalStateException("Machine " + vmSpec.getVmName() + " is already registered.");
|
||||||
} catch (VBoxException e) {
|
} catch (VBoxException e) {
|
||||||
if (machineNotFoundException(e))
|
if (machineNotFoundException(e))
|
||||||
|
@ -85,8 +86,8 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
|
||||||
}
|
}
|
||||||
|
|
||||||
private IMachine cloneMachine(VmSpec vmSpec, IMachine master) {
|
private IMachine cloneMachine(VmSpec vmSpec, IMachine master) {
|
||||||
String settingsFile = manager.getVBox().composeMachineFilename(vmSpec.getVmName(), workingDir);
|
String settingsFile = manager.get().getVBox().composeMachineFilename(vmSpec.getVmName(), workingDir);
|
||||||
IMachine clonedMachine = manager.getVBox().createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(),
|
IMachine clonedMachine = manager.get().getVBox().createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(),
|
||||||
vmSpec.getVmId(), vmSpec.isForceOverwrite());
|
vmSpec.getVmId(), vmSpec.isForceOverwrite());
|
||||||
List<CloneOptions> options = new ArrayList<CloneOptions>();
|
List<CloneOptions> options = new ArrayList<CloneOptions>();
|
||||||
if (isLinkedClone)
|
if (isLinkedClone)
|
||||||
|
@ -103,7 +104,7 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu
|
||||||
logger.debug("clone done");
|
logger.debug("clone done");
|
||||||
|
|
||||||
// registering
|
// registering
|
||||||
manager.getVBox().registerMachine(clonedMachine);
|
manager.get().getVBox().registerMachine(clonedMachine);
|
||||||
return clonedMachine;
|
return clonedMachine;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -19,133 +19,102 @@
|
||||||
|
|
||||||
package org.jclouds.virtualbox.functions;
|
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.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.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE;
|
||||||
import static org.jclouds.virtualbox.util.MachineUtils.applyForMachine;
|
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.jclouds.virtualbox.util.MachineUtils.lockSessionOnMachineAndApply;
|
||||||
import static org.virtualbox_4_1.LockType.Shared;
|
import static org.virtualbox_4_1.LockType.Shared;
|
||||||
import static org.virtualbox_4_1.LockType.Write;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.net.URI;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
import javax.inject.Named;
|
import javax.inject.Named;
|
||||||
|
import javax.inject.Singleton;
|
||||||
|
|
||||||
import org.jclouds.compute.ComputeServiceContext;
|
import org.jclouds.compute.callables.RunScriptOnNode;
|
||||||
import org.jclouds.compute.domain.ExecResponse;
|
import org.jclouds.compute.callables.RunScriptOnNode.Factory;
|
||||||
import org.jclouds.compute.options.RunScriptOptions;
|
import org.jclouds.compute.domain.NodeMetadata;
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||||
|
import org.jclouds.config.ValueOfConfigurationKeyOrNull;
|
||||||
import org.jclouds.logging.Logger;
|
import org.jclouds.logging.Logger;
|
||||||
import org.jclouds.net.IPSocket;
|
import org.jclouds.scriptbuilder.domain.Statements;
|
||||||
import org.jclouds.ssh.SshException;
|
import org.jclouds.ssh.SshClient;
|
||||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
import org.jclouds.virtualbox.Preconfiguration;
|
||||||
import org.jclouds.virtualbox.domain.DeviceDetails;
|
|
||||||
import org.jclouds.virtualbox.domain.ExecutionType;
|
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.domain.VmSpec;
|
||||||
import org.jclouds.virtualbox.settings.KeyboardScancodes;
|
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.IMachine;
|
||||||
import org.virtualbox_4_1.IMedium;
|
|
||||||
import org.virtualbox_4_1.IProgress;
|
import org.virtualbox_4_1.IProgress;
|
||||||
import org.virtualbox_4_1.ISession;
|
import org.virtualbox_4_1.ISession;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
import com.google.common.base.Predicate;
|
import com.google.common.base.Predicate;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
import com.google.inject.Inject;
|
import com.google.inject.Inject;
|
||||||
|
|
||||||
|
@Singleton
|
||||||
public class CreateAndInstallVm implements Function<VmSpec, IMachine> {
|
public class CreateAndInstallVm implements Function<VmSpec, IMachine> {
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
protected Logger logger = Logger.NULL;
|
||||||
|
|
||||||
private final VirtualBoxManager manager;
|
private final Supplier<VirtualBoxManager> manager;
|
||||||
private final CreateAndRegisterMachineFromIsoIfNotAlreadyExists createAndRegisterMachineFromIsoIfNotAlreadyExists;
|
private final CreateAndRegisterMachineFromIsoIfNotAlreadyExists createAndRegisterMachineFromIsoIfNotAlreadyExists;
|
||||||
private String guestId;
|
private final ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull;
|
||||||
private final ComputeServiceContext context;
|
|
||||||
private final String hostId;
|
private final Supplier<URI> preconfiguration;
|
||||||
private final Predicate<IPSocket> socketTester;
|
private final Predicate<SshClient> sshResponds;
|
||||||
private final String webServerHost;
|
|
||||||
private final int webServerPort;
|
|
||||||
private final ExecutionType executionType;
|
private final ExecutionType executionType;
|
||||||
|
|
||||||
|
private final Factory scriptRunner;
|
||||||
|
private final Supplier<NodeMetadata> host;
|
||||||
|
|
||||||
|
private final Function<IMachine, SshClient> sshClientForIMachine;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public CreateAndInstallVm(VirtualBoxManager manager,
|
public CreateAndInstallVm(Supplier<VirtualBoxManager> manager,
|
||||||
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
|
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
|
||||||
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, String guestId,
|
ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull, Predicate<SshClient> sshResponds,
|
||||||
ComputeServiceContext context, String hostId, Predicate<IPSocket> socketTester, String webServerHost,
|
Function<IMachine, SshClient> sshClientForIMachine, Supplier<NodeMetadata> host,
|
||||||
int webServerPort, ExecutionType executionType) {
|
RunScriptOnNode.Factory scriptRunner, @Preconfiguration Supplier<URI> preconfiguration,
|
||||||
|
ExecutionType executionType) {
|
||||||
this.manager = manager;
|
this.manager = manager;
|
||||||
this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
|
this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
|
||||||
this.guestId = guestId;
|
this.valueOfConfigurationKeyOrNull = valueOfConfigurationKeyOrNull;
|
||||||
this.context = context;
|
this.sshResponds = sshResponds;
|
||||||
this.hostId = hostId;
|
this.sshClientForIMachine = sshClientForIMachine;
|
||||||
this.socketTester = socketTester;
|
this.scriptRunner = scriptRunner;
|
||||||
this.webServerHost = webServerHost;
|
this.host = host;
|
||||||
this.webServerPort = webServerPort;
|
this.preconfiguration = preconfiguration;
|
||||||
this.executionType = executionType;
|
this.executionType = executionType;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public IMachine apply(VmSpec vmSpec) {
|
public IMachine apply(VmSpec vmSpec) {
|
||||||
|
|
||||||
ensureWebServerIsRunning();
|
|
||||||
|
|
||||||
final IMachine vm =createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(vmSpec);
|
|
||||||
|
|
||||||
String vmName = vmSpec.getVmName();
|
String vmName = vmSpec.getVmName();
|
||||||
|
|
||||||
// Change RAM
|
// note this may not be reachable, as this likely uses the 10.2.2 address
|
||||||
ensureMachineHasMemory(vmName, vmSpec.getMemory());
|
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();
|
final IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(vmSpec);
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Launch machine and wait for it to come online
|
// Launch machine and wait for it to come online
|
||||||
ensureMachineIsLaunched(vmName);
|
ensureMachineIsLaunched(vmName);
|
||||||
|
|
||||||
final String installKeySequence = System.getProperty(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, defaultInstallSequence(vmName));
|
sendKeyboardSequence(keySequence, vmName);
|
||||||
sendKeyboardSequence(installKeySequence, vmName);
|
|
||||||
|
|
||||||
boolean sshDeamonIsRunning = false;
|
SshClient client = sshClientForIMachine.apply(vm);
|
||||||
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...");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.debug("Installation of image complete. Powering down...");
|
logger.debug(">> awaiting installation to finish node(%s)", vmName);
|
||||||
lockSessionOnMachineAndApply(manager, Shared, vmName, new Function<ISession, Void>() {
|
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
|
@Override
|
||||||
public Void apply(ISession session) {
|
public Void apply(ISession session) {
|
||||||
|
@ -158,70 +127,8 @@ public class CreateAndInstallVm implements Function<VmSpec, IMachine> {
|
||||||
return vm;
|
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) {
|
private void ensureMachineIsLaunched(String vmName) {
|
||||||
applyForMachine(manager, vmName, new LaunchMachineIfNotAlreadyRunning(manager, executionType, ""));
|
applyForMachine(manager.get(), vmName, new LaunchMachineIfNotAlreadyRunning(manager.get(), 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 sendKeyboardSequence(String keyboardSequence, String vmName) {
|
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) {
|
private void runScriptIfWordEndsWith(StringBuilder sb, String word, String key) {
|
||||||
if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get(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);
|
sb.delete(0, sb.length() - 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -267,9 +174,4 @@ public class CreateAndInstallVm implements Function<VmSpec, IMachine> {
|
||||||
|
|
||||||
return keycodes.toString();
|
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.Nullable;
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
|
import javax.inject.Inject;
|
||||||
import javax.inject.Named;
|
import javax.inject.Named;
|
||||||
|
import javax.inject.Singleton;
|
||||||
|
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.logging.Logger;
|
import org.jclouds.logging.Logger;
|
||||||
|
@ -49,20 +51,23 @@ import org.virtualbox_4_1.VBoxException;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Mattias Holmqvist
|
* @author Mattias Holmqvist
|
||||||
*/
|
*/
|
||||||
|
@Singleton
|
||||||
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<VmSpec, IMachine> {
|
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<VmSpec, IMachine> {
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
protected Logger logger = Logger.NULL;
|
||||||
|
|
||||||
private final VirtualBoxManager manager;
|
private final Supplier<VirtualBoxManager> manager;
|
||||||
private final String workingDir;
|
private final String workingDir;
|
||||||
|
|
||||||
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(VirtualBoxManager manager,
|
@Inject
|
||||||
|
public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Supplier<VirtualBoxManager> manager,
|
||||||
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir) {
|
@Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir) {
|
||||||
this.manager = manager;
|
this.manager = manager;
|
||||||
this.workingDir = workingDir;
|
this.workingDir = workingDir;
|
||||||
|
@ -70,7 +75,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public IMachine apply(@Nullable VmSpec launchSpecification) {
|
public IMachine apply(@Nullable VmSpec launchSpecification) {
|
||||||
final IVirtualBox vBox = manager.getVBox();
|
final IVirtualBox vBox = manager.get().getVBox();
|
||||||
String vmName = launchSpecification.getVmName();
|
String vmName = launchSpecification.getVmName();
|
||||||
try {
|
try {
|
||||||
vBox.findMachine(vmName);
|
vBox.findMachine(vmName);
|
||||||
|
@ -92,8 +97,12 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
||||||
|
|
||||||
IMachine newMachine = vBox.createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(),
|
IMachine newMachine = vBox.createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(),
|
||||||
vmSpec.getVmId(), vmSpec.isForceOverwrite());
|
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();
|
String vmName = vmSpec.getVmName();
|
||||||
|
|
||||||
// Change RAM
|
// Change RAM
|
||||||
|
@ -115,14 +124,13 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
||||||
NatAdapter natAdapter = natAdapterAndSlot.getValue();
|
NatAdapter natAdapter = natAdapterAndSlot.getValue();
|
||||||
ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter);
|
ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter);
|
||||||
}
|
}
|
||||||
return newMachine;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setupDvdsForController(VmSpec vmSpecification, String vmName, StorageController controller) {
|
private void setupDvdsForController(VmSpec vmSpecification, String vmName, StorageController controller) {
|
||||||
Set<IsoImage> dvds = controller.getIsoImages();
|
Set<IsoImage> dvds = controller.getIsoImages();
|
||||||
for (IsoImage dvd : dvds) {
|
for (IsoImage dvd : dvds) {
|
||||||
String dvdSource = dvd.getSourcePath();
|
String dvdSource = dvd.getSourcePath();
|
||||||
final IMedium dvdMedium = manager.getVBox().openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly,
|
final IMedium dvdMedium = manager.get().getVBox().openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly,
|
||||||
vmSpecification.isForceOverwrite());
|
vmSpecification.isForceOverwrite());
|
||||||
ensureMachineDevicesAttached(vmName, dvdMedium, dvd.getDeviceDetails(), controller.getName());
|
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,
|
private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails,
|
||||||
String controllerName) {
|
String controllerName) {
|
||||||
lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium,
|
lockMachineAndApply(manager.get(), Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium,
|
||||||
controllerName));
|
controllerName));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -157,15 +165,16 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ensureMachineHasMemory(String vmName, final long memorySize) {
|
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) {
|
private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId,
|
||||||
lockMachineAndApply(manager, Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
|
NatAdapter natAdapter) {
|
||||||
|
lockMachineAndApply(manager.get(), Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) {
|
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")));
|
storageController, "storageController")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,6 +26,8 @@ import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import javax.inject.Singleton;
|
||||||
|
|
||||||
import org.jclouds.virtualbox.domain.HardDisk;
|
import org.jclouds.virtualbox.domain.HardDisk;
|
||||||
import org.virtualbox_4_1.DeviceType;
|
import org.virtualbox_4_1.DeviceType;
|
||||||
|
@ -39,25 +41,29 @@ import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
import com.google.common.base.Predicate;
|
import com.google.common.base.Predicate;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
import com.google.common.collect.Iterables;
|
import com.google.common.collect.Iterables;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Mattias Holmqvist
|
* @author Mattias Holmqvist
|
||||||
*/
|
*/
|
||||||
|
@Singleton
|
||||||
public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMedium> {
|
public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMedium> {
|
||||||
|
|
||||||
private final VirtualBoxManager manager;
|
private final Supplier<VirtualBoxManager> manager;
|
||||||
private boolean overwriteIfExists;
|
private final boolean overwriteIfExists;
|
||||||
|
|
||||||
public CreateMediumIfNotAlreadyExists(VirtualBoxManager manager, boolean overwriteIfExists) {
|
@Inject
|
||||||
|
public CreateMediumIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, boolean overwriteIfExists) {
|
||||||
this.manager = manager;
|
this.manager = manager;
|
||||||
this.overwriteIfExists = overwriteIfExists;
|
this.overwriteIfExists = overwriteIfExists;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final Pattern ATTACHED_PATTERN = Pattern.compile(".*is still attached.*: ([-0-9a-f]+) .*");
|
public static final Pattern ATTACHED_PATTERN = Pattern.compile(".*is still attached.*: ([-0-9a-f]+) .*");
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public IMedium apply(@Nullable HardDisk hardDisk) {
|
public IMedium apply(@Nullable HardDisk hardDisk) {
|
||||||
IVirtualBox vBox = manager.getVBox();
|
IVirtualBox vBox = manager.get().getVBox();
|
||||||
try {
|
try {
|
||||||
String diskPath = hardDisk.getDiskPath();
|
String diskPath = hardDisk.getDiskPath();
|
||||||
final IMedium medium = vBox.findMedium(diskPath, DeviceType.HardDisk);
|
final IMedium medium = vBox.findMedium(diskPath, DeviceType.HardDisk);
|
||||||
|
@ -83,12 +89,13 @@ public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMediu
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
String machineId = matcher.group(1);
|
String machineId = matcher.group(1);
|
||||||
IMachine immutableMachine = vBox.findMachine(machineId);
|
IMachine immutableMachine = vBox.findMachine(machineId);
|
||||||
IMediumAttachment mediumAttachment = Iterables.find(immutableMachine.getMediumAttachments(), new Predicate<IMediumAttachment>(){
|
IMediumAttachment mediumAttachment = Iterables.find(immutableMachine.getMediumAttachments(),
|
||||||
|
new Predicate<IMediumAttachment>() {
|
||||||
public boolean apply(IMediumAttachment in) {
|
public boolean apply(IMediumAttachment in) {
|
||||||
return in.getMedium().getId().equals(medium.getId());
|
return in.getMedium().getId().equals(medium.getId());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
lockMachineAndApply(manager, Write, immutableMachine.getName(), new DetachDistroMediumFromMachine(
|
lockMachineAndApply(manager.get(), Write, immutableMachine.getName(), new DetachDistroMediumFromMachine(
|
||||||
mediumAttachment.getController(), mediumAttachment.getPort(), mediumAttachment.getDevice()));
|
mediumAttachment.getController(), mediumAttachment.getPort(), mediumAttachment.getDevice()));
|
||||||
deleteMediumAndBlockUntilComplete(medium);
|
deleteMediumAndBlockUntilComplete(medium);
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -30,13 +30,14 @@ import org.virtualbox_4_1.IMachine;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
|
|
||||||
public class IMachineToHardware implements Function<IMachine, Hardware> {
|
public class IMachineToHardware implements Function<IMachine, Hardware> {
|
||||||
|
|
||||||
private VirtualBoxManager virtualBoxManager;
|
private Supplier<VirtualBoxManager> virtualBoxManager;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public IMachineToHardware(VirtualBoxManager virtualBoxManager) {
|
public IMachineToHardware(Supplier<VirtualBoxManager> virtualBoxManager) {
|
||||||
this.virtualBoxManager = virtualBoxManager;
|
this.virtualBoxManager = virtualBoxManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -44,7 +45,7 @@ public class IMachineToHardware implements Function<IMachine, Hardware> {
|
||||||
public Hardware apply(@Nullable IMachine vm) {
|
public Hardware apply(@Nullable IMachine vm) {
|
||||||
String osTypeId = vm.getOSTypeId();
|
String osTypeId = vm.getOSTypeId();
|
||||||
|
|
||||||
IGuestOSType guestOSType = virtualBoxManager.getVBox().getGuestOSType(osTypeId);
|
IGuestOSType guestOSType = virtualBoxManager.get().getVBox().getGuestOSType(osTypeId);
|
||||||
Boolean is64Bit = guestOSType.getIs64Bit();
|
Boolean is64Bit = guestOSType.getIs64Bit();
|
||||||
HardwareBuilder hardwareBuilder = new HardwareBuilder();
|
HardwareBuilder hardwareBuilder = new HardwareBuilder();
|
||||||
hardwareBuilder.ids(vm.getId());
|
hardwareBuilder.ids(vm.getId());
|
||||||
|
|
|
@ -38,15 +38,16 @@ import org.virtualbox_4_1.IMachine;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
public class IMachineToImage implements Function<IMachine, Image> {
|
public class IMachineToImage implements Function<IMachine, Image> {
|
||||||
|
|
||||||
private final VirtualBoxManager virtualboxManager;
|
private final Supplier<VirtualBoxManager> virtualboxManager;
|
||||||
private final Map<OsFamily, Map<String, String>> osVersionMap;
|
private final Map<OsFamily, Map<String, String>> osVersionMap;
|
||||||
|
|
||||||
@Inject
|
@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.virtualboxManager = checkNotNull(virtualboxManager, "virtualboxManager");
|
||||||
this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap");
|
this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap");
|
||||||
}
|
}
|
||||||
|
@ -56,7 +57,7 @@ public class IMachineToImage implements Function<IMachine, Image> {
|
||||||
if (from == null)
|
if (from == null)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
IGuestOSType guestOSType = virtualboxManager.getVBox().getGuestOSType(from.getOSTypeId());
|
IGuestOSType guestOSType = virtualboxManager.get().getVBox().getGuestOSType(from.getOSTypeId());
|
||||||
OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription());
|
OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription());
|
||||||
String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), osVersionMap);
|
String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), osVersionMap);
|
||||||
OperatingSystem os = OperatingSystem.builder().description(guestOSType.getDescription()).family(family)
|
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.NodeState;
|
||||||
import org.jclouds.compute.domain.Processor;
|
import org.jclouds.compute.domain.Processor;
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.domain.Credentials;
|
|
||||||
import org.jclouds.domain.LocationBuilder;
|
import org.jclouds.domain.LocationBuilder;
|
||||||
import org.jclouds.domain.LocationScope;
|
import org.jclouds.domain.LocationScope;
|
||||||
import org.jclouds.javax.annotation.Nullable;
|
import org.jclouds.javax.annotation.Nullable;
|
||||||
|
@ -43,6 +42,9 @@ import org.virtualbox_4_1.INetworkAdapter;
|
||||||
import org.virtualbox_4_1.MachineState;
|
import org.virtualbox_4_1.MachineState;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
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> {
|
public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata> {
|
||||||
|
|
||||||
|
@ -54,8 +56,7 @@ public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata>
|
||||||
public NodeMetadata apply(@Nullable IMachine vm) {
|
public NodeMetadata apply(@Nullable IMachine vm) {
|
||||||
|
|
||||||
NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder();
|
NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder();
|
||||||
String s = vm.getName();
|
nodeMetadataBuilder.name(vm.getName()).ids(vm.getName());
|
||||||
nodeMetadataBuilder.name(s);
|
|
||||||
|
|
||||||
// TODO Set up location properly
|
// TODO Set up location properly
|
||||||
LocationBuilder locationBuilder = new LocationBuilder();
|
LocationBuilder locationBuilder = new LocationBuilder();
|
||||||
|
@ -79,7 +80,7 @@ public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata>
|
||||||
hardwareBuilder.is64Bit(false);
|
hardwareBuilder.is64Bit(false);
|
||||||
|
|
||||||
nodeMetadataBuilder.hostname(vm.getName());
|
nodeMetadataBuilder.hostname(vm.getName());
|
||||||
nodeMetadataBuilder.loginPort(18083);
|
|
||||||
|
|
||||||
MachineState vmState = vm.getState();
|
MachineState vmState = vm.getState();
|
||||||
NodeState nodeState = machineToNodeState.get(vmState);
|
NodeState nodeState = machineToNodeState.get(vmState);
|
||||||
|
@ -91,14 +92,21 @@ public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata>
|
||||||
|
|
||||||
INetworkAdapter networkAdapter = vm.getNetworkAdapter(0l);
|
INetworkAdapter networkAdapter = vm.getNetworkAdapter(0l);
|
||||||
if (networkAdapter != null) {
|
if (networkAdapter != null) {
|
||||||
String bridgedInterface = networkAdapter.getBridgedInterface();
|
nodeMetadataBuilder.privateAddresses(ImmutableSet.of(networkAdapter.getNatDriver().getHostIP()));
|
||||||
System.out.println("Interface: " + bridgedInterface);
|
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.imageId("");
|
||||||
// nodeMetadataBuilder.group("");
|
// nodeMetadataBuilder.group("");
|
||||||
|
|
||||||
nodeMetadataBuilder.id(vm.getId());
|
|
||||||
return nodeMetadataBuilder.build();
|
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 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.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.logging.Logger;
|
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.Function;
|
||||||
import com.google.common.base.Predicate;
|
import com.google.common.base.Predicate;
|
||||||
|
@ -47,27 +50,25 @@ import com.google.inject.name.Named;
|
||||||
/**
|
/**
|
||||||
* @author Andrea Turli
|
* @author Andrea Turli
|
||||||
*/
|
*/
|
||||||
public class RetrieveActiveBridgedInterfaces implements Function<String, List<String>> {
|
public class RetrieveActiveBridgedInterfaces implements Function<NodeMetadata, List<String>> {
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
protected Logger logger = Logger.NULL;
|
||||||
|
|
||||||
private ComputeServiceContext context;
|
private final Factory runScriptOnNodeFactory;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public RetrieveActiveBridgedInterfaces(ComputeServiceContext context) {
|
public RetrieveActiveBridgedInterfaces(Factory runScriptOnNodeFactory) {
|
||||||
this.context = context;
|
this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, "runScriptOnNodeFactory");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<String> apply(String hostId) {
|
public List<String> apply(NodeMetadata host) {
|
||||||
// Bridged Network
|
// Bridged Network
|
||||||
String command = "vboxmanage list bridgedifs";
|
Statement command = Statements.exec("vboxmanage list bridgedifs");
|
||||||
String bridgedIfBlocks = context
|
String bridgedIfBlocks = runScriptOnNodeFactory.create(host, command, runAsRoot(false).wrapInInitScript(false))
|
||||||
.getComputeService()
|
.init().call().getOutput();
|
||||||
.runScriptOnNode(hostId, command,
|
|
||||||
runAsRoot(false).wrapInInitScript(false)).getOutput();
|
|
||||||
|
|
||||||
List<String> bridgedInterfaces = retrieveBridgedInterfaceNames(bridgedIfBlocks);
|
List<String> bridgedInterfaces = retrieveBridgedInterfaceNames(bridgedIfBlocks);
|
||||||
checkNotNull(bridgedInterfaces);
|
checkNotNull(bridgedInterfaces);
|
||||||
|
@ -125,8 +126,7 @@ public class RetrieveActiveBridgedInterfaces implements Function<String, List<St
|
||||||
@Override
|
@Override
|
||||||
public boolean apply(String bridgedInterfaceName) {
|
public boolean apply(String bridgedInterfaceName) {
|
||||||
try {
|
try {
|
||||||
return (bridgedInterfaceName.startsWith(networkInterface
|
return (bridgedInterfaceName.startsWith(networkInterface.getDisplayName()) && networkInterface.isUp() && !networkInterface
|
||||||
.getDisplayName()) && networkInterface.isUp() && !networkInterface
|
|
||||||
.isLoopback());
|
.isLoopback());
|
||||||
} catch (SocketException e) {
|
} catch (SocketException e) {
|
||||||
logger.error(e, "Problem in listing network interfaces.");
|
logger.error(e, "Problem in listing network interfaces.");
|
||||||
|
|
|
@ -32,6 +32,7 @@ import org.virtualbox_4_1.ISnapshot;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
import com.google.common.base.Throwables;
|
import com.google.common.base.Throwables;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -44,12 +45,12 @@ public class TakeSnapshotIfNotAlreadyAttached implements Function<IMachine, ISna
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
protected Logger logger = Logger.NULL;
|
||||||
|
|
||||||
private VirtualBoxManager manager;
|
private Supplier<VirtualBoxManager> manager;
|
||||||
private String snapshotName;
|
private String snapshotName;
|
||||||
private String snapshotDesc;
|
private String snapshotDesc;
|
||||||
|
|
||||||
|
|
||||||
public TakeSnapshotIfNotAlreadyAttached(VirtualBoxManager manager, String snapshotName, String snapshotDesc) {
|
public TakeSnapshotIfNotAlreadyAttached(Supplier<VirtualBoxManager> manager, String snapshotName, String snapshotDesc) {
|
||||||
this.manager = manager;
|
this.manager = manager;
|
||||||
this.snapshotName = snapshotName;
|
this.snapshotName = snapshotName;
|
||||||
this.snapshotDesc = snapshotDesc;
|
this.snapshotDesc = snapshotDesc;
|
||||||
|
@ -61,7 +62,7 @@ public class TakeSnapshotIfNotAlreadyAttached implements Function<IMachine, ISna
|
||||||
ISession session = null;
|
ISession session = null;
|
||||||
if(machine.getCurrentSnapshot() == null ) {
|
if(machine.getCurrentSnapshot() == null ) {
|
||||||
try {
|
try {
|
||||||
session = manager.openMachineSession(machine);
|
session = manager.get().openMachineSession(machine);
|
||||||
IProgress progress = session.getConsole().takeSnapshot(snapshotName, snapshotDesc);
|
IProgress progress = session.getConsole().takeSnapshot(snapshotName, snapshotDesc);
|
||||||
if (progress.getCompleted())
|
if (progress.getCompleted())
|
||||||
logger.debug("Snapshot %s (description: %s) taken from %s", snapshotName, snapshotDesc, machine.getName());
|
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.Inject;
|
||||||
import javax.inject.Named;
|
import javax.inject.Named;
|
||||||
|
|
||||||
import org.jclouds.compute.ComputeServiceContext;
|
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.javax.annotation.Nullable;
|
import org.jclouds.javax.annotation.Nullable;
|
||||||
import org.jclouds.logging.Logger;
|
import org.jclouds.logging.Logger;
|
||||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
import org.jclouds.rest.HttpClient;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
|
||||||
|
@ -52,26 +51,22 @@ public class FileDownloadFromURI implements Function<URI, File> {
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
protected Logger logger = Logger.NULL;
|
||||||
|
|
||||||
private final ComputeServiceContext context;
|
private final HttpClient client;
|
||||||
private final String workingDir;
|
private final String workingDir;
|
||||||
private final String isoFile;
|
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public FileDownloadFromURI(final ComputeServiceContext context,
|
public FileDownloadFromURI(HttpClient client, @Named(VIRTUALBOX_WORKINGDIR) String workingDir) {
|
||||||
@Named(VIRTUALBOX_WORKINGDIR) final String workingDir,
|
this.client = client;
|
||||||
@Named(VirtualBoxConstants.VIRTUALBOX_ISOFILE) final String isoFile) {
|
|
||||||
this.context = context;
|
|
||||||
this.workingDir = workingDir;
|
this.workingDir = workingDir;
|
||||||
this.isoFile = isoFile;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public File apply(@Nullable URI input) {
|
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()) {
|
if (!file.exists()) {
|
||||||
final InputStream inputStream = context.utils().http().get(input);
|
final InputStream inputStream = client.get(input);
|
||||||
checkNotNull(inputStream, "%s not found", input);
|
checkNotNull(inputStream, "%s not found", input);
|
||||||
try {
|
try {
|
||||||
copy(inputStream, new FileOutputStream(file));
|
copy(inputStream, new FileOutputStream(file));
|
||||||
|
|
|
@ -21,6 +21,10 @@ package org.jclouds.virtualbox.functions.admin;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkNotNull;
|
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.annotation.Resource;
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
import javax.inject.Named;
|
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.HandlerList;
|
||||||
import org.eclipse.jetty.server.handler.ResourceHandler;
|
import org.eclipse.jetty.server.handler.ResourceHandler;
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.javax.annotation.Nullable;
|
|
||||||
import org.jclouds.logging.Logger;
|
import org.jclouds.logging.Logger;
|
||||||
import org.jclouds.net.IPSocket;
|
import org.jclouds.virtualbox.Preconfiguration;
|
||||||
import org.jclouds.predicates.InetSocketAddressConnect;
|
|
||||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Supplier;
|
||||||
import com.google.inject.Singleton;
|
import com.google.inject.Singleton;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Andrea Turli
|
* @author Andrea Turli
|
||||||
*/
|
*/
|
||||||
public class StartJettyIfNotAlreadyRunning implements Function<String, Server> {
|
@Preconfiguration
|
||||||
|
@Singleton
|
||||||
|
public class StartJettyIfNotAlreadyRunning implements Supplier<URI> {
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
protected Logger logger = Logger.NULL;
|
||||||
|
|
||||||
|
private final URI preconfigurationUrl;
|
||||||
private final Server jetty;
|
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
|
@Inject
|
||||||
public StartJettyIfNotAlreadyRunning(@Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) int port) {
|
public StartJettyIfNotAlreadyRunning(
|
||||||
this(ServerJetty.getInstance().getServer(), port);
|
@Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
|
||||||
|
this(new Server(URI.create(preconfigurationUrl).getPort()), preconfigurationUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
public StartJettyIfNotAlreadyRunning(Server jetty,
|
||||||
public Server apply(@Nullable String baseResource) {
|
@Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
|
||||||
if (!jetty.getState().equals(Server.STARTED)
|
this.preconfigurationUrl = URI.create(checkNotNull(preconfigurationUrl, "preconfigurationUrl"));
|
||||||
// TODO code smell = hard coding addresses or ports!!
|
this.jetty = jetty;
|
||||||
&& !new InetSocketAddressConnect().apply(new IPSocket("localhost", port))) {
|
}
|
||||||
|
|
||||||
|
@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();
|
ResourceHandler resource_handler = new ResourceHandler();
|
||||||
resource_handler.setDirectoriesListed(true);
|
resource_handler.setDirectoriesListed(true);
|
||||||
resource_handler.setWelcomeFiles(new String[] { "index.html" });
|
resource_handler.setWelcomeFiles(new String[] { "index.html" });
|
||||||
|
|
||||||
resource_handler.setResourceBase(baseResource);
|
resource_handler.setResourceBase("");
|
||||||
logger.info("serving " + resource_handler.getBaseResource());
|
|
||||||
|
|
||||||
HandlerList handlers = new HandlerList();
|
HandlerList handlers = new HandlerList();
|
||||||
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
|
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
|
||||||
jetty.setHandler(handlers);
|
jetty.setHandler(handlers);
|
||||||
|
@ -83,34 +87,23 @@ public class StartJettyIfNotAlreadyRunning implements Function<String, Server> {
|
||||||
try {
|
try {
|
||||||
jetty.start();
|
jetty.start();
|
||||||
} catch (Exception e) {
|
} 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;
|
logger.debug("<< serving %s", resource_handler.getBaseResource());
|
||||||
} else {
|
|
||||||
logger.debug("Server jetty serving %s already running. Skipping start", baseResource);
|
|
||||||
return jetty;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Singleton
|
@PreDestroy()
|
||||||
private static class ServerJetty {
|
public void stop() {
|
||||||
private static ServerJetty instance;
|
try {
|
||||||
private Server server;
|
jetty.stop();
|
||||||
private String port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080");
|
} catch (Exception e) {
|
||||||
|
}
|
||||||
private ServerJetty() {
|
|
||||||
this.server = new Server(Integer.parseInt(port));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ServerJetty getInstance() {
|
@Override
|
||||||
if (instance == null)
|
public URI get() {
|
||||||
instance = new ServerJetty();
|
return preconfigurationUrl;
|
||||||
return instance;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Server getServer() {
|
|
||||||
return server;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,68 +25,84 @@ import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
|
||||||
|
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
|
import javax.inject.Inject;
|
||||||
import javax.inject.Named;
|
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.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.domain.Credentials;
|
import org.jclouds.location.Provider;
|
||||||
import org.jclouds.logging.Logger;
|
import org.jclouds.logging.Logger;
|
||||||
import org.jclouds.net.IPSocket;
|
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 org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
import com.google.common.base.Predicate;
|
import com.google.common.base.Supplier;
|
||||||
|
|
||||||
public class StartVBoxIfNotAlreadyRunning implements Function<URI, VirtualBoxManager> {
|
@Singleton
|
||||||
|
public class StartVBoxIfNotAlreadyRunning implements Supplier<VirtualBoxManager> {
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
protected Logger logger = Logger.NULL;
|
||||||
|
|
||||||
private final ComputeService compute;
|
private final Factory runScriptOnNodeFactory;
|
||||||
private final VirtualBoxManager manager;
|
private final RetryIfSocketNotYetOpen socketTester;
|
||||||
private final Predicate<IPSocket> socketTester;
|
private final Supplier<NodeMetadata> host;
|
||||||
private final String hostId;
|
private final URI provider;
|
||||||
private final Credentials credentials;
|
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,
|
// the functions and suppliers here are to ensure we don't do heavy i/o in injection
|
||||||
Predicate<IPSocket> socketTester, String hostId, Credentials credentials) {
|
@Inject
|
||||||
this.compute = checkNotNull(compute, "compute");
|
public StartVBoxIfNotAlreadyRunning(Function<Supplier<NodeMetadata>, VirtualBoxManager> managerForNode,
|
||||||
this.manager = checkNotNull(manager, "manager");
|
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.socketTester = checkNotNull(socketTester, "socketTester");
|
||||||
this.hostId = checkNotNull(hostId, "hostId");
|
this.host = checkNotNull(host, "host");
|
||||||
this.credentials = checkNotNull(credentials, "credentials");
|
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
|
@Override
|
||||||
public VirtualBoxManager apply(URI endpoint) {
|
public VirtualBoxManager get() {
|
||||||
checkState(compute.getNodeMetadata(hostId) != null, "compute service %s cannot locate node with id %s", compute,
|
checkState(manager != null, "start not called");
|
||||||
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;
|
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);
|
|
||||||
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.annotation.Resource;
|
||||||
import javax.inject.Named;
|
import javax.inject.Named;
|
||||||
|
import javax.inject.Singleton;
|
||||||
|
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.logging.Logger;
|
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.base.Throwables;
|
||||||
import com.google.common.collect.Lists;
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
public class UnregisterMachineIfExistsAndDeleteItsMedia implements
|
@Singleton
|
||||||
Function<IMachine, Void> {
|
public class UnregisterMachineIfExistsAndDeleteItsMedia implements Function<IMachine, Void> {
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
|
@ -67,17 +68,15 @@ public class UnregisterMachineIfExistsAndDeleteItsMedia implements
|
||||||
ErrorCode errorCode = ErrorCode.valueOf(e);
|
ErrorCode errorCode = ErrorCode.valueOf(e);
|
||||||
switch (errorCode) {
|
switch (errorCode) {
|
||||||
case VBOX_E_OBJECT_NOT_FOUND:
|
case VBOX_E_OBJECT_NOT_FOUND:
|
||||||
logger.debug("Machine %s does not exists, cannot unregister",
|
logger.debug("Machine %s does not exists, cannot unregister", vmSpec.getVmName());
|
||||||
vmSpec.getVmName());
|
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
List<IMedium> filteredMediaToBeDeleted = Lists.newArrayList(transform(
|
List<IMedium> filteredMediaToBeDeleted = Lists.newArrayList(transform(filter(mediaToBeDeleted,
|
||||||
filter(mediaToBeDeleted, new AutoDeleteHardDiskPredicate(vmSpec)),
|
new AutoDeleteHardDiskPredicate(vmSpec)), new DeleteChildrenOfMedium()));
|
||||||
new DeleteChildrenOfMedium()));
|
|
||||||
|
|
||||||
checkNotNull(filteredMediaToBeDeleted);
|
checkNotNull(filteredMediaToBeDeleted);
|
||||||
if (!filteredMediaToBeDeleted.isEmpty()) {
|
if (!filteredMediaToBeDeleted.isEmpty()) {
|
||||||
|
@ -85,8 +84,7 @@ public class UnregisterMachineIfExistsAndDeleteItsMedia implements
|
||||||
IProgress deletion = machine.delete(filteredMediaToBeDeleted);
|
IProgress deletion = machine.delete(filteredMediaToBeDeleted);
|
||||||
deletion.waitForCompletion(-1);
|
deletion.waitForCompletion(-1);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error(e, "Problem in deleting the media attached to %s",
|
logger.error(e, "Problem in deleting the media attached to %s", machine.getName());
|
||||||
machine.getName());
|
|
||||||
Throwables.propagate(e);
|
Throwables.propagate(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -21,7 +21,9 @@ package org.jclouds.virtualbox.predicates;
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
|
import javax.inject.Inject;
|
||||||
import javax.inject.Named;
|
import javax.inject.Named;
|
||||||
|
import javax.inject.Singleton;
|
||||||
|
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.logging.Logger;
|
import org.jclouds.logging.Logger;
|
||||||
|
@ -33,20 +35,23 @@ import org.virtualbox_4_1.IStorageController;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Predicate;
|
import com.google.common.base.Predicate;
|
||||||
|
import com.google.common.base.Supplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author Andrea Turli
|
* @author Andrea Turli
|
||||||
*/
|
*/
|
||||||
|
@Singleton
|
||||||
public class IsLinkedClone implements Predicate<IMachine> {
|
public class IsLinkedClone implements Predicate<IMachine> {
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||||
protected Logger logger = Logger.NULL;
|
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;
|
this.manager = manager;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -64,7 +69,7 @@ public class IsLinkedClone implements Predicate<IMachine> {
|
||||||
// more than one machine is attached to this hd
|
// more than one machine is attached to this hd
|
||||||
for (IMedium child : iMedium.getParent().getChildren()) {
|
for (IMedium child : iMedium.getParent().getChildren()) {
|
||||||
for (String machineId : child.getMachineIds()) {
|
for (String machineId : child.getMachineIds()) {
|
||||||
IMachine iMachine = manager.getVBox().findMachine(
|
IMachine iMachine = manager.get().getVBox().findMachine(
|
||||||
machineId);
|
machineId);
|
||||||
if (!iMachine.getName().equals(machine.getName())) {
|
if (!iMachine.getName().equals(machine.getName())) {
|
||||||
logger.debug("Machine %s is a linked clone",
|
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;
|
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.jclouds.util.Throwables2;
|
||||||
import org.virtualbox_4_1.IMachine;
|
import org.virtualbox_4_1.IMachine;
|
||||||
import org.virtualbox_4_1.ISession;
|
import org.virtualbox_4_1.ISession;
|
||||||
import org.virtualbox_4_1.LockType;
|
import org.virtualbox_4_1.LockType;
|
||||||
|
import org.virtualbox_4_1.SessionState;
|
||||||
import org.virtualbox_4_1.VBoxException;
|
import org.virtualbox_4_1.VBoxException;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
import org.virtualbox_4_1.jaxws.SessionState;
|
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
|
||||||
|
@ -138,9 +144,15 @@ public class MachineUtils {
|
||||||
* Since the machine is unlocked it is possible to delete the IMachine.
|
* Since the machine is unlocked it is possible to delete the IMachine.
|
||||||
* <p/>
|
* <p/>
|
||||||
*
|
*
|
||||||
* @param manager the VirtualBoxManager
|
*<h3>Note!</h3> Currently, this can only unlock the machine, if the lock was created in the
|
||||||
* @param machineId the id of the machine
|
* current session.
|
||||||
* @param function the function to execute
|
*
|
||||||
|
* @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.
|
* @return the result from applying the function to the machine.
|
||||||
*/
|
*/
|
||||||
public static <T> T unlockMachineAndApply(VirtualBoxManager manager, final String machineId,
|
public static <T> T unlockMachineAndApply(VirtualBoxManager manager, final String machineId,
|
||||||
|
@ -148,14 +160,17 @@ public class MachineUtils {
|
||||||
try {
|
try {
|
||||||
ISession session = manager.getSessionObject();
|
ISession session = manager.getSessionObject();
|
||||||
IMachine immutableMachine = manager.getVBox().findMachine(machineId);
|
IMachine immutableMachine = manager.getVBox().findMachine(machineId);
|
||||||
if(immutableMachine.getSessionState().equals(SessionState.LOCKED))
|
SessionState state = immutableMachine.getSessionState();
|
||||||
|
if (state.equals(SessionState.Locked))
|
||||||
session.unlockMachine();
|
session.unlockMachine();
|
||||||
|
//TODO: wire this in
|
||||||
|
Statement kill = newStatementList(call("default"), findPid(machineId), kill());
|
||||||
|
|
||||||
return function.apply(immutableMachine);
|
return function.apply(immutableMachine);
|
||||||
|
|
||||||
} catch (VBoxException e) {
|
} catch (VBoxException e) {
|
||||||
throw new RuntimeException(String.format("error applying %s to %s: %s", function, machineId,
|
throw new RuntimeException(String.format("error applying %s to %s: %s", function, machineId, e.getMessage()),
|
||||||
e.getMessage()), e);
|
e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -19,35 +19,40 @@
|
||||||
|
|
||||||
package org.jclouds.virtualbox;
|
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 java.util.Properties;
|
||||||
|
|
||||||
import org.eclipse.jetty.server.Server;
|
|
||||||
import org.jclouds.Constants;
|
import org.jclouds.Constants;
|
||||||
|
import org.jclouds.byon.Node;
|
||||||
|
import org.jclouds.byon.config.CacheNodeStoreModule;
|
||||||
import org.jclouds.compute.BaseVersionedServiceLiveTest;
|
import org.jclouds.compute.BaseVersionedServiceLiveTest;
|
||||||
import org.jclouds.compute.ComputeServiceContext;
|
import org.jclouds.compute.ComputeServiceContext;
|
||||||
import org.jclouds.compute.ComputeServiceContextFactory;
|
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.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.config.ValueOfConfigurationKeyOrNull;
|
import org.jclouds.config.ValueOfConfigurationKeyOrNull;
|
||||||
import org.jclouds.domain.Credentials;
|
|
||||||
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
|
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
|
||||||
import org.jclouds.predicates.InetSocketAddressConnect;
|
|
||||||
import org.jclouds.sshj.config.SshjSshClientModule;
|
import org.jclouds.sshj.config.SshjSshClientModule;
|
||||||
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
import org.jclouds.virtualbox.config.VirtualBoxConstants;
|
||||||
import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning;
|
import org.jclouds.virtualbox.domain.VmSpec;
|
||||||
import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning;
|
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
|
||||||
import org.testng.annotations.AfterClass;
|
import org.testng.annotations.AfterClass;
|
||||||
import org.testng.annotations.BeforeClass;
|
import org.testng.annotations.BeforeClass;
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
import org.virtualbox_4_1.SessionState;
|
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
import com.google.common.base.Splitter;
|
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.ImmutableSet;
|
||||||
import com.google.common.collect.Iterables;
|
import com.google.common.collect.Iterables;
|
||||||
|
import com.google.inject.Key;
|
||||||
import com.google.inject.Module;
|
import com.google.inject.Module;
|
||||||
|
import com.google.inject.TypeLiteral;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests behavior of {@code VirtualBoxClient}
|
* Tests behavior of {@code VirtualBoxClient}
|
||||||
|
@ -61,17 +66,19 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
protected ComputeServiceContext context;
|
protected ComputeServiceContext context;
|
||||||
protected VirtualBoxManager manager;
|
protected Supplier<VirtualBoxManager> manager;
|
||||||
protected Server jetty;
|
protected Supplier<URI> preconfigurationUri;
|
||||||
protected String hostVersion;
|
protected String hostVersion;
|
||||||
protected String operatingSystemIso;
|
protected String operatingSystemIso;
|
||||||
protected String guestAdditionsIso;
|
protected String guestAdditionsIso;
|
||||||
protected String adminDisk;
|
protected String adminDisk;
|
||||||
protected String workingDir;
|
protected String workingDir;
|
||||||
|
protected Supplier<NodeMetadata> host;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void setupCredentials() {
|
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();
|
ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults();
|
||||||
super.setupCredentials();
|
super.setupCredentials();
|
||||||
}
|
}
|
||||||
|
@ -87,44 +94,48 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest {
|
||||||
public void setupClient() {
|
public void setupClient() {
|
||||||
setupCredentials();
|
setupCredentials();
|
||||||
Properties overrides = setupProperties();
|
Properties overrides = setupProperties();
|
||||||
context = new ComputeServiceContextFactory().createContext(provider, identity, credential,
|
|
||||||
ImmutableSet.<Module> of(new Log4JLoggingModule(), new SshjSshClientModule()), overrides);
|
CacheNodeStoreModule hostModule = new CacheNodeStoreModule(ImmutableMap.of("host", Node.builder().id("host")
|
||||||
Function<String, String> configProperties = context.utils().injector().getInstance(ValueOfConfigurationKeyOrNull.class);
|
.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);
|
imageId = configProperties.apply(ComputeServiceConstants.PROPERTY_IMAGE_ID);
|
||||||
workingDir = configProperties.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR);
|
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();
|
||||||
|
|
||||||
|
manager = context.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<VirtualBoxManager>>() {
|
||||||
|
}));
|
||||||
|
// this will eagerly startup vbox
|
||||||
|
manager.get();
|
||||||
|
|
||||||
jetty = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource);
|
|
||||||
startVboxIfNotAlreadyRunning();
|
|
||||||
hostVersion = Iterables.get(Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0);
|
hostVersion = Iterables.get(Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0);
|
||||||
adminDisk = workingDir + "/testadmin.vdi";
|
adminDisk = workingDir + "/testadmin.vdi";
|
||||||
operatingSystemIso = String.format("%s/%s.iso", workingDir, imageId);
|
operatingSystemIso = String.format("%s/%s.iso", workingDir, imageId);
|
||||||
guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", workingDir, hostVersion);
|
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")
|
@AfterClass(groups = "live")
|
||||||
protected void tearDown() throws Exception {
|
protected void tearDown() throws Exception {
|
||||||
if (context != null)
|
if (context != null)
|
||||||
context.close();
|
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.assertEquals;
|
||||||
import static org.testng.Assert.assertFalse;
|
import static org.testng.Assert.assertFalse;
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;
|
import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;
|
||||||
import org.jclouds.compute.config.BaseComputeServiceContextModule;
|
|
||||||
import org.jclouds.compute.domain.ExecResponse;
|
import org.jclouds.compute.domain.ExecResponse;
|
||||||
import org.jclouds.compute.domain.Image;
|
import org.jclouds.compute.domain.Image;
|
||||||
import org.jclouds.compute.domain.OsFamily;
|
|
||||||
import org.jclouds.compute.domain.Template;
|
import org.jclouds.compute.domain.Template;
|
||||||
import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;
|
import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
|
||||||
import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;
|
import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;
|
||||||
import org.jclouds.domain.Credentials;
|
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.net.IPSocket;
|
||||||
import org.jclouds.ssh.SshClient;
|
import org.jclouds.ssh.SshClient;
|
||||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||||
import org.jclouds.virtualbox.functions.IMachineToImage;
|
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
import org.virtualbox_4_1.IMachine;
|
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.common.collect.Iterables;
|
||||||
import com.google.inject.Guice;
|
|
||||||
|
|
||||||
@Test(groups = "live", singleThreaded = true, testName = "VirtualBoxComputeServiceAdapterLiveTest")
|
@Test(groups = "live", singleThreaded = true, testName = "VirtualBoxComputeServiceAdapterLiveTest")
|
||||||
public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClientLiveTest {
|
public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||||
|
|
||||||
private VirtualBoxComputeServiceAdapter adapter;
|
private VirtualBoxComputeServiceAdapter adapter;
|
||||||
private NodeAndInitialCredentials<IMachine> machine;
|
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
|
@Override
|
||||||
public void setupClient() {
|
public void setupClient() {
|
||||||
super.setupClient();
|
super.setupClient();
|
||||||
final VirtualBoxManager manager = getManager();
|
adapter = context.utils().injector().getInstance(VirtualBoxComputeServiceAdapter.class);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -46,6 +46,7 @@ import org.virtualbox_4_1.IVirtualBox;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
import com.google.common.base.Suppliers;
|
||||||
import com.google.common.collect.Iterators;
|
import com.google.common.collect.Iterators;
|
||||||
import com.google.inject.Guice;
|
import com.google.inject.Guice;
|
||||||
|
|
||||||
|
@ -83,8 +84,8 @@ public class VirtualBoxComputeServiceAdapterTest {
|
||||||
|
|
||||||
replay(manager, justProvider, vBox, clonedMachine, imageMachine, osType);
|
replay(manager, justProvider, vBox, clonedMachine, imageMachine, osType);
|
||||||
|
|
||||||
Function<IMachine, Image> iMachineToImage = new IMachineToImage(manager, osMap);
|
Function<IMachine, Image> iMachineToImage = new IMachineToImage(Suppliers.ofInstance(manager), osMap);
|
||||||
VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(manager, justProvider,
|
VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(Suppliers.ofInstance(manager), justProvider,
|
||||||
iMachineToImage);
|
iMachineToImage);
|
||||||
|
|
||||||
Iterator<Image> iterator = adapter.listImages().iterator();
|
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 controllerName = "IDE Controller";
|
||||||
String diskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
|
String diskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
|
||||||
String diskName = "admin";
|
|
||||||
String diskFormat = "vdi";
|
String diskFormat = "vdi";
|
||||||
int controllerPort = 0;
|
int controllerPort = 0;
|
||||||
int deviceSlot = 1;
|
int deviceSlot = 1;
|
||||||
|
|
|
@ -51,12 +51,12 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
|
||||||
networkAdapter.setAttachmentType(NAT);
|
networkAdapter.setAttachmentType(NAT);
|
||||||
expect(networkAdapter.getNatDriver()).andReturn(natEngine);
|
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);
|
networkAdapter.setEnabled(true);
|
||||||
machine.saveSettings();
|
machine.saveSettings();
|
||||||
|
|
||||||
replay(machine, networkAdapter, natEngine);
|
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);
|
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
|
||||||
|
|
||||||
verify(machine, networkAdapter, natEngine);
|
verify(machine, networkAdapter, natEngine);
|
||||||
|
@ -73,7 +73,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
|
||||||
networkAdapter.setAttachmentType(NAT);
|
networkAdapter.setAttachmentType(NAT);
|
||||||
expect(networkAdapter.getNatDriver()).andReturn(natEngine);
|
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(
|
expectLastCall().andThrow(
|
||||||
new VBoxException(null, "VirtualBox error: A NAT rule of this name already exists (0x80070057)"));
|
new VBoxException(null, "VirtualBox error: A NAT rule of this name already exists (0x80070057)"));
|
||||||
|
|
||||||
|
@ -81,7 +81,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
|
||||||
machine.saveSettings();
|
machine.saveSettings();
|
||||||
|
|
||||||
replay(machine, networkAdapter, natEngine);
|
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);
|
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
|
||||||
|
|
||||||
verify(machine, networkAdapter, natEngine);
|
verify(machine, networkAdapter, natEngine);
|
||||||
|
@ -102,7 +102,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
replay(machine, networkAdapter, natEngine);
|
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);
|
new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine);
|
||||||
|
|
||||||
verify(machine, networkAdapter, natEngine);
|
verify(machine, networkAdapter, natEngine);
|
||||||
|
|
|
@ -19,95 +19,83 @@
|
||||||
|
|
||||||
package org.jclouds.virtualbox.functions;
|
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 static org.testng.Assert.assertEquals;
|
||||||
|
|
||||||
import org.jclouds.compute.ComputeServiceContext;
|
|
||||||
import org.jclouds.domain.Credentials;
|
|
||||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||||
import org.jclouds.virtualbox.domain.HardDisk;
|
import org.jclouds.virtualbox.domain.HardDisk;
|
||||||
import org.jclouds.virtualbox.domain.StorageController;
|
import org.jclouds.virtualbox.domain.StorageController;
|
||||||
import org.jclouds.virtualbox.domain.VmSpec;
|
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.testng.annotations.Test;
|
||||||
import org.virtualbox_4_1.CleanupMode;
|
import org.virtualbox_4_1.CleanupMode;
|
||||||
import org.virtualbox_4_1.IMachine;
|
import org.virtualbox_4_1.IMachine;
|
||||||
import org.virtualbox_4_1.ISession;
|
import org.virtualbox_4_1.ISession;
|
||||||
import org.virtualbox_4_1.StorageBus;
|
import org.virtualbox_4_1.StorageBus;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
|
||||||
|
|
||||||
|
import com.google.common.base.CaseFormat;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Andrea Turli
|
* @author Andrea Turli
|
||||||
*/
|
*/
|
||||||
@Test(groups = "live", singleThreaded = true, testName = "CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
|
@Test(groups = "live", singleThreaded = true, testName = "CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
|
||||||
public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
|
public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||||
BaseVirtualBoxClientLiveTest {
|
|
||||||
|
|
||||||
private static final boolean IS_LINKED_CLONE = true;
|
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 clonedVmSpec;
|
||||||
|
private VmSpec sourceVmSpec;
|
||||||
|
|
||||||
private String ideControllerName = "IDE Controller";
|
|
||||||
private CleanupMode mode = CleanupMode.Full;
|
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
|
@Test
|
||||||
public void testCloneMachineFromAnotherMachine() throws Exception {
|
public void testCloneMachineFromAnotherMachine() throws Exception {
|
||||||
VirtualBoxManager manager = (VirtualBoxManager) context
|
try {
|
||||||
.getProviderSpecificContext().getApi();
|
IMachine source = getSourceNode();
|
||||||
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(
|
|
||||||
hostId, "localhost", guestId, "localhost", new Credentials("toor",
|
|
||||||
"password"));
|
|
||||||
|
|
||||||
IMachine master = getMasterNode(manager, localHostContext);
|
if (source.getCurrentSnapshot() != null) {
|
||||||
|
ISession session = manager.get().openMachineSession(source);
|
||||||
if (master.getCurrentSnapshot() != null) {
|
session.getConsole().deleteSnapshot(source.getCurrentSnapshot().getId());
|
||||||
ISession session = manager.openMachineSession(master);
|
|
||||||
session.getConsole().deleteSnapshot(
|
|
||||||
master.getCurrentSnapshot().getId());
|
|
||||||
session.unlockMachine();
|
session.unlockMachine();
|
||||||
}
|
}
|
||||||
|
|
||||||
clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(512)
|
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, clonedVmSpec,
|
||||||
.cleanUpMode(mode)
|
IS_LINKED_CLONE).apply(source);
|
||||||
.forceOverwrite(true).build();
|
|
||||||
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(
|
|
||||||
manager, workingDir, clonedVmSpec, IS_LINKED_CLONE).apply(master);
|
|
||||||
assertEquals(clone.getName(), clonedVmSpec.getVmName());
|
assertEquals(clone.getName(), clonedVmSpec.getVmName());
|
||||||
for (VmSpec spec : ImmutableSet.of(clonedVmSpec, new IMachineToVmSpec().apply(master)))
|
} finally {
|
||||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, spec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(spec));
|
for (VmSpec spec : ImmutableSet.of(clonedVmSpec, sourceVmSpec))
|
||||||
|
undoVm(spec);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private IMachine getMasterNode(VirtualBoxManager manager,
|
private IMachine getSourceNode() {
|
||||||
ComputeServiceContext localHostContext) {
|
|
||||||
try {
|
try {
|
||||||
StorageController ideController = StorageController
|
return context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(
|
||||||
.builder()
|
sourceVmSpec);
|
||||||
.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);
|
|
||||||
|
|
||||||
} catch (IllegalStateException e) {
|
} catch (IllegalStateException e) {
|
||||||
// already created
|
// 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.base.Predicates.equalTo;
|
||||||
import static com.google.common.collect.Iterables.any;
|
import static com.google.common.collect.Iterables.any;
|
||||||
import static com.google.common.collect.Iterables.transform;
|
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.testng.Assert.assertTrue;
|
||||||
import static org.virtualbox_4_1.LockType.Write;
|
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
|
|
||||||
import org.jclouds.compute.ComputeServiceContext;
|
|
||||||
import org.jclouds.compute.config.BaseComputeServiceContextModule;
|
import org.jclouds.compute.config.BaseComputeServiceContextModule;
|
||||||
import org.jclouds.compute.domain.Image;
|
import org.jclouds.compute.domain.Image;
|
||||||
import org.jclouds.compute.domain.OsFamily;
|
import org.jclouds.compute.domain.OsFamily;
|
||||||
import org.jclouds.compute.reference.ComputeServiceConstants;
|
import org.jclouds.compute.reference.ComputeServiceConstants;
|
||||||
import org.jclouds.domain.Credentials;
|
|
||||||
import org.jclouds.json.Json;
|
import org.jclouds.json.Json;
|
||||||
import org.jclouds.json.config.GsonModule;
|
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.BaseVirtualBoxClientLiveTest;
|
||||||
import org.jclouds.virtualbox.domain.HardDisk;
|
import org.jclouds.virtualbox.domain.HardDisk;
|
||||||
import org.jclouds.virtualbox.domain.NatAdapter;
|
import org.jclouds.virtualbox.domain.NatAdapter;
|
||||||
import org.jclouds.virtualbox.domain.StorageController;
|
import org.jclouds.virtualbox.domain.StorageController;
|
||||||
import org.jclouds.virtualbox.domain.VmSpec;
|
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.BeforeClass;
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
import org.virtualbox_4_1.CleanupMode;
|
import org.virtualbox_4_1.CleanupMode;
|
||||||
import org.virtualbox_4_1.IMachine;
|
import org.virtualbox_4_1.IMachine;
|
||||||
import org.virtualbox_4_1.StorageBus;
|
import org.virtualbox_4_1.StorageBus;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
import com.google.common.base.Predicate;
|
|
||||||
import com.google.inject.Guice;
|
import com.google.inject.Guice;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -72,43 +60,31 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||||
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
|
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
|
||||||
.getInstance(Json.class));
|
.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;
|
private VmSpec vmSpecification;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@BeforeClass(groups = "live")
|
@BeforeClass(groups = "live")
|
||||||
public void setupClient() {
|
public void setupClient() {
|
||||||
super.setupClient();
|
super.setupClient();
|
||||||
|
String vmName = "jclouds-image-virtualbox-iso-to-machine-test";
|
||||||
|
|
||||||
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true)
|
HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true)
|
||||||
.controllerPort(0).deviceSlot(1).build();
|
.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)
|
.attachISO(0, 0, operatingSystemIso)
|
||||||
.attachHardDisk(hardDisk)
|
.attachHardDisk(hardDisk)
|
||||||
.attachISO(1, 1, guestAdditionsIso).build();
|
.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)
|
.controller(ideController)
|
||||||
.forceOverwrite(true)
|
.forceOverwrite(true)
|
||||||
.cleanUpMode(CleanupMode.Full)
|
.cleanUpMode(CleanupMode.Full)
|
||||||
.natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build()).build();
|
.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 {
|
public void testCreateImageMachineFromIso() throws Exception {
|
||||||
|
|
||||||
VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
|
IMachine imageMachine = context.utils().injector().getInstance(CreateAndInstallVm.class).apply(vmSpecification);
|
||||||
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);
|
|
||||||
|
|
||||||
IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
|
IMachineToImage iMachineToImage = new IMachineToImage(manager, map);
|
||||||
Image newImage = iMachineToImage.apply(imageMachine);
|
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;
|
package org.jclouds.virtualbox.functions;
|
||||||
|
|
||||||
import static org.jclouds.virtualbox.util.MachineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered;
|
|
||||||
import static org.testng.Assert.assertEquals;
|
import static org.testng.Assert.assertEquals;
|
||||||
import static org.testng.Assert.fail;
|
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.HardDisk;
|
||||||
import org.jclouds.virtualbox.domain.StorageController;
|
import org.jclouds.virtualbox.domain.StorageController;
|
||||||
import org.jclouds.virtualbox.domain.VmSpec;
|
import org.jclouds.virtualbox.domain.VmSpec;
|
||||||
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
|
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
import org.virtualbox_4_1.CleanupMode;
|
import org.virtualbox_4_1.CleanupMode;
|
||||||
import org.virtualbox_4_1.IMachine;
|
import org.virtualbox_4_1.IMachine;
|
||||||
|
@ -39,8 +37,7 @@ import org.virtualbox_4_1.VBoxException;
|
||||||
* @author Mattias Holmqvist
|
* @author Mattias Holmqvist
|
||||||
*/
|
*/
|
||||||
@Test(groups = "live", singleThreaded = true, testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
|
@Test(groups = "live", singleThreaded = true, testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest")
|
||||||
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
|
public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||||
BaseVirtualBoxClientLiveTest {
|
|
||||||
|
|
||||||
private String ideControllerName;
|
private String ideControllerName;
|
||||||
private CleanupMode mode;
|
private CleanupMode mode;
|
||||||
|
@ -51,50 +48,48 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends
|
||||||
super.setupClient();
|
super.setupClient();
|
||||||
ideControllerName = "IDE Controller";
|
ideControllerName = "IDE Controller";
|
||||||
mode = CleanupMode.Full;
|
mode = CleanupMode.Full;
|
||||||
ideController = StorageController
|
ideController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE).attachISO(0, 0,
|
||||||
.builder()
|
operatingSystemIso).attachHardDisk(
|
||||||
.name(ideControllerName)
|
HardDisk.builder().diskpath(adminDisk).controllerPort(0).deviceSlot(1).build()).attachISO(1, 1,
|
||||||
.bus(StorageBus.IDE)
|
guestAdditionsIso).build();
|
||||||
.attachISO(0, 0, operatingSystemIso)
|
|
||||||
.attachHardDisk(
|
|
||||||
HardDisk.builder().diskpath(adminDisk)
|
|
||||||
.controllerPort(0).deviceSlot(1).build())
|
|
||||||
.attachISO(1, 1, guestAdditionsIso)
|
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateNewMachine() throws Exception {
|
public void testCreateNewMachine() throws Exception {
|
||||||
String vmName = "jclouds-test-create-1-node";
|
String vmName = "jclouds-test-create-1-node";
|
||||||
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName)
|
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).controller(ideController)
|
||||||
.memoryMB(512).controller(ideController).cleanUpMode(mode)
|
.cleanUpMode(mode).osTypeId("Debian").forceOverwrite(true).build();
|
||||||
.osTypeId("Debian").forceOverwrite(true).build();
|
undoVm(launchSpecification);
|
||||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification));
|
try {
|
||||||
IMachine debianNode = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(
|
IMachine debianNode = context.utils().injector().getInstance(
|
||||||
manager, workingDir).apply(launchSpecification);
|
CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(launchSpecification);
|
||||||
IMachine machine = manager.getVBox().findMachine(vmName);
|
IMachine machine = manager.get().getVBox().findMachine(vmName);
|
||||||
assertEquals(debianNode.getName(), machine.getName());
|
assertEquals(debianNode.getName(), machine.getName());
|
||||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification));
|
} finally {
|
||||||
|
undoVm(launchSpecification);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateNewMachineWithBadOsType() throws Exception {
|
public void testCreateNewMachineWithBadOsType() throws Exception {
|
||||||
String vmName = "jclouds-test-create-2-node";
|
String vmName = "jclouds-test-create-2-node";
|
||||||
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName)
|
VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).controller(ideController)
|
||||||
.memoryMB(512).controller(ideController).cleanUpMode(mode)
|
.cleanUpMode(mode).osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build();
|
||||||
.osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build();
|
|
||||||
unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification));
|
undoVm(launchSpecification);
|
||||||
//new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification).apply(manager.getVBox().findMachine(vmName));
|
|
||||||
try {
|
try {
|
||||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir)
|
context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(
|
||||||
.apply(launchSpecification);
|
launchSpecification);
|
||||||
fail();
|
fail();
|
||||||
} catch (VBoxException e) {
|
} catch (VBoxException e) {
|
||||||
ErrorCode errorCode = ErrorCode.valueOf(e);
|
ErrorCode errorCode = ErrorCode.valueOf(e);
|
||||||
// According to the documentation VBOX_E_OBJECT_NOT_FOUND
|
// According to the documentation VBOX_E_OBJECT_NOT_FOUND
|
||||||
// if osTypeId is not found.
|
// if osTypeId is not found.
|
||||||
assertEquals(errorCode, ErrorCode.VBOX_E_OBJECT_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.VBoxException;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
|
import com.google.common.base.Suppliers;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Mattias Holmqvist
|
* @author Mattias Holmqvist
|
||||||
*/
|
*/
|
||||||
|
@ -86,7 +88,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
replay(manager, createdMachine, vBox, session);
|
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);
|
verify(manager, createdMachine, vBox, session);
|
||||||
}
|
}
|
||||||
|
@ -107,7 +109,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").memoryMB(1024).cleanUpMode(
|
VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").memoryMB(1024).cleanUpMode(
|
||||||
CleanupMode.Full).build();
|
CleanupMode.Full).build();
|
||||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, "/tmp/workingDir").apply(launchSpecification);
|
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(launchSpecification);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expectedExceptions = VBoxException.class)
|
@Test(expectedExceptions = VBoxException.class)
|
||||||
|
@ -129,7 +131,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full)
|
VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full)
|
||||||
.memoryMB(1024).build();
|
.memoryMB(1024).build();
|
||||||
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, "/tmp/workingDir").apply(launchSpecification);
|
new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(launchSpecification);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -44,10 +44,13 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
|
||||||
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-1.vdi";
|
String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-1.vdi";
|
||||||
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
|
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
|
||||||
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||||
manager.getVBox().findMedium(path, DeviceType.HardDisk);
|
manager.get().getVBox().findMedium(path, DeviceType.HardDisk);
|
||||||
|
try {
|
||||||
assertFileCanBeDeleted(path);
|
assertFileCanBeDeleted(path);
|
||||||
|
} finally {
|
||||||
deleteMediumAndBlockUntilComplete(iMedium);
|
deleteMediumAndBlockUntilComplete(iMedium);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateMediumFailWhenUsingNonFullyQualifiedPath() throws Exception {
|
public void testCreateMediumFailWhenUsingNonFullyQualifiedPath() throws Exception {
|
||||||
|
@ -68,9 +71,12 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient
|
||||||
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
|
HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build();
|
||||||
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||||
iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
||||||
manager.getVBox().findMedium(path, DeviceType.HardDisk);
|
manager.get().getVBox().findMedium(path, DeviceType.HardDisk);
|
||||||
|
try {
|
||||||
assertFileCanBeDeleted(path);
|
assertFileCanBeDeleted(path);
|
||||||
|
} finally {
|
||||||
deleteMediumAndBlockUntilComplete(iMedium);
|
deleteMediumAndBlockUntilComplete(iMedium);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -42,6 +42,7 @@ import org.virtualbox_4_1.LockType;
|
||||||
import org.virtualbox_4_1.VBoxException;
|
import org.virtualbox_4_1.VBoxException;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
|
import com.google.common.base.Suppliers;
|
||||||
import com.google.common.collect.ImmutableList;
|
import com.google.common.collect.ImmutableList;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -51,14 +52,11 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
private String adminDiskPath;
|
private String adminDiskPath;
|
||||||
private String diskFormat;
|
private String diskFormat;
|
||||||
private String diskName;
|
|
||||||
|
|
||||||
|
|
||||||
@BeforeMethod
|
@BeforeMethod
|
||||||
public void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
|
adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi";
|
||||||
diskFormat = "vdi";
|
diskFormat = "vdi";
|
||||||
diskName = "diskName";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -87,7 +85,7 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
replay(manager, machine, vBox, medium);
|
replay(manager, machine, vBox, medium);
|
||||||
|
|
||||||
new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
|
||||||
|
|
||||||
verify(machine, vBox);
|
verify(machine, vBox);
|
||||||
|
|
||||||
|
@ -113,14 +111,15 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
replay(manager, machine, vBox, medium, newHardDisk, progress);
|
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);
|
verify(machine, vBox, medium);
|
||||||
assertNotSame(newDisk, medium);
|
assertNotSame(newDisk, medium);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwriteAndStillAttachedDetachesOldThing() throws Exception {
|
public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwriteAndStillAttachedDetachesOldThing()
|
||||||
|
throws Exception {
|
||||||
HardDisk hardDisk = createTestHardDisk();
|
HardDisk hardDisk = createTestHardDisk();
|
||||||
|
|
||||||
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
|
VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class);
|
||||||
|
@ -134,7 +133,6 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
||||||
expect(manager.getVBox()).andReturn(vBox).anyTimes();
|
expect(manager.getVBox()).andReturn(vBox).anyTimes();
|
||||||
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(medium);
|
expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(medium);
|
||||||
|
|
||||||
|
|
||||||
String oldMachineId = "a1e03931-29f3-4370-ada3-9547b1009212";
|
String oldMachineId = "a1e03931-29f3-4370-ada3-9547b1009212";
|
||||||
String oldMachineName = "oldMachine";
|
String oldMachineName = "oldMachine";
|
||||||
IMachine oldMachine = createMock(IMachine.class);
|
IMachine oldMachine = createMock(IMachine.class);
|
||||||
|
@ -180,7 +178,7 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
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);
|
assertNotSame(newDisk, medium);
|
||||||
|
@ -202,7 +200,7 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
replay(manager, machine, vBox, medium, newHardDisk, progress);
|
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)
|
@Test(expectedExceptions = VBoxException.class)
|
||||||
|
@ -227,7 +225,7 @@ public class CreateMediumIfNotAlreadyExistsTest {
|
||||||
|
|
||||||
replay(manager, machine, vBox, medium);
|
replay(manager, machine, vBox, medium);
|
||||||
|
|
||||||
new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk);
|
new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk);
|
||||||
}
|
}
|
||||||
|
|
||||||
private HardDisk createTestHardDisk() {
|
private HardDisk createTestHardDisk() {
|
||||||
|
|
|
@ -33,6 +33,8 @@ import org.virtualbox_4_1.IMachine;
|
||||||
import org.virtualbox_4_1.IVirtualBox;
|
import org.virtualbox_4_1.IVirtualBox;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
|
import com.google.common.base.Suppliers;
|
||||||
|
|
||||||
@Test(groups = "unit")
|
@Test(groups = "unit")
|
||||||
public class IMachineToHardwareTest {
|
public class IMachineToHardwareTest {
|
||||||
|
|
||||||
|
@ -57,7 +59,7 @@ public class IMachineToHardwareTest {
|
||||||
|
|
||||||
replay(vbm, vBox, vm, guestOsType);
|
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.getId(), machineId);
|
||||||
assertEquals(hardware.getProviderId(), 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.IVirtualBox;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
|
import com.google.common.base.Suppliers;
|
||||||
import com.google.inject.Guice;
|
import com.google.inject.Guice;
|
||||||
|
|
||||||
@Test(groups = "unit")
|
@Test(groups = "unit")
|
||||||
|
@ -67,7 +68,7 @@ public class IMachineToImageTest {
|
||||||
|
|
||||||
replay(vbm, vBox, vm, guestOsType);
|
replay(vbm, vBox, vm, guestOsType);
|
||||||
|
|
||||||
IMachineToImage fn = new IMachineToImage(vbm, map);
|
IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map);
|
||||||
|
|
||||||
Image image = fn.apply(vm);
|
Image image = fn.apply(vm);
|
||||||
|
|
||||||
|
@ -98,7 +99,7 @@ public class IMachineToImageTest {
|
||||||
|
|
||||||
replay(vbm, vBox, vm, guestOsType);
|
replay(vbm, vBox, vm, guestOsType);
|
||||||
|
|
||||||
IMachineToImage fn = new IMachineToImage(vbm, map);
|
IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map);
|
||||||
|
|
||||||
Image image = fn.apply(vm);
|
Image image = fn.apply(vm);
|
||||||
|
|
||||||
|
@ -129,7 +130,9 @@ public class IMachineToImageTest {
|
||||||
|
|
||||||
replay(vbm, vBox, vm, guestOsType);
|
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().getDescription(), "SomeOtherOs 2.04");
|
||||||
assertEquals(image.getOperatingSystem().getVersion(), "");
|
assertEquals(image.getOperatingSystem().getVersion(), "");
|
||||||
|
|
|
@ -31,6 +31,7 @@ import org.testng.annotations.Test;
|
||||||
import org.virtualbox_4_1.MachineState;
|
import org.virtualbox_4_1.MachineState;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
|
import com.google.common.base.Suppliers;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
||||||
|
|
||||||
public class IMachineToNodeMetadataTest {
|
public class IMachineToNodeMetadataTest {
|
||||||
|
@ -47,7 +48,7 @@ public class IMachineToNodeMetadataTest {
|
||||||
|
|
||||||
VirtualBox virtualBox = new VirtualBox();
|
VirtualBox virtualBox = new VirtualBox();
|
||||||
IMachineToNodeMetadata parser = new IMachineToNodeMetadata();
|
IMachineToNodeMetadata parser = new IMachineToNodeMetadata();
|
||||||
IMachineToHardware hwParser = new IMachineToHardware(manager);
|
IMachineToHardware hwParser = new IMachineToHardware(Suppliers.ofInstance(manager));
|
||||||
|
|
||||||
// hwParser.apply()
|
// hwParser.apply()
|
||||||
|
|
||||||
|
|
|
@ -19,15 +19,12 @@
|
||||||
|
|
||||||
package org.jclouds.virtualbox.functions;
|
package org.jclouds.virtualbox.functions;
|
||||||
|
|
||||||
import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest;
|
|
||||||
import static org.jclouds.virtualbox.functions.RetrieveActiveBridgedInterfaces.retrieveBridgedInterfaceNames;
|
import static org.jclouds.virtualbox.functions.RetrieveActiveBridgedInterfaces.retrieveBridgedInterfaceNames;
|
||||||
import static org.testng.Assert.assertEquals;
|
import static org.testng.Assert.assertEquals;
|
||||||
import static org.testng.Assert.assertFalse;
|
import static org.testng.Assert.assertFalse;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.jclouds.compute.ComputeServiceContext;
|
|
||||||
import org.jclouds.domain.Credentials;
|
|
||||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
|
|
||||||
|
@ -40,34 +37,19 @@ import com.google.common.collect.ImmutableList;
|
||||||
public class RetrieveActiveBridgedInterfacesLiveTest extends BaseVirtualBoxClientLiveTest {
|
public class RetrieveActiveBridgedInterfacesLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||||
|
|
||||||
public static final String TEST1 = "Name: eth0\n"
|
public static final String TEST1 = "Name: eth0\n"
|
||||||
+ "GUID: 30687465-0000-4000-8000-00261834d0cb\n"
|
+ "GUID: 30687465-0000-4000-8000-00261834d0cb\n" + "Dhcp: Disabled\n"
|
||||||
+ "Dhcp: Disabled\n"
|
+ "IPAddress: 209.x.x.x\n" + "NetworkMask: 255.255.255.0\n"
|
||||||
+ "IPAddress: 209.x.x.x\n"
|
+ "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n" + "IPV6NetworkMaskPrefixLength: 64\n"
|
||||||
+ "NetworkMask: 255.255.255.0\n"
|
+ "HardwareAddress: 00:26:18:34:d0:cb\n" + "MediumType: Ethernet\n" + "Status: Up\n"
|
||||||
+ "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n"
|
+ "VBoxNetworkName: HostInterfaceNetworking-eth0\n" + "\n" + "Name: vbox0\n"
|
||||||
+ "IPV6NetworkMaskPrefixLength: 64\n"
|
+ "GUID: 786f6276-0030-4000-8000-5a3ded993fed\n" + "Dhcp: Disabled\n"
|
||||||
+ "HardwareAddress: 00:26:18:34:d0:cb\n"
|
+ "IPAddress: 192.168.56.1\n" + "NetworkMask: 255.255.255.0\n"
|
||||||
+ "MediumType: Ethernet\n"
|
+ "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n" + "IPV6NetworkMaskPrefixLength: 0\n"
|
||||||
+ "Status: Up\n"
|
+ "HardwareAddress: 5a:3d:ed:99:3f:ed\n" + "MediumType: Ethernet\n" + "Status: Down\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";
|
+ "VBoxNetworkName: HostInterfaceNetworking-vbox0\n";
|
||||||
|
|
||||||
public static final List<String> expectedBridgedInterfaces = ImmutableList.of("eth0", "vbox0");
|
public static final List<String> expectedBridgedInterfaces = ImmutableList.of("eth0", "vbox0");
|
||||||
|
|
||||||
private String guestId = "guest";
|
|
||||||
private String hostId = "host";
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void retrieveBridgedInterfaceNamesTest() {
|
public void retrieveBridgedInterfaceNamesTest() {
|
||||||
List<String> activeBridgedInterfaceNames = retrieveBridgedInterfaceNames(TEST1);
|
List<String> activeBridgedInterfaceNames = retrieveBridgedInterfaceNames(TEST1);
|
||||||
|
@ -76,10 +58,8 @@ public class RetrieveActiveBridgedInterfacesLiveTest extends BaseVirtualBoxClien
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void retrieveAvailableBridgedInterfaceInfoTest() {
|
public void retrieveAvailableBridgedInterfaceInfoTest() {
|
||||||
ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(
|
List<String> bridgedInterface = context.utils().injector().getInstance(RetrieveActiveBridgedInterfaces.class)
|
||||||
hostId, "localhost", guestId, "localhost", new Credentials("toor",
|
.apply(host.get());
|
||||||
"password"));
|
|
||||||
List<String> bridgedInterface = new RetrieveActiveBridgedInterfaces(localHostContext).apply(hostId);
|
|
||||||
assertFalse(bridgedInterface.isEmpty());
|
assertFalse(bridgedInterface.isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -33,6 +33,8 @@ import org.virtualbox_4_1.ISnapshot;
|
||||||
import org.virtualbox_4_1.IVirtualBox;
|
import org.virtualbox_4_1.IVirtualBox;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
import org.virtualbox_4_1.VirtualBoxManager;
|
||||||
|
|
||||||
|
import com.google.common.base.Suppliers;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Andrea Turli
|
* @author Andrea Turli
|
||||||
*/
|
*/
|
||||||
|
@ -64,7 +66,7 @@ public class TakeSnapshotIfNotAlreadyAttachedTest {
|
||||||
session.unlockMachine();
|
session.unlockMachine();
|
||||||
replay(manager, machine, vBox, session, console, progress);
|
replay(manager, machine, vBox, session, console, progress);
|
||||||
|
|
||||||
new TakeSnapshotIfNotAlreadyAttached(manager, snapshotName, snapshotDesc)
|
new TakeSnapshotIfNotAlreadyAttached(Suppliers.ofInstance(manager), snapshotName, snapshotDesc)
|
||||||
.apply(machine);
|
.apply(machine);
|
||||||
|
|
||||||
verify(machine);
|
verify(machine);
|
||||||
|
@ -94,7 +96,7 @@ public class TakeSnapshotIfNotAlreadyAttachedTest {
|
||||||
session.unlockMachine();
|
session.unlockMachine();
|
||||||
replay(manager, machine, vBox, session, console, progress);
|
replay(manager, machine, vBox, session, console, progress);
|
||||||
|
|
||||||
new TakeSnapshotIfNotAlreadyAttached(manager, snapshotName, snapshotDesc)
|
new TakeSnapshotIfNotAlreadyAttached(Suppliers.ofInstance(manager), snapshotName, snapshotDesc)
|
||||||
.apply(machine);
|
.apply(machine);
|
||||||
|
|
||||||
verify(machine);
|
verify(machine);
|
||||||
|
|
|
@ -25,29 +25,34 @@ import static org.easymock.classextension.EasyMock.replay;
|
||||||
import static org.easymock.classextension.EasyMock.verify;
|
import static org.easymock.classextension.EasyMock.verify;
|
||||||
import static org.testng.Assert.assertEquals;
|
import static org.testng.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
|
||||||
import org.eclipse.jetty.server.Server;
|
import org.eclipse.jetty.server.Server;
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Andrea Turli
|
* @author Andrea Turli, Adrian Cole
|
||||||
*/
|
*/
|
||||||
@Test(groups = "unit", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningTest")
|
@Test(groups = "unit", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningTest")
|
||||||
public class StartJettyIfNotAlreadyRunningTest {
|
public class StartJettyIfNotAlreadyRunningTest {
|
||||||
|
|
||||||
private String basebaseResource = ".";
|
|
||||||
private int port = 8080;
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testLaunchJettyServerWhenAlreadyRunningDoesntLaunchAgain() {
|
public void testLaunchJettyServerWhenAlreadyRunningDoesntLaunchAgain() {
|
||||||
Server jetty = createMock(Server.class);
|
Server jetty = createMock(Server.class);
|
||||||
|
|
||||||
|
String preconfigurationUrl = "http://foo:8080";
|
||||||
|
|
||||||
expect(jetty.getState()).andReturn(Server.STARTED);
|
expect(jetty.getState()).andReturn(Server.STARTED);
|
||||||
replay(jetty);
|
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);
|
verify(jetty);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testLaunchJettyServerWhenNotRunningStartsJettyOnCorrectHostPortAndBasedir() {
|
public void testLaunchJettyServerWhenNotRunningStartsJettyOnCorrectHostPortAndBasedir() {
|
||||||
// TODO: all yours!
|
// TODO: all yours!
|
||||||
|
|
|
@ -19,147 +19,92 @@
|
||||||
|
|
||||||
package org.jclouds.virtualbox.functions.admin;
|
package org.jclouds.virtualbox.functions.admin;
|
||||||
|
|
||||||
import com.google.common.base.Predicate;
|
import static org.easymock.EasyMock.expect;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import static org.easymock.classextension.EasyMock.createMock;
|
||||||
import com.google.common.collect.Iterables;
|
import static org.easymock.classextension.EasyMock.replay;
|
||||||
import com.google.inject.AbstractModule;
|
import static org.easymock.classextension.EasyMock.verify;
|
||||||
import com.google.inject.Module;
|
import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;
|
||||||
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 java.net.URI;
|
import java.net.URI;
|
||||||
|
|
||||||
import static org.easymock.EasyMock.expect;
|
import org.jclouds.compute.callables.RunScriptOnNode;
|
||||||
import static org.easymock.classextension.EasyMock.*;
|
import org.jclouds.compute.callables.RunScriptOnNode.Factory;
|
||||||
import static org.testng.Assert.assertEquals;
|
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")
|
@Test(groups = "unit", singleThreaded = true, testName = "StartVBoxIfNotAlreadyRunningTest")
|
||||||
public class 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")
|
@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);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testStartVboxConnectsToManagerWhenPortAlreadyListening() throws Exception {
|
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);
|
VirtualBoxManager manager = createMock(VirtualBoxManager.class);
|
||||||
|
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(client.apply(new IPSocket(provider.getHost(), provider.getPort()))).andReturn(true);
|
||||||
|
|
||||||
|
manager.connect(provider.toASCIIString(), identity, credential);
|
||||||
|
|
||||||
|
replay(manager, runScriptOnNodeFactory, client);
|
||||||
|
|
||||||
|
new StartVBoxIfNotAlreadyRunning((Function) Functions.constant(manager), runScriptOnNodeFactory, client,
|
||||||
|
Suppliers.ofInstance(host), provider, identity, credential).start();
|
||||||
|
|
||||||
|
verify(manager, runScriptOnNodeFactory, client);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
Predicate<IPSocket> socketTester = createMock(Predicate.class);
|
|
||||||
URI endpointUri = URI.create("http://localhost:18083/");
|
|
||||||
Credentials localhostCredentials = new Credentials("toor", "password");
|
|
||||||
|
|
||||||
expect(socketTester.apply(new IPSocket(endpointUri.getHost(), endpointUri.getPort()))).andReturn(true);
|
|
||||||
manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential);
|
|
||||||
|
|
||||||
replay(socketTester);
|
|
||||||
replay(manager);
|
|
||||||
|
|
||||||
assertEquals(
|
|
||||||
new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials)
|
|
||||||
.apply(endpointUri),
|
|
||||||
manager);
|
|
||||||
|
|
||||||
verify(socketTester);
|
|
||||||
verify(manager);
|
|
||||||
}
|
|
||||||
|
|
||||||
@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);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testStartVboxDisablesPasswordAccessOnWebsrvauthlibraryStartsVboxwebsrvInBackgroundAndConnectsManagerWhenPortIsNotListening()
|
public void testStartVboxDisablesPasswordAccessOnWebsrvauthlibraryStartsVboxwebsrvInBackgroundAndConnectsManagerWhenPortIsNotListening()
|
||||||
throws Exception {
|
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();
|
|
||||||
|
|
||||||
VirtualBoxManager manager = createMock(VirtualBoxManager.class);
|
VirtualBoxManager manager = createMock(VirtualBoxManager.class);
|
||||||
@SuppressWarnings("unchecked")
|
Factory runScriptOnNodeFactory = createMock(Factory.class);
|
||||||
Predicate<IPSocket> socketTester = createMock(Predicate.class);
|
RetryIfSocketNotYetOpen client = createMock(RetryIfSocketNotYetOpen.class);
|
||||||
Credentials localhostCredentials = new Credentials("toor", "password");
|
RunScriptOnNode runScriptOnNode = createMock(RunScriptOnNode.class);
|
||||||
URI endpointUri = URI.create("http://localhost:18083/");
|
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));
|
||||||
|
|
||||||
manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential);
|
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));
|
||||||
|
|
||||||
replay(socketTester);
|
manager.connect(provider.toASCIIString(), identity, credential);
|
||||||
replay(manager);
|
|
||||||
|
|
||||||
assertEquals(
|
replay(manager, runScriptOnNodeFactory, runScriptOnNode, client);
|
||||||
new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials)
|
new StartVBoxIfNotAlreadyRunning((Function) Functions.constant(manager), runScriptOnNodeFactory, client,
|
||||||
.apply(endpointUri),
|
Suppliers.ofInstance(host), provider, identity, credential).start();
|
||||||
manager);
|
verify(manager, runScriptOnNodeFactory, runScriptOnNode, client);
|
||||||
|
|
||||||
verify(socketTester);
|
|
||||||
verify(manager);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -19,10 +19,8 @@
|
||||||
|
|
||||||
package org.jclouds.virtualbox.predicates;
|
package org.jclouds.virtualbox.predicates;
|
||||||
|
|
||||||
import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApplyOrReturnNullIfNotRegistered;
|
|
||||||
import static org.testng.Assert.assertFalse;
|
import static org.testng.Assert.assertFalse;
|
||||||
import static org.testng.Assert.assertTrue;
|
import static org.testng.Assert.assertTrue;
|
||||||
import static org.virtualbox_4_1.LockType.Write;
|
|
||||||
|
|
||||||
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest;
|
||||||
import org.jclouds.virtualbox.domain.HardDisk;
|
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.domain.VmSpec;
|
||||||
import org.jclouds.virtualbox.functions.CloneAndRegisterMachineFromIMachineIfNotAlreadyExists;
|
import org.jclouds.virtualbox.functions.CloneAndRegisterMachineFromIMachineIfNotAlreadyExists;
|
||||||
import org.jclouds.virtualbox.functions.CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
|
import org.jclouds.virtualbox.functions.CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
|
||||||
import org.jclouds.virtualbox.functions.IMachineToVmSpec;
|
import org.testng.annotations.AfterMethod;
|
||||||
import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia;
|
|
||||||
import org.testng.annotations.BeforeClass;
|
import org.testng.annotations.BeforeClass;
|
||||||
|
import org.testng.annotations.BeforeMethod;
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
import org.virtualbox_4_1.CleanupMode;
|
import org.virtualbox_4_1.CleanupMode;
|
||||||
import org.virtualbox_4_1.IMachine;
|
import org.virtualbox_4_1.IMachine;
|
||||||
import org.virtualbox_4_1.StorageBus;
|
import org.virtualbox_4_1.StorageBus;
|
||||||
import org.virtualbox_4_1.VirtualBoxManager;
|
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
||||||
|
|
||||||
|
@ -78,29 +75,28 @@ public class IsLinkedClonesLiveTest extends BaseVirtualBoxClientLiveTest {
|
||||||
@Test
|
@Test
|
||||||
public void testLinkedClone() {
|
public void testLinkedClone() {
|
||||||
|
|
||||||
VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
|
IMachine master = context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
|
||||||
lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, masterSpec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(masterSpec));
|
.apply(masterSpec);
|
||||||
|
|
||||||
IMachine master = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir).apply(masterSpec);
|
|
||||||
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec,
|
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec,
|
||||||
IS_LINKED_CLONE).apply(master);
|
IS_LINKED_CLONE).apply(master);
|
||||||
|
|
||||||
assertTrue(new IsLinkedClone(manager).apply(clone));
|
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() {
|
public void testFullClone() {
|
||||||
|
IMachine master = context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class)
|
||||||
VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi();
|
.apply(masterSpec);
|
||||||
lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, masterSpec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(masterSpec));
|
|
||||||
|
|
||||||
IMachine master = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir).apply(masterSpec);
|
|
||||||
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec,
|
IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec,
|
||||||
!IS_LINKED_CLONE).apply(master);
|
!IS_LINKED_CLONE).apply(master);
|
||||||
|
|
||||||
assertFalse(new IsLinkedClone(manager).apply(clone));
|
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