http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsLocationTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsLocationTest.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsLocationTest.java deleted file mode 100644 index 5821a07..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsLocationTest.java +++ /dev/null @@ -1,510 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.test.entity.LocalManagementContextForTests; -import org.jclouds.scriptbuilder.domain.OsFamily; -import org.jclouds.scriptbuilder.domain.StatementList; -import org.mockito.Mockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.reflect.TypeToken; - -import brooklyn.config.BrooklynProperties; -import brooklyn.config.ConfigKey; -import brooklyn.entity.basic.ConfigKeys; -import brooklyn.entity.basic.Entities; -import brooklyn.location.LocationSpec; -import brooklyn.location.MachineLocation; -import brooklyn.location.MachineLocationCustomizer; -import brooklyn.location.NoMachinesAvailableException; -import brooklyn.location.basic.LocationConfigKeys; -import brooklyn.location.cloud.names.CustomMachineNamer; -import brooklyn.location.geo.HostGeoInfo; -import brooklyn.location.jclouds.JcloudsLocation.UserCreation; -import brooklyn.management.internal.LocalManagementContext; -import brooklyn.test.Asserts; -import brooklyn.util.collections.MutableMap; -import brooklyn.util.config.ConfigBag; -import brooklyn.util.exceptions.Exceptions; - -/** - * @author Shane Witbeck - */ -public class JcloudsLocationTest implements JcloudsLocationConfig { - - private static final Logger log = LoggerFactory.getLogger(JcloudsLocationTest.class); - - public static Predicate<ConfigBag> checkerFor(final String user, final Integer minRam, final Integer minCores) { - return new Predicate<ConfigBag>() { - @Override - public boolean apply(@Nullable ConfigBag input) { - Assert.assertEquals(input.get(USER), user); - Assert.assertEquals(input.get(MIN_RAM), minRam); - Assert.assertEquals(input.get(MIN_CORES), minCores); - return true; - } - }; - } - - public static Predicate<ConfigBag> templateCheckerFor(final String ports) { - return new Predicate<ConfigBag>() { - @Override - public boolean apply(@Nullable ConfigBag input) { - Assert.assertEquals(input.get(INBOUND_PORTS), ports); - return false; - } - }; - } - - private LocalManagementContext managementContext; - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - managementContext = LocalManagementContextForTests.newInstance(BrooklynProperties.Factory.builderEmpty().build()); - } - - @AfterMethod(alwaysRun=true) - public void tearUp() throws Exception { - if (managementContext != null) Entities.destroyAll(managementContext); - } - - @Test - public void testCreateWithFlagsDirectly() throws Exception { - BailOutJcloudsLocation jcl = BailOutJcloudsLocation.newBailOutJcloudsLocation(managementContext); - jcl.tryObtainAndCheck(MutableMap.of(MIN_CORES, 2), checkerFor("fred", 16, 2)); - } - - @Test - public void testCreateWithFlagsDirectlyAndOverride() throws Exception { - BailOutJcloudsLocation jcl = BailOutJcloudsLocation.newBailOutJcloudsLocation(managementContext); - jcl.tryObtainAndCheck(MutableMap.of(MIN_CORES, 2, MIN_RAM, 8), checkerFor("fred", 8, 2)); - } - - @Test - public void testCreateWithFlagsSubLocation() throws Exception { - BailOutJcloudsLocation jcl = BailOutJcloudsLocation.newBailOutJcloudsLocation(managementContext); - jcl = (BailOutJcloudsLocation) jcl.newSubLocation(MutableMap.of(USER, "jon", MIN_CORES, 2)); - jcl.tryObtainAndCheck(MutableMap.of(MIN_CORES, 3), checkerFor("jon", 16, 3)); - } - - @Test - public void testStringListToIntArray() { - String listString = "[1, 2, 3, 4]"; - int[] intArray = new int[] {1, 2, 3, 4}; - Assert.assertEquals(JcloudsLocation.toIntArray(listString), intArray); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testMalformedStringListToIntArray() { - String listString = "1, 2, 3, 4"; - JcloudsLocation.toIntArray(listString); - } - - @Test - public void testEmptyStringListToIntArray() { - String listString = "[]"; - int[] intArray = new int[] {}; - Assert.assertEquals(JcloudsLocation.toIntArray(listString), intArray); - } - - @Test - public void testIntArrayToIntArray() { - int[] intArray = new int[] {1, 2, 3, 4}; - Assert.assertEquals(JcloudsLocation.toIntArray(intArray), intArray); - } - - @Test - public void testObjectArrayToIntArray() { - Object[] longArray = new Object[] {1, 2, 3, 4}; - int[] intArray = new int[] {1, 2, 3, 4}; - Assert.assertEquals(JcloudsLocation.toIntArray(longArray), intArray); - } - - @Test(expectedExceptions = ClassCastException.class) - public void testInvalidObjectArrayToIntArray() { - String[] stringArray = new String[] {"1", "2", "3"}; - JcloudsLocation.toIntArray(stringArray); - } - - @Test - public void testVMCreationIsRetriedOnFailure() { - final AtomicInteger count = new AtomicInteger(); - Function<ConfigBag, Void> countingInterceptor = new Function<ConfigBag, Void>() { - @Override public Void apply(ConfigBag input) { - count.incrementAndGet(); - return null; - } - }; - BailOutJcloudsLocation loc = BailOutJcloudsLocation.newBailOutJcloudsLocation(managementContext, ImmutableMap.<ConfigKey<?>, Object>of( - MACHINE_CREATE_ATTEMPTS, 3, - BailOutJcloudsLocation.BUILD_TEMPLATE_INTERCEPTOR, countingInterceptor)); - loc.tryObtain(); - Assert.assertEquals(count.get(), 3); - } - - @Test(groups={"Live", "Live-sanity"}) - public void testCreateWithInboundPorts() { - BailOutJcloudsLocation jcloudsLocation = BailOutJcloudsLocation.newBailOutJcloudsLocationForLiveTest(managementContext); - jcloudsLocation = (BailOutJcloudsLocation) jcloudsLocation.newSubLocation(MutableMap.of()); - jcloudsLocation.tryObtainAndCheck(MutableMap.of(), templateCheckerFor("[22, 80, 9999]")); - int[] ports = new int[] {22, 80, 9999}; - Assert.assertEquals(jcloudsLocation.getTemplate().getOptions().getInboundPorts(), ports); - } - - @Test(groups={"Live", "Live-sanity"}) - public void testCreateWithInboundPortsOverride() { - BailOutJcloudsLocation jcloudsLocation = BailOutJcloudsLocation.newBailOutJcloudsLocationForLiveTest(managementContext); - jcloudsLocation = (BailOutJcloudsLocation) jcloudsLocation.newSubLocation(MutableMap.of()); - jcloudsLocation.tryObtainAndCheck(MutableMap.of(INBOUND_PORTS, "[23, 81, 9998]"), templateCheckerFor("[23, 81, 9998]")); - int[] ports = new int[] {23, 81, 9998}; - Assert.assertEquals(jcloudsLocation.getTemplate().getOptions().getInboundPorts(), ports); - } - - @Test - public void testCreateWithMaxConcurrentCallsUnboundedByDefault() throws Exception { - final int numCalls = 20; - ConcurrencyTracker interceptor = new ConcurrencyTracker(); - ExecutorService executor = Executors.newCachedThreadPool(); - - try { - final BailOutJcloudsLocation jcloudsLocation = BailOutJcloudsLocation.newBailOutJcloudsLocation( - managementContext, ImmutableMap.<ConfigKey<?>, Object>of( - BailOutJcloudsLocation.BUILD_TEMPLATE_INTERCEPTOR, interceptor)); - for (int i = 0; i < numCalls; i++) { - executor.execute(new Runnable() { - @Override - public void run() { - jcloudsLocation.tryObtain(); - } - }); - } - interceptor.assertCallCountEventually(numCalls); - interceptor.unblock(); - executor.shutdown(); - executor.awaitTermination(10, TimeUnit.SECONDS); - } finally { - executor.shutdownNow(); - } - } - - @Test(groups="Integration") // because takes 1 sec - public void testCreateWithMaxConcurrentCallsRespectsConfig() throws Exception { - final int numCalls = 4; - final int maxConcurrentCreations = 2; - ConcurrencyTracker interceptor = new ConcurrencyTracker(); - ExecutorService executor = Executors.newCachedThreadPool(); - - try { - final BailOutJcloudsLocation jcloudsLocation = BailOutJcloudsLocation.newBailOutJcloudsLocation( - managementContext, ImmutableMap.of( - BailOutJcloudsLocation.BUILD_TEMPLATE_INTERCEPTOR, interceptor, - JcloudsLocation.MAX_CONCURRENT_MACHINE_CREATIONS, maxConcurrentCreations)); - - for (int i = 0; i < numCalls; i++) { - executor.execute(new Runnable() { - @Override - public void run() { - jcloudsLocation.tryObtain(); - } - }); - } - - interceptor.assertCallCountEventually(maxConcurrentCreations); - interceptor.assertCallCountContinually(maxConcurrentCreations); - - interceptor.unblock(); - interceptor.assertCallCountEventually(numCalls); - executor.shutdown(); - executor.awaitTermination(10, TimeUnit.SECONDS); - - } finally { - executor.shutdownNow(); - } - } - - @Test(groups="Integration") // because takes 1 sec - public void testCreateWithMaxConcurrentCallsAppliesToSubLocations() throws Exception { - final int numCalls = 4; - final int maxConcurrentCreations = 2; - ConcurrencyTracker interceptor = new ConcurrencyTracker(); - ExecutorService executor = Executors.newCachedThreadPool(); - - try { - final BailOutJcloudsLocation jcloudsLocation = BailOutJcloudsLocation.newBailOutJcloudsLocation( - managementContext, ImmutableMap.of( - BailOutJcloudsLocation.BUILD_TEMPLATE_INTERCEPTOR, interceptor, - JcloudsLocation.MAX_CONCURRENT_MACHINE_CREATIONS, maxConcurrentCreations)); - - for (int i = 0; i < numCalls; i++) { - final BailOutJcloudsLocation subLocation = (BailOutJcloudsLocation) jcloudsLocation.newSubLocation(MutableMap.of()); - executor.execute(new Runnable() { - @Override - public void run() { - subLocation.tryObtain(); - } - }); - } - - interceptor.assertCallCountEventually(maxConcurrentCreations); - interceptor.assertCallCountContinually(maxConcurrentCreations); - - interceptor.unblock(); - interceptor.assertCallCountEventually(numCalls); - executor.shutdown(); - executor.awaitTermination(10, TimeUnit.SECONDS); - - } finally { - executor.shutdownNow(); - } - } - - @Test - public void testCreateWithCustomMachineNamer() { - final String machineNamerClass = CustomMachineNamer.class.getName(); - BailOutJcloudsLocation jcloudsLocation = BailOutJcloudsLocation.newBailOutJcloudsLocation( - managementContext, ImmutableMap.<ConfigKey<?>, Object>of( - LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS, machineNamerClass)); - jcloudsLocation.tryObtainAndCheck(ImmutableMap.of(CustomMachineNamer.MACHINE_NAME_TEMPLATE, "ignored"), new Predicate<ConfigBag>() { - public boolean apply(ConfigBag input) { - Assert.assertEquals(input.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS), machineNamerClass); - return true; - } - }); - } - - @Test - public void testCreateWithCustomMachineNamerOnObtain() { - final String machineNamerClass = CustomMachineNamer.class.getName(); - BailOutJcloudsLocation jcloudsLocation = BailOutJcloudsLocation.newBailOutJcloudsLocation(managementContext); - ImmutableMap<ConfigKey<String>, String> flags = ImmutableMap.of( - CustomMachineNamer.MACHINE_NAME_TEMPLATE, "ignored", - LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS, machineNamerClass); - jcloudsLocation.tryObtainAndCheck(flags, new Predicate<ConfigBag>() { - public boolean apply(ConfigBag input) { - Assert.assertEquals(input.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS), machineNamerClass); - return true; - } - }); - } - - public static class ConcurrencyTracker implements Function<ConfigBag,Void> { - final AtomicInteger concurrentCallsCounter = new AtomicInteger(); - final CountDownLatch continuationLatch = new CountDownLatch(1); - - @Override public Void apply(ConfigBag input) { - concurrentCallsCounter.incrementAndGet(); - try { - continuationLatch.await(); - } catch (InterruptedException e) { - throw Exceptions.propagate(e); - } - return null; - } - - public void unblock() { - continuationLatch.countDown(); - } - - public void assertCallCountEventually(final int expected) { - Asserts.succeedsEventually(new Runnable() { - @Override public void run() { - Assert.assertEquals(concurrentCallsCounter.get(), expected); - } - }); - } - - public void assertCallCountContinually(final int expected) { - Asserts.succeedsContinually(new Runnable() { - @Override public void run() { - Assert.assertEquals(concurrentCallsCounter.get(), expected); - } - }); - } - } - - - @SuppressWarnings("serial") - public static class FakeLocalhostWithParentJcloudsLocation extends JcloudsLocation { - public static final ConfigKey<Function<ConfigBag,Void>> BUILD_TEMPLATE_INTERCEPTOR = ConfigKeys.newConfigKey(new TypeToken<Function<ConfigBag,Void>>() {}, "buildtemplateinterceptor"); - - ConfigBag lastConfigBag; - - public FakeLocalhostWithParentJcloudsLocation() { - super(); - } - - public FakeLocalhostWithParentJcloudsLocation(Map<?, ?> conf) { - super(conf); - } - - @Override - public JcloudsSshMachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException { - JcloudsSshMachineLocation result = getManagementContext().getLocationManager().createLocation(LocationSpec.create(JcloudsSshMachineLocation.class) - .configure("address", "127.0.0.1") - .configure("port", 22) - .configure("user", "bob") - .configure("jcloudsParent", this)); - registerJcloudsMachineLocation("bogus", result); - - // explicitly invoke this customizer, to comply with tests - for (JcloudsLocationCustomizer customizer : getCustomizers(config().getBag())) { - customizer.customize(this, null, (JcloudsMachineLocation)result); - } - for (MachineLocationCustomizer customizer : getMachineCustomizers(config().getBag())) { - customizer.customize((JcloudsMachineLocation)result); - } - - return result; - } - - @Override - protected void releaseNode(String instanceId) { - // no-op - } - } - - @Test - public void testInheritsGeo() throws Exception { - ConfigBag allConfig = ConfigBag.newInstance() - .configure(IMAGE_ID, "bogus") - .configure(CLOUD_PROVIDER, "aws-ec2") - .configure(CLOUD_REGION_ID, "bogus") - .configure(ACCESS_IDENTITY, "bogus") - .configure(ACCESS_CREDENTIAL, "bogus") - .configure(LocationConfigKeys.LATITUDE, 42d) - .configure(LocationConfigKeys.LONGITUDE, -20d) - .configure(JcloudsLocation.MACHINE_CREATE_ATTEMPTS, 1); - FakeLocalhostWithParentJcloudsLocation ll = managementContext.getLocationManager().createLocation(LocationSpec.create(FakeLocalhostWithParentJcloudsLocation.class).configure(allConfig.getAllConfig())); - MachineLocation l = ll.obtain(); - log.info("loc:" +l); - HostGeoInfo geo = HostGeoInfo.fromLocation(l); - log.info("geo: "+geo); - Assert.assertEquals(geo.latitude, 42d, 0.00001); - Assert.assertEquals(geo.longitude, -20d, 0.00001); - } - - @SuppressWarnings("unchecked") - @Test - public void testInheritsGeoFromLocationMetadataProperties() throws Exception { - // in location-metadata.properties: -// [email protected]=38.909202 -// [email protected]=-77.47314 - ConfigBag allConfig = ConfigBag.newInstance() - .configure(IMAGE_ID, "bogus") - .configure(CLOUD_PROVIDER, "softlayer") - .configure(CLOUD_REGION_ID, "wdc01") - .configure(ACCESS_IDENTITY, "bogus") - .configure(ACCESS_CREDENTIAL, "bogus") - .configure(JcloudsLocation.MACHINE_CREATE_ATTEMPTS, 1); - FakeLocalhostWithParentJcloudsLocation ll = managementContext.getLocationManager().createLocation(LocationSpec.create(FakeLocalhostWithParentJcloudsLocation.class) - .configure(new JcloudsPropertiesFromBrooklynProperties().getJcloudsProperties("softlayer", "wdc01", null, managementContext.getBrooklynProperties())) - .configure(allConfig.getAllConfig())); - MachineLocation l = ll.obtain(); - log.info("loc:" +l); - HostGeoInfo geo = HostGeoInfo.fromLocation(l); - log.info("geo: "+geo); - Assert.assertEquals(geo.latitude, 38.909202d, 0.00001); - Assert.assertEquals(geo.longitude, -77.47314d, 0.00001); - } - - @Test - public void testInvokesCustomizerCallbacks() throws Exception { - JcloudsLocationCustomizer customizer = Mockito.mock(JcloudsLocationCustomizer.class); - MachineLocationCustomizer machineCustomizer = Mockito.mock(MachineLocationCustomizer.class); -// Mockito.when(customizer.customize(Mockito.any(JcloudsLocation.class), Mockito.any(ComputeService.class), Mockito.any(JcloudsSshMachineLocation.class))); - ConfigBag allConfig = ConfigBag.newInstance() - .configure(CLOUD_PROVIDER, "aws-ec2") - .configure(ACCESS_IDENTITY, "bogus") - .configure(ACCESS_CREDENTIAL, "bogus") - .configure(JcloudsLocationConfig.JCLOUDS_LOCATION_CUSTOMIZERS, ImmutableList.of(customizer)) - .configure(JcloudsLocation.MACHINE_LOCATION_CUSTOMIZERS, ImmutableList.of(machineCustomizer)) - .configure(JcloudsLocation.MACHINE_CREATE_ATTEMPTS, 1); - FakeLocalhostWithParentJcloudsLocation ll = managementContext.getLocationManager().createLocation(LocationSpec.create(FakeLocalhostWithParentJcloudsLocation.class).configure(allConfig.getAllConfig())); - JcloudsMachineLocation l = (JcloudsMachineLocation)ll.obtain(); - Mockito.verify(customizer, Mockito.times(1)).customize(ll, null, l); - Mockito.verify(customizer, Mockito.never()).preRelease(l); - Mockito.verify(customizer, Mockito.never()).postRelease(l); - Mockito.verify(machineCustomizer, Mockito.times(1)).customize(l); - Mockito.verify(machineCustomizer, Mockito.never()).preRelease(l); - - ll.release(l); - Mockito.verify(customizer, Mockito.times(1)).preRelease(l); - Mockito.verify(customizer, Mockito.times(1)).postRelease(l); - Mockito.verify(machineCustomizer, Mockito.times(1)).preRelease(l); - } - - // now test creating users - - protected String getCreateUserStatementsFor(Map<ConfigKey<?>,?> config) { - BailOutJcloudsLocation jl = BailOutJcloudsLocation.newBailOutJcloudsLocation( - managementContext, MutableMap.<ConfigKey<?>, Object>builder() - .put(JcloudsLocationConfig.LOGIN_USER, "root").put(JcloudsLocationConfig.LOGIN_USER_PASSWORD, "m0ck") - .put(JcloudsLocationConfig.USER, "bob").put(JcloudsLocationConfig.LOGIN_USER_PASSWORD, "b0b") - .putAll(config).build()); - - UserCreation creation = jl.createUserStatements(null, jl.config().getBag()); - return new StatementList(creation.statements).render(OsFamily.UNIX); - } - - @Test - public void testDisablesRoot() { - String statements = getCreateUserStatementsFor(ImmutableMap.<ConfigKey<?>, Object>of()); - Assert.assertTrue(statements.contains("PermitRootLogin"), "Error:\n"+statements); - Assert.assertTrue(statements.matches("(?s).*sudoers.*useradd.*bob.*wheel.*"), "Error:\n"+statements); - } - - @Test - public void testDisableRootFalse() { - String statements = getCreateUserStatementsFor(ImmutableMap.<ConfigKey<?>, Object>of( - JcloudsLocationConfig.DISABLE_ROOT_AND_PASSWORD_SSH, false)); - Assert.assertFalse(statements.contains("PermitRootLogin"), "Error:\n"+statements); - Assert.assertTrue(statements.matches("(?s).*sudoers.*useradd.*bob.*wheel.*"), "Error:\n"+statements); - } - - @Test - public void testDisableRootAndSudoFalse() { - String statements = getCreateUserStatementsFor(ImmutableMap.<ConfigKey<?>, Object>of( - JcloudsLocationConfig.DISABLE_ROOT_AND_PASSWORD_SSH, false, - JcloudsLocationConfig.GRANT_USER_SUDO, false)); - Assert.assertFalse(statements.contains("PermitRootLogin"), "Error:\n"+statements); - Assert.assertFalse(statements.matches("(?s).*sudoers.*useradd.*bob.*wheel.*"), "Error:\n"+statements); - } - - // TODO more tests, where flags come in from resolver, named locations, etc - -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsLoginLiveTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsLoginLiveTest.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsLoginLiveTest.java deleted file mode 100644 index ef0862f..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsLoginLiveTest.java +++ /dev/null @@ -1,408 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import static org.testng.Assert.assertEquals; - -import java.io.File; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.location.LocationSpec; -import brooklyn.location.basic.SshMachineLocation; -import brooklyn.util.collections.MutableList; -import brooklyn.util.collections.MutableMap; -import brooklyn.util.os.Os; -import brooklyn.util.stream.Streams; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Tests different login options for ssh keys, passwords, etc. - */ -public class JcloudsLoginLiveTest extends AbstractJcloudsLiveTest { - - private static final Logger LOG = LoggerFactory.getLogger(JcloudsLoginLiveTest.class); - - public static final String AWS_EC2_REGION_NAME = AWS_EC2_USEAST_REGION_NAME; - public static final String AWS_EC2_LOCATION_SPEC = "jclouds:" + AWS_EC2_PROVIDER + (AWS_EC2_REGION_NAME == null ? "" : ":" + AWS_EC2_REGION_NAME); - - // Image: {id=us-east-1/ami-7d7bfc14, providerId=ami-7d7bfc14, name=RightImage_CentOS_6.3_x64_v5.8.8.5, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=centos, arch=paravirtual, version=6.0, description=rightscale-us-east/RightImage_CentOS_6.3_x64_v5.8.8.5.manifest.xml, is64Bit=true}, description=rightscale-us-east/RightImage_CentOS_6.3_x64_v5.8.8.5.manifest.xml, version=5.8.8.5, status=AVAILABLE[available], loginUser=root, userMetadata={owner=411009282317, rootDeviceType=instance-store, virtualizationType=paravirtual, hypervisor=xen}} - public static final String AWS_EC2_CENTOS_IMAGE_ID = "us-east-1/ami-7d7bfc14"; - - // Image: {id=us-east-1/ami-d0f89fb9, providerId=ami-d0f89fb9, name=ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=ubuntu, arch=paravirtual, version=12.04, description=099720109477/ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, is64Bit=true}, description=099720109477/ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1, version=20130411.1, status=AVAILABLE[available], loginUser=ubuntu, userMetadata={owner=099720109477, rootDeviceType=ebs, virtualizationType=paravirtual, hypervisor=xen}} - public static final String AWS_EC2_UBUNTU_IMAGE_ID = "us-east-1/ami-d0f89fb9"; - - // Image: {id=us-east-1/ami-5e008437, providerId=ami-5e008437, name=RightImage_Ubuntu_10.04_x64_v5.8.8.3, location={scope=REGION, id=us-east-1, description=us-east-1, parent=aws-ec2, iso3166Codes=[US-VA]}, os={family=ubuntu, arch=paravirtual, version=10.04, description=rightscale-us-east/RightImage_Ubuntu_10.04_x64_v5.8.8.3.manifest.xml, is64Bit=true}, description=rightscale-us-east/RightImage_Ubuntu_10.04_x64_v5.8.8.3.manifest.xml, version=5.8.8.3, status=AVAILABLE[available], loginUser=root, userMetadata={owner=411009282317, rootDeviceType=instance-store, virtualizationType=paravirtual, hypervisor=xen}} - // Uses "root" as loginUser - public static final String AWS_EC2_UBUNTU_10_IMAGE_ID = "us-east-1/ami-5e008437"; - - public static final String RACKSPACE_LOCATION_SPEC = "jclouds:" + RACKSPACE_PROVIDER; - - // Image: {id=LON/c52a0ca6-c1f2-4cd1-b7d6-afbcd1ebda22, providerId=c52a0ca6-c1f2-4cd1-b7d6-afbcd1ebda22, name=CentOS 6.0, location={scope=ZONE, id=LON, description=LON, parent=rackspace-cloudservers-uk, iso3166Codes=[GB-SLG]}, os={family=centos, name=CentOS 6.0, version=6.0, description=CentOS 6.0, is64Bit=true}, description=CentOS 6.0, status=AVAILABLE, loginUser=root, userMetadata={os_distro=centos, com.rackspace__1__visible_core=1, com.rackspace__1__build_rackconnect=1, com.rackspace__1__options=0, image_type=base, cache_in_nova=True, com.rackspace__1__source=kickstart, org.openstack__1__os_distro=org.centos, com.rackspace__1__release_build_date=2013-07-25_18-56-29, auto_disk_config=True, com.rackspace__1__release_version=5, os_type=linux, com.rackspace__1__visible_rackconnect=1, com.rackspace__1__release_id=210, com.rackspace__1__visible_managed=0, com.rackspace__1__build_core=1, org.openstack__1__os_version=6.0, org.openstack__1__architecture=x64, com.rackspace__1__build_ma naged=0}} - public static final String RACKSPACE_CENTOS_IMAGE_NAME_REGEX = "CentOS 6.0"; - - // Image: {id=LON/29fe3e2b-f119-4715-927b-763e99ebe23e, providerId=29fe3e2b-f119-4715-927b-763e99ebe23e, name=Debian 6.06 (Squeeze), location={scope=ZONE, id=LON, description=LON, parent=rackspace-cloudservers-uk, iso3166Codes=[GB-SLG]}, os={family=debian, name=Debian 6.06 (Squeeze), version=6.0, description=Debian 6.06 (Squeeze), is64Bit=true}, description=Debian 6.06 (Squeeze), status=AVAILABLE, loginUser=root, userMetadata={os_distro=debian, com.rackspace__1__visible_core=1, com.rackspace__1__build_rackconnect=1, com.rackspace__1__options=0, image_type=base, cache_in_nova=True, com.rackspace__1__source=kickstart, org.openstack__1__os_distro=org.debian, com.rackspace__1__release_build_date=2013-08-06_13-05-36, auto_disk_config=True, com.rackspace__1__release_version=4, os_type=linux, com.rackspace__1__visible_rackconnect=1, com.rackspace__1__release_id=300, com.rackspace__1__visible_managed=0, com.rackspace__1__build_core=1, org.openstack__1__os_version=6.06, org.openstack__1_ _architecture=x64, com.rackspace__1__build_managed=0}} - public static final String RACKSPACE_DEBIAN_IMAGE_NAME_REGEX = "Debian 6"; - - protected JcloudsSshMachineLocation machine; - - private File privateRsaFile = new File(Os.tidyPath("~/.ssh/id_rsa")); - private File privateDsaFile = new File(Os.tidyPath("~/.ssh/id_dsa")); - private File privateRsaFileTmp = new File(privateRsaFile.getAbsoluteFile()+".tmp"); - private File privateDsaFileTmp = new File(privateDsaFile.getAbsoluteFile()+".tmp"); - private File publicRsaFile = new File(Os.tidyPath("~/.ssh/id_rsa.pub")); - private File publicDsaFile = new File(Os.tidyPath("~/.ssh/id_dsa.pub")); - private File publicRsaFileTmp = new File(publicRsaFile.getAbsoluteFile()+".tmp"); - private File publicDsaFileTmp = new File(publicDsaFile.getAbsoluteFile()+".tmp"); - private boolean privateRsaFileMoved; - private boolean privateDsaFileMoved; - private boolean publicRsaFileMoved; - private boolean publicDsaFileMoved; - - @Test(groups = {"Live"}) - protected void testAwsEc2SpecifyingJustPrivateSshKeyInDeprecatedForm() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.LEGACY_PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(AWS_EC2_LOCATION_SPEC); - - machine = createEc2Machine(ImmutableMap.<String,Object>of()); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - } - - @Test(groups = {"Live"}) - protected void testAwsEc2SpecifyingPrivateAndPublicSshKeyInDeprecatedForm() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.LEGACY_PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.LEGACY_PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(AWS_EC2_LOCATION_SPEC); - - machine = createEc2Machine(ImmutableMap.<String,Object>of()); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - } - - // Uses default key files - @Test(groups = {"Live"}) - protected void testAwsEc2SpecifyingNoKeyFiles() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(AWS_EC2_LOCATION_SPEC); - - machine = createEc2Machine(ImmutableMap.<String,Object>of()); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - } - - @Test(groups = {"Live"}) - public void testSpecifyingPasswordAndNoDefaultKeyFilesExist() throws Exception { - try { - moveSshKeyFiles(); - - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PASSWORD.getName(), "mypassword"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(RACKSPACE_LOCATION_SPEC); - - machine = createRackspaceMachine(ImmutableMap.of("imageNameRegex", RACKSPACE_DEBIAN_IMAGE_NAME_REGEX)); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PASSWORD, "mypassword") - .build()); - } finally { - restoreSshKeyFiles(); - } - } - - // Generates and uses a random password - @Test(groups = {"Live"}) - protected void testSpecifyingNothingAndNoDefaultKeyFilesExist() throws Exception { - try { - moveSshKeyFiles(); - - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(RACKSPACE_LOCATION_SPEC); - - machine = createRackspaceMachine(ImmutableMap.of("imageNameRegex", RACKSPACE_DEBIAN_IMAGE_NAME_REGEX)); - assertSshable(machine); - assertEquals(machine.getUser(), "myname"); - } finally { - restoreSshKeyFiles(); - } - } - - @Test(groups = {"Live"}) - protected void testSpecifyingPasswordAndSshKeysPrefersKeys() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PASSWORD.getName(), "mypassword"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(RACKSPACE_LOCATION_SPEC); - - machine = createRackspaceMachine(ImmutableMap.of("imageNameRegex", RACKSPACE_DEBIAN_IMAGE_NAME_REGEX)); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PASSWORD, "mypassword") - .build()); - } - - @Test(groups = {"Live"}) - protected void testSpecifyingPasswordIgnoresDefaultSshKeys() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PASSWORD.getName(), "mypassword"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(RACKSPACE_LOCATION_SPEC); - - machine = createRackspaceMachine(ImmutableMap.of("imageNameRegex", RACKSPACE_DEBIAN_IMAGE_NAME_REGEX)); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PASSWORD, "mypassword") - .build()); - - assertNotSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - } - - @Test(groups = {"Live"}) - protected void testSpecifyingPasswordWithPublicKeyAllowsKeyAccess() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PASSWORD.getName(), "mypassword"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(RACKSPACE_LOCATION_SPEC); - - machine = createRackspaceMachine(ImmutableMap.of("imageNameRegex", RACKSPACE_DEBIAN_IMAGE_NAME_REGEX)); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "myname") - .put(SshMachineLocation.PASSWORD, "mypassword") - .build()); - } - - // user "root" matches the loginUser=root - @Test(groups = {"Live"}) - protected void testSpecifyingPasswordWhenNoDefaultKeyFilesExistWithRootUser() throws Exception { - try { - moveSshKeyFiles(); - - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "root"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PASSWORD.getName(), "mypassword"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(RACKSPACE_LOCATION_SPEC); - - machine = createRackspaceMachine(ImmutableMap.of("imageNameRegex", RACKSPACE_DEBIAN_IMAGE_NAME_REGEX)); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "root") - .put(SshMachineLocation.PASSWORD, "mypassword") - .build()); - } finally { - restoreSshKeyFiles(); - } - } - - @Test(groups = {"Live"}) - protected void testAwsEc2SpecifyingRootUser() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "root"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(AWS_EC2_LOCATION_SPEC); - - machine = createEc2Machine(ImmutableMap.<String,Object>of("imageId", AWS_EC2_UBUNTU_10_IMAGE_ID)); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "root") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - } - - @Test(groups = {"Live"}) - protected void testAwsEc2WhenBlankUserSoUsesRootLoginUser() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), ""); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(AWS_EC2_LOCATION_SPEC); - - machine = createEc2Machine(ImmutableMap.<String,Object>of("imageId", AWS_EC2_UBUNTU_10_IMAGE_ID)); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "root") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - } - - // In JcloudsLocation.NON_ADDABLE_USERS, "ec2-user" was treated special and was not added! - // That was very bad for if someone is running brooklyn on a new AWS VM, and just installs brooklyn+runs as the default ec2-user. - @Test(groups = {"Live"}) - protected void testAwsEc2SpecifyingSpecialUser() throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "ec2-user"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa"); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(AWS_EC2_LOCATION_SPEC); - - machine = createEc2Machine(ImmutableMap.<String,Object>of("imageId", AWS_EC2_UBUNTU_10_IMAGE_ID)); - assertSshable(machine); - - assertSshable(ImmutableMap.builder() - .put("address", machine.getAddress()) - .put("user", "ec2-user") - .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa")) - .build()); - } - - @Override - protected void releaseMachine(JcloudsSshMachineLocation machine) { - jcloudsLocation.release(machine); - } - - private JcloudsSshMachineLocation createEc2Machine(Map<String,? extends Object> conf) throws Exception { - return obtainMachine(MutableMap.<String,Object>builder() - .putAll(conf) - .putIfAbsent("imageId", AWS_EC2_CENTOS_IMAGE_ID) - .putIfAbsent("hardwareId", AWS_EC2_SMALL_HARDWARE_ID) - .putIfAbsent("inboundPorts", ImmutableList.of(22)) - .build()); - } - - private JcloudsSshMachineLocation createRackspaceMachine(Map<String,? extends Object> conf) throws Exception { - return obtainMachine(MutableMap.<String,Object>builder() - .putAll(conf) - .putIfAbsent("inboundPorts", ImmutableList.of(22)) - .build()); - } - - protected void assertSshable(Map<?,?> machineConfig) { - SshMachineLocation machineWithThatConfig = managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class) - .configure(machineConfig)); - try { - assertSshable(machineWithThatConfig); - } finally { - Streams.closeQuietly(machineWithThatConfig); - } - } - - protected void assertNotSshable(Map<?,?> machineConfig) { - try { - assertSshable(machineConfig); - Assert.fail("ssh should not have succeeded "+machineConfig); - } catch (Exception e) { - // expected - LOG.debug("Exception as expected when testing sshable "+machineConfig); - } - } - - private void moveSshKeyFiles() throws Exception { - privateRsaFileMoved = false; - privateDsaFileMoved = false; - publicRsaFileMoved = false; - publicDsaFileMoved = false; - - if (privateRsaFile.exists()) { - LOG.info("Moving {} to {}", privateRsaFile, privateRsaFileTmp); - Runtime.getRuntime().exec("mv "+privateRsaFile.getAbsolutePath()+" "+privateRsaFileTmp.getAbsolutePath()); - privateRsaFileMoved = true; - } - if (privateDsaFile.exists()) { - LOG.info("Moving {} to {}", privateDsaFile, privateDsaFileTmp); - Runtime.getRuntime().exec("mv "+privateDsaFile.getAbsolutePath()+" "+privateDsaFileTmp.getAbsolutePath()); - privateDsaFileMoved = true; - } - if (publicRsaFile.exists()) { - LOG.info("Moving {} to {}", publicRsaFile, publicRsaFileTmp); - Runtime.getRuntime().exec("mv "+publicRsaFile.getAbsolutePath()+" "+publicRsaFileTmp.getAbsolutePath()); - publicRsaFileMoved = true; - } - if (publicDsaFile.exists()) { - LOG.info("Moving {} to {}", publicDsaFile, publicDsaFileTmp); - Runtime.getRuntime().exec("mv "+publicDsaFile.getAbsolutePath()+" "+publicDsaFileTmp.getAbsolutePath()); - publicDsaFileMoved = true; - } - } - - private void restoreSshKeyFiles() throws Exception { - if (privateRsaFileMoved) { - LOG.info("Restoring {} form {}", privateRsaFile, privateRsaFileTmp); - Runtime.getRuntime().exec("mv "+privateRsaFileTmp.getAbsolutePath()+" "+privateRsaFile.getAbsolutePath()); - privateRsaFileMoved = false; - } - if (privateDsaFileMoved) { - LOG.info("Restoring {} form {}", privateDsaFile, privateDsaFileTmp); - Runtime.getRuntime().exec("mv "+privateDsaFileTmp.getAbsolutePath()+" "+privateDsaFile.getAbsolutePath()); - privateDsaFileMoved = false; - } - if (publicRsaFileMoved) { - LOG.info("Restoring {} form {}", publicRsaFile, publicRsaFileTmp); - Runtime.getRuntime().exec("mv "+publicRsaFileTmp.getAbsolutePath()+" "+publicRsaFile.getAbsolutePath()); - publicRsaFileMoved = false; - } - if (publicDsaFileMoved) { - LOG.info("Restoring {} form {}", publicDsaFile, publicDsaFileTmp); - Runtime.getRuntime().exec("mv "+publicDsaFileTmp.getAbsolutePath()+" "+publicDsaFile.getAbsolutePath()); - publicDsaFileMoved = false; - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsMachineNamerTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsMachineNamerTest.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsMachineNamerTest.java deleted file mode 100644 index da21750..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsMachineNamerTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.config.ConfigBag; -import brooklyn.util.text.Strings; - -public class JcloudsMachineNamerTest { - - private static final Logger log = LoggerFactory.getLogger(JcloudsMachineNamerTest.class); - - @Test - public void testGenerateGroupIdInVcloud() { - ConfigBag cfg = new ConfigBag() - .configure(JcloudsLocationConfig.CLOUD_PROVIDER, "vcloud") - .configure(JcloudsLocationConfig.CALLER_CONTEXT, "!mycontext!"); - - String result = new JcloudsMachineNamer().generateNewGroupId(cfg); - - log.info("test mycontext vcloud group id gives: "+result); - // brooklyn-user-!mycontext!-1234 - // br-<code>-<user>-myco-1234 - Assert.assertTrue(result.length() <= 24-4-1, "result: "+result); - - String user = Strings.maxlen(System.getProperty("user.name"), 2).toLowerCase(); - // (length 2 will happen if user is brooklyn, to avoid brooklyn-brooklyn at start!) - Assert.assertTrue(result.indexOf(user) >= 0); - Assert.assertTrue(result.indexOf("-myc") >= 0); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynPropertiesTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynPropertiesTest.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynPropertiesTest.java deleted file mode 100644 index d3134a4..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsPropertiesFromBrooklynPropertiesTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import java.util.Map; - -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.collect.Maps; - -public class JcloudsPropertiesFromBrooklynPropertiesTest { - - protected static Map<String, Object> sampleProviderOrApiProps() { - Map<String, Object> map = Maps.newHashMap(); - map.put("brooklyn.location.jclouds.FooServers.identity", "bob"); - map.put("brooklyn.location.jclouds.FooServers.credential", "s3cr3t"); - map.put("brooklyn.location.jclouds.FooServers.jclouds.ssh.max-retries", "100"); - return map; - } - - protected static Map<String, Object> sampleNamedProps() { - Map<String, Object> map = Maps.newHashMap(); - map.put("brooklyn.location.named.cloudfirst", "jclouds:openstack-nova"); - map.put("brooklyn.location.named.cloudfirst.identity", "myId"); - map.put("brooklyn.location.named.cloudfirst.credential", "password"); - map.put("brooklyn.location.named.cloudfirst.imageId", "RegionOne/1"); - map.put("brooklyn.location.named.cloudfirst.securityGroups", "universal"); - return map; - } - - protected static Map<String, Object> unsupportedSampleProviderOrApiProps() { - Map<String, Object> map = Maps.newHashMap(); - map.put("brooklyn.location.jclouds.FooServers.image-id", "invalid-image-id"); - return map; - } - - protected static Map<String, Object> unsupportedNamedProps() { - Map<String, Object> map = Maps.newHashMap(); - map.put("brooklyn.location.named.cloudfirst", "jclouds:openstack-nova"); - map.put("brooklyn.location.named.cloudfirst.hardware-id", "invalid-hardware-id"); - return map; - } - - private JcloudsPropertiesFromBrooklynProperties parser; - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - parser = new JcloudsPropertiesFromBrooklynProperties(); - } - - @Test - public void testProviderOrApiProperties() { - Map<String, Object> map = parser.getJcloudsProperties("FooServers", null, null, sampleProviderOrApiProps()); - Assert.assertEquals(map.get("identity"), "bob"); - Assert.assertEquals(map.get("credential"), "s3cr3t"); - Assert.assertEquals(map.get("provider"), "FooServers"); - } - - @Test - public void testNamedProperties() { - Map<String, Object> map = parser.getJcloudsProperties("openstack-nova", null, "cloudfirst", sampleNamedProps()); - Assert.assertEquals(map.get("provider"), "openstack-nova"); - Assert.assertEquals(map.get("identity"), "myId"); - Assert.assertEquals(map.get("credential"), "password"); - Assert.assertEquals(map.get("imageId"), "RegionOne/1"); - Assert.assertEquals(map.get("securityGroups"), "universal"); - } - - @Test - public void testOrderOfPreference() { - Map<String, Object> allProperties = Maps.newHashMap(); - allProperties.putAll(sampleProviderOrApiProps()); - allProperties.putAll(sampleNamedProps()); - Map<String, Object> map = parser.getJcloudsProperties("openstack-nova", null, "cloudfirst", allProperties); - Assert.assertEquals(map.get("provider"), "openstack-nova"); - Assert.assertEquals(map.get("identity"), "myId"); - Assert.assertEquals(map.get("credential"), "password"); - Assert.assertEquals(map.get("imageId"), "RegionOne/1"); - Assert.assertEquals(map.get("securityGroups"), "universal"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsSshingLiveTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsSshingLiveTest.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsSshingLiveTest.java deleted file mode 100644 index bc89fe6..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/JcloudsSshingLiveTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableMap; - -import com.google.common.collect.ImmutableList; - -/** - * Tests the initial ssh command execution (e.g. user creation), using jclouds TemplateOptions - * and using just brooklyn. - */ -public class JcloudsSshingLiveTest extends AbstractJcloudsLiveTest { - - public static final String SOFTLAYER_REGION_NAME = SOFTLAYER_AMS01_REGION_NAME; - public static final String SOTLAYER_LOCATION_SPEC = "jclouds:" + SOFTLAYER_PROVIDER + (SOFTLAYER_REGION_NAME == null ? "" : ":" + SOFTLAYER_REGION_NAME); - - protected JcloudsSshMachineLocation machine; - - @Test(groups = {"Live"}) - public void testCreatesUserUsingJcloudsTemplateOptions() throws Exception { - runCreatesUser(true); - } - - @Test(groups = {"Live"}) - public void testCreatesUserWithoutUsingJcloudsTemplateOptions() throws Exception { - runCreatesUser(false); - } - - protected void runCreatesUser(boolean useJcloudsSshInit) throws Exception { - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USE_JCLOUDS_SSH_INIT.getName(), Boolean.toString(useJcloudsSshInit)); - brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname"); - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(SOTLAYER_LOCATION_SPEC); - - JcloudsSshMachineLocation machine = obtainMachine(MutableMap.<String,Object>builder() - .putIfAbsent("inboundPorts", ImmutableList.of(22)) - .build()); - assertSshable(machine); - assertEquals(machine.getUser(), "myname"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/LiveTestEntity.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/LiveTestEntity.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/LiveTestEntity.java deleted file mode 100644 index c8db561..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/LiveTestEntity.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import java.util.Collection; - -import org.apache.brooklyn.api.entity.proxying.ImplementedBy; -import org.apache.brooklyn.test.entity.TestEntity; -import org.apache.brooklyn.test.entity.TestEntityImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.entity.basic.Lifecycle; -import brooklyn.location.Location; -import brooklyn.location.MachineProvisioningLocation; -import brooklyn.location.NoMachinesAvailableException; -import brooklyn.location.basic.LocationInternal; - -import com.google.common.base.Predicates; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -@ImplementedBy(LiveTestEntity.LiveTestEntityImpl.class) -public interface LiveTestEntity extends TestEntity { - - MachineProvisioningLocation<?> getProvisioningLocation(); - JcloudsSshMachineLocation getObtainedLocation(); - - public static class LiveTestEntityImpl extends TestEntityImpl implements LiveTestEntity { - - private static final Logger LOG = LoggerFactory.getLogger(LiveTestEntityImpl.class); - private JcloudsLocation provisioningLocation; - private JcloudsSshMachineLocation obtainedLocation; - - @Override - public void start(final Collection<? extends Location> locs) { - LOG.trace("Starting {}", this); - callHistory.add("start"); - setAttribute(SERVICE_STATE, Lifecycle.STARTING); - counter.incrementAndGet(); - addLocations(locs); - provisioningLocation = (JcloudsLocation) Iterables.find(locs, Predicates.instanceOf(JcloudsLocation.class)); - try { - obtainedLocation = (JcloudsSshMachineLocation)provisioningLocation.obtain(((LocationInternal)provisioningLocation).config().getBag().getAllConfig()); - } catch (NoMachinesAvailableException e) { - throw Throwables.propagate(e); - } - addLocations(ImmutableList.of(obtainedLocation)); - setAttribute(SERVICE_STATE, Lifecycle.RUNNING); - } - - @Override - public void stop() { - LOG.trace("Stopping {}", this); - callHistory.add("stop"); - setAttribute(SERVICE_STATE, Lifecycle.STOPPING); - counter.decrementAndGet(); - if (provisioningLocation != null && obtainedLocation != null) { - provisioningLocation.release(obtainedLocation); - } - setAttribute(SERVICE_STATE, Lifecycle.STOPPED); - } - - public MachineProvisioningLocation<?> getProvisioningLocation() { - return provisioningLocation; - } - - public JcloudsSshMachineLocation getObtainedLocation() { - return obtainedLocation; - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/RebindJcloudsLocationLiveTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/RebindJcloudsLocationLiveTest.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/RebindJcloudsLocationLiveTest.java deleted file mode 100644 index 6d73e59..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/RebindJcloudsLocationLiveTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -import java.io.File; - -import org.apache.brooklyn.api.entity.proxying.EntitySpec; -import org.apache.brooklyn.test.entity.TestApplication; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.ApplicationBuilder; -import brooklyn.entity.basic.Entities; -import brooklyn.entity.rebind.RebindTestUtils; -import brooklyn.location.OsDetails; -import brooklyn.management.internal.LocalManagementContext; -import brooklyn.util.config.ConfigBag; - -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.io.Files; - -public class RebindJcloudsLocationLiveTest extends AbstractJcloudsLiveTest { - - public static final String AWS_EC2_REGION_NAME = AWS_EC2_USEAST_REGION_NAME; - public static final String AWS_EC2_LOCATION_SPEC = "jclouds:" + AWS_EC2_PROVIDER + ":" + AWS_EC2_REGION_NAME; - - private ClassLoader classLoader = getClass().getClassLoader(); - private TestApplication origApp; - private LiveTestEntity origEntity; - private File mementoDir; - - @BeforeMethod(alwaysRun=true) - @Override - public void setUp() throws Exception { - super.setUp(); - origApp = ApplicationBuilder.newManagedApp(EntitySpec.create(TestApplication.class), managementContext); - origEntity = origApp.createAndManageChild(EntitySpec.create(LiveTestEntity.class)); - - jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().resolve(AWS_EC2_LOCATION_SPEC); - jcloudsLocation.setConfig(JcloudsLocation.HARDWARE_ID, AWS_EC2_SMALL_HARDWARE_ID); - } - - @AfterMethod(alwaysRun = true) - @Override - public void tearDown() throws Exception { - super.tearDown(); - if (origApp != null) Entities.destroyAll(origApp.getManagementContext()); - if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir); - } - - @Override - protected LocalManagementContext newManagementContext() { - mementoDir = Files.createTempDir(); - return RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader, 1); - } - - @Test(groups="Live") - public void testRebindsToJcloudsMachine() throws Exception { - origApp.start(ImmutableList.of(jcloudsLocation)); - JcloudsLocation origJcloudsLocation = jcloudsLocation; - System.out.println("orig locations: " + origEntity.getLocations()); - JcloudsSshMachineLocation origMachine = (JcloudsSshMachineLocation) Iterables.find(origEntity.getLocations(), Predicates.instanceOf(JcloudsSshMachineLocation.class)); - - TestApplication newApp = rebind(); - LiveTestEntity newEntity = (LiveTestEntity) Iterables.find(newApp.getChildren(), Predicates.instanceOf(LiveTestEntity.class)); - JcloudsSshMachineLocation newMachine = (JcloudsSshMachineLocation) Iterables.find(newEntity.getLocations(), Predicates.instanceOf(JcloudsSshMachineLocation.class)); - - assertMachineEquals(newMachine, origMachine); - assertTrue(newMachine.isSshable()); - - JcloudsLocation newJcloudsLoction = newMachine.getParent(); - assertJcloudsLocationEquals(newJcloudsLoction, origJcloudsLocation); - } - - private void assertMachineEquals(JcloudsSshMachineLocation actual, JcloudsSshMachineLocation expected) { - String errmsg = "actual="+actual.toVerboseString()+"; expected="+expected.toVerboseString(); - assertEquals(actual.getId(), expected.getId(), errmsg); - assertEquals(actual.getJcloudsId(), expected.getJcloudsId(), errmsg); - assertOsDetailEquals(actual.getOsDetails(), expected.getOsDetails()); - assertEquals(actual.getSshHostAndPort(), expected.getSshHostAndPort()); - assertEquals(actual.getPrivateAddress(), expected.getPrivateAddress()); - assertConfigBagEquals(actual.config().getBag(), expected.config().getBag(), errmsg); - } - - private void assertOsDetailEquals(OsDetails actual, OsDetails expected) { - String errmsg = "actual="+actual+"; expected="+expected; - if (actual == null) assertNull(expected, errmsg); - assertEquals(actual.isWindows(), expected.isWindows()); - assertEquals(actual.isLinux(), expected.isLinux()); - assertEquals(actual.isMac(), expected.isMac()); - assertEquals(actual.getName(), expected.getName()); - assertEquals(actual.getArch(), expected.getArch()); - assertEquals(actual.getVersion(), expected.getVersion()); - assertEquals(actual.is64bit(), expected.is64bit()); - } - - private void assertJcloudsLocationEquals(JcloudsLocation actual, JcloudsLocation expected) { - String errmsg = "actual="+actual.toVerboseString()+"; expected="+expected.toVerboseString(); - assertEquals(actual.getId(), expected.getId(), errmsg); - assertEquals(actual.getProvider(), expected.getProvider(), errmsg); - assertEquals(actual.getRegion(), expected.getRegion(), errmsg); - assertEquals(actual.getIdentity(), expected.getIdentity(), errmsg); - assertEquals(actual.getCredential(), expected.getCredential(), errmsg); - assertEquals(actual.getHostGeoInfo(), expected.getHostGeoInfo(), errmsg); - assertConfigBagEquals(actual.config().getBag(), expected.config().getBag(), errmsg); - } - - private void assertConfigBagEquals(ConfigBag actual, ConfigBag expected, String errmsg) { - // TODO revisit the strong assertion that configBags are equal - -// // TODO Can we include all of these things (e.g. when locations are entities, so flagged fields not treated special)? -// List<String> configToIgnore = ImmutableList.of("id", "template", "usedPorts", "machineCreationSemaphore", "config"); -// MutableMap<Object, Object> actualMap = MutableMap.builder().putAll(actual.getAllConfig()) -// .removeAll(configToIgnore) -// .build(); -// MutableMap<Object, Object> expectedMap = MutableMap.builder().putAll(expected.getAllConfig()) -// .removeAll(configToIgnore) -// .build(); -// -// assertEquals(actualMap, expectedMap, errmsg+"; actualBag="+actualMap+"; expectedBag="+expectedMap); - } - - private TestApplication rebind() throws Exception { - RebindTestUtils.waitForPersisted(origApp); - return (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/RebindJcloudsLocationTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/RebindJcloudsLocationTest.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/RebindJcloudsLocationTest.java deleted file mode 100644 index 7ce0ad3..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/RebindJcloudsLocationTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNull; - -import org.jclouds.domain.LoginCredentials; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.rebind.RebindTestFixtureWithApp; -import brooklyn.location.basic.SshMachineLocation; -import brooklyn.util.config.ConfigBag; - -import com.google.common.net.HostAndPort; - -public class RebindJcloudsLocationTest extends RebindTestFixtureWithApp { - - public static final String LOC_SPEC = "jclouds:aws-ec2:us-east-1"; - - private JcloudsLocation origLoc; - - @BeforeMethod(alwaysRun=true) - @Override - public void setUp() throws Exception { - super.setUp(); - origLoc = (JcloudsLocation) origManagementContext.getLocationRegistry().resolve(LOC_SPEC); - } - - // Previously, the rebound config contained "id" which was then passed to createTemporarySshMachineLocation, causing - // that to fail (because the LocationSpec should not have had "id" in its config) - @Test - public void testReboundConfigDoesNotContainId() throws Exception { - rebind(); - - JcloudsLocation newLoc = (JcloudsLocation) newManagementContext.getLocationManager().getLocation(origLoc.getId()); - - ConfigBag newLocConfig = newLoc.config().getBag(); - ConfigBag config = ConfigBag.newInstanceCopying(newLocConfig); - - assertNull(newLocConfig.getStringKey(("id"))); - - SshMachineLocation tempMachine = newLoc.createTemporarySshMachineLocation( - HostAndPort.fromParts("localhost", 1234), - LoginCredentials.builder().identity("myuser").password("mypass").noPrivateKey().build(), - config); - assertNotEquals(tempMachine.getId(), newLoc.getId()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/locations/jclouds/src/test/java/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java b/locations/jclouds/src/test/java/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java deleted file mode 100644 index 193f108..0000000 --- a/locations/jclouds/src/test/java/brooklyn/location/jclouds/SimpleJcloudsLocationUserLoginAndConfigLiveTest.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF 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 brooklyn.location.jclouds; - -import java.io.ByteArrayOutputStream; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.location.NoMachinesAvailableException; -import brooklyn.location.basic.SshMachineLocation; -import brooklyn.util.collections.MutableMap; -import brooklyn.util.ssh.BashCommands; -import brooklyn.util.text.Identifiers; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; - -public class SimpleJcloudsLocationUserLoginAndConfigLiveTest extends AbstractJcloudsLiveTest { - - // FIXME And tidy up this one - - private static final String LOCATION_SPEC = AWS_EC2_PROVIDER + ":" + AWS_EC2_USEAST_REGION_NAME; - - private static final Logger log = LoggerFactory.getLogger(SimpleJcloudsLocationUserLoginAndConfigLiveTest.class); - - @BeforeMethod(alwaysRun=true) - @Override - public void setUp() throws Exception { - super.setUp(); - jcloudsLocation = resolve(LOCATION_SPEC); - } - - @SuppressWarnings("rawtypes") - @Test(groups="Live") - public void testJcloudsCreateBogStandard() throws Exception { - log.info("TEST testJcloudsCreateBogStandard"); - JcloudsSshMachineLocation m1 = obtainMachine(ImmutableMap.of()); - - Map details = MutableMap.of("id", m1.getJcloudsId(), "hostname", m1.getAddress().getHostAddress(), "user", m1.getUser()); - log.info("got machine "+m1+" at "+jcloudsLocation+": "+details+"; now trying to rebind"); - String result; - // echo conflates spaces of arguments - result = execWithOutput(m1, Arrays.asList("echo trying m1", "hostname", "date")); - Assert.assertTrue(result.contains("trying m1")); - - log.info("now trying rebind "+m1); - JcloudsSshMachineLocation m2 = jcloudsLocation.rebindMachine(details); - result = execWithOutput(m2, Arrays.asList("echo trying m2", "hostname", "date")); - Assert.assertTrue(result.contains("trying m2")); - } - - @SuppressWarnings("rawtypes") - @Test(groups="Live") - public void testJcloudsCreateBogStandardWithUserBrooklyn() throws Exception { - log.info("TEST testJcloudsCreateBogStandardWithUserBrooklyn"); - JcloudsSshMachineLocation m1 = obtainMachine(MutableMap.of("user", "brooklyn")); - - Map details = MutableMap.of("id", m1.getJcloudsId(), "hostname", m1.getAddress().getHostAddress(), "user", m1.getUser()); - log.info("got machine "+m1+" at "+jcloudsLocation+": "+details+"; now trying to rebind"); - String result; - // echo conflates spaces of arguments - result = execWithOutput(m1, Arrays.asList("echo trying m1", "hostname", "date")); - Assert.assertTrue(result.contains("trying m1")); - - log.info("now trying rebind "+m1); - JcloudsSshMachineLocation m2 = jcloudsLocation.rebindMachine(details); - result = execWithOutput(m2, Arrays.asList("echo trying m2", "hostname", "date")); - Assert.assertTrue(result.contains("trying m2")); - - Assert.assertEquals(m2.getUser(), "brooklyn"); - } - - @SuppressWarnings("rawtypes") - @Test(groups="Live") - public void testJcloudsCreateUserMetadata() throws Exception { - log.info("TEST testJcloudsCreateBogStandard"); - String key = "brooklyn-test-user-data"; - String value = "test-"+Identifiers.makeRandomId(4); - JcloudsSshMachineLocation m1 = obtainMachine(MutableMap.of("userMetadata", key+"="+value)); - - Map details = MutableMap.of("id", m1.getJcloudsId(), "hostname", m1.getAddress().getHostAddress(), "user", m1.getUser(), - "userMetadata", key+"="+value); - Assert.assertEquals(m1.node.getUserMetadata().get(key), value); - - log.info("got machine "+m1+" at "+jcloudsLocation+": "+details+"; now trying to rebind"); - String result; - // echo conflates spaces of arguments - result = execWithOutput(m1, Arrays.asList("echo trying m1", "hostname", "date")); - Assert.assertTrue(result.contains("trying m1")); - - log.info("now trying rebind "+m1); - JcloudsSshMachineLocation m2 = jcloudsLocation.rebindMachine(details); - result = execWithOutput(m2, Arrays.asList("echo trying m2", "hostname", "date")); - Assert.assertTrue(result.contains("trying m2")); - Assert.assertEquals(m2.node.getUserMetadata().get(key), value); - } - - // a curious image, centos, but user is ec2-user, and handily not correctly auto-detected - // test we can specify a loginUser different from user, and that user is created etc... - // imageId=us-east-1/ami-f95cf390 - public static final String EC2_CENTOS_IMAGE = "us-east-1/ami-f95cf390"; - - @Test(groups="Live") - public void testJcloudsMissingUser() throws Exception { - log.info("TEST testJcloudsMissingUser"); - try { - // wait up to 30s for login (override default of 5m so test runs faster) - obtainMachine(MutableMap.of("imageId", EC2_CENTOS_IMAGE, "waitForSshable", 30*1000)); - log.info("whoops we logged in"); - } catch (NoMachinesAvailableException e) { - log.info("got error as expected, for missing user: "+e); // success - } - } - - @SuppressWarnings("rawtypes") - @Test(groups="Live") - public void testJcloudsWithSpecificLoginUserAndSameUser() throws Exception { - log.info("TEST testJcloudsWithSpecificLoginUserAndSameUser"); - JcloudsSshMachineLocation m1 = obtainMachine(MutableMap.of( - "imageId", EC2_CENTOS_IMAGE, - "loginUser", "ec2-user", - "user", "ec2-user", - "waitForSshable", 30*1000)); - - Map details = MutableMap.of("id", m1.getJcloudsId(), "hostname", m1.getAddress().getHostAddress(), "user", m1.getUser()); - log.info("got machine "+m1+" at "+jcloudsLocation+": "+details+"; now trying to rebind"); - String result; - // echo conflates spaces of arguments - result = execWithOutput(m1, Arrays.asList("echo trying m1", "hostname", "date")); - Assert.assertTrue(result.contains("trying m1")); - - log.info("now trying rebind "+m1); - JcloudsSshMachineLocation m2 = jcloudsLocation.rebindMachine(details); - result = execWithOutput(m2, Arrays.asList("echo trying m2", "hostname", "date")); - Assert.assertTrue(result.contains("trying m2")); - - Assert.assertEquals(m2.getUser(), "ec2-user"); - } - - @SuppressWarnings("rawtypes") - @Test(groups="Live") - public void testJcloudsWithSpecificLoginUserAndNewUser() throws Exception { - log.info("TEST testJcloudsWithSpecificLoginUserAndNewUser"); - JcloudsSshMachineLocation m1 = obtainMachine(MutableMap.of( - "imageId", EC2_CENTOS_IMAGE, - "loginUser", "ec2-user", - "user", "newbob", - "waitForSshable", 30*1000)); - - Map details = MutableMap.of("id", m1.getJcloudsId(), "hostname", m1.getAddress().getHostAddress(), "user", m1.getUser()); - log.info("got machine "+m1+" at "+jcloudsLocation+": "+details+"; now trying to rebind"); - String result; - // echo conflates spaces of arguments - result = execWithOutput(m1, Arrays.asList("echo trying m1", "hostname", "date")); - Assert.assertTrue(result.contains("trying m1")); - - log.info("now trying rebind "+m1); - JcloudsSshMachineLocation m2 = jcloudsLocation.rebindMachine(details); - result = execWithOutput(m2, Arrays.asList("echo trying m2", "hostname", "date")); - Assert.assertTrue(result.contains("trying m2")); - - Assert.assertEquals(m2.getUser(), "newbob"); - } - - @SuppressWarnings("rawtypes") - @Test(groups="Live") - public void testJcloudsWithSpecificLoginUserAndDefaultUser() throws Exception { - log.info("TEST testJcloudsWithSpecificLoginUserAndDefaultUser"); - JcloudsSshMachineLocation m1 = obtainMachine(MutableMap.of( - "imageId", EC2_CENTOS_IMAGE, - "loginUser", "ec2-user", - "waitForSshable", 30*1000)); - - Map details = MutableMap.of("id", m1.getJcloudsId(), "hostname", m1.getAddress().getHostAddress(), "user", m1.getUser()); - log.info("got machine "+m1+" at "+jcloudsLocation+": "+details+"; now trying to rebind"); - String result; - // echo conflates spaces of arguments - result = execWithOutput(m1, Arrays.asList("echo trying m1", "hostname", "date")); - Assert.assertTrue(result.contains("trying m1")); - - log.info("now trying rebind "+m1); - JcloudsSshMachineLocation m2 = jcloudsLocation.rebindMachine(details); - result = execWithOutput(m2, Arrays.asList("echo trying m2", "hostname", "date")); - Assert.assertTrue(result.contains("trying m2")); - } - - @Test(groups="Live") - public void testJcloudsCreateWithNoSudoGranted() throws Exception { - log.info("TEST testJcloudsCreateWithNoSudoGranted"); - JcloudsSshMachineLocation m = obtainMachine(MutableMap.of( - "grantUserSudo", false, - "waitForSshable", 30*1000)); - - int exitCode = execWithExitCode(m, ImmutableList.of(BashCommands.sudo("echo yes"))); - Assert.assertFalse(exitCode == 0, "exit code for sudo command should not have been 0"); - } - - private String execWithOutput(SshMachineLocation m, List<String> commands) { - ByteArrayOutputStream stdout = new ByteArrayOutputStream(); - ByteArrayOutputStream stderr = new ByteArrayOutputStream(); - exec(m, commands, stdout, stderr); - return new String(stdout.toByteArray()); - } - - private int execWithExitCode(SshMachineLocation m, List<String> commands) { - ByteArrayOutputStream stdout = new ByteArrayOutputStream(); - ByteArrayOutputStream stderr = new ByteArrayOutputStream(); - return exec(m, commands, stdout, stderr); - } - - private int exec(SshMachineLocation m, List<String> commands, ByteArrayOutputStream stdout, ByteArrayOutputStream stderr) { - Map<String, Object> flags = Maps.newLinkedHashMap(); - flags.put("out", stdout); - flags.put("err", stderr); - int exitCode = m.execCommands(flags, "test", commands); - log.info("stdout from "+commands+":\n"+new String(stdout.toByteArray())); - log.info("stderr from "+commands+":\n"+new String(stderr.toByteArray())); - log.info("exit code: " + exitCode); - return exitCode; - } - - private JcloudsLocation resolve(String spec) { - return (JcloudsLocation) managementContext.getLocationRegistry().resolve("jclouds:"+spec); - } -}
