From b2a9313c855ecd4fe869c2f6a9108233250f9262 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 7 Jan 2012 06:11:01 -0800 Subject: [PATCH] refactored config handling in virtualbox and cleaned up classes --- sandbox-apis/virtualbox/pom.xml | 4 +- .../jclouds/virtualbox/Preconfiguration.java | 39 ++++ .../virtualbox/VirtualBoxContextBuilder.java | 7 +- .../VirtualBoxPropertiesBuilder.java | 41 ++-- .../VirtualBoxComputeServiceAdapter.java | 47 +++-- ...VirtualBoxComputeServiceContextModule.java | 130 +++++++++--- .../config/VirtualBoxConstants.java | 14 +- .../jclouds/virtualbox/domain/NatAdapter.java | 16 +- .../virtualbox/domain/RedirectRule.java | 10 +- .../AddIDEControllerIfNotExists.java | 1 - ...MachineFromIMachineIfNotAlreadyExists.java | 13 +- .../functions/CreateAndInstallVm.java | 194 +++++------------- ...isterMachineFromIsoIfNotAlreadyExists.java | 31 ++- .../CreateMediumIfNotAlreadyExists.java | 37 ++-- .../functions/IMachineToHardware.java | 7 +- .../virtualbox/functions/IMachineToImage.java | 7 +- .../functions/IMachineToNodeMetadata.java | 22 +- .../functions/IMachineToSshClient.java | 66 ++++++ .../RetrieveActiveBridgedInterfaces.java | 28 +-- .../TakeSnapshotIfNotAlreadyAttached.java | 7 +- .../functions/admin/FileDownloadFromURI.java | 17 +- .../admin/StartJettyIfNotAlreadyRunning.java | 83 ++++---- .../admin/StartVBoxIfNotAlreadyRunning.java | 98 +++++---- ...isterMachineIfExistsAndDeleteItsMedia.java | 24 +-- .../virtualbox/predicates/IsLinkedClone.java | 11 +- .../virtualbox/predicates/SshResponds.java | 52 +++++ .../jclouds/virtualbox/util/MachineUtils.java | 41 ++-- .../BaseVirtualBoxClientLiveTest.java | 85 ++++---- ...rtualBoxComputeServiceAdapterLiveTest.java | 26 +-- .../VirtualBoxComputeServiceAdapterTest.java | 5 +- .../virtualbox/experiment/TestUtils.java | 93 --------- ...diumToMachineIfNotAlreadyAttachedTest.java | 1 - ...dapterToMachineIfNotAlreadyExistsTest.java | 10 +- ...hineFromIsoIfNotAlreadyExistsLiveTest.java | 94 ++++----- .../functions/CreateAndInstallVmLiveTest.java | 45 ++-- ...hineFromIsoIfNotAlreadyExistsLiveTest.java | 55 +++-- ...rMachineFromIsoIfNotAlreadyExistsTest.java | 8 +- ...reateMediumIfNotAlreadyExistsLiveTest.java | 24 ++- .../CreateMediumIfNotAlreadyExistsTest.java | 22 +- .../functions/IMachineToHardwareTest.java | 4 +- .../functions/IMachineToImageTest.java | 9 +- .../functions/IMachineToNodeMetadataTest.java | 3 +- ...trieveActiveBridgedInterfacesLiveTest.java | 52 ++--- .../TakeSnapshotIfNotAlreadyAttachedTest.java | 6 +- .../StartJettyIfNotAlreadyRunningTest.java | 17 +- .../StartVBoxIfNotAlreadyRunningTest.java | 183 ++++++----------- .../predicates/IsLinkedClonesLiveTest.java | 32 ++- .../predicates/SshAvailableLiveTest.java | 92 --------- 48 files changed, 909 insertions(+), 1004 deletions(-) create mode 100644 sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/Preconfiguration.java create mode 100644 sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java create mode 100644 sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/predicates/SshResponds.java delete mode 100644 sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java delete mode 100644 sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/SshAvailableLiveTest.java diff --git a/sandbox-apis/virtualbox/pom.xml b/sandbox-apis/virtualbox/pom.xml index cdc25af787..13a1cdd81b 100644 --- a/sandbox-apis/virtualbox/pom.xml +++ b/sandbox-apis/virtualbox/pom.xml @@ -40,8 +40,8 @@ administrator 12345 ubuntu-11.04-server-i386 - - + toor:password + true diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/Preconfiguration.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/Preconfiguration.java new file mode 100644 index 0000000000..03bbcbe5ac --- /dev/null +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/Preconfiguration.java @@ -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 { + +} \ No newline at end of file diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxContextBuilder.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxContextBuilder.java index 5a1ce5638d..1b7d6d43e6 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxContextBuilder.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxContextBuilder.java @@ -24,8 +24,8 @@ import java.util.Properties; import org.jclouds.compute.StandaloneComputeServiceContextBuilder; import org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule; -import org.virtualbox_4_1.VirtualBoxManager; +import com.google.common.base.Supplier; import com.google.inject.Module; /** @@ -33,10 +33,11 @@ import com.google.inject.Module; * * @author Mattias Holmqvist, Andrea Turli */ -public class VirtualBoxContextBuilder extends StandaloneComputeServiceContextBuilder { +@SuppressWarnings("unchecked") +public class VirtualBoxContextBuilder extends StandaloneComputeServiceContextBuilder { public VirtualBoxContextBuilder(Properties properties) { - super(VirtualBoxManager.class, properties); + super(Supplier.class, properties); } @Override diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxPropertiesBuilder.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxPropertiesBuilder.java index 2bf4ca7d37..7b2014b818 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxPropertiesBuilder.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxPropertiesBuilder.java @@ -29,8 +29,8 @@ import java.io.File; import java.util.Properties; import org.jclouds.PropertiesBuilder; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.virtualbox.config.VirtualBoxConstants; +import static org.jclouds.compute.reference.ComputeServiceConstants.*; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.*; /** * Builds properties for VirtualBox integration. @@ -56,27 +56,28 @@ public class VirtualBoxPropertiesBuilder extends PropertiesBuilder { properties.put(PROPERTY_BUILD_VERSION, "4.1.8r75467"); properties.put(PROPERTY_IDENTITY, "administrator"); properties.put(PROPERTY_CREDENTIAL, "12345"); - properties.put(ComputeServiceConstants.PROPERTY_IMAGE_ID, "ubuntu-11.04-server-i386"); - properties.put(VirtualBoxConstants.VIRTUALBOX_PRESEED_URL, "http://dl.dropbox.com/u/693111/preseed.cfg"); - properties.put(VirtualBoxConstants.VIRTUALBOX_SNAPSHOT_DESCRIPTION, "jclouds-virtualbox-snaphot"); - properties.put(VirtualBoxConstants.VIRTUALBOX_HOSTNAME, "jclouds-virtualbox-kickstart-admin"); - properties - .put(VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, - " " - + "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg " - + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " - + "hostname=" - + properties.get(VirtualBoxConstants.VIRTUALBOX_HOSTNAME) - + " " - + "fb=false debconf/frontend=noninteractive " - + "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false " - + "initrd=/install/initrd.gz -- "); - properties.put(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR, System.getProperty("user.home") + File.separator - + System.getProperty("test.virtualbox.workingDir", "jclouds-virtualbox-test")); + properties.put(PROPERTY_IMAGE_ID, "ubuntu-11.04-server-i386"); + properties.put(PROPERTY_IMAGE_LOGIN_USER, "toor:password"); + properties.put(PROPERTY_IMAGE_AUTHENTICATE_SUDO, "true"); + + properties.put(VIRTUALBOX_ISO_URL, "http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso"); + properties.put(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, " " + + "/install/vmlinuz noapic preseed/url=PRECONFIGURATION_URL " + + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + "HOSTNAME " + + "fb=false debconf/frontend=noninteractive " + + "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false " + + "initrd=/install/initrd.gz -- "); + + properties.put(VIRTUALBOX_WORKINGDIR, System.getProperty("user.home") + File.separator + + System.getProperty("test.virtualbox.workingDir", "jclouds-virtualbox-test")); + + properties.put(VIRTUALBOX_PRECONFIGURATION_URL, "http://10.0.2.2:8080/src/test/resources/preseed.cfg"); + + - properties.put(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"); return properties; } + } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java index 3fb4ac2cf2..0207063859 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java @@ -24,8 +24,6 @@ import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.transform; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; -import java.util.Collections; - import javax.inject.Inject; import org.jclouds.compute.ComputeServiceAdapter; @@ -43,7 +41,9 @@ import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; import com.google.common.base.Predicate; +import com.google.common.base.Supplier; import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; import com.google.inject.Singleton; /** @@ -56,12 +56,12 @@ import com.google.inject.Singleton; @Singleton public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter { - private final VirtualBoxManager manager; + private final Supplier manager; private final JustProvider justProvider; - private Function iMachineToImage; + private final Function iMachineToImage; @Inject - public VirtualBoxComputeServiceAdapter(VirtualBoxManager manager, JustProvider justProvider, + public VirtualBoxComputeServiceAdapter(Supplier manager, JustProvider justProvider, Function iMachineToImage) { this.iMachineToImage = iMachineToImage; this.manager = checkNotNull(manager, "manager"); @@ -76,24 +76,35 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter listNodes() { - return Collections.emptyList(); + return Iterables.filter(manager.get().getVBox().getMachines(), new Predicate() { + + @Override + public boolean apply(IMachine arg0) { + return !arg0.getName().startsWith(VIRTUALBOX_IMAGE_PREFIX); + } + + }); } @Override public Iterable listHardwareProfiles() { - return manager.getVBox().getMachines(); + return imageMachines(); } @Override public Iterable listImages() { + return transform(imageMachines(), iMachineToImage); + } + + private Iterable imageMachines() { final Predicate imagePredicate = new Predicate() { @Override public boolean apply(@Nullable IMachine iMachine) { return iMachine.getName().startsWith(VIRTUALBOX_IMAGE_PREFIX); } }; - final Iterable imageMachines = filter(manager.getVBox().getMachines(), imagePredicate); - return transform(imageMachines, iMachineToImage); + final Iterable imageMachines = filter(manager.get().getVBox().getMachines(), imagePredicate); + return imageMachines; } @SuppressWarnings("unchecked") @@ -104,29 +115,29 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter { + ComputeServiceAdapterContextModule { public VirtualBoxComputeServiceContextModule() { - super(VirtualBoxManager.class, VirtualBoxManager.class); + super(Supplier.class, Supplier.class); } - @Provides - @Singleton - protected VirtualBoxManager createInstance(@Provider URI endpoint, - @Named(Constants.PROPERTY_IDENTITY) String identity, @Named(Constants.PROPERTY_CREDENTIAL) String credential) { - - VirtualBoxManager manager = VirtualBoxManager.createInstance(""); - manager.connect(endpoint.toASCIIString(), identity, credential); - return manager; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings( { "unchecked", "rawtypes" }) @Override protected void configure() { super.configure(); @@ -92,6 +98,53 @@ public class VirtualBoxComputeServiceContextModule extends }).to(IMachineToImage.class); bind(new TypeLiteral>() { }).to(OnlyLocationOrFirstZone.class); + + // for byon + bind(new TypeLiteral>() { + }).to(SupplyFromProviderURIOrNodesProperty.class); + + bind(new TypeLiteral>() { + }).to(IMachineToSshClient.class); + + bind(ExecutionType.class).toInstance(ExecutionType.HEADLESS); + } + + @Provides + @Singleton + @Preconfiguration + protected Supplier preconfiguration(javax.inject.Provider lazyGet) { + return lazyGet.get(); + } + + @Provides + @Singleton + protected Function, VirtualBoxManager> provideVBox(Supplier host) { + return new Function, VirtualBoxManager>(){ + + @Override + public VirtualBoxManager apply(Supplier arg0) { + return VirtualBoxManager.createInstance(arg0.get().getId()); + } + + }; + } + + @Provides + @Singleton + protected Supplier defaultClient(Supplier in) { + return in; + } + + @Provides + @Singleton + protected Supplier vbox(javax.inject.Provider lazyGet) { + return lazyGet.get(); + } + + @Provides + @Singleton + protected Predicate sshResponds(SshResponds sshResponds, Timeouts timeouts) { + return new RetryablePredicate(sshResponds, timeouts.nodeRunning); } @Override @@ -99,26 +152,37 @@ public class VirtualBoxComputeServiceContextModule extends return template.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04"); } + @Provides + @Singleton + protected Supplier host(Supplier> nodes, NodeToNodeMetadata converter) + throws ExecutionException { + return Suppliers.compose(Functions.compose(converter, new Function, Node>() { + + @Override + public Node apply(LoadingCache arg0) { + return arg0.apply("host"); + } + }), nodes); + } + @VisibleForTesting public static final Map machineToNodeState = ImmutableMap - . builder().put(MachineState.Running, NodeState.RUNNING) - .put(MachineState.PoweredOff, NodeState.SUSPENDED).put(MachineState.DeletingSnapshot, NodeState.PENDING) - .put(MachineState.DeletingSnapshotOnline, NodeState.PENDING) - .put(MachineState.DeletingSnapshotPaused, NodeState.PENDING) - .put(MachineState.FaultTolerantSyncing, NodeState.PENDING) - .put(MachineState.LiveSnapshotting, NodeState.PENDING) - .put(MachineState.SettingUp, NodeState.PENDING) - .put(MachineState.Starting, NodeState.PENDING) - .put(MachineState.Stopping, NodeState.PENDING) - .put(MachineState.Restoring, NodeState.PENDING) - // TODO What to map these states to? - .put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING) - .put(MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING) - .put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING) - .put(MachineState.TeleportingPausedVM, NodeState.PENDING) + . builder().put(MachineState.Running, NodeState.RUNNING).put( + MachineState.PoweredOff, NodeState.SUSPENDED) + .put(MachineState.DeletingSnapshot, NodeState.PENDING).put(MachineState.DeletingSnapshotOnline, + NodeState.PENDING).put(MachineState.DeletingSnapshotPaused, NodeState.PENDING).put( + MachineState.FaultTolerantSyncing, NodeState.PENDING).put(MachineState.LiveSnapshotting, + NodeState.PENDING).put(MachineState.SettingUp, NodeState.PENDING).put(MachineState.Starting, + NodeState.PENDING).put(MachineState.Stopping, NodeState.PENDING).put(MachineState.Restoring, + NodeState.PENDING) + // TODO What to map these states to? + .put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING).put( + MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING) + .put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING).put( + MachineState.TeleportingPausedVM, NodeState.PENDING) - .put(MachineState.Aborted, NodeState.ERROR).put(MachineState.Stuck, NodeState.ERROR) + .put(MachineState.Aborted, NodeState.ERROR).put(MachineState.Stuck, NodeState.ERROR) - .put(MachineState.Null, NodeState.UNRECOGNIZED).build(); + .put(MachineState.Null, NodeState.UNRECOGNIZED).build(); } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java index 6db1f1c237..5f949eca14 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java @@ -27,19 +27,15 @@ package org.jclouds.virtualbox.config; */ public interface VirtualBoxConstants { - public static final String VIRTUALBOX_IMAGE_PREFIX = "jclouds-image-"; + public static final String VIRTUALBOX_IMAGE_PREFIX = "jclouds#image#"; - public static final String VIRTUALBOX_PRESEED_URL = "jclouds.virtualbox.preseedurl"; - - public static final String VIRTUALBOX_SNAPSHOT_DESCRIPTION = "jclouds.virtualbox.snapshotDescription"; + public static final String VIRTUALBOX_PRECONFIGURATION_URL = "jclouds.virtualbox.preconfigurationurl"; public static final String VIRTUALBOX_INSTALLATION_KEY_SEQUENCE = "jclouds.virtualbox.installationkeysequence"; - public static final String VIRTUALBOX_HOSTNAME = "jclouds.virtualbox.hostname"; - public static final String VIRTUALBOX_WORKINGDIR = "jclouds.virtualbox.workingdir"; - public static final String VIRTUALBOX_ISOFILE = "jclouds.virtualbox.isofile"; + public static final String VIRTUALBOX_ISO_URL = "jclouds.virtualbox.isourl"; public static final String VIRTUALBOX_MACHINE_GROUP = "jclouds.virtualbox.machinegroup"; @@ -51,10 +47,6 @@ public interface VirtualBoxConstants { public static final String VIRTUALBOX_HOST_ID = "jclouds.virtualbox.hostid"; - public static final String VIRTUALBOX_JETTY_PORT = "jclouds.virtualbox.jetty.port"; - - public static final String VIRTUALBOX_JETTY_BASE_RESOURCE = "jclouds.virtualbox.jetty.baseresource"; - public static final String VIRTUALBOX_WEBSERVER_IDENTITY = "jclouds.virtualbox.webserver.identity"; public static final String VIRTUALBOX_WEBSERVER_CREDENTIAL = "jclouds.virtualbox.webserver.credential"; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/NatAdapter.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/NatAdapter.java index 18df5527b6..ac2dfae317 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/NatAdapter.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/NatAdapter.java @@ -50,11 +50,25 @@ public class NatAdapter { private Set redirectRules = Sets.newLinkedHashSet(); + /** + * @param host incoming address + * @param hostPort + * @param guest guest address or empty string for all addresses + * @param guestPort + * @return + */ public Builder tcpRedirectRule(String host, int hostPort, String guest, int guestPort) { redirectRules.add(new RedirectRule(NATProtocol.TCP, host, hostPort, guest, guestPort)); return this; } - + + /** + * @param host incoming address + * @param hostPort + * @param guest guest address or empty string for all addresses + * @param guestPort + * @return + */ public Builder udpRedirectRule(String host, int hostPort, String guest, int guestPort) { redirectRules.add(new RedirectRule(NATProtocol.UDP, host, hostPort, guest, guestPort)); return this; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/RedirectRule.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/RedirectRule.java index e52b3b9a98..fcc275b52c 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/RedirectRule.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/RedirectRule.java @@ -34,7 +34,15 @@ public class RedirectRule { private final int hostPort; private final String guest; private final int guestPort; - + + /** + * @param protocol + * @param host incoming address + * @param hostPort + * @param guest guest address or empty string for all addresses + * @param guestPort + * @return + */ public RedirectRule(NATProtocol protocol, String host, int hostPort, String guest, int guestPort) { checkNotNull(protocol); checkNotNull(host); diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AddIDEControllerIfNotExists.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AddIDEControllerIfNotExists.java index 21a61549d1..c048b9c92a 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AddIDEControllerIfNotExists.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AddIDEControllerIfNotExists.java @@ -23,7 +23,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import org.jclouds.virtualbox.domain.StorageController; import org.virtualbox_4_1.IMachine; -import org.virtualbox_4_1.StorageBus; import org.virtualbox_4_1.VBoxException; import com.google.common.base.Function; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.java index e3c8b7b922..adae172ff8 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.java @@ -39,6 +39,7 @@ import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; +import com.google.common.base.Supplier; import com.google.inject.Inject; /** @@ -53,13 +54,13 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private final VirtualBoxManager manager; + private final Supplier manager; private final String workingDir; private final VmSpec vmSpec; private final boolean isLinkedClone; @Inject - public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(VirtualBoxManager manager, + public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(Supplier manager, @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, VmSpec vmSpec, boolean isLinkedClone) { this.manager = manager; this.workingDir = workingDir; @@ -70,7 +71,7 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu @Override public IMachine apply(@Nullable IMachine master) { try { - manager.getVBox().findMachine(vmSpec.getVmName()); + manager.get().getVBox().findMachine(vmSpec.getVmName()); throw new IllegalStateException("Machine " + vmSpec.getVmName() + " is already registered."); } catch (VBoxException e) { if (machineNotFoundException(e)) @@ -85,8 +86,8 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu } private IMachine cloneMachine(VmSpec vmSpec, IMachine master) { - String settingsFile = manager.getVBox().composeMachineFilename(vmSpec.getVmName(), workingDir); - IMachine clonedMachine = manager.getVBox().createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(), + String settingsFile = manager.get().getVBox().composeMachineFilename(vmSpec.getVmName(), workingDir); + IMachine clonedMachine = manager.get().getVBox().createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(), vmSpec.getVmId(), vmSpec.isForceOverwrite()); List options = new ArrayList(); if (isLinkedClone) @@ -103,7 +104,7 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu logger.debug("clone done"); // registering - manager.getVBox().registerMachine(clonedMachine); + manager.get().getVBox().registerMachine(clonedMachine); return clonedMachine; } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java index a28f34da68..e5c08a3e10 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java @@ -19,133 +19,102 @@ package org.jclouds.virtualbox.functions; -import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; -import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; import static org.jclouds.virtualbox.util.MachineUtils.applyForMachine; -import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApply; import static org.jclouds.virtualbox.util.MachineUtils.lockSessionOnMachineAndApply; import static org.virtualbox_4_1.LockType.Shared; -import static org.virtualbox_4_1.LockType.Write; -import java.io.File; -import java.util.Map; -import java.util.Set; +import java.net.URI; import javax.annotation.Resource; import javax.inject.Named; +import javax.inject.Singleton; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.domain.ExecResponse; -import org.jclouds.compute.options.RunScriptOptions; +import org.jclouds.compute.callables.RunScriptOnNode; +import org.jclouds.compute.callables.RunScriptOnNode.Factory; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.logging.Logger; -import org.jclouds.net.IPSocket; -import org.jclouds.ssh.SshException; -import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.jclouds.virtualbox.domain.DeviceDetails; +import org.jclouds.scriptbuilder.domain.Statements; +import org.jclouds.ssh.SshClient; +import org.jclouds.virtualbox.Preconfiguration; import org.jclouds.virtualbox.domain.ExecutionType; -import org.jclouds.virtualbox.domain.HardDisk; -import org.jclouds.virtualbox.domain.IsoImage; -import org.jclouds.virtualbox.domain.NatAdapter; -import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.settings.KeyboardScancodes; -import org.virtualbox_4_1.AccessMode; -import org.virtualbox_4_1.DeviceType; import org.virtualbox_4_1.IMachine; -import org.virtualbox_4_1.IMedium; import org.virtualbox_4_1.IProgress; import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; import com.google.common.base.Predicate; +import com.google.common.base.Supplier; import com.google.inject.Inject; +@Singleton public class CreateAndInstallVm implements Function { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private final VirtualBoxManager manager; + private final Supplier manager; private final CreateAndRegisterMachineFromIsoIfNotAlreadyExists createAndRegisterMachineFromIsoIfNotAlreadyExists; - private String guestId; - private final ComputeServiceContext context; - private final String hostId; - private final Predicate socketTester; - private final String webServerHost; - private final int webServerPort; + private final ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull; + + private final Supplier preconfiguration; + private final Predicate sshResponds; private final ExecutionType executionType; + private final Factory scriptRunner; + private final Supplier host; + + private final Function sshClientForIMachine; + @Inject - public CreateAndInstallVm(VirtualBoxManager manager, + public CreateAndInstallVm(Supplier manager, CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists, - @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, String guestId, - ComputeServiceContext context, String hostId, Predicate socketTester, String webServerHost, - int webServerPort, ExecutionType executionType) { + ValueOfConfigurationKeyOrNull valueOfConfigurationKeyOrNull, Predicate sshResponds, + Function sshClientForIMachine, Supplier host, + RunScriptOnNode.Factory scriptRunner, @Preconfiguration Supplier preconfiguration, + ExecutionType executionType) { this.manager = manager; this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists; - this.guestId = guestId; - this.context = context; - this.hostId = hostId; - this.socketTester = socketTester; - this.webServerHost = webServerHost; - this.webServerPort = webServerPort; + this.valueOfConfigurationKeyOrNull = valueOfConfigurationKeyOrNull; + this.sshResponds = sshResponds; + this.sshClientForIMachine = sshClientForIMachine; + this.scriptRunner = scriptRunner; + this.host = host; + this.preconfiguration = preconfiguration; this.executionType = executionType; } @Override public IMachine apply(VmSpec vmSpec) { - - ensureWebServerIsRunning(); - - final IMachine vm =createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(vmSpec); - String vmName = vmSpec.getVmName(); - // Change RAM - ensureMachineHasMemory(vmName, vmSpec.getMemory()); + // note this may not be reachable, as this likely uses the 10.2.2 address + URI preconfigurationUri = preconfiguration.get(); + String keySequence = valueOfConfigurationKeyOrNull.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace( + "PRECONFIGURATION_URL", preconfigurationUri.toASCIIString()).replace("HOSTNAME", vmName); - Set controllers = vmSpec.getControllers(); - if (controllers.isEmpty()) { - throw new IllegalStateException(missingIDEControllersMessage(vmSpec)); - } - StorageController controller = controllers.iterator().next(); - ensureMachineHasIDEControllerNamed(vmName, controller); - setupHardDisksForController(vmName, controller); - setupDvdsForController(vmSpec, vmName, controller); - - // NAT - Map natNetworkAdapters = vmSpec.getNatNetworkAdapters(); - for (Map.Entry natAdapterAndSlot : natNetworkAdapters.entrySet()) { - long slotId = natAdapterAndSlot.getKey(); - NatAdapter natAdapter = natAdapterAndSlot.getValue(); - ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter); - } + final IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(vmSpec); // Launch machine and wait for it to come online ensureMachineIsLaunched(vmName); - final String installKeySequence = System.getProperty(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, defaultInstallSequence(vmName)); - sendKeyboardSequence(installKeySequence, vmName); + sendKeyboardSequence(keySequence, vmName); - boolean sshDeamonIsRunning = false; - while (!sshDeamonIsRunning) { - try { - if (runScriptOnNode(guestId, "id", wrapInInitScript(false).runAsRoot(false)).getExitCode() == 0) { - logger.debug("Got response from ssh daemon."); - sshDeamonIsRunning = true; - } - } catch (SshException e) { - logger.debug("No response from ssh daemon..."); - } - } + SshClient client = sshClientForIMachine.apply(vm); - logger.debug("Installation of image complete. Powering down..."); - lockSessionOnMachineAndApply(manager, Shared, vmName, new Function() { + logger.debug(">> awaiting installation to finish node(%s)", vmName); + checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", vmName); + + logger.debug("<< installation of image complete. Powering down node(%s)", vmName); + lockSessionOnMachineAndApply(manager.get(), Shared, vmName, new Function() { @Override public Void apply(ISession session) { @@ -158,70 +127,8 @@ public class CreateAndInstallVm implements Function { return vm; } - private void setupDvdsForController(VmSpec vmSpecification, String vmName, StorageController controller) { - Set 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 hardDisks = controller.getHardDisks(); - for (HardDisk hardDisk : hardDisks) { - String sourcePath = hardDisk.getDiskPath(); - if (new File(sourcePath).exists()) { - boolean deleted = new File(sourcePath).delete(); - if (!deleted) { - logger.error(String.format("File %s could not be deleted.", sourcePath)); - } - } - IMedium medium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk); - ensureMachineDevicesAttached(vmName, medium, hardDisk.getDeviceDetails(), controller.getName()); - } - } - - private String missingIDEControllersMessage(VmSpec vmSpecification) { - return String.format("First controller is not an IDE controller. Please verify that the VM spec is a correct master node: %s", vmSpecification); - } - - private void ensureWebServerIsRunning() { - final IPSocket webServerSocket = new IPSocket(webServerHost, webServerPort); - if (!socketTester.apply(webServerSocket)) { - throw new IllegalStateException(String.format("Web server is not running on host %s:%s which is needed to serve preseed.cfg.", webServerHost, webServerPort)); - } - } - - private void ensureMachineIsLaunched(String vmName) { - applyForMachine(manager, vmName, new LaunchMachineIfNotAlreadyRunning(manager, executionType, "")); - } - - private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails, String controllerName) { - lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium, controllerName)); - } - - private void ensureMachineHasMemory(String vmName, final long memorySize) { - lockMachineAndApply(manager, Write, vmName, new ApplyMemoryToMachine(memorySize)); - } - - private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, NatAdapter natAdapter) { - lockMachineAndApply(manager, Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter)); - } - - public void ensureMachineHasIDEControllerNamed(String vmName, StorageController storageController) { - lockMachineAndApply(manager, Write, checkNotNull(vmName, "vmName"), - new AddIDEControllerIfNotExists(checkNotNull(storageController, "storageController"))); - } - - private String defaultInstallSequence(String vmName) { - return " " - + "/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 -- "; + private void ensureMachineIsLaunched(String vmName) { + applyForMachine(manager.get(), vmName, new LaunchMachineIfNotAlreadyRunning(manager.get(), executionType, "")); } private void sendKeyboardSequence(String keyboardSequence, String vmName) { @@ -239,7 +146,7 @@ public class CreateAndInstallVm implements Function { private void runScriptIfWordEndsWith(StringBuilder sb, String word, String key) { if (word.endsWith(KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP.get(key))) { - runScriptOnNode(hostId, sb.toString(), runAsRoot(false).wrapInInitScript(false)); + scriptRunner.create(host.get(), Statements.exec(sb.toString()), runAsRoot(false).wrapInInitScript(false)).init().call(); sb.delete(0, sb.length() - 1); } } @@ -267,9 +174,4 @@ public class CreateAndInstallVm implements Function { return keycodes.toString(); } - - protected ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) { - return context.getComputeService().runScriptOnNode(nodeId, command, options); - } - } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java index 3cfdfd567d..5947b6ebe1 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java @@ -29,7 +29,9 @@ import java.util.Set; import javax.annotation.Nullable; import javax.annotation.Resource; +import javax.inject.Inject; import javax.inject.Named; +import javax.inject.Singleton; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; @@ -49,20 +51,23 @@ import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; +import com.google.common.base.Supplier; /** * @author Mattias Holmqvist */ +@Singleton public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private final VirtualBoxManager manager; + private final Supplier manager; private final String workingDir; - public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(VirtualBoxManager manager, + @Inject + public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Supplier manager, @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir) { this.manager = manager; this.workingDir = workingDir; @@ -70,7 +75,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi @Override public IMachine apply(@Nullable VmSpec launchSpecification) { - final IVirtualBox vBox = manager.getVBox(); + final IVirtualBox vBox = manager.get().getVBox(); String vmName = launchSpecification.getVmName(); try { vBox.findMachine(vmName); @@ -92,8 +97,12 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi IMachine newMachine = vBox.createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(), vmSpec.getVmId(), vmSpec.isForceOverwrite()); - manager.getVBox().registerMachine(newMachine); + manager.get().getVBox().registerMachine(newMachine); + ensureConfiguration(vmSpec); + return newMachine; + } + private void ensureConfiguration(VmSpec vmSpec) { String vmName = vmSpec.getVmName(); // Change RAM @@ -115,14 +124,13 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi NatAdapter natAdapter = natAdapterAndSlot.getValue(); ensureNATNetworkingIsAppliedToMachine(vmName, slotId, natAdapter); } - return newMachine; } private void setupDvdsForController(VmSpec vmSpecification, String vmName, StorageController controller) { Set dvds = controller.getIsoImages(); for (IsoImage dvd : dvds) { String dvdSource = dvd.getSourcePath(); - final IMedium dvdMedium = manager.getVBox().openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly, + final IMedium dvdMedium = manager.get().getVBox().openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly, vmSpecification.isForceOverwrite()); ensureMachineDevicesAttached(vmName, dvdMedium, dvd.getDeviceDetails(), controller.getName()); } @@ -130,7 +138,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails, String controllerName) { - lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium, + lockMachineAndApply(manager.get(), Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, medium, controllerName)); } @@ -157,15 +165,16 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi } private void ensureMachineHasMemory(String vmName, final long memorySize) { - lockMachineAndApply(manager, Write, vmName, new ApplyMemoryToMachine(memorySize)); + lockMachineAndApply(manager.get(), Write, vmName, new ApplyMemoryToMachine(memorySize)); } - private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, NatAdapter natAdapter) { - lockMachineAndApply(manager, Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter)); + private void ensureNATNetworkingIsAppliedToMachine(String vmName, long slotId, + NatAdapter natAdapter) { + lockMachineAndApply(manager.get(), Write, vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter)); } public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) { - lockMachineAndApply(manager, Write, checkNotNull(vmName, "vmName"), new AddIDEControllerIfNotExists(checkNotNull( + lockMachineAndApply(manager.get(), Write, checkNotNull(vmName, "vmName"), new AddIDEControllerIfNotExists(checkNotNull( storageController, "storageController"))); } } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExists.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExists.java index 46fa820079..d0b3f7cc4a 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExists.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExists.java @@ -26,6 +26,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; import org.jclouds.virtualbox.domain.HardDisk; import org.virtualbox_4_1.DeviceType; @@ -39,32 +41,36 @@ import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; import com.google.common.base.Predicate; +import com.google.common.base.Supplier; import com.google.common.collect.Iterables; /** * @author Mattias Holmqvist */ +@Singleton public class CreateMediumIfNotAlreadyExists implements Function { - private final VirtualBoxManager manager; - private boolean overwriteIfExists; + private final Supplier manager; + private final boolean overwriteIfExists; - public CreateMediumIfNotAlreadyExists(VirtualBoxManager manager, boolean overwriteIfExists) { + @Inject + public CreateMediumIfNotAlreadyExists(Supplier manager, boolean overwriteIfExists) { this.manager = manager; this.overwriteIfExists = overwriteIfExists; } + public static final Pattern ATTACHED_PATTERN = Pattern.compile(".*is still attached.*: ([-0-9a-f]+) .*"); @Override public IMedium apply(@Nullable HardDisk hardDisk) { - IVirtualBox vBox = manager.getVBox(); + IVirtualBox vBox = manager.get().getVBox(); try { String diskPath = hardDisk.getDiskPath(); final IMedium medium = vBox.findMedium(diskPath, DeviceType.HardDisk); if (overwriteIfExists) { try { deleteMediumAndBlockUntilComplete(medium); - } catch (VBoxException e){ + } catch (VBoxException e) { onAlreadyAttachedExceptionDetachOrPropagate(vBox, medium, e); } return createNewMedium(vBox, hardDisk); @@ -83,12 +89,13 @@ public class CreateMediumIfNotAlreadyExists implements Function(){ - public boolean apply(IMediumAttachment in){ - return in.getMedium().getId().equals(medium.getId()); - } - }); - lockMachineAndApply(manager, Write, immutableMachine.getName(), new DetachDistroMediumFromMachine( + IMediumAttachment mediumAttachment = Iterables.find(immutableMachine.getMediumAttachments(), + new Predicate() { + public boolean apply(IMediumAttachment in) { + return in.getMedium().getId().equals(medium.getId()); + } + }); + lockMachineAndApply(manager.get(), Write, immutableMachine.getName(), new DetachDistroMediumFromMachine( mediumAttachment.getController(), mediumAttachment.getPort(), mediumAttachment.getDevice())); deleteMediumAndBlockUntilComplete(medium); } else { @@ -96,11 +103,11 @@ public class CreateMediumIfNotAlreadyExists implements Function { - private VirtualBoxManager virtualBoxManager; + private Supplier virtualBoxManager; @Inject - public IMachineToHardware(VirtualBoxManager virtualBoxManager) { + public IMachineToHardware(Supplier virtualBoxManager) { this.virtualBoxManager = virtualBoxManager; } @@ -44,7 +45,7 @@ public class IMachineToHardware implements Function { public Hardware apply(@Nullable IMachine vm) { String osTypeId = vm.getOSTypeId(); - IGuestOSType guestOSType = virtualBoxManager.getVBox().getGuestOSType(osTypeId); + IGuestOSType guestOSType = virtualBoxManager.get().getVBox().getGuestOSType(osTypeId); Boolean is64Bit = guestOSType.getIs64Bit(); HardwareBuilder hardwareBuilder = new HardwareBuilder(); hardwareBuilder.ids(vm.getId()); diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java index b3b4f26a05..acc8ccd9dd 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java @@ -38,15 +38,16 @@ import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; +import com.google.common.base.Supplier; @Singleton public class IMachineToImage implements Function { - private final VirtualBoxManager virtualboxManager; + private final Supplier virtualboxManager; private final Map> osVersionMap; @Inject - public IMachineToImage(VirtualBoxManager virtualboxManager, Map> osVersionMap) { + public IMachineToImage(Supplier virtualboxManager, Map> osVersionMap) { this.virtualboxManager = checkNotNull(virtualboxManager, "virtualboxManager"); this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap"); } @@ -56,7 +57,7 @@ public class IMachineToImage implements Function { if (from == null) return null; - IGuestOSType guestOSType = virtualboxManager.getVBox().getGuestOSType(from.getOSTypeId()); + IGuestOSType guestOSType = virtualboxManager.get().getVBox().getGuestOSType(from.getOSTypeId()); OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription()); String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), osVersionMap); OperatingSystem os = OperatingSystem.builder().description(guestOSType.getDescription()).family(family) diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java index ee7d74eaa3..1976e64e00 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java @@ -33,7 +33,6 @@ import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Processor; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.javax.annotation.Nullable; @@ -43,6 +42,9 @@ import org.virtualbox_4_1.INetworkAdapter; import org.virtualbox_4_1.MachineState; import com.google.common.base.Function; +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; public class IMachineToNodeMetadata implements Function { @@ -54,8 +56,7 @@ public class IMachineToNodeMetadata implements Function public NodeMetadata apply(@Nullable IMachine vm) { NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder(); - String s = vm.getName(); - nodeMetadataBuilder.name(s); + nodeMetadataBuilder.name(vm.getName()).ids(vm.getName()); // TODO Set up location properly LocationBuilder locationBuilder = new LocationBuilder(); @@ -79,7 +80,7 @@ public class IMachineToNodeMetadata implements Function hardwareBuilder.is64Bit(false); nodeMetadataBuilder.hostname(vm.getName()); - nodeMetadataBuilder.loginPort(18083); + MachineState vmState = vm.getState(); NodeState nodeState = machineToNodeState.get(vmState); @@ -91,14 +92,21 @@ public class IMachineToNodeMetadata implements Function INetworkAdapter networkAdapter = vm.getNetworkAdapter(0l); if (networkAdapter != null) { - String bridgedInterface = networkAdapter.getBridgedInterface(); - System.out.println("Interface: " + bridgedInterface); + nodeMetadataBuilder.privateAddresses(ImmutableSet.of(networkAdapter.getNatDriver().getHostIP())); + for (String nameProtocolnumberAddressInboudportGuestTargetport : networkAdapter.getNatDriver().getRedirects()){ + Iterable stuff = Splitter.on(',').split(nameProtocolnumberAddressInboudportGuestTargetport); + String protocolNumber = Iterables.get(stuff, 1); + String hostAddress= Iterables.get(stuff, 2); + String inboundPort= Iterables.get(stuff, 3); + String targetPort= Iterables.get(stuff, 5); + if ("1".equals(protocolNumber) && "22".equals(targetPort)) + nodeMetadataBuilder.privateAddresses(ImmutableSet.of(hostAddress)).loginPort(Integer.parseInt(inboundPort)); + } } // nodeMetadataBuilder.imageId(""); // nodeMetadataBuilder.group(""); - nodeMetadataBuilder.id(vm.getId()); return nodeMetadataBuilder.build(); } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java new file mode 100644 index 0000000000..97020abf22 --- /dev/null +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java @@ -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 { + 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 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; + } +} \ No newline at end of file diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/RetrieveActiveBridgedInterfaces.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/RetrieveActiveBridgedInterfaces.java index 5e1e4a26e9..caa6d97d1c 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/RetrieveActiveBridgedInterfaces.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/RetrieveActiveBridgedInterfaces.java @@ -31,9 +31,12 @@ import java.util.regex.Pattern; import javax.annotation.Resource; -import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.callables.RunScriptOnNode.Factory; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; +import org.jclouds.scriptbuilder.domain.Statement; +import org.jclouds.scriptbuilder.domain.Statements; import com.google.common.base.Function; import com.google.common.base.Predicate; @@ -47,27 +50,25 @@ import com.google.inject.name.Named; /** * @author Andrea Turli */ -public class RetrieveActiveBridgedInterfaces implements Function> { +public class RetrieveActiveBridgedInterfaces implements Function> { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private ComputeServiceContext context; + private final Factory runScriptOnNodeFactory; @Inject - public RetrieveActiveBridgedInterfaces(ComputeServiceContext context) { - this.context = context; + public RetrieveActiveBridgedInterfaces(Factory runScriptOnNodeFactory) { + this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, "runScriptOnNodeFactory"); } @Override - public List apply(String hostId) { + public List apply(NodeMetadata host) { // Bridged Network - String command = "vboxmanage list bridgedifs"; - String bridgedIfBlocks = context - .getComputeService() - .runScriptOnNode(hostId, command, - runAsRoot(false).wrapInInitScript(false)).getOutput(); + Statement command = Statements.exec("vboxmanage list bridgedifs"); + String bridgedIfBlocks = runScriptOnNodeFactory.create(host, command, runAsRoot(false).wrapInInitScript(false)) + .init().call().getOutput(); List bridgedInterfaces = retrieveBridgedInterfaceNames(bridgedIfBlocks); checkNotNull(bridgedInterfaces); @@ -125,9 +126,8 @@ public class RetrieveActiveBridgedInterfaces implements Function manager; private String snapshotName; private String snapshotDesc; - public TakeSnapshotIfNotAlreadyAttached(VirtualBoxManager manager, String snapshotName, String snapshotDesc) { + public TakeSnapshotIfNotAlreadyAttached(Supplier manager, String snapshotName, String snapshotDesc) { this.manager = manager; this.snapshotName = snapshotName; this.snapshotDesc = snapshotDesc; @@ -61,7 +62,7 @@ public class TakeSnapshotIfNotAlreadyAttached implements Function { @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private final ComputeServiceContext context; + private final HttpClient client; private final String workingDir; - private final String isoFile; @Inject - public FileDownloadFromURI(final ComputeServiceContext context, - @Named(VIRTUALBOX_WORKINGDIR) final String workingDir, - @Named(VirtualBoxConstants.VIRTUALBOX_ISOFILE) final String isoFile) { - this.context = context; + public FileDownloadFromURI(HttpClient client, @Named(VIRTUALBOX_WORKINGDIR) String workingDir) { + this.client = client; this.workingDir = workingDir; - this.isoFile = isoFile; } @Override public File apply(@Nullable URI input) { - final File file = new File(workingDir, isoFile); + final File file = new File(workingDir, new File(input.getPath()).getName()); if (!file.exists()) { - final InputStream inputStream = context.utils().http().get(input); + final InputStream inputStream = client.get(input); checkNotNull(inputStream, "%s not found", input); try { copy(inputStream, new FileOutputStream(file)); diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java index 9ca1b1799d..d5359b9bb7 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java @@ -21,6 +21,10 @@ package org.jclouds.virtualbox.functions.admin; import static com.google.common.base.Preconditions.checkNotNull; +import java.net.URI; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; @@ -31,51 +35,51 @@ import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.javax.annotation.Nullable; import org.jclouds.logging.Logger; -import org.jclouds.net.IPSocket; -import org.jclouds.predicates.InetSocketAddressConnect; +import org.jclouds.virtualbox.Preconfiguration; import org.jclouds.virtualbox.config.VirtualBoxConstants; -import com.google.common.base.Function; +import com.google.common.base.Supplier; import com.google.inject.Singleton; /** * @author Andrea Turli */ -public class StartJettyIfNotAlreadyRunning implements Function { +@Preconfiguration +@Singleton +public class StartJettyIfNotAlreadyRunning implements Supplier { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; + private final URI preconfigurationUrl; private final Server jetty; - private final int port; - public StartJettyIfNotAlreadyRunning(Server jetty, @Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) int port) { - this.jetty = checkNotNull(jetty, "jetty"); - this.port = port; - } - - // TODO: getting an instance of the Server object should really be done in - // Guice, so inside a *Module class, perhaps as a @Provides method @Inject - public StartJettyIfNotAlreadyRunning(@Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) int port) { - this(ServerJetty.getInstance().getServer(), port); + public StartJettyIfNotAlreadyRunning( + @Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) { + this(new Server(URI.create(preconfigurationUrl).getPort()), preconfigurationUrl); } - @Override - public Server apply(@Nullable String baseResource) { - if (!jetty.getState().equals(Server.STARTED) - // TODO code smell = hard coding addresses or ports!! - && !new InetSocketAddressConnect().apply(new IPSocket("localhost", port))) { + public StartJettyIfNotAlreadyRunning(Server jetty, + @Named(VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) { + this.preconfigurationUrl = URI.create(checkNotNull(preconfigurationUrl, "preconfigurationUrl")); + this.jetty = jetty; + } + + @PostConstruct + public void start() { + + if (jetty.getState().equals(Server.STARTED)) { + logger.debug("not starting jetty, as existing host is serving %s", preconfigurationUrl); + } else { + logger.debug(">> starting jetty to serve %s", preconfigurationUrl); ResourceHandler resource_handler = new ResourceHandler(); resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[] { "index.html" }); - resource_handler.setResourceBase(baseResource); - logger.info("serving " + resource_handler.getBaseResource()); - + resource_handler.setResourceBase(""); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() }); jetty.setHandler(handlers); @@ -83,34 +87,23 @@ public class StartJettyIfNotAlreadyRunning implements Function { try { jetty.start(); } catch (Exception e) { - logger.error(e, "Server jetty could not be started at this %s", baseResource); + logger.error(e, "Server jetty could not be started for %s", preconfigurationUrl); } - return jetty; - } else { - logger.debug("Server jetty serving %s already running. Skipping start", baseResource); - return jetty; + logger.debug("<< serving %s", resource_handler.getBaseResource()); } } - @Singleton - private static class ServerJetty { - private static ServerJetty instance; - private Server server; - private String port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"); - - private ServerJetty() { - this.server = new Server(Integer.parseInt(port)); + @PreDestroy() + public void stop() { + try { + jetty.stop(); + } catch (Exception e) { } + } - public static ServerJetty getInstance() { - if (instance == null) - instance = new ServerJetty(); - return instance; - } - - public Server getServer() { - return server; - } + @Override + public URI get() { + return preconfigurationUrl; } } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java index 59c4898800..91edfcd3bb 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java @@ -25,68 +25,84 @@ import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; import java.net.URI; +import javax.annotation.PostConstruct; import javax.annotation.Resource; +import javax.inject.Inject; import javax.inject.Named; +import javax.inject.Singleton; -import org.jclouds.compute.ComputeService; +import org.jclouds.compute.callables.RunScriptOnNode.Factory; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.predicates.RetryIfSocketNotYetOpen; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; +import org.jclouds.location.Provider; import org.jclouds.logging.Logger; import org.jclouds.net.IPSocket; +import org.jclouds.rest.annotations.Credential; +import org.jclouds.rest.annotations.Identity; +import org.jclouds.scriptbuilder.domain.Statements; +import org.virtualbox_4_1.SessionState; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; -import com.google.common.base.Predicate; +import com.google.common.base.Supplier; -public class StartVBoxIfNotAlreadyRunning implements Function { +@Singleton +public class StartVBoxIfNotAlreadyRunning implements Supplier { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private final ComputeService compute; - private final VirtualBoxManager manager; - private final Predicate socketTester; - private final String hostId; - private final Credentials credentials; + private final Factory runScriptOnNodeFactory; + private final RetryIfSocketNotYetOpen socketTester; + private final Supplier host; + private final URI provider; + private final String identity; + private final String credential; + private final Function, VirtualBoxManager> managerForNode; + private transient VirtualBoxManager manager; - public StartVBoxIfNotAlreadyRunning(ComputeService compute, VirtualBoxManager manager, - Predicate socketTester, String hostId, Credentials credentials) { - this.compute = checkNotNull(compute, "compute"); - this.manager = checkNotNull(manager, "manager"); + // the functions and suppliers here are to ensure we don't do heavy i/o in injection + @Inject + public StartVBoxIfNotAlreadyRunning(Function, VirtualBoxManager> managerForNode, + Factory runScriptOnNodeFactory, RetryIfSocketNotYetOpen socketTester, Supplier host, + @Provider URI provider, @Identity String identity, @Credential String credential) { + this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, "runScriptOnNodeFactory"); this.socketTester = checkNotNull(socketTester, "socketTester"); - this.hostId = checkNotNull(hostId, "hostId"); - this.credentials = checkNotNull(credentials, "credentials"); + this.host = checkNotNull(host, "host"); + this.provider = checkNotNull(provider, "endpoint to virtualbox websrvd is needed"); + this.identity = checkNotNull(identity, "identity"); + this.credential = checkNotNull(credential, "credential"); + this.managerForNode = checkNotNull(managerForNode, "managerForNode"); + } + + @PostConstruct + public void start() { + if (!socketTester.apply(new IPSocket(provider.getHost(), provider.getPort()))) { + logger.debug("disabling password access"); + runScriptOnNodeFactory.create(host.get(), Statements.exec("VBoxManage setproperty websrvauthlibrary null"), + runAsRoot(false).wrapInInitScript(false)).init().call(); + logger.debug(">> starting vboxwebsrv"); + String vboxwebsrv = "vboxwebsrv -t 10000 -v -b"; + if (host.get().getOperatingSystem() != null + && host.get().getOperatingSystem().getDescription().equals("Mac OS X")) + vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " + vboxwebsrv; + + runScriptOnNodeFactory.create(host.get(), Statements.exec(vboxwebsrv), + runAsRoot(false).wrapInInitScript(false).blockOnComplete(false).nameTask("vboxwebsrv")).init().call(); + } + manager = managerForNode.apply(host); + manager.connect(provider.toASCIIString(), identity, credential); + if (logger.isDebugEnabled()) + if (manager.getSessionObject().getState() == SessionState.Unlocked) + logger.warn("manager is not in unlocked state " + manager); } @Override - public VirtualBoxManager apply(URI endpoint) { - checkState(compute.getNodeMetadata(hostId) != null, "compute service %s cannot locate node with id %s", compute, - hostId); - checkNotNull(endpoint, "endpoint to virtualbox websrvd is needed"); - - if (socketTester.apply(new IPSocket(endpoint.getHost(), endpoint.getPort()))) { - manager.connect(endpoint.toASCIIString(), credentials.identity, credentials.credential); - return manager; - } - - logger.debug("disabling password access"); - compute.runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null", runAsRoot(false) - .wrapInInitScript(false)); - logger.debug("starting vboxwebsrv"); - String vboxwebsrv = "vboxwebsrv -t 10000 -v -b"; - if (isOSX(hostId)) - vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " + vboxwebsrv; - - compute.runScriptOnNode(hostId, vboxwebsrv, runAsRoot(false).wrapInInitScript(false).blockOnComplete(false) - .nameTask("vboxwebsrv")); - - manager.connect(endpoint.toASCIIString(), credentials.identity, credentials.credential); + public VirtualBoxManager get() { + checkState(manager != null, "start not called"); return manager; } - private boolean isOSX(String hostId) { - return compute.getNodeMetadata(hostId).getOperatingSystem().getDescription().equals("Mac OS X"); - } - } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndDeleteItsMedia.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndDeleteItsMedia.java index bad662ee20..a9ddd0a6d2 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndDeleteItsMedia.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndDeleteItsMedia.java @@ -28,6 +28,7 @@ import java.util.List; import javax.annotation.Resource; import javax.inject.Named; +import javax.inject.Singleton; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; @@ -45,8 +46,8 @@ import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Lists; -public class UnregisterMachineIfExistsAndDeleteItsMedia implements - Function { +@Singleton +public class UnregisterMachineIfExistsAndDeleteItsMedia implements Function { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) @@ -66,18 +67,16 @@ public class UnregisterMachineIfExistsAndDeleteItsMedia implements } catch (VBoxException e) { ErrorCode errorCode = ErrorCode.valueOf(e); switch (errorCode) { - case VBOX_E_OBJECT_NOT_FOUND: - logger.debug("Machine %s does not exists, cannot unregister", - vmSpec.getVmName()); - break; - default: - throw e; + case VBOX_E_OBJECT_NOT_FOUND: + logger.debug("Machine %s does not exists, cannot unregister", vmSpec.getVmName()); + break; + default: + throw e; } } - List filteredMediaToBeDeleted = Lists.newArrayList(transform( - filter(mediaToBeDeleted, new AutoDeleteHardDiskPredicate(vmSpec)), - new DeleteChildrenOfMedium())); + List filteredMediaToBeDeleted = Lists.newArrayList(transform(filter(mediaToBeDeleted, + new AutoDeleteHardDiskPredicate(vmSpec)), new DeleteChildrenOfMedium())); checkNotNull(filteredMediaToBeDeleted); if (!filteredMediaToBeDeleted.isEmpty()) { @@ -85,8 +84,7 @@ public class UnregisterMachineIfExistsAndDeleteItsMedia implements IProgress deletion = machine.delete(filteredMediaToBeDeleted); deletion.waitForCompletion(-1); } catch (Exception e) { - logger.error(e, "Problem in deleting the media attached to %s", - machine.getName()); + logger.error(e, "Problem in deleting the media attached to %s", machine.getName()); Throwables.propagate(e); } } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/predicates/IsLinkedClone.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/predicates/IsLinkedClone.java index e2ac3f933d..abc8e33720 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/predicates/IsLinkedClone.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/predicates/IsLinkedClone.java @@ -21,7 +21,9 @@ package org.jclouds.virtualbox.predicates; import javax.annotation.Nullable; import javax.annotation.Resource; +import javax.inject.Inject; import javax.inject.Named; +import javax.inject.Singleton; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; @@ -33,20 +35,23 @@ import org.virtualbox_4_1.IStorageController; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Predicate; +import com.google.common.base.Supplier; /** * * @author Andrea Turli */ +@Singleton public class IsLinkedClone implements Predicate { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private VirtualBoxManager manager; + private final Supplier manager; - public IsLinkedClone(VirtualBoxManager manager) { + @Inject + public IsLinkedClone(Supplier manager) { this.manager = manager; } @@ -64,7 +69,7 @@ public class IsLinkedClone implements Predicate { // more than one machine is attached to this hd for (IMedium child : iMedium.getParent().getChildren()) { for (String machineId : child.getMachineIds()) { - IMachine iMachine = manager.getVBox().findMachine( + IMachine iMachine = manager.get().getVBox().findMachine( machineId); if (!iMachine.getName().equals(machine.getName())) { logger.debug("Machine %s is a linked clone", diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/predicates/SshResponds.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/predicates/SshResponds.java new file mode 100644 index 0000000000..676f42a169 --- /dev/null +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/predicates/SshResponds.java @@ -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 { + @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; + } +} \ No newline at end of file diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineUtils.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineUtils.java index 1ebf921860..46f51196c3 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineUtils.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineUtils.java @@ -19,13 +19,19 @@ package org.jclouds.virtualbox.util; +import static org.jclouds.scriptbuilder.domain.Statements.call; +import static org.jclouds.scriptbuilder.domain.Statements.findPid; +import static org.jclouds.scriptbuilder.domain.Statements.kill; +import static org.jclouds.scriptbuilder.domain.Statements.newStatementList; + +import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.util.Throwables2; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.LockType; +import org.virtualbox_4_1.SessionState; import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VirtualBoxManager; -import org.virtualbox_4_1.jaxws.SessionState; import com.google.common.base.Function; @@ -132,33 +138,42 @@ public class MachineUtils { return null; } } - + /** * Unlocks the machine and executes the given function using the machine matching the given id. * Since the machine is unlocked it is possible to delete the IMachine. *

- * - * @param manager the VirtualBoxManager - * @param machineId the id of the machine - * @param function the function to execute + * + *

Note!

Currently, this can only unlock the machine, if the lock was created in the + * current session. + * + * @param manager + * the VirtualBoxManager + * @param machineId + * the id of the machine + * @param function + * the function to execute * @return the result from applying the function to the machine. */ public static T unlockMachineAndApply(VirtualBoxManager manager, final String machineId, - final Function function) { + final Function function) { try { ISession session = manager.getSessionObject(); IMachine immutableMachine = manager.getVBox().findMachine(machineId); - if(immutableMachine.getSessionState().equals(SessionState.LOCKED)) + SessionState state = immutableMachine.getSessionState(); + if (state.equals(SessionState.Locked)) session.unlockMachine(); - + //TODO: wire this in + Statement kill = newStatementList(call("default"), findPid(machineId), kill()); + return function.apply(immutableMachine); - + } catch (VBoxException e) { - throw new RuntimeException(String.format("error applying %s to %s: %s", function, machineId, - e.getMessage()), e); + throw new RuntimeException(String.format("error applying %s to %s: %s", function, machineId, e.getMessage()), + e); } } - + /** * Unlocks the machine and executes the given function, if the machine is registered. * Since the machine is unlocked it is possible to delete the machine. diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java index 04da8f47de..4f5a3b82b7 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java @@ -19,35 +19,40 @@ package org.jclouds.virtualbox; -import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; +import static org.jclouds.virtualbox.util.MachineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered; +import java.net.URI; import java.util.Properties; -import org.eclipse.jetty.server.Server; import org.jclouds.Constants; +import org.jclouds.byon.Node; +import org.jclouds.byon.config.CacheNodeStoreModule; import org.jclouds.compute.BaseVersionedServiceLiveTest; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.config.ValueOfConfigurationKeyOrNull; -import org.jclouds.domain.Credentials; import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning; -import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning; +import org.jclouds.virtualbox.domain.VmSpec; +import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import org.virtualbox_4_1.SessionState; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; import com.google.common.base.Splitter; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; +import com.google.inject.Key; import com.google.inject.Module; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code VirtualBoxClient} @@ -59,19 +64,21 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest { public BaseVirtualBoxClientLiveTest() { provider = "virtualbox"; } - + protected ComputeServiceContext context; - protected VirtualBoxManager manager; - protected Server jetty; + protected Supplier manager; + protected Supplier preconfigurationUri; protected String hostVersion; protected String operatingSystemIso; protected String guestAdditionsIso; protected String adminDisk; protected String workingDir; - + protected Supplier host; + @Override protected void setupCredentials() { - // default behavior is to bomb when no user is configured, but we know the default user of vbox + // default behavior is to bomb when no user is configured, but we know the default user of + // vbox ensureIdentityPropertyIsSpecifiedOrTakeFromDefaults(); super.setupCredentials(); } @@ -87,44 +94,48 @@ public class BaseVirtualBoxClientLiveTest extends BaseVersionedServiceLiveTest { public void setupClient() { setupCredentials(); Properties overrides = setupProperties(); - context = new ComputeServiceContextFactory().createContext(provider, identity, credential, - ImmutableSet. of(new Log4JLoggingModule(), new SshjSshClientModule()), overrides); - Function configProperties = context.utils().injector().getInstance(ValueOfConfigurationKeyOrNull.class); + + CacheNodeStoreModule hostModule = new CacheNodeStoreModule(ImmutableMap.of("host", Node.builder().id("host") + .name("host installing virtualbox").hostname("localhost").osFamily(OsFamily.LINUX.toString()) + .osDescription(System.getProperty("os.name")).osVersion(System.getProperty("os.version")).group("ssh") + .username(System.getProperty("user.name")).credentialUrl( + URI.create("file://" + System.getProperty("user.home") + "/.ssh/id_rsa")).build())); + + context = new ComputeServiceContextFactory().createContext(provider, identity, credential, ImmutableSet + . of(new Log4JLoggingModule(), new SshjSshClientModule(), hostModule), overrides); + Function configProperties = context.utils().injector().getInstance( + ValueOfConfigurationKeyOrNull.class); imageId = configProperties.apply(ComputeServiceConstants.PROPERTY_IMAGE_ID); workingDir = configProperties.apply(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR); + host = context.utils().injector().getInstance(Key.get(new TypeLiteral>(){})); + + // this will eagerly startup Jetty, note the impl will shut itself down + preconfigurationUri = context.utils().injector().getInstance(Key.get(new TypeLiteral>() { + }, Preconfiguration.class)); + // this will eagerly startup Jetty, note the impl will shut itself down + preconfigurationUri.get(); - jetty = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource); - startVboxIfNotAlreadyRunning(); + manager = context.utils().injector().getInstance(Key.get(new TypeLiteral>() { + })); + // this will eagerly startup vbox + manager.get(); + hostVersion = Iterables.get(Splitter.on('r').split(context.getProviderSpecificContext().getBuildVersion()), 0); adminDisk = workingDir + "/testadmin.vdi"; operatingSystemIso = String.format("%s/%s.iso", workingDir, imageId); guestAdditionsIso = String.format("%s/VBoxGuestAdditions_%s.iso", workingDir, hostVersion); + + } + + protected void undoVm(VmSpec vmSpecification) { + unlockMachineAndApplyOrReturnNullIfNotRegistered(manager.get(), vmSpecification.getVmName(), + new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification)); } @AfterClass(groups = "live") protected void tearDown() throws Exception { if (context != null) context.close(); - if (jetty != null) - jetty.stop(); - // TODO: should we stop the vbox manager? } - private String basebaseResource = "."; - // TODO: I'd not use 8080, maybe something like 28080 - // also update pom.xml so that this passes through - private int port = Integer.parseInt(System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080")); - - protected void startVboxIfNotAlreadyRunning() { - Credentials localhostCredentials = new Credentials("toor", "password"); - ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest("hostId", "localhost", "guestId", - "localhost", localhostCredentials); - - manager = new StartVBoxIfNotAlreadyRunning(localHostContext.getComputeService(), - VirtualBoxManager.createInstance("hostId"), new InetSocketAddressConnect(), "hostId", localhostCredentials) - .apply(context.getProviderSpecificContext().getEndpoint()); - - assert manager.getSessionObject().getState() == SessionState.Unlocked : "manager needs to be in unlocked state or all tests will fail!!: " - + manager; - } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java index 8d899114f7..23c7003623 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java @@ -22,55 +22,31 @@ package org.jclouds.virtualbox.compute; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; -import java.net.URI; -import java.util.Map; - import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials; -import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Template; import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials; -import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate; import org.jclouds.domain.Credentials; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.location.suppliers.JustProvider; import org.jclouds.net.IPSocket; import org.jclouds.ssh.SshClient; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; -import org.jclouds.virtualbox.functions.IMachineToImage; import org.testng.annotations.Test; import org.virtualbox_4_1.IMachine; -import org.virtualbox_4_1.VirtualBoxManager; -import com.google.common.base.Function; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; -import com.google.inject.Guice; @Test(groups = "live", singleThreaded = true, testName = "VirtualBoxComputeServiceAdapterLiveTest") public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClientLiveTest { private VirtualBoxComputeServiceAdapter adapter; private NodeAndInitialCredentials machine; - private final Map> osVersionMap = new BaseComputeServiceContextModule() { - }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) - .getInstance(Json.class)); @Override public void setupClient() { super.setupClient(); - final VirtualBoxManager manager = getManager(); - Function iMachineToImage = new IMachineToImage(manager, osVersionMap); - adapter = new VirtualBoxComputeServiceAdapter(manager, new JustProvider(provider, URI.create(endpoint), - ImmutableSet. of()), iMachineToImage); - } - - protected VirtualBoxManager getManager() { - return (VirtualBoxManager) context.getProviderSpecificContext().getApi(); + adapter = context.utils().injector().getInstance(VirtualBoxComputeServiceAdapter.class); } @Test diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterTest.java index 71d6a4f302..b22fb7676c 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterTest.java @@ -46,6 +46,7 @@ import org.virtualbox_4_1.IVirtualBox; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; +import com.google.common.base.Suppliers; import com.google.common.collect.Iterators; import com.google.inject.Guice; @@ -83,8 +84,8 @@ public class VirtualBoxComputeServiceAdapterTest { replay(manager, justProvider, vBox, clonedMachine, imageMachine, osType); - Function iMachineToImage = new IMachineToImage(manager, osMap); - VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(manager, justProvider, + Function iMachineToImage = new IMachineToImage(Suppliers.ofInstance(manager), osMap); + VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(Suppliers.ofInstance(manager), justProvider, iMachineToImage); Iterator iterator = adapter.listImages().iterator(); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java deleted file mode 100644 index c7d265b325..0000000000 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java +++ /dev/null @@ -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 nodeMap = ImmutableMap. builder().put("host", host).put("guest", guest) - .build(); - return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet. 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 nodeMap = ImmutableMap. builder().put(hostId, host).put(guestId, guest) - .build(); - return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet. 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 cache) { - return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet. of( - new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(), - new CacheNodeStoreModule(cache))); - } -} diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttachedTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttachedTest.java index 7b1266bf93..b0843f11cd 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttachedTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttachedTest.java @@ -52,7 +52,6 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest { String controllerName = "IDE Controller"; String diskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi"; - String diskName = "admin"; String diskFormat = "vdi"; int controllerPort = 0; int deviceSlot = 1; diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExistsTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExistsTest.java index 601304c983..a778e7dfa0 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExistsTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExistsTest.java @@ -51,12 +51,12 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest { networkAdapter.setAttachmentType(NAT); expect(networkAdapter.getNatDriver()).andReturn(natEngine); - natEngine.addRedirect("TCP@127.0.0.1:2222->guest:22", TCP, "127.0.0.1", 2222, "guest", 22); + natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1", 2222, "", 22); networkAdapter.setEnabled(true); machine.saveSettings(); replay(machine, networkAdapter, natEngine); - NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "guest", 22).build(); + NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine); verify(machine, networkAdapter, natEngine); @@ -73,7 +73,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest { networkAdapter.setAttachmentType(NAT); expect(networkAdapter.getNatDriver()).andReturn(natEngine); - natEngine.addRedirect("TCP@127.0.0.1:2222->guest:22", TCP, "127.0.0.1", 2222, "guest", 22); + natEngine.addRedirect("TCP@127.0.0.1:2222->:22", TCP, "127.0.0.1", 2222, "", 22); expectLastCall().andThrow( new VBoxException(null, "VirtualBox error: A NAT rule of this name already exists (0x80070057)")); @@ -81,7 +81,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest { machine.saveSettings(); replay(machine, networkAdapter, natEngine); - NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "guest", 22).build(); + NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine); verify(machine, networkAdapter, natEngine); @@ -102,7 +102,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExistsTest { replay(machine, networkAdapter, natEngine); - NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "guest", 22).build(); + NatAdapter natAdapter = NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); new AttachNATAdapterToMachineIfNotAlreadyExists(slotId, natAdapter).apply(machine); verify(machine, networkAdapter, natEngine); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest.java index 2103222493..6b98224c8f 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest.java @@ -19,95 +19,83 @@ package org.jclouds.virtualbox.functions; -import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; -import static org.jclouds.virtualbox.util.MachineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered; import static org.testng.Assert.assertEquals; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.domain.Credentials; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.domain.HardDisk; import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.VmSpec; -import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.StorageBus; -import org.virtualbox_4_1.VirtualBoxManager; +import com.google.common.base.CaseFormat; import com.google.common.collect.ImmutableSet; /** * @author Andrea Turli */ @Test(groups = "live", singleThreaded = true, testName = "CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest") -public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends - BaseVirtualBoxClientLiveTest { +public class CloneAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClientLiveTest { private static final boolean IS_LINKED_CLONE = true; - private String vmId = "jclouds-image-iso-1"; - private String osTypeId = ""; - private String guestId = "guest"; - private String hostId = "host"; - private String vmName = "jclouds-virtualbox-clone-test"; - private String cloneName = vmName + "_clone"; private VmSpec clonedVmSpec; + private VmSpec sourceVmSpec; - private String ideControllerName = "IDE Controller"; private CleanupMode mode = CleanupMode.Full; + @Override + @BeforeClass(groups = "live") + public void setupClient() { + setupCredentials(); + String sourceName = "jclouds#image#" + + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName()); + String cloneName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName()); + + StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE) + .attachISO(0, 0, operatingSystemIso).attachHardDisk( + HardDisk.builder().diskpath(adminDisk).controllerPort(0).deviceSlot(1).build()).attachISO(1, 1, + guestAdditionsIso).build(); + + sourceVmSpec = VmSpec.builder().id(sourceName).name(sourceName).osTypeId("").memoryMB(512).cleanUpMode( + CleanupMode.Full).controller(ideController).forceOverwrite(true).build(); + + clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(512).cleanUpMode(mode) + .forceOverwrite(true).build(); + } + @Test public void testCloneMachineFromAnotherMachine() throws Exception { - VirtualBoxManager manager = (VirtualBoxManager) context - .getProviderSpecificContext().getApi(); - ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest( - hostId, "localhost", guestId, "localhost", new Credentials("toor", - "password")); + try { + IMachine source = getSourceNode(); - IMachine master = getMasterNode(manager, localHostContext); + if (source.getCurrentSnapshot() != null) { + ISession session = manager.get().openMachineSession(source); + session.getConsole().deleteSnapshot(source.getCurrentSnapshot().getId()); + session.unlockMachine(); + } - if (master.getCurrentSnapshot() != null) { - ISession session = manager.openMachineSession(master); - session.getConsole().deleteSnapshot( - master.getCurrentSnapshot().getId()); - session.unlockMachine(); + IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, clonedVmSpec, + IS_LINKED_CLONE).apply(source); + assertEquals(clone.getName(), clonedVmSpec.getVmName()); + } finally { + for (VmSpec spec : ImmutableSet.of(clonedVmSpec, sourceVmSpec)) + undoVm(spec); } - clonedVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(512) - .cleanUpMode(mode) - .forceOverwrite(true).build(); - IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists( - manager, workingDir, clonedVmSpec, IS_LINKED_CLONE).apply(master); - assertEquals(clone.getName(), clonedVmSpec.getVmName()); - for (VmSpec spec : ImmutableSet.of(clonedVmSpec, new IMachineToVmSpec().apply(master))) - unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, spec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(spec)); - } - private IMachine getMasterNode(VirtualBoxManager manager, - ComputeServiceContext localHostContext) { + private IMachine getSourceNode() { try { - StorageController ideController = StorageController - .builder() - .name(ideControllerName) - .bus(StorageBus.IDE) - .attachISO(0, 0, operatingSystemIso) - .attachHardDisk( - HardDisk.builder().diskpath(adminDisk) - .controllerPort(0).deviceSlot(1).build()) - .attachISO(1, 1, guestAdditionsIso) - .build(); - VmSpec vmSpec = VmSpec.builder().id(vmId).name(vmName) - .osTypeId(osTypeId).memoryMB(512).cleanUpMode(CleanupMode.Full) - .controller(ideController).forceOverwrite(true).build(); - return new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir).apply(vmSpec); - + return context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply( + sourceVmSpec); } catch (IllegalStateException e) { // already created - return manager.getVBox().findMachine(vmName); + return manager.get().getVBox().findMachine(sourceVmSpec.getVmId()); } } } \ No newline at end of file diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndInstallVmLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndInstallVmLiveTest.java index 297362f9d9..71dececb23 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndInstallVmLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndInstallVmLiveTest.java @@ -22,44 +22,32 @@ package org.jclouds.virtualbox.functions; import static com.google.common.base.Predicates.equalTo; import static com.google.common.collect.Iterables.any; import static com.google.common.collect.Iterables.transform; -import static org.jclouds.virtualbox.domain.ExecutionType.HEADLESS; -import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; -import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApplyOrReturnNullIfNotRegistered; import static org.testng.Assert.assertTrue; -import static org.virtualbox_4_1.LockType.Write; import java.util.Map; import java.util.Set; -import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; -import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.json.Json; import org.jclouds.json.config.GsonModule; -import org.jclouds.net.IPSocket; -import org.jclouds.predicates.InetSocketAddressConnect; -import org.jclouds.predicates.RetryablePredicate; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.domain.HardDisk; import org.jclouds.virtualbox.domain.NatAdapter; import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.VmSpec; -import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia; +import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.StorageBus; -import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; -import com.google.common.base.Predicate; import com.google.inject.Guice; /** @@ -72,43 +60,31 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest { }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) .getInstance(Json.class)); - private String vmId = "jclouds-image-iso-1"; - private String osTypeId = ""; - private String ideControllerName = "IDE Controller"; - private String guestId = "guest"; - private String hostId = "host"; - private String vmName = "jclouds-image-virtualbox-iso-to-machine-test"; - private StorageController ideController; private VmSpec vmSpecification; @Override @BeforeClass(groups = "live") public void setupClient() { super.setupClient(); + String vmName = "jclouds-image-virtualbox-iso-to-machine-test"; + HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true) .controllerPort(0).deviceSlot(1).build(); - ideController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE) + StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE) .attachISO(0, 0, operatingSystemIso) .attachHardDisk(hardDisk) .attachISO(1, 1, guestAdditionsIso).build(); - vmSpecification = VmSpec.builder().id(vmId).name(vmName).memoryMB(512).osTypeId(osTypeId) + vmSpecification = VmSpec.builder().id("jclouds-image-iso-1").name(vmName).memoryMB(512).osTypeId("") .controller(ideController) .forceOverwrite(true) .cleanUpMode(CleanupMode.Full) .natNetworkAdapter(0, NatAdapter.builder().tcpRedirectRule("127.0.0.1", 2222, "", 22).build()).build(); - lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, vmName, new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpecification)); + undoVm(vmSpecification); } public void testCreateImageMachineFromIso() throws Exception { - VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi(); - ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(hostId, "localhost", guestId, - "localhost", new Credentials("toor", "password")); - Predicate socketTester = new RetryablePredicate(new InetSocketAddressConnect(), 10, 1, TimeUnit.SECONDS); - - IMachine imageMachine = new CreateAndInstallVm(manager, new CreateAndRegisterMachineFromIsoIfNotAlreadyExists( - manager, workingDir), workingDir, guestId, localHostContext, hostId, socketTester, "127.0.0.1", 8080, - HEADLESS).apply(vmSpecification); + IMachine imageMachine = context.utils().injector().getInstance(CreateAndInstallVm.class).apply(vmSpecification); IMachineToImage iMachineToImage = new IMachineToImage(manager, map); Image newImage = iMachineToImage.apply(imageMachine); @@ -128,5 +104,10 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest { } }; } - + @Override + @AfterClass(groups = "live") + protected void tearDown() throws Exception { + undoVm(vmSpecification); + super.tearDown(); + } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest.java index 66f6ac7217..db6dce8ef9 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest.java @@ -19,7 +19,6 @@ package org.jclouds.virtualbox.functions; -import static org.jclouds.virtualbox.util.MachineUtils.unlockMachineAndApplyOrReturnNullIfNotRegistered; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; @@ -28,7 +27,6 @@ import org.jclouds.virtualbox.domain.ErrorCode; import org.jclouds.virtualbox.domain.HardDisk; import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.VmSpec; -import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia; import org.testng.annotations.Test; import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.IMachine; @@ -39,8 +37,7 @@ import org.virtualbox_4_1.VBoxException; * @author Mattias Holmqvist */ @Test(groups = "live", singleThreaded = true, testName = "CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest") -public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends - BaseVirtualBoxClientLiveTest { +public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClientLiveTest { private String ideControllerName; private CleanupMode mode; @@ -51,50 +48,48 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsLiveTest extends super.setupClient(); ideControllerName = "IDE Controller"; mode = CleanupMode.Full; - ideController = StorageController - .builder() - .name(ideControllerName) - .bus(StorageBus.IDE) - .attachISO(0, 0, operatingSystemIso) - .attachHardDisk( - HardDisk.builder().diskpath(adminDisk) - .controllerPort(0).deviceSlot(1).build()) - .attachISO(1, 1, guestAdditionsIso) - .build(); + ideController = StorageController.builder().name(ideControllerName).bus(StorageBus.IDE).attachISO(0, 0, + operatingSystemIso).attachHardDisk( + HardDisk.builder().diskpath(adminDisk).controllerPort(0).deviceSlot(1).build()).attachISO(1, 1, + guestAdditionsIso).build(); } @Test public void testCreateNewMachine() throws Exception { String vmName = "jclouds-test-create-1-node"; - VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName) - .memoryMB(512).controller(ideController).cleanUpMode(mode) - .osTypeId("Debian").forceOverwrite(true).build(); - unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification)); - IMachine debianNode = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists( - manager, workingDir).apply(launchSpecification); - IMachine machine = manager.getVBox().findMachine(vmName); - assertEquals(debianNode.getName(), machine.getName()); - unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification)); + VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).controller(ideController) + .cleanUpMode(mode).osTypeId("Debian").forceOverwrite(true).build(); + undoVm(launchSpecification); + try { + IMachine debianNode = context.utils().injector().getInstance( + CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply(launchSpecification); + IMachine machine = manager.get().getVBox().findMachine(vmName); + assertEquals(debianNode.getName(), machine.getName()); + } finally { + undoVm(launchSpecification); + } } @Test public void testCreateNewMachineWithBadOsType() throws Exception { String vmName = "jclouds-test-create-2-node"; - VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName) - .memoryMB(512).controller(ideController).cleanUpMode(mode) - .osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build(); - unlockMachineAndApplyOrReturnNullIfNotRegistered(manager, launchSpecification.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification)); - //new UnregisterMachineIfExistsAndDeleteItsMedia(launchSpecification).apply(manager.getVBox().findMachine(vmName)); + VmSpec launchSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).controller(ideController) + .cleanUpMode(mode).osTypeId("SomeWeirdUnknownOs").forceOverwrite(true).build(); + + undoVm(launchSpecification); try { - new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir) - .apply(launchSpecification); + context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class).apply( + launchSpecification); fail(); } catch (VBoxException e) { ErrorCode errorCode = ErrorCode.valueOf(e); // According to the documentation VBOX_E_OBJECT_NOT_FOUND // if osTypeId is not found. assertEquals(errorCode, ErrorCode.VBOX_E_OBJECT_NOT_FOUND); + } finally { + undoVm(launchSpecification); } + } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest.java index 00ff3ac2fc..85bc067af0 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest.java @@ -39,6 +39,8 @@ import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VirtualBoxManager; +import com.google.common.base.Suppliers; + /** * @author Mattias Holmqvist */ @@ -86,7 +88,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest { replay(manager, createdMachine, vBox, session); - new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, "/tmp/workingDir").apply(launchSpecification); + new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(launchSpecification); verify(manager, createdMachine, vBox, session); } @@ -107,7 +109,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest { VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").memoryMB(1024).cleanUpMode( CleanupMode.Full).build(); - new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, "/tmp/workingDir").apply(launchSpecification); + new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(launchSpecification); } @Test(expectedExceptions = VBoxException.class) @@ -129,7 +131,7 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest { VmSpec launchSpecification = VmSpec.builder().id("").name(vmName).osTypeId("").cleanUpMode(CleanupMode.Full) .memoryMB(1024).build(); - new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, "/tmp/workingDir").apply(launchSpecification); + new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Suppliers.ofInstance(manager), "/tmp/workingDir").apply(launchSpecification); } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsLiveTest.java index e9dc309698..70ecd63410 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsLiveTest.java @@ -44,9 +44,12 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient String path = System.getProperty("user.home") + "/jclouds-virtualbox-test/test-medium-1.vdi"; HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build(); IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk); - manager.getVBox().findMedium(path, DeviceType.HardDisk); - assertFileCanBeDeleted(path); - deleteMediumAndBlockUntilComplete(iMedium); + manager.get().getVBox().findMedium(path, DeviceType.HardDisk); + try { + assertFileCanBeDeleted(path); + } finally { + deleteMediumAndBlockUntilComplete(iMedium); + } } @Test @@ -68,9 +71,12 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient HardDisk hardDisk = HardDisk.builder().diskpath(path).controllerPort(0).deviceSlot(0).build(); IMedium iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk); iMedium = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk); - manager.getVBox().findMedium(path, DeviceType.HardDisk); - assertFileCanBeDeleted(path); - deleteMediumAndBlockUntilComplete(iMedium); + manager.get().getVBox().findMedium(path, DeviceType.HardDisk); + try { + assertFileCanBeDeleted(path); + } finally { + deleteMediumAndBlockUntilComplete(iMedium); + } } @@ -79,10 +85,10 @@ public class CreateMediumIfNotAlreadyExistsLiveTest extends BaseVirtualBoxClient boolean mediumDeleted = file.delete(); assertTrue(mediumDeleted); } - - void deleteMediumAndBlockUntilComplete(IMedium medium){ + + void deleteMediumAndBlockUntilComplete(IMedium medium) { final IProgress progress = medium.deleteStorage(); progress.waitForCompletion(-1); } - + } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsTest.java index d0e5c88896..685cd252e7 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsTest.java @@ -42,6 +42,7 @@ import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VirtualBoxManager; +import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; /** @@ -51,14 +52,11 @@ public class CreateMediumIfNotAlreadyExistsTest { private String adminDiskPath; private String diskFormat; - private String diskName; - @BeforeMethod public void setUp() throws Exception { adminDiskPath = "/Users/johndoe/jclouds-virtualbox-images/admin.vdi"; diskFormat = "vdi"; - diskName = "diskName"; } @Test @@ -87,7 +85,7 @@ public class CreateMediumIfNotAlreadyExistsTest { replay(manager, machine, vBox, medium); - new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk); + new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk); verify(machine, vBox); @@ -113,14 +111,15 @@ public class CreateMediumIfNotAlreadyExistsTest { replay(manager, machine, vBox, medium, newHardDisk, progress); - IMedium newDisk = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk); + IMedium newDisk = new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk); verify(machine, vBox, medium); assertNotSame(newDisk, medium); } @Test - public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwriteAndStillAttachedDetachesOldThing() throws Exception { + public void testDeleteAndCreateNewStorageWhenMediumExistsAndUsingOverwriteAndStillAttachedDetachesOldThing() + throws Exception { HardDisk hardDisk = createTestHardDisk(); VirtualBoxManager manager = createNiceMock(VirtualBoxManager.class); @@ -133,7 +132,6 @@ public class CreateMediumIfNotAlreadyExistsTest { expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(vBox.findMedium(adminDiskPath, DeviceType.HardDisk)).andReturn(medium); - String oldMachineId = "a1e03931-29f3-4370-ada3-9547b1009212"; String oldMachineName = "oldMachine"; @@ -178,11 +176,11 @@ public class CreateMediumIfNotAlreadyExistsTest { expect(vBox.createHardDisk(diskFormat, adminDiskPath)).andReturn(newHardDisk); expect(newHardDisk.createBaseStorage(anyLong(), anyLong())).andReturn(progress); - replay(manager,oldMachine, oldAttachment,oldMedium, detachSession, machine, vBox, medium, newHardDisk, progress); + replay(manager, oldMachine, oldAttachment, oldMedium, detachSession, machine, vBox, medium, newHardDisk, progress); - IMedium newDisk = new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk); + IMedium newDisk = new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk); - verify(machine,oldMachine,oldAttachment, detachSession, oldMedium, vBox, medium); + verify(machine, oldMachine, oldAttachment, detachSession, oldMedium, vBox, medium); assertNotSame(newDisk, medium); } @@ -202,7 +200,7 @@ public class CreateMediumIfNotAlreadyExistsTest { replay(manager, machine, vBox, medium, newHardDisk, progress); - new CreateMediumIfNotAlreadyExists(manager, false).apply(hardDisk); + new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), false).apply(hardDisk); } @Test(expectedExceptions = VBoxException.class) @@ -227,7 +225,7 @@ public class CreateMediumIfNotAlreadyExistsTest { replay(manager, machine, vBox, medium); - new CreateMediumIfNotAlreadyExists(manager, true).apply(hardDisk); + new CreateMediumIfNotAlreadyExists(Suppliers.ofInstance(manager), true).apply(hardDisk); } private HardDisk createTestHardDisk() { diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToHardwareTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToHardwareTest.java index 6a6014490a..0b0989de65 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToHardwareTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToHardwareTest.java @@ -33,6 +33,8 @@ import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IVirtualBox; import org.virtualbox_4_1.VirtualBoxManager; +import com.google.common.base.Suppliers; + @Test(groups = "unit") public class IMachineToHardwareTest { @@ -57,7 +59,7 @@ public class IMachineToHardwareTest { replay(vbm, vBox, vm, guestOsType); - Hardware hardware = new IMachineToHardware(vbm).apply(vm); + Hardware hardware = new IMachineToHardware(Suppliers.ofInstance(vbm)).apply(vm); assertEquals(hardware.getId(), machineId); assertEquals(hardware.getProviderId(), machineId); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToImageTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToImageTest.java index 8ff77d2b76..af114a9acf 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToImageTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToImageTest.java @@ -40,6 +40,7 @@ import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IVirtualBox; import org.virtualbox_4_1.VirtualBoxManager; +import com.google.common.base.Suppliers; import com.google.inject.Guice; @Test(groups = "unit") @@ -67,7 +68,7 @@ public class IMachineToImageTest { replay(vbm, vBox, vm, guestOsType); - IMachineToImage fn = new IMachineToImage(vbm, map); + IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map); Image image = fn.apply(vm); @@ -98,7 +99,7 @@ public class IMachineToImageTest { replay(vbm, vBox, vm, guestOsType); - IMachineToImage fn = new IMachineToImage(vbm, map); + IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map); Image image = fn.apply(vm); @@ -129,7 +130,9 @@ public class IMachineToImageTest { replay(vbm, vBox, vm, guestOsType); - Image image = new IMachineToImage(vbm, map).apply(vm); + IMachineToImage fn = new IMachineToImage(Suppliers.ofInstance(vbm), map); + + Image image = fn.apply(vm); assertEquals(image.getOperatingSystem().getDescription(), "SomeOtherOs 2.04"); assertEquals(image.getOperatingSystem().getVersion(), ""); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java index 62c454f19d..ce590cae33 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java @@ -31,6 +31,7 @@ import org.testng.annotations.Test; import org.virtualbox_4_1.MachineState; import org.virtualbox_4_1.VirtualBoxManager; +import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableSet; public class IMachineToNodeMetadataTest { @@ -47,7 +48,7 @@ public class IMachineToNodeMetadataTest { VirtualBox virtualBox = new VirtualBox(); IMachineToNodeMetadata parser = new IMachineToNodeMetadata(); - IMachineToHardware hwParser = new IMachineToHardware(manager); + IMachineToHardware hwParser = new IMachineToHardware(Suppliers.ofInstance(manager)); // hwParser.apply() diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/RetrieveActiveBridgedInterfacesLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/RetrieveActiveBridgedInterfacesLiveTest.java index 30c9196ceb..2e95b0f482 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/RetrieveActiveBridgedInterfacesLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/RetrieveActiveBridgedInterfacesLiveTest.java @@ -19,15 +19,12 @@ package org.jclouds.virtualbox.functions; -import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; import static org.jclouds.virtualbox.functions.RetrieveActiveBridgedInterfaces.retrieveBridgedInterfaceNames; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import java.util.List; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.domain.Credentials; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.testng.annotations.Test; @@ -38,48 +35,31 @@ import com.google.common.collect.ImmutableList; */ @Test(groups = "live", singleThreaded = true, testName = "RetrieveActiveBridgedInterfacesLiveTest") public class RetrieveActiveBridgedInterfacesLiveTest extends BaseVirtualBoxClientLiveTest { - - public static final String TEST1 = "Name: eth0\n" - + "GUID: 30687465-0000-4000-8000-00261834d0cb\n" - + "Dhcp: Disabled\n" - + "IPAddress: 209.x.x.x\n" - + "NetworkMask: 255.255.255.0\n" - + "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n" - + "IPV6NetworkMaskPrefixLength: 64\n" - + "HardwareAddress: 00:26:18:34:d0:cb\n" - + "MediumType: Ethernet\n" - + "Status: Up\n" - + "VBoxNetworkName: HostInterfaceNetworking-eth0\n" - + "\n" - + "Name: vbox0\n" - + "GUID: 786f6276-0030-4000-8000-5a3ded993fed\n" - + "Dhcp: Disabled\n" - + "IPAddress: 192.168.56.1\n" - + "NetworkMask: 255.255.255.0\n" - + "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n" - + "IPV6NetworkMaskPrefixLength: 0\n" - + "HardwareAddress: 5a:3d:ed:99:3f:ed\n" - + "MediumType: Ethernet\n" - + "Status: Down\n" - + "VBoxNetworkName: HostInterfaceNetworking-vbox0\n"; - - public static final List expectedBridgedInterfaces = ImmutableList.of("eth0", "vbox0"); - private String guestId = "guest"; - private String hostId = "host"; + public static final String TEST1 = "Name: eth0\n" + + "GUID: 30687465-0000-4000-8000-00261834d0cb\n" + "Dhcp: Disabled\n" + + "IPAddress: 209.x.x.x\n" + "NetworkMask: 255.255.255.0\n" + + "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n" + "IPV6NetworkMaskPrefixLength: 64\n" + + "HardwareAddress: 00:26:18:34:d0:cb\n" + "MediumType: Ethernet\n" + "Status: Up\n" + + "VBoxNetworkName: HostInterfaceNetworking-eth0\n" + "\n" + "Name: vbox0\n" + + "GUID: 786f6276-0030-4000-8000-5a3ded993fed\n" + "Dhcp: Disabled\n" + + "IPAddress: 192.168.56.1\n" + "NetworkMask: 255.255.255.0\n" + + "IPV6Address: fe80:0000:0000:0000:0226:18ff:fe34:d0cb\n" + "IPV6NetworkMaskPrefixLength: 0\n" + + "HardwareAddress: 5a:3d:ed:99:3f:ed\n" + "MediumType: Ethernet\n" + "Status: Down\n" + + "VBoxNetworkName: HostInterfaceNetworking-vbox0\n"; + + public static final List expectedBridgedInterfaces = ImmutableList.of("eth0", "vbox0"); @Test public void retrieveBridgedInterfaceNamesTest() { List activeBridgedInterfaceNames = retrieveBridgedInterfaceNames(TEST1); assertEquals(activeBridgedInterfaceNames, expectedBridgedInterfaces); } - + @Test public void retrieveAvailableBridgedInterfaceInfoTest() { - ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest( - hostId, "localhost", guestId, "localhost", new Credentials("toor", - "password")); - List bridgedInterface = new RetrieveActiveBridgedInterfaces(localHostContext).apply(hostId); + List bridgedInterface = context.utils().injector().getInstance(RetrieveActiveBridgedInterfaces.class) + .apply(host.get()); assertFalse(bridgedInterface.isEmpty()); } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/TakeSnapshotIfNotAlreadyAttachedTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/TakeSnapshotIfNotAlreadyAttachedTest.java index a03baa37d1..3be0490fec 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/TakeSnapshotIfNotAlreadyAttachedTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/TakeSnapshotIfNotAlreadyAttachedTest.java @@ -33,6 +33,8 @@ import org.virtualbox_4_1.ISnapshot; import org.virtualbox_4_1.IVirtualBox; import org.virtualbox_4_1.VirtualBoxManager; +import com.google.common.base.Suppliers; + /** * @author Andrea Turli */ @@ -64,7 +66,7 @@ public class TakeSnapshotIfNotAlreadyAttachedTest { session.unlockMachine(); replay(manager, machine, vBox, session, console, progress); - new TakeSnapshotIfNotAlreadyAttached(manager, snapshotName, snapshotDesc) + new TakeSnapshotIfNotAlreadyAttached(Suppliers.ofInstance(manager), snapshotName, snapshotDesc) .apply(machine); verify(machine); @@ -94,7 +96,7 @@ public class TakeSnapshotIfNotAlreadyAttachedTest { session.unlockMachine(); replay(manager, machine, vBox, session, console, progress); - new TakeSnapshotIfNotAlreadyAttached(manager, snapshotName, snapshotDesc) + new TakeSnapshotIfNotAlreadyAttached(Suppliers.ofInstance(manager), snapshotName, snapshotDesc) .apply(machine); verify(machine); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningTest.java index bcca15eaab..f89d4dc5c9 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningTest.java @@ -25,29 +25,34 @@ import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; import static org.testng.Assert.assertEquals; +import java.net.URI; + import org.eclipse.jetty.server.Server; import org.testng.annotations.Test; /** - * @author Andrea Turli + * @author Andrea Turli, Adrian Cole */ @Test(groups = "unit", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningTest") public class StartJettyIfNotAlreadyRunningTest { - - private String basebaseResource = "."; - private int port = 8080; - @Test public void testLaunchJettyServerWhenAlreadyRunningDoesntLaunchAgain() { Server jetty = createMock(Server.class); + + String preconfigurationUrl = "http://foo:8080"; + expect(jetty.getState()).andReturn(Server.STARTED); replay(jetty); - assertEquals(new StartJettyIfNotAlreadyRunning(jetty, port).apply(basebaseResource), jetty); + StartJettyIfNotAlreadyRunning starter = new StartJettyIfNotAlreadyRunning(jetty, preconfigurationUrl); + starter.start(); + + assertEquals(starter.get(), URI.create(preconfigurationUrl)); verify(jetty); } + @Test public void testLaunchJettyServerWhenNotRunningStartsJettyOnCorrectHostPortAndBasedir() { // TODO: all yours! diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningTest.java index 6328cf164b..c6645cee3e 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningTest.java @@ -19,147 +19,92 @@ package org.jclouds.virtualbox.functions.admin; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.inject.AbstractModule; -import com.google.inject.Module; -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.compute.domain.ExecResponse; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.LoginCredentials; -import org.jclouds.net.IPSocket; -import org.jclouds.ssh.ConfiguresSshClient; -import org.jclouds.ssh.SshClient; -import org.testng.annotations.Test; -import org.virtualbox_4_1.VirtualBoxManager; +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; +import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; import java.net.URI; -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.*; -import static org.testng.Assert.assertEquals; +import org.jclouds.compute.callables.RunScriptOnNode; +import org.jclouds.compute.callables.RunScriptOnNode.Factory; +import org.jclouds.compute.domain.ExecResponse; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.predicates.RetryIfSocketNotYetOpen; +import org.jclouds.net.IPSocket; +import org.jclouds.scriptbuilder.domain.Statements; +import org.testng.annotations.Test; +import org.virtualbox_4_1.VirtualBoxManager; + +import com.google.common.base.Function; +import com.google.common.base.Functions; +import com.google.common.base.Suppliers; @Test(groups = "unit", singleThreaded = true, testName = "StartVBoxIfNotAlreadyRunningTest") public class StartVBoxIfNotAlreadyRunningTest { - @Test(expectedExceptions = IllegalStateException.class) - public void testStartVboxThrowsIllegalStateExceptionIfTheNodeIdConfiguredIsntAround() throws Exception { - - ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar") - .getComputeService(); - - VirtualBoxManager manager = createMock(VirtualBoxManager.class); - @SuppressWarnings("unchecked") - Predicate socketTester = createMock(Predicate.class); - String hostId = "hostId"; - URI endpointUri = URI.create("http://localhost:18083/"); - Credentials localhostCredentials = new Credentials("toor", "password"); - - manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential); - - replay(socketTester); - replay(manager); - - new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials).apply(endpointUri); - - } - + @SuppressWarnings("unchecked") @Test public void testStartVboxConnectsToManagerWhenPortAlreadyListening() throws Exception { - - ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar") - .getComputeService(); - - // TODO: possibly better to use a defined name as opposed to an id, since - // most compute services the id is not predictable. - NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup("foo", 1)); - String hostId = node.getId(); - VirtualBoxManager manager = createMock(VirtualBoxManager.class); - @SuppressWarnings("unchecked") - Predicate socketTester = createMock(Predicate.class); - URI endpointUri = URI.create("http://localhost:18083/"); - Credentials localhostCredentials = new Credentials("toor", "password"); + Factory runScriptOnNodeFactory = createMock(Factory.class); + RetryIfSocketNotYetOpen client = createMock(RetryIfSocketNotYetOpen.class); + NodeMetadata host = new NodeMetadataBuilder().id("host").state(NodeState.RUNNING).build(); + URI provider = URI.create("http://localhost:18083/"); + String identity = "adminstrator"; + String credential = "12345"; - expect(socketTester.apply(new IPSocket(endpointUri.getHost(), endpointUri.getPort()))).andReturn(true); - manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential); + expect(client.apply(new IPSocket(provider.getHost(), provider.getPort()))).andReturn(true); - replay(socketTester); - replay(manager); + manager.connect(provider.toASCIIString(), identity, credential); - assertEquals( - new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials) - .apply(endpointUri), - manager); + replay(manager, runScriptOnNodeFactory, client); - verify(socketTester); - verify(manager); - } + new StartVBoxIfNotAlreadyRunning((Function) Functions.constant(manager), runScriptOnNodeFactory, client, + Suppliers.ofInstance(host), provider, identity, credential).start(); - @ConfiguresSshClient - static class StartingVBoxWhenNotRunningModule extends AbstractModule { - - @Override - protected void configure() { - SshClient.Factory factory = createMock(SshClient.Factory.class); - SshClient client = createMock(SshClient.class); - // NOTE we may want to switch to a node supplier so that we can predict - // these values. Right now, it is node 2 since the above test made node - // 1. - IPSocket expectedSshSockectFor2ndCreatedNode = new IPSocket("144.175.1.2", 22); - LoginCredentials loginCredentials = new LoginCredentials("root", "password2", null, false); - expect(factory.create(expectedSshSockectFor2ndCreatedNode, loginCredentials)).andReturn( - client).times(2); - - expect(client.getUsername()).andReturn(loginCredentials.identity).times(2); - expect(client.getHostAddress()).andReturn(expectedSshSockectFor2ndCreatedNode.getAddress()).times(2); - - client.disconnect(); - client.connect(); - expect(client.exec("VBoxManage setproperty websrvauthlibrary null\n")).andReturn(new ExecResponse("", "", 0)); - - client.disconnect(); - client.connect(); - expect(client.exec("vboxwebsrv -t 10000 -v -b\n")).andReturn(new ExecResponse("", "", 0)); - - replay(factory); - replay(client); - bind(SshClient.Factory.class).toInstance(factory); - - } + verify(manager, runScriptOnNodeFactory, client); } + @SuppressWarnings("unchecked") @Test public void testStartVboxDisablesPasswordAccessOnWebsrvauthlibraryStartsVboxwebsrvInBackgroundAndConnectsManagerWhenPortIsNotListening() - throws Exception { - ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar", - ImmutableSet. of(new StartingVBoxWhenNotRunningModule())).getComputeService(); - NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup("foo", 1)); - String hostId = node.getId(); - + throws Exception { VirtualBoxManager manager = createMock(VirtualBoxManager.class); - @SuppressWarnings("unchecked") - Predicate socketTester = createMock(Predicate.class); - Credentials localhostCredentials = new Credentials("toor", "password"); - URI endpointUri = URI.create("http://localhost:18083/"); + Factory runScriptOnNodeFactory = createMock(Factory.class); + RetryIfSocketNotYetOpen client = createMock(RetryIfSocketNotYetOpen.class); + RunScriptOnNode runScriptOnNode = createMock(RunScriptOnNode.class); + NodeMetadata host = new NodeMetadataBuilder().id("host").state(NodeState.RUNNING).operatingSystem( + OperatingSystem.builder().description("unix").build()).build(); + URI provider = URI.create("http://localhost:18083/"); + String identity = "adminstrator"; + String credential = "12345"; - expect(socketTester.apply(new IPSocket(endpointUri.getHost(), endpointUri.getPort()))).andReturn(false); + expect(client.apply(new IPSocket(provider.getHost(), provider.getPort()))).andReturn(false); + expect( + runScriptOnNodeFactory.create(host, Statements.exec("VBoxManage setproperty websrvauthlibrary null"), + runAsRoot(false).wrapInInitScript(false))).andReturn(runScriptOnNode); + expect(runScriptOnNode.init()).andReturn(runScriptOnNode); + expect(runScriptOnNode.call()).andReturn(new ExecResponse("", "", 0)); + + expect( + runScriptOnNodeFactory.create(host, Statements.exec("vboxwebsrv -t 10000 -v -b"), runAsRoot(false) + .wrapInInitScript(false).blockOnComplete(false).nameTask("vboxwebsrv"))).andReturn( + runScriptOnNode); + expect(runScriptOnNode.init()).andReturn(runScriptOnNode); + expect(runScriptOnNode.call()).andReturn(new ExecResponse("", "", 0)); + + manager.connect(provider.toASCIIString(), identity, credential); - manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential); + replay(manager, runScriptOnNodeFactory, runScriptOnNode, client); + new StartVBoxIfNotAlreadyRunning((Function) Functions.constant(manager), runScriptOnNodeFactory, client, + Suppliers.ofInstance(host), provider, identity, credential).start(); + verify(manager, runScriptOnNodeFactory, runScriptOnNode, client); - replay(socketTester); - replay(manager); - - assertEquals( - new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials) - .apply(endpointUri), - manager); - - verify(socketTester); - verify(manager); } -} +} \ No newline at end of file diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/IsLinkedClonesLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/IsLinkedClonesLiveTest.java index 07400131a1..b3e780bf61 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/IsLinkedClonesLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/IsLinkedClonesLiveTest.java @@ -19,10 +19,8 @@ package org.jclouds.virtualbox.predicates; -import static org.jclouds.virtualbox.util.MachineUtils.lockMachineAndApplyOrReturnNullIfNotRegistered; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; -import static org.virtualbox_4_1.LockType.Write; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.domain.HardDisk; @@ -30,14 +28,13 @@ import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.functions.CloneAndRegisterMachineFromIMachineIfNotAlreadyExists; import org.jclouds.virtualbox.functions.CreateAndRegisterMachineFromIsoIfNotAlreadyExists; -import org.jclouds.virtualbox.functions.IMachineToVmSpec; -import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.StorageBus; -import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.collect.ImmutableSet; @@ -78,29 +75,28 @@ public class IsLinkedClonesLiveTest extends BaseVirtualBoxClientLiveTest { @Test public void testLinkedClone() { - VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi(); - lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, masterSpec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(masterSpec)); - - IMachine master = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir).apply(masterSpec); + IMachine master = context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class) + .apply(masterSpec); IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec, IS_LINKED_CLONE).apply(master); assertTrue(new IsLinkedClone(manager).apply(clone)); - for (VmSpec spec : ImmutableSet.of(new IMachineToVmSpec().apply(clone), masterSpec)) - lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, spec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(spec)); } public void testFullClone() { - - VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi(); - lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, masterSpec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(masterSpec)); - - IMachine master = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(manager, workingDir).apply(masterSpec); + IMachine master = context.utils().injector().getInstance(CreateAndRegisterMachineFromIsoIfNotAlreadyExists.class) + .apply(masterSpec); IMachine clone = new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, cloneSpec, !IS_LINKED_CLONE).apply(master); assertFalse(new IsLinkedClone(manager).apply(clone)); - for (VmSpec spec : ImmutableSet.of(new IMachineToVmSpec().apply(clone), masterSpec)) - lockMachineAndApplyOrReturnNullIfNotRegistered(manager, Write, spec.getVmName(), new UnregisterMachineIfExistsAndDeleteItsMedia(spec)); + + } + + @BeforeMethod + @AfterMethod + void cleanUpVms() { + for (VmSpec spec : ImmutableSet.of(cloneSpec, masterSpec)) + this.undoVm(spec); } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/SshAvailableLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/SshAvailableLiveTest.java deleted file mode 100644 index 421d0be8b0..0000000000 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/SshAvailableLiveTest.java +++ /dev/null @@ -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 predicate = new RetryablePredicate(new SshAvailable(localHostContext), 5, 1, - TimeUnit.SECONDS); - assertTrue(predicate.apply(guestId)); - - lockSessionOnMachineAndApply(manager, Shared, vmName, new Function() { - - @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 socketTester = new RetryablePredicate(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, "")); - } - -} \ No newline at end of file