private Map<String, Object> getExtraTemplateSubstitutions(String imageName, Entity context) { Map<String, Object> templateSubstitutions = MutableMap.<String, Object>of("fullyQualifiedImageName", imageName); templateSubstitutions.putAll(getOwner().config().get(DockerInfrastructure.DOCKERFILE_SUBSTITUTIONS)); // Add any extra substitutions on the entity (if present) if (context != null) { templateSubstitutions.putAll(context.config().get(DockerInfrastructure.DOCKERFILE_SUBSTITUTIONS)); } return templateSubstitutions; }
@Override public void customize(MachineLocation machine) { if (config.get(MACHINE_FILTER).apply(machine)) { log.info("SetHostnameCustomizer setting hostname on "+machine); } else { log.info("SetHostnameCustomizer ignoring non-ssh machine "+machine); return; } try { String localHostname = setLocalHostname((SshMachineLocation) machine); machine.config().set(LOCAL_HOSTNAME, localHostname); String localIp = execHostnameMinusI((SshMachineLocation) machine); machine.config().set(LOCAL_IP, localIp); } catch (Exception e) { log.info("SetHostnameCustomizer failed to set hostname on "+machine+" (rethrowing)", e); throw e; } }
/** also see {@link RebindWithDeserializingClassRenamesTest} */ @Test public void testPreBasicConfigInheritance_2016_07() throws Exception { doReadConfigInheritance("prebasic-2016-07", "toruf2wxg4"); ConfigKey<?> k = Iterables.getOnlyElement( rebindedApp.config().findKeysDeclared(ConfigPredicates.nameEqualTo("my.config.inheritanceMerged")) ); Asserts.assertStringContains(origMemento, "<parentInheritance class=\"org.apache.brooklyn.config.ConfigInheritance$Merged\"/>"); Asserts.assertStringDoesNotContain(origMemento, BasicConfigInheritance.DEEP_MERGE.getClass().getName()); // should now convert it to BasicConfigInheritance.DEEP_MERGE Asserts.assertStringDoesNotContain(newMemento, "ConfigInheritance$Merged"); Asserts.assertStringDoesNotContain(newMemento, "ConfigInheritance$Legacy$Merged"); Asserts.assertStringContains(newMemento, BasicConfigInheritance.DEEP_MERGE.getClass().getName()); ConfigInheritance inh = k.getInheritanceByContext(InheritanceContext.RUNTIME_MANAGEMENT); Assert.assertEquals(inh, BasicConfigInheritance.DEEP_MERGE); }
/** * Looks up {@link ConfigKey configuration} with the entity value taking precedence over the * location, and returning a default value (normally {@literal null}) if neither is present. */ public <T> T lookup(final ConfigKey<T> config, Entity entity, ConfigBag setup, T defaultValue) { boolean entityConfigPresent = !entity.config().findKeysPresent(new Predicate<ConfigKey<?>>() { @Override public boolean apply(@Nullable ConfigKey<?> configKey) { return config.equals(configKey); } }).isEmpty(); boolean setupBagConfigPresent = setup.containsKey(config); if (entityConfigPresent) { return entity.config().get(config); } else if (setupBagConfigPresent) { return setup.get(config); } return defaultValue; }
private static Map<String, Object> getSshFlags(Location location) { Set<ConfigKey<?>> sshConfig = MutableSet.of(); StringConfigMap mgmtConfig = null; sshConfig.addAll(location.config().findKeysPresent(ConfigPredicates.nameStartsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX))); if (location instanceof AbstractLocation) { ManagementContext mgmt = ((AbstractLocation)location).getManagementContext(); if (mgmt!=null) { mgmtConfig = mgmt.getConfig(); sshConfig.addAll(mgmtConfig.findKeysPresent(ConfigPredicates.nameStartsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX))); } } Map<String, Object> result = Maps.newLinkedHashMap(); for (ConfigKey<?> key : sshConfig) { Maybe<Object> v = ((LocationInternal)location).config().getRaw(key); if (v.isAbsent() && mgmtConfig!=null) v = Maybe.of( (Object) mgmtConfig.getConfig(key) ); result.put(ConfigUtils.unprefixedKey(SshTool.BROOKLYN_CONFIG_KEY_PREFIX, key).getName(), v.get()); } return result; }
@SuppressWarnings({ "unchecked", "rawtypes" }) public static void setConfig(Object objectOfField, ConfigKey<?> key, Object value, SetFromFlag optionalAnnotation) { if (objectOfField instanceof Configurable) { ((Configurable)objectOfField).config().set((ConfigKey)key, value); return; } else { if (optionalAnnotation==null) { log.warn("Cannot set key "+key.getName()+" on "+objectOfField+": containing class is not Configurable"); } else if (!key.getName().equals(optionalAnnotation.value())) { log.warn("Cannot set key "+key.getName()+" on "+objectOfField+" from flag "+optionalAnnotation.value()+": containing class is not Configurable"); } else { // if key and flag are the same, then it will probably happen automatically if (log.isDebugEnabled()) log.debug("Cannot set key "+key.getName()+" on "+objectOfField+" from flag "+optionalAnnotation.value()+": containing class is not Configurable"); } return; } }
@Test(groups = "Integration", dataProvider = "entitiesWithWarAndURL") public void initialNamedWarDeployments(final SoftwareProcess entity, final String war, final String urlSubPathToWebApp, final String urlSubPathToPageToQuery) { this.entity = entity; log.info("test=initialNamedWarDeployments; entity="+entity+"; app="+entity.getApplication()); URL resource = getClass().getClassLoader().getResource(war); assertNotNull(resource); entity.config().set(JavaWebAppService.NAMED_WARS, ImmutableList.of(resource.toString())); Entities.start(entity.getApplication(), ImmutableList.of(loc)); Asserts.succeedsEventually(MutableMap.of("timeout", 60*1000), new Runnable() { @Override public void run() { // TODO get this URL from a WAR file entity HttpTestUtils.assertHttpStatusCodeEquals(Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery), 200); }}); }
@Test public void testDeferredDslChainingOnConfigNoFunction() throws Exception { final Entity app = createAndStartApplication( "services:", "- type: " + BasicApplication.class.getName(), " brooklyn.config:", " dest: $brooklyn:config(\"targetValue\").getNonExistent()"); ConfigKey<TestDslSupplierValue> targetValueKey = ConfigKeys.newConfigKey(TestDslSupplierValue.class, "targetValue"); app.config().set(targetValueKey, new TestDslSupplierValue()); try { assertEquals(getConfigEventually(app, DEST), app.getId()); Asserts.shouldHaveFailedPreviously("Expected to fail because method does not exist"); } catch (Exception e) { Asserts.expectedFailureContains(e, "No such function 'getNonExistent'"); Asserts.expectedFailureDoesNotContain(e, "$brooklyn:$brooklyn:"); } }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testGetConfigWithFutureWaitsForResult() throws Exception { LatchingCallable<String> work = new LatchingCallable<String>("abc"); Future<String> future = executor.submit(work); final MyOtherEntity entity = app.addChild(EntitySpec.create(MyOtherEntity.class)); entity.config().set((ConfigKey)MyOtherEntity.STRING_KEY, future); Future<String> getConfigFuture = executor.submit(new Callable<String>() { @Override public String call() { return entity.getConfig(MyOtherEntity.STRING_KEY); }}); assertTrue(work.latchCalled.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); assertFalse(getConfigFuture.isDone()); work.latchContinued.countDown(); assertEquals(getConfigFuture.get(TIMEOUT_MS, TimeUnit.MILLISECONDS), "abc"); }
@Test public void testDeferredDslInaccessibleCall() throws Exception { final Entity app = createAndStartApplication( "services:", "- type: " + BasicApplication.class.getName(), " brooklyn.config:", " dest: $brooklyn:config(\"targetValue\").doesFail()"); app.config().set(ConfigKeys.newConfigKey(InaccessibleType.class, "targetValue"), new InaccessibleType()); try { getConfigEventually(app, DEST); Asserts.shouldHaveFailedPreviously("Outside of allowed package scope"); } catch (ExecutionException e) { Asserts.expectedFailureContains(e, "(outside allowed package scope)"); } }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testGetConfigWithDeferredSupplierReturnsSupplied() throws Exception { DeferredSupplier<Integer> supplier = new DeferredSupplier<Integer>() { volatile int next = 0; @Override public Integer get() { return next++; } }; MyOtherEntity entity = app.addChild(EntitySpec.create(MyOtherEntity.class)); entity.config().set((ConfigKey)MyOtherEntity.INT_KEY, supplier); assertEquals(entity.getConfig(MyOtherEntity.INT_KEY), Integer.valueOf(0)); assertEquals(entity.getConfig(MyOtherEntity.INT_KEY), Integer.valueOf(1)); }
@Test public void testReplacesEntityInSameZone() throws Exception { cluster.config().set(DynamicCluster.AVAILABILITY_ZONE_NAMES, ImmutableList.of("zone1", "zone2")); cluster.start(ImmutableList.of(loc)); cluster.resize(4); List<String> locsUsed = getLocationNames(getLocationsOf(cluster.getMembers())); Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("zone1", "zone1", "zone2", "zone2")); String idToRemove = Iterables.getFirst(cluster.getMembers(), null).getId(); String idAdded = cluster.replaceMember(idToRemove); locsUsed = getLocationNames(getLocationsOf(cluster.getMembers())); Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("zone1", "zone1", "zone2", "zone2")); assertNull(Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(idToRemove), null)); assertNotNull(Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(idAdded), null)); }
@Test public void testSpreadsEntitiesAcrossZonesEvenly() throws Exception { cluster.config().set(DynamicCluster.AVAILABILITY_ZONE_NAMES, ImmutableList.of("zone1", "zone2")); cluster.start(ImmutableList.of(loc)); cluster.resize(4); List<String> locsUsed = getLocationNames(getLocationsOf(cluster.getMembers())); Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("zone1", "zone1", "zone2", "zone2")); cluster.resize(2); locsUsed = getLocationNames(getLocationsOf(cluster.getMembers())); Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("zone1", "zone2")); cluster.resize(0); locsUsed = getLocationNames(getLocationsOf(cluster.getMembers())); Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of()); }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Response set(String application, String entityToken, String policyToken, String configKeyName, Object value) { Entity entity = brooklyn().getEntity(application, entityToken); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'", Entitlements.getEntitlementContext().user(), entity); } Policy policy = brooklyn().getPolicy(application, entityToken, policyToken); ConfigKey<?> ck = policy.getPolicyType().getConfigKey(configKeyName); if (ck == null) throw WebResourceUtils.notFound("Cannot find config key '%s' in policy '%s' of entity '%s'", configKeyName, policy, entityToken); policy.config().set((ConfigKey) ck, TypeCoercions.coerce(value, ck.getTypeToken())); return Response.status(Response.Status.OK).build(); }
@Test public void testReplacesEntityInSameZone() throws Exception { cluster.config().set(DynamicCluster.ENABLE_AVAILABILITY_ZONES, true); cluster.start(ImmutableList.of(multiLoc)); cluster.resize(4); List<String> locsUsed = getLocationNames(getLocationsOf(cluster.getMembers(), Predicates.instanceOf(MachineProvisioningLocation.class))); Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("loc1", "loc1", "loc2", "loc2")); String idToRemove = Iterables.getFirst(cluster.getMembers(), null).getId(); String idAdded = cluster.replaceMember(idToRemove); locsUsed = getLocationNames(getLocationsOf(cluster.getMembers(), Predicates.instanceOf(MachineProvisioningLocation.class))); Asserts.assertEqualsIgnoringOrder(locsUsed, ImmutableList.of("loc1", "loc1", "loc2", "loc2")); assertNull(Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(idToRemove), null)); assertNotNull(Iterables.find(cluster.getMembers(), EntityPredicates.idEqualTo(idAdded), null)); }
<T> void setConfig(ConfigKey<T> key, T value) { getEntity().config().set(key, value); }
static boolean removeFromWarsByContext(Entity entity, String targetName) { targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName); // TODO a better way to do atomic updates, see comment above synchronized (entity) { Map<String,String> newWarsMap = MutableMap.copyOf(entity.getConfig(WARS_BY_CONTEXT)); String url = newWarsMap.remove(targetName); if (url==null) { return false; } entity.config().set(WARS_BY_CONTEXT, newWarsMap); return true; } }
@Override public <T> T setConfig(ConfigKey<T> key, T value) { return config().set(key, value); }
@Override public <T> T setConfig(ConfigKey<T> key, T val) { return config().set(key, val); }
@Test public void testApplyTemplatedConfigWithAtributeWhenReadyInSpec() { DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class).configure(DynamicCluster.INITIAL_SIZE, 0) .location(LocationSpec.create(LocalhostMachineProvisioningLocation.LocalhostMachine.class))); cluster.config().set(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class).configure(TestEntity.CONF_NAME, DependentConfiguration.attributeWhenReady(cluster, TestEntity.NAME))); cluster.sensors().set(TestEntity.NAME, "myval"); cluster.resize(1); String templateContents = "${config['"+TestEntity.CONF_NAME.getName()+"']}"; String result = TemplateProcessor.processTemplateContents(templateContents, (EntityInternal)Iterables.getOnlyElement(cluster.getChildren()), ImmutableMap.<String,Object>of()); assertEquals(result, "myval"); }